text stringlengths 14 6.51M |
|---|
unit ncsMessageInterfaces;
// Модуль: "w:\common\components\rtl\Garant\cs\ncsMessageInterfaces.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "ncsMessageInterfaces" MUID: (5460A4DB018A)
{$Include w:\common\components\rtl\Garant\cs\CsDefine.inc}
interface
{$If NOT Defined(Nemesis)}
uses
l3IntfUses
, CsCommon
, ncsMessage
, Windows
, csIdIOHandlerAbstractAdapter
;
type
PIncsMessageExecutorFactory = ^IncsMessageExecutorFactory;
IncsTransporter = interface
['{CE5512DA-5FA9-423C-A266-65F24CF2501C}']
function Get_Connected: Boolean;
function Get_ClientID: TCsClientId;
procedure Set_ClientID(aValue: TCsClientId);
function Get_Processing: Boolean;
function Get_SessionID: AnsiString;
procedure Send(aMessage: TncsMessage);
function WaitForReply(aMessage: TncsMessage;
var theReply: TncsMessage;
aTimeOut: LongWord = Windows.INFINITE): Boolean;
procedure RegisterHelper(const aHelper: IUnknown);
procedure UnregisterHelper(const aHelper: IUnknown);
property Connected: Boolean
read Get_Connected;
{* Есть физический коннект }
property ClientID: TCsClientId
read Get_ClientID
write Set_ClientID;
property Processing: Boolean
read Get_Processing;
{* Есть полноценная обработка сообщений }
property SessionID: AnsiString
read Get_SessionID;
end;//IncsTransporter
TncsExecuteContext = {$IfDef XE4}record{$Else}object{$EndIf}
public
rMessage: TncsMessage;
rTransporter: IncsTransporter;
end;//TncsExecuteContext
IncsExecutor = interface
['{A6EB1A21-7939-4C8E-B5BC-65A97C27D138}']
procedure Execute(const aContext: TncsExecuteContext);
end;//IncsExecutor
IncsMessageExecutorFactory = interface
['{EB847F25-81CC-421B-ADFF-D135A33AC78B}']
function MakeExecutor(aMessage: TncsMessage): IncsExecutor;
end;//IncsMessageExecutorFactory
IncsClientTransporter = interface(IncsTransporter)
['{CD83C556-C3C5-40FA-91B1-6C1CA7CF87D7}']
procedure Connect(const aServerHost: AnsiString;
aServerPort: Integer;
const aSessionID: AnsiString);
procedure Disconnect(Immidiate: Boolean = False);
{* Immidiate = True - отрубить сразу
Immidiate = False - дождаться завершения обмена послав ncsDisconnect и дождавшись ответа }
end;//IncsClientTransporter
IncsServerTransporter = interface(IncsTransporter)
['{2DF810B8-EB59-4A34-8945-D6D35E58B03C}']
function Get_Terminated: Boolean;
procedure ProcessMessages(IsMainSocket: Boolean);
procedure Terminate(WaitForTermination: Boolean = True);
procedure RegisterSendBackHandler(aHandler: TcsIdIOHandlerAbstractAdapter);
property Terminated: Boolean
read Get_Terminated;
end;//IncsServerTransporter
TncsSocketKind = (
ncs_skSend
, ncs_skReceive
);//TncsSocketKind
function TncsExecuteContext_C(aMessage: TncsMessage;
const aTransporter: IncsTransporter): TncsExecuteContext;
{$IfEnd} // NOT Defined(Nemesis)
implementation
{$If NOT Defined(Nemesis)}
uses
l3ImplUses
//#UC START# *5460A4DB018Aimpl_uses*
//#UC END# *5460A4DB018Aimpl_uses*
;
function TncsExecuteContext_C(aMessage: TncsMessage;
const aTransporter: IncsTransporter): TncsExecuteContext;
//#UC START# *5464B3AA0087_5464B37E01ED_var*
//#UC END# *5464B3AA0087_5464B37E01ED_var*
begin
Finalize(Result);
System.FillChar(Result, SizeOf(Result), 0);
//#UC START# *5464B3AA0087_5464B37E01ED_impl*
Result.rMessage := aMessage;
Result.rTransporter := aTransporter;
//#UC END# *5464B3AA0087_5464B37E01ED_impl*
end;//TncsExecuteContext_C
{$IfEnd} // NOT Defined(Nemesis)
end.
|
unit SubViewer;
interface
const
SUBVIEWER_TIME = '([0-9]{2}:){2}[0-9]{2}.[0-9]{2},([0-9]{2}:){2}[0-9]{2}.[0-9]{2}';
OPENTAG = '\[|\(';
CLOSETAG = '\]|\)';
function RemoveSubViewer(Filename: string): boolean;
function RemoveSubViewerTagsFromLine(sLine:string): string;
implementation
uses
Windows, TwoDeskRegExp, MyUtilities, SysUtils;
function RemoveSubViewer(Filename: string): boolean;
var
fileSub: TextFile;
fileNew: TextFile;
sLine:string;
begin
AssignFile(fileSub, Filename);
Reset(fileSub);
AssignFile(fileNew, Filename + '.new');
Rewrite(fileNew);
//to avoid removing infos on begining of file
repeat
begin
Readln(fileSub, sLine);
Writeln(fileNew, Trim(sLine));
end;
until PatternMatch(SUBVIEWER_TIME, sLine);
repeat
begin
Readln(fileSub, sLine);
sLine := RemoveSubViewerTagsFromLine(sLine);
if ValidTextLine(sLine) then
Writeln(fileNew, Trim(sLine));
end;
until EOF(fileSub);
Closefile(fileSub);
Closefile(fileNew);
RenameFile(Filename, Filename + '.old');
RenameFile(Filename + '.new', Filename);
Result := True;
end;
function RemoveSubViewerTagsFromLine(sLine:string): string;
var
iBeginTag, iEndTag: integer;
begin
repeat
begin
iBeginTag := RegExpPos(OPENTAG, sLine);
iEndTag := RegExpPos(CLOSETAG, sLine);
Delete(sLine, iBeginTag, iEndTag - iBeginTag + 1);
end;
until (iBeginTag = 0) or (iEndTag = 0);
Delete(sLine, iBeginTag, Length(sLine));
Delete(sLine, 1, iEndTag);
sLine := Trim(sLine);
if PatternMatch(NAME_PREFIX, sLine) then
Delete(sLine, 1, Pos(':', sLine));
sLine := Trim(sLine);
if Pos('|', sLine) = 1 then
Delete(sLine, 1, 1);
Result := sLine;
end;
end.
|
unit ActivityActionsUnit;
interface
uses
SysUtils, BaseActionUnit,
ActivityRequestUnit, ActivityParametersUnit, ActivityUnit, EnumsUnit;
type
TActivityActions = class(TBaseAction)
public
/// <summary>
/// Create User Activity. Send custom message to Activity Stream.
/// </summary>
/// <returns> True/False </returns>
function LogSpecificMessage(RouteId: String; Message: String;
out ErrorString: String): boolean;
/// <summary>
/// Get Activity Feed
/// </summary>
/// <returns> List of Activity objects </returns>
function GetAllActivities(Limit, Offset: integer; out Total: integer;
out ErrorString: String): TActivityList;
/// <summary>
/// Get all recorded activities associated not only with a specific Route4Me account,
/// but also with other users of a memberís team.
/// </summary>
/// <returns> List of Activity objects </returns>
function GetTeamActivities(RouteId: String; Limit, Offset: integer;
out Total: integer; out ErrorString: String): TActivityList;
function GetActivities(ActivityType: TActivityType;
Limit, Offset: integer; out Total: integer;
out ErrorString: String): TActivityList; overload;
function GetActivities(RouteId: String; ActivityType: TActivityType;
Limit, Offset: integer; out Total: integer;
out ErrorString: String): TActivityList; overload;
end;
implementation
uses
SettingsUnit, GetActivitiesResponseUnit, StatusResponseUnit,
GenericParametersUnit, GetActivitiesQueryUnit;
function TActivityActions.GetActivities(RouteId: String; ActivityType: TActivityType;
Limit, Offset: integer; out Total: integer; out ErrorString: String): TActivityList;
var
Response: TGetActivitiesResponse;
Request: TGetActivitiesQuery;
i: integer;
begin
Result := TActivityList.Create();
Request := TGetActivitiesQuery.Create(ActivityType, RouteId, Limit, Offset);
try
Response := FConnection.Get(TSettings.EndPoints.GetActivities, Request,
TGetActivitiesResponse, ErrorString) as TGetActivitiesResponse;
try
if (Response <> nil) then
begin
for i := 0 to Length(Response.Results) - 1 do
Result.Add(Response.Results[i]);
Total := Response.Total;
end;
if (Response = nil) and (ErrorString = EmptyStr) then
ErrorString := TActivityTypeDescription[ActivityType] + ' fault';
finally
FreeAndNil(Response);
end;
finally
FreeAndNil(Request);
end;
end;
function TActivityActions.GetActivities(ActivityType: TActivityType; Limit,
Offset: integer; out Total: integer; out ErrorString: String): TActivityList;
var
Response: TGetActivitiesResponse;
Request: TGetActivitiesQuery;
i: integer;
begin
Result := TActivityList.Create();
Request := TGetActivitiesQuery.Create(ActivityType, Limit, Offset);
try
Response := FConnection.Get(TSettings.EndPoints.GetActivities, Request,
TGetActivitiesResponse, ErrorString) as TGetActivitiesResponse;
try
if (Response <> nil) then
begin
for i := 0 to Length(Response.Results) - 1 do
Result.Add(Response.Results[i]);
Total := Response.Total;
end;
if (Response = nil) and (ErrorString = EmptyStr) then
ErrorString := TActivityTypeDescription[ActivityType] + ' fault';
finally
FreeAndNil(Response);
end;
finally
FreeAndNil(Request);
end;
end;
function TActivityActions.GetAllActivities(Limit, Offset: integer;
out Total: integer; out ErrorString: String): TActivityList;
var
Response: TGetActivitiesResponse;
Parameters: TActivityParameters;
i: integer;
begin
Result := TActivityList.Create;
Total := 0;
Parameters := TActivityParameters.Create(Limit, Offset);
try
Response := FConnection.Get(TSettings.EndPoints.ActivityFeed, Parameters,
TGetActivitiesResponse, ErrorString) as TGetActivitiesResponse;
try
if (Response <> nil) then
begin
for i := 0 to Length(Response.Results) - 1 do
Result.Add(Response.Results[i]);
Total := Response.Total;
end;
finally
FreeAndNil(Response);
end;
finally
FreeAndNil(Parameters);
end;
end;
function TActivityActions.GetTeamActivities(RouteId: String; Limit, Offset: integer;
out Total: integer; out ErrorString: String): TActivityList;
var
Response: TGetActivitiesResponse;
Request: TActivityParameters;
i: integer;
begin
Result := TActivityList.Create;
Request := TActivityParameters.Create(Limit, Offset);
try
Request.AddParameter('route_id', RouteId);
Request.AddParameter('team', 'true');
Response := FConnection.Get(TSettings.EndPoints.ActivityFeed, Request,
TGetActivitiesResponse, ErrorString) as TGetActivitiesResponse;
try
if (Response <> nil) then
begin
for i := 0 to Length(Response.Results) - 1 do
Result.Add(Response.Results[i]);
Total := Response.Total;
end;
finally
FreeAndNil(Response);
end;
finally
FreeAndNil(Request);
end;
end;
function TActivityActions.LogSpecificMessage(RouteId: String; Message: String;
out ErrorString: String): boolean;
var
Response: TStatusResponse;
Activity: TActivity;
begin
Activity := TActivity.Create;
try
Activity.RouteId := RouteId;
Activity.ActivityMessage := Message;
Activity.ActivityType := TActivityType.atUserMessage;
Response := FConnection.Post(TSettings.EndPoints.ActivityFeed, Activity,
TStatusResponse, ErrorString) as TStatusResponse;
try
Result := (Response <> nil) and (Response.Status);
finally
FreeAndNil(Response);
end;
finally
FreeAndNil(Activity);
end;
end;
end.
|
unit TTSSemTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSSemRecord = record
PUserName: String[10];
PSemNum: Integer;
End;
TTTSSemBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSSemRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSSem = (TTSSemByUserName, TTSSemBySemNum);
TTTSSemTable = class( TDBISAMTableAU )
private
FDFUserName: TStringField;
FDFSemNum: TIntegerField;
procedure SetPUserName(const Value: String);
function GetPUserName:String;
procedure SetPSemNum(const Value: Integer);
function GetPSemNum:Integer;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEITTSSem);
function GetEnumIndex: TEITTSSem;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSSemRecord;
procedure StoreDataBuffer(ABuffer:TTTSSemRecord);
property DFUserName: TStringField read FDFUserName;
property DFSemNum: TIntegerField read FDFSemNum;
property PUserName: String read GetPUserName write SetPUserName;
property PSemNum: Integer read GetPSemNum write SetPSemNum;
published
property Active write SetActive;
property EnumIndex: TEITTSSem read GetEnumIndex write SetEnumIndex;
end; { TTTSSemTable }
procedure Register;
implementation
function TTTSSemTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TTTSSemTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TTTSSemTable.GenerateNewFieldName }
function TTTSSemTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TTTSSemTable.CreateField }
procedure TTTSSemTable.CreateFields;
begin
FDFUserName := CreateField( 'UserName' ) as TStringField;
FDFSemNum := CreateField( 'SemNum' ) as TIntegerField;
end; { TTTSSemTable.CreateFields }
procedure TTTSSemTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSSemTable.SetActive }
procedure TTTSSemTable.SetPUserName(const Value: String);
begin
DFUserName.Value := Value;
end;
function TTTSSemTable.GetPUserName:String;
begin
result := DFUserName.Value;
end;
procedure TTTSSemTable.SetPSemNum(const Value: Integer);
begin
DFSemNum.Value := Value;
end;
function TTTSSemTable.GetPSemNum:Integer;
begin
result := DFSemNum.Value;
end;
procedure TTTSSemTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
//VG 260717: RecId added as a primary key, because otherwise DBISAM ads one automatically, which causes the VerifyStructure to fail
Add('RecId, AutoInc, 0, N');
Add('UserName, String, 10, N');
Add('SemNum, Integer, 0, N');
end;
end;
procedure TTTSSemTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, RecId, Y, Y, N, N');
Add('ByUserName, UserName, N, N, N, N');
Add('BySemNum, SemNum, N, N, N, N');
end;
end;
procedure TTTSSemTable.SetEnumIndex(Value: TEITTSSem);
begin
case Value of
TTSSemByUserName: IndexName := 'ByUserName';
TTSSemBySemNum : IndexName := 'BySemNum';
end;
end;
function TTTSSemTable.GetDataBuffer:TTTSSemRecord;
var buf: TTTSSemRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PUserName := DFUserName.Value;
buf.PSemNum := DFSemNum.Value;
result := buf;
end;
procedure TTTSSemTable.StoreDataBuffer(ABuffer:TTTSSemRecord);
begin
DFUserName.Value := ABuffer.PUserName;
DFSemNum.Value := ABuffer.PSemNum;
end;
function TTTSSemTable.GetEnumIndex: TEITTSSem;
var iname : string;
begin
result := TTSSemByUserName;
iname := uppercase(indexname);
if iname = '' then result := TTSSemByUserName;
if iname = 'BYUSERNAME' then result := TTSSemByUserName;
if iname = 'BYSEMNUM' then result := TTSSemBySemNum;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSSemTable, TTTSSemBuffer ] );
end; { Register }
function TTTSSemBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..2] of string = ('USERNAME','SEMNUM');
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 2) and (flist[x] <> s) do inc(x);
if x <= 2 then result := x else result := 0;
end;
function TTTSSemBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftInteger;
end;
end;
function TTTSSemBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PUserName;
2: result := @Data.PSemNum;
end;
end;
end. |
unit ScoreboardMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
Data.Bind.GenData, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.Bind.Components,
Data.Bind.ObjectScope, System.Rtti, Data.Bind.EngExt, Fmx.Bind.DBEngExt,
Fmx.Bind.Grid, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Grid,
FMX.Layouts, FMX.Grid, Data.Bind.DBScope, IPPeerClient, IPPeerServer,
System.Tether.Manager, System.Tether.AppProfile, FireDAC.Stan.StorageXML,
System.Actions, FMX.ActnList, Data.Bind.Controls, Fmx.Bind.Navigator, FMX.Memo;
type
TForm6 = class(TForm)
tableScores: TFDMemTable;
tableScoresScore: TIntegerField;
tableScoresName: TStringField;
BindSourceDB1: TBindSourceDB;
Grid1: TGrid;
BindingsList1: TBindingsList;
LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource;
TetheringManager1: TTetheringManager;
TetheringAppProfile1: TTetheringAppProfile;
FDStanStorageXMLLink1: TFDStanStorageXMLLink;
ActionList1: TActionList;
actGetScores: TAction;
NavigatorBindSourceDB1: TBindNavigator;
Memo1: TMemo;
Splitter1: TSplitter;
procedure TetheringAppProfile1ResourceReceived(const Sender: TObject;
const AResource: TRemoteResource);
procedure tableScoresAfterPost(DataSet: TDataSet);
procedure FormCreate(Sender: TObject);
procedure actGetScoresExecute(Sender: TObject);
private
procedure UpdateScoreObjects;
{ Private declarations }
public
{ Public declarations }
end;
var
Form6: TForm6;
implementation
{$R *.fmx}
uses unitGamePlayer, Rest.JSON;
procedure TForm6.actGetScoresExecute(Sender: TObject);
begin
Memo1.Lines.Add('actGetScores.Execute');
UpdateScoreObjects;
end;
procedure TForm6.FormCreate(Sender: TObject);
begin
Randomize;
try
tableScores.LoadFromFile('Score.xml');
except
tableScores.CreateDataSet;
end;
end;
procedure TForm6.UpdateScoreObjects;
var
clone: TFDMemTable;
GP: TGamePlayer;
SL : TStringList;
begin
Memo1.Lines.Add('Updating Score Objects Data');
clone := TFDMemTable.Create(Self);
try
clone.CloneCursor(tableScores);
clone.First;
SL := TStringList.Create;
try
while not Clone.Eof do
begin
GP := TGamePlayer.Create(clone.FieldByName('Name').AsString);
try
GP.Score := clone.FieldByName('Score').AsInteger;
SL.Add(TJson.ObjectToJsonString(GP));
finally
GP.Free;
end;
Clone.Next;
if SL.Count >= 5 then // Passes top 5 scores
Break;
end;
SL.Delimiter := Data_Delimiter;
TetheringAppProfile1.Resources.FindByName('Scoreboard').Value := SL.DelimitedText;
Memo1.Lines.Add(SL.DelimitedText);
finally
SL.Free;
end;
finally
clone.Free;
end;
end;
procedure TForm6.tableScoresAfterPost(DataSet: TDataSet);
begin
tableScores.SaveToFile('Score.xml');
UpdateScoreObjects;
end;
procedure TForm6.TetheringAppProfile1ResourceReceived(const Sender: TObject;
const AResource: TRemoteResource);
var
Player : TGamePlayer;
begin
if AResource.ResType = TRemoteResourceType.Data then begin
// Take the string value, convert to the object and add to the dataset.
Player := TJson.JsonToObject<TGamePlayer>(AResource.Value.AsString);
if tableScores.Locate('Name',Player.Name,[loCaseInsensitive]) then
tableScores.Edit
else begin
tableScores.Insert;
tableScoresName.AsString := Player.Name;
end;
tableScoresScore.AsInteger := Player.Score;
tableScores.Post;
end;
end;
end.
|
unit Benjamim.Payload;
interface
uses
{$IF DEFINED(FPC)}
Classes, fpjson, SysUtils, DateUtils,
{$ELSE}
System.Classes, System.JSON, System.SysUtils, System.DateUtils, System.NetEncoding,
{$ENDIF}
Benjamim.Utils, Benjamim.Payload.Interfaces;
type
TPayload = class(TInterfacedObject, iPayload)
class function New: iPayload;
constructor Create;
destructor Destroy; override;
strict private
FData: TStrings;
public
function Clear: iPayload;
function Add(const aKey: string; const aValue: string; aFormat: string = '"%s":"%s"'): iPayload; overload;
function Add(const aKey: string; const aValue: Int64; aFormat: string = '"%s":%s'): iPayload; overload;
function Add(const aKey: string; const aValue: UInt64; aFormat: string = '"%s":%s'): iPayload; overload;
function Add(const aKey: string; const aValue: Extended; aFormat: string = '"%s":%s'): iPayload; overload;
function Add(const aKey: string; const aValue: TDateTime; aFormat: string = '"%s":"%s"'): iPayload; overload;
function Add(const aKey: string; const aValue: Boolean; aFormat: string = '"%s":%s'): iPayload; overload;
function Add(const aKey: string; const aValue: TJsonObject): iPayload; overload;
function Add(const aKey: string; const aValue: TJsonArray): iPayload; overload;
function Add(const aKey: string; const aValue: Variant): iPayload; overload;
function jti(const aID: UInt64): iPayload; { jti - Jwt ID - Jwt ID ( ID ) }
function iss(const aEmissor: String): iPayload; { iss - Issuer - Emissor ( Emissor ) }
function sub(const aAssunto: String): iPayload; { sub - Subject - Assunto }
function aud(const aRemoteIP: String): iPayload; { aud - Audience - Audiência ( Remote IP ) }
function iat(const aEmissionAt: TDateTime): iPayload; overload; { iat - Issued At - Emitido em ( Quando o Token foi Emitido / Automático ) }
function iat(const aEmissionAtUsDateTime: string): iPayload; overload; { iat - Issued At - Emitido em ( Quando o Token foi Emitido / Automático ) }
function nbf(const aValidityStarted: TDateTime): iPayload; overload; { nbf - Not Before - Validade Iniciada ( Inicia Em ) }
function nbf(const aValidityStartedUsDateTime: string): iPayload; overload; { nbf - Not Before - Validade Iniciada ( Inicia Em ) }
function exp(const aValidityEnded: TDateTime): iPayload; overload; { exp - Expiration Time - Validade Terminada ( Expirar Em ) }
function exp(const aValidityEndedUsDateTime: string): iPayload; overload; { exp - Expiration Time - Validade Terminada ( Expirar Em ) }
function AsJson(const aAsBase64: Boolean = false): string;
function AsJsonObject: TJsonObject;
end;
implementation
{ TPayload }
class function TPayload.New: iPayload;
begin
Result := Self.Create;
end;
constructor TPayload.Create;
begin
FData := TStringList.Create;
FData.Clear;
end;
destructor TPayload.Destroy;
begin
FData.Free;
inherited;
end;
function TPayload.Clear: iPayload;
begin
FData.Clear;
Result := Self;
end;
function TPayload.Add(const aKey: string; const aValue: string; aFormat: string = '"%s":"%s"'): iPayload;
begin
FData.Values[aKey] := Format(aFormat, [aKey, aValue]);
Result := Self;
end;
function TPayload.Add(const aKey: string; const aValue: Int64; aFormat: string = '"%s":%s'): iPayload;
begin
FData.Values[aKey] := Format(aFormat, [aKey, aValue.ToString]);
Result := Self;
end;
function TPayload.Add(const aKey: string; const aValue: UInt64; aFormat: string): iPayload;
begin
FData.Values[aKey] := Format(aFormat, [aKey, aValue.ToString]);
Result := Self;
end;
function TPayload.Add(const aKey: string; const aValue: Boolean; aFormat: string = '"%s":%s'): iPayload;
begin
FData.Values[aKey] := Format(aFormat, [aKey, LowerCase(BoolToStr(aValue, true))]);
Result := Self;
end;
function TPayload.Add(const aKey: string; const aValue: TDateTime; aFormat: string = '"%s":"%s"'): iPayload;
begin
FData.Values[aKey] := Format(aFormat, [aKey, FormatDateTime('yyyy-mm-dd HH:mm:ss.zzz', aValue)]);
Result := Self;
end;
function TPayload.Add(const aKey: string; const aValue: Extended; aFormat: string): iPayload;
begin
FData.Values[aKey] := Format(aFormat, [aKey, StringReplace(FormatFloat('0.00', aValue), ',', '.', [])]);
Result := Self;
end;
function TPayload.Add(const aKey: string; const aValue: TJsonObject): iPayload;
begin
Result := Add(aKey, {$IF DEFINED(FPC)}aValue.AsJSON{$ELSE}aValue.ToJSON{$ENDIF});
end;
function TPayload.Add(const aKey: string; const aValue: TJsonArray): iPayload;
begin
Result := Add(aKey, {$IF DEFINED(FPC)}aValue.AsJSON{$ELSE}aValue.ToJSON{$ENDIF});
end;
function TPayload.Add(const aKey: string; const aValue: Variant): iPayload;
begin
Result := Add(aKey, aValue.AsString);
end;
function TPayload.jti(const aID: UInt64): iPayload; { jti - Jwt ID - Jwt ID ( ID ) }
begin
Result := Add('jti', aID);
end;
function TPayload.iss(const aEmissor: String): iPayload; { iss - Issuer - Emissor ( Emissor ) }
begin
Result := Add('iss', aEmissor);
end;
function TPayload.sub(const aAssunto: String): iPayload; { sub - Subject - Assunto }
begin
Result := Add('sub', aAssunto);
end;
function TPayload.aud(const aRemoteIP: String): iPayload; { aud - Audience - Audiência ( Remote IP ) }
begin
Result := Add('aud', aRemoteIP);
end;
function TPayload.iat(const aEmissionAt: TDateTime): iPayload; { iat - Issued At - Emitido em }
begin
Result := Add('iat', aEmissionAt);
end;
function TPayload.iat(const aEmissionAtUsDateTime: string): iPayload;
begin
Result := Add('iat', aEmissionAtUsDateTime);
end;
function TPayload.nbf(const aValidityStarted: TDateTime): iPayload; { nbf - Not Before - Não antes }
begin
Result := Add('nbf', aValidityStarted);
end;
function TPayload.nbf(const aValidityStartedUsDateTime: string): iPayload;
begin
Result := Add('nbf', aValidityStartedUsDateTime);
end;
function TPayload.exp(const aValidityEnded: TDateTime): iPayload; { exp - Expiration Time - Prazo de Validade ( Expirar Em ) }
begin
Result := Add('exp', aValidityEnded);
end;
function TPayload.exp(const aValidityEndedUsDateTime: string): iPayload;
begin
Result := Add('exp', aValidityEndedUsDateTime);
end;
function TPayload.AsJson(const aAsBase64: Boolean = false): string;
var
I: integer;
LSep: string;
begin
LSep := EmptyStr;
Result := EmptyStr;
for I := 0 to pred(FData.Count) do
begin
Result := Result + LSep + FData.ValueFromIndex[I];
LSep := ',';
end;
Result := '{' + Result + '}';
if aAsBase64 then
Result := Result.AsBase64url.ClearLineBreak;
end;
function TPayload.AsJsonObject: TJsonObject;
begin
Result := AsJson(false).ClearLineBreak.AsJsonObject;
end;
end.
|
unit viewporter_protocol;
{$mode objfpc} {$H+}
{$interfaces corba}
interface
uses
Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol;
type
Pwp_viewporter = Pointer;
Pwp_viewport = Pointer;
const
WP_VIEWPORTER_ERROR_VIEWPORT_EXISTS = 0; // the surface already has a viewport object associated
type
Pwp_viewporter_listener = ^Twp_viewporter_listener;
Twp_viewporter_listener = record
end;
const
WP_VIEWPORT_ERROR_BAD_VALUE = 0; // negative or zero values in width or height
WP_VIEWPORT_ERROR_BAD_SIZE = 1; // destination size is not integer
WP_VIEWPORT_ERROR_OUT_OF_BUFFER = 2; // source rectangle extends outside of the content area
WP_VIEWPORT_ERROR_NO_SURFACE = 3; // the wl_surface was destroyed
type
Pwp_viewport_listener = ^Twp_viewport_listener;
Twp_viewport_listener = record
end;
TWpViewporter = class;
TWpViewport = class;
IWpViewporterListener = interface
['IWpViewporterListener']
end;
IWpViewportListener = interface
['IWpViewportListener']
end;
TWpViewporter = class(TWLProxyObject)
private
const _DESTROY = 0;
const _GET_VIEWPORT = 1;
public
destructor Destroy; override;
function GetViewport(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TWpViewport}): TWpViewport;
function AddListener(AIntf: IWpViewporterListener): LongInt;
end;
TWpViewport = class(TWLProxyObject)
private
const _DESTROY = 0;
const _SET_SOURCE = 1;
const _SET_DESTINATION = 2;
public
destructor Destroy; override;
procedure SetSource(AX: Longint{24.8}; AY: Longint{24.8}; AWidth: Longint{24.8}; AHeight: Longint{24.8});
procedure SetDestination(AWidth: LongInt; AHeight: LongInt);
function AddListener(AIntf: IWpViewportListener): LongInt;
end;
var
wp_viewporter_interface: Twl_interface;
wp_viewport_interface: Twl_interface;
implementation
var
vIntf_wp_viewporter_Listener: Twp_viewporter_listener;
vIntf_wp_viewport_Listener: Twp_viewport_listener;
destructor TWpViewporter.Destroy;
begin
wl_proxy_marshal(FProxy, _DESTROY);
inherited Destroy;
end;
function TWpViewporter.GetViewport(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TWpViewport}): TWpViewport;
var
id: Pwl_proxy;
begin
id := wl_proxy_marshal_constructor(FProxy,
_GET_VIEWPORT, @wp_viewport_interface, nil, ASurface.Proxy);
if AProxyClass = nil then
AProxyClass := TWpViewport;
Result := TWpViewport(AProxyClass.Create(id));
if not AProxyClass.InheritsFrom(TWpViewport) then
Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TWpViewport]);
end;
function TWpViewporter.AddListener(AIntf: IWpViewporterListener): LongInt;
begin
FUserDataRec.ListenerUserData := Pointer(AIntf);
Result := wl_proxy_add_listener(FProxy, @vIntf_wp_viewporter_Listener, @FUserDataRec);
end;
destructor TWpViewport.Destroy;
begin
wl_proxy_marshal(FProxy, _DESTROY);
inherited Destroy;
end;
procedure TWpViewport.SetSource(AX: Longint{24.8}; AY: Longint{24.8}; AWidth: Longint{24.8}; AHeight: Longint{24.8});
begin
wl_proxy_marshal(FProxy, _SET_SOURCE, AX, AY, AWidth, AHeight);
end;
procedure TWpViewport.SetDestination(AWidth: LongInt; AHeight: LongInt);
begin
wl_proxy_marshal(FProxy, _SET_DESTINATION, AWidth, AHeight);
end;
function TWpViewport.AddListener(AIntf: IWpViewportListener): LongInt;
begin
FUserDataRec.ListenerUserData := Pointer(AIntf);
Result := wl_proxy_add_listener(FProxy, @vIntf_wp_viewport_Listener, @FUserDataRec);
end;
const
pInterfaces: array[0..9] of Pwl_interface = (
(nil),
(nil),
(nil),
(nil),
(nil),
(nil),
(nil),
(nil),
(@wp_viewport_interface),
(@wl_surface_interface)
);
wp_viewporter_requests: array[0..1] of Twl_message = (
(name: 'destroy'; signature: ''; types: @pInterfaces[0]),
(name: 'get_viewport'; signature: 'no'; types: @pInterfaces[8])
);
wp_viewport_requests: array[0..2] of Twl_message = (
(name: 'destroy'; signature: ''; types: @pInterfaces[0]),
(name: 'set_source'; signature: 'ffff'; types: @pInterfaces[0]),
(name: 'set_destination'; signature: 'ii'; types: @pInterfaces[0])
);
initialization
wp_viewporter_interface.name := 'wp_viewporter';
wp_viewporter_interface.version := 1;
wp_viewporter_interface.method_count := 2;
wp_viewporter_interface.methods := @wp_viewporter_requests;
wp_viewporter_interface.event_count := 0;
wp_viewporter_interface.events := nil;
wp_viewport_interface.name := 'wp_viewport';
wp_viewport_interface.version := 1;
wp_viewport_interface.method_count := 3;
wp_viewport_interface.methods := @wp_viewport_requests;
wp_viewport_interface.event_count := 0;
wp_viewport_interface.events := nil;
end.
|
{====================================================}
{ }
{ EldoS Visual Components }
{ }
{ Copyright (c) 1997 Paolo Giacomuzzi }
{ Copyright (c) 1998-2003, EldoS Corporation }
{ }
{====================================================}
(*
Version History
12/16/2000
Improved auto-hiding of the auto-hide bars.
*)
{$include elpack2.inc}
{$ifdef ELPACK_SINGLECOMP}
{$I ElPack.inc}
{$else}
{$ifdef LINUX}
{$I ../ElPack.inc}
{$else}
{$I ..\ElPack.inc}
{$endif}
{$endif}
unit ElAppBar;
interface
uses
Windows, Messages, SysUtils, Classes, Forms, Controls,
{$ifdef VCL_6_USED}
Types,
{$endif}
ElHook,
ElTimers,
ElVCLUtils,
ShellApi;
const
// AppBar's user notification message
WM_APPBARNOTIFY = WM_USER + 100;
// Timer interval
SLIDE_DEF_TIMER_INTERVAL = 400; // milliseconds
// Defaults
AB_DEF_SIZE_INC = 1;
AB_DEF_DOCK_DIM = 32;
type
// You can send to the Windows shell one of the following messages:
// Message Description
// -------------- --------------------------------------------------
// ABM_NEW Register a new AppBar to the system
// ABM_REMOVE Remove a previously created AppBar from the system
// ABM_QUERYPOS Query the AppBar position
// ABM_SETPOS Set the AppBar position
// ABM_GETSTATE Get the edge the Appbar is docked to
// ABM_GETTASKBARPOS Get the Explorer Taskbar position
// ABM_ACTIVATE Activate the AppBar
// ABM_GETAUTOHIDEBAR Query if AppBar has Auto-hide behavior
// ABM_SETAUTOHIDEBAR Set the AppBar's Auto-hide behavior
// The ABM_message constants are defined in SHELLAPI.PAS as follows:
// ABM_NEW = $00000000;
// ABM_REMOVE = $00000001;
// ABM_QUERYPOS = $00000002;
// ABM_SETPOS = $00000003;
// ABM_GETSTATE = $00000004;
// ABM_GETTASKBARPOS = $00000005;
// ABM_ACTIVATE = $00000006;
// ABM_GETAUTOHIDEBAR = $00000007;
// ABM_SETAUTOHIDEBAR = $00000008;
// ABM_WINDOWPOSCHANGED = $00000009;
// The following enumerated type defines the constants in the table
TAppBarMessage = (abmNew, abmRemove, abmQueryPos, abmSetPos, abmGetState,
abmGetTaskBarPos, abmActivate, abmGetAutoHideBar,
abmSetAutoHideBar, abmWindowPosChanged);
// An AppBar can be in one of 6 states shown in the table below:
// State Description
// ----------- -----------------------------------------------------
// ABE_UNKNOWN The Appbar is in an unknown state
// (usually during construction/destruction)
// ABE_FLOAT The AppBar is floating on the screen
// ABE_LEFT The Appbar is docked on the left edge of the screen
// ABE_TOP The Appbar is docked on the top edge of the screen
// ABE_RIGHT The Appbar is docked on the right edge of the screen
// ABE_BOTTOM The Appbar is docked on the bottom edge of the screen
// The ABE_edge state constants are defined in SHELLAPI.PAS as follows:
// ABE_LEFT = 0;
// ABE_TOP = 1;
// ABE_RIGHT = 2;
// ABE_BOTTOM = 3;
// The ABE_UNKNOWN and ABE_FLOAT constants are defined here as follows:
// ABE_UNKNOWN = 4;
// ABE_FLOAT = 5;
// The following enumerated type defines the constants in the table
// (Values are mutually exclusive)
TAppBarEdge = (abeLeft, abeTop, abeRight, abeBottom, abeUnknown, abeFloat);
// An AppBar can have several behavior flags as shown below:
// Flag Description
// --------------------------- -----------------------------------
// ABF_ALLOWLEFT Allow dock on left of screen
// ABF_ALLOWRIGHT Allow dock on right of screen
// ABF_ALLOWTOP Allow dock on top of screen
// ABF_ALLOWBOTTOM Allow dock on bottom of screen
// ABF_ALLOWFLOAT Allow float in the middle of screen
// The following enumerated type defines the constants in the table
TAppBarFlag = (abfAllowLeft, abfAllowTop, abfAllowRight, abfAllowBottom,
abfAllowFloat);
TAppBarFlags = set of TAppBarFlag;
// The following enumerated type defines the AppBar behavior in the Taskbar
TElAppBarTaskEntry = (abtShow, abtHide, abtFloatDependent);
// The record below contains all of the AppBar settings that
// can be saved/loaded in/from the Registry
TAppBarSettings = record
abEdge : TAppBarEdge; // ABE_UNKNOWN, ABE_FLOAT, or ABE_edge
bAutohide : Boolean; // Should AppBar be auto-hidden when docked?
bAlwaysOnTop : Boolean; // Should AppBar always be on top?
bSlideEffect : Boolean; // Should AppBar slide?
nTimerInterval : Integer; // Slide Timer Interval (determines speed)
rcDockDims : TRect; // Width/height for docked bar on 4 edges
rcFloat : TRect; // Floating rectangle (in screen coordinates)
nMinWidth : LongInt; // Min allowed width
nMinHeight : LongInt; // Min allowed height
nMaxWidth : LongInt; // Max allowed width
nMaxHeight : LongInt; // Max allowed height
abTaskEntry : TElAppBarTaskEntry; // AppBar behavior in the Windows Taskbar
end;
// TAppBar class ////////////////////////////////////////////////////////////
TElAppBar = class(TComponent)
private
FInPosChanged : boolean;
protected
FHook : TElHook;
FForceReHide : boolean;
FPreventOffScreen : Boolean;
FKeepSize : Boolean;
FDraggingOffset : TPoint; // offset from TopLeft corner to mouse cursor
// when the window is about to be moved
{ Internal implementation state variables }
// This AppBar's settings info
FABS : TAppBarSettings;
// ABF_* flags
FabFlags : TAppBarFlags;
// Discrete width/height size increments
FszSizeInc : TSize;
// We need a member variable which tracks the proposed edge of the
// AppBar while the user is moving it, deciding where to position it.
// While not moving, this member must contain ABE_UNKNOWN so that
// GetEdge returns the current edge contained in FABS.abEdge.
// While moving the AppBar, FabEdgeProposedPrev contains the
// proposed edge based on the position of the AppBar. The proposed
// edge becomes the new edge when the user stops moving the AppBar.
FabEdgeProposedPrev : TAppBarEdge;
// We need a member variable which tracks whether a full screen
// application window is open
FbFullScreenAppOpen : Boolean;
// We need a member variable which tracks whether our autohide window
// is visible or not
FbAutoHideIsVisible : Boolean;
// We need a timer to to determine when the AppBar should be re-hidden
FTimer : TElTimer;
FOnEdgeChanged : TNotifyEvent;
FActive: Boolean;
FOnForcedToDocked: TNotifyEvent;
// These functions encapsulate the shell's SHAppBarMessage function
function AppBarMessage(abMessage : TAppBarMessage; abEdge : TAppBarEdge; lParam : LPARAM; bRect : Boolean; var rc : TRect) : UINT;
function AppBarMessage1(abMessage : TAppBarMessage) : UINT;
function AppBarMessage2(abMessage : TAppBarMessage; abEdge : TAppBarEdge) : UINT;
function AppBarMessage3(abMessage : TAppBarMessage; abEdge : TAppBarEdge; lParam : LPARAM) : UINT;
function AppBarMessage4(abMessage : TAppBarMessage; abEdge : TAppBarEdge; lParam : LPARAM; var rc : TRect) : UINT;
// Gets a edge (ABE_FLOAT or ABE_edge) from a point (screen coordinates)
function CalcProposedState(var pt : TSmallPoint) : TAppBarEdge;
// Adjusts the AppBar's location to account for autohide
// Returns TRUE if rectangle was adjusted
function AdjustLocationForAutohide(bShow : Boolean;
var rc : TRect) : Boolean;
// When Autohide AppBar is shown/hidden, slides in/out of view
procedure SlideWindow(var rcEnd : TRect);
// Returns which edge we're autohidden on or ABE_UNKNOWN
function GetAutohideEdge : TAppBarEdge;
// Returns a TSmallPoint that gives the cursor position in screen coords
function GetMessagePosition : TSmallPoint;
procedure SetKeepSize(newValue : Boolean);
procedure SetPreventOffScreen(newValue : Boolean);
procedure SetHorzInc(newValue : integer);
procedure SetVertInc(newValue : integer);
function GetVertInc : integer;
function GetHorzInc : integer;
procedure DoEdgeChanged;
// Gets a retangle position (screen coordinates) from a proposed state
procedure GetRect(abEdgeProposed : TAppBarEdge; var rcProposed : TRect); virtual;
{ Property selector functions }
// Retrieves the AppBar's edge. If the AppBar is being positioned, its
// proposed state is returned instead
function GetEdge : TAppBarEdge;
// Changes the AppBar's edge to ABE_UNKNOWN, ABE_FLOAT or an ABE_edge
procedure SetEdge(abEdge : TAppBarEdge);
procedure SetSlideTime(nInterval : Integer);
// Returns TRUE if Auto-hide is on, FALSE if Auto-hide is off
function IsAutoHide : Boolean;
// Sets the Auto-hide behavior
procedure SetAutoHide(bAutoHide : Boolean);
// Returns TRUE if AppBar is always on topAuto-hide, FALSE otherwise
function IsAlwaysOnTop : Boolean;
// Sets the AlwaysOnTop behavior
procedure SetAlwaysOnTop(bAlwaysOnTop : Boolean);
procedure SetFlags(newValue : TAppBarFlags);
{ Overridable functions }
// Called if user attempts to dock an Autohide AppBar on
// an edge that already contains an Autohide AppBar
procedure DoForcedToDocked; virtual;
// Called when AppBar gets an ABN_FULLSCREENAPP notification
procedure OnABNFullScreenApp(bOpen : Boolean); virtual;
// Called when AppBar gets an ABN_POSCHANGED notification
procedure OnABNPosChanged; virtual;
// Called when AppBar gets an ABN_WINDOWARRANGE notification
procedure OnABNWindowArrange(bBeginning : Boolean); virtual;
{ Message handlers }
// Called when the AppBar receives a WM_APPBARNOTIFY window message
procedure OnAppBarCallbackMsg(var Msg : TMessage);
// Called when the AppBar form is first created
procedure WMCreate(var Msg : TWMCreate);
// Called when the AppBar form is about to be destroyed
procedure WMDestroy(var Msg : TWMDestroy);
// Called when the AppBar receives a WM_WINDOWPOSCHANGED message
procedure WMWindowPosChanged(var Msg : TWMWindowPosChanged);
// Called when the AppBar receives a WM_ACTIVATE message
procedure WMActivate(var Msg : TWMActivate);
// Called every timer tick
procedure OnAppBarTimer(Sender : TObject);
// Called when the AppBar receives a WM_NCMOUSEMOVE message
procedure WMNCMouseMove(var Msg : TMessage);
procedure WMMouseMove(var Msg : TMessage);
// Called when the AppBar receives a WM_NCHITTEST message
procedure WMNCHitTest(var Msg : TWMNCHitTest);
// Called when the AppBar receives a WM_ENTERSIZEMOVE message
procedure WMEnterSizeMove(var Msg : TMessage);
// Called when the AppBar receives a WM_EXITSIZEMOVE message
procedure WMExitSizeMove(var Msg : TMessage);
// Called when the AppBar receives a WM_MOVING message
procedure WMMoving(var Msg : TMessage);
// Called when the AppBar receives a WM_SIZING message
procedure WMSizing(var Msg : TMessage);
// Called when the AppBar receives a WM_GETMINMAXINFO message
procedure WMGetMinMaxInfo(var Msg : TWMGetMinMaxInfo);
{ AppBar-specific helper functions }
// Returns TRUE if abEdge is ABE_LEFT or ABE_RIGHT, else FALSE is returned
function IsEdgeLeftOrRight(abEdge : TAppBarEdge) : Boolean;
// Returns TRUE if abEdge is ABE_TOP or ABE_BOTTOM, else FALSE is returned
function IsEdgeTopOrBottom(abEdge : TAppBarEdge) : Boolean;
// Returns TRUE if abEdge is ABE_FLOAT, else FALSE is returned
function IsFloating(abEdge : TAppBarEdge) : Boolean;
// Returns TRUE if abFlags contain an at least allowed edge to dock on
function IsDockable(abFlags : TAppBarFlags) : Boolean;
// Returns TRUE if abFlags contain abfAllowLeft and abfAllowRight
function IsDockableVertically(abFlags : TAppBarFlags) : Boolean;
// Returns TRUE if abFlags contain abfAllowTop and abfAllowBottom
function IsDockableHorizontally(abFlags : TAppBarFlags) : Boolean;
// Forces the shell to update its AppBar list and the workspace area
procedure ResetSystemKnowledge;
// Returns a proposed edge or ABE_FLOAT based on ABF_* flags and a
// point specified in screen coordinates
function GetEdgeFromPoint(abFlags : TAppBarFlags;
pt : TSmallPoint) : TAppBarEdge;
procedure OnHook(Sender : TObject; var Msg : TMessage; var Handled : boolean);
procedure OnAfterHook(Sender : TObject; var Msg : TMessage; var Handled : boolean);
procedure SetActive(Value: Boolean);
procedure AdjustWindowStyles;
procedure ActivateAppBar;
procedure DeactivateAppBar;
public
// Gets the AppBar's docked dimensions
{$IFDEF BUILDER_USED}
procedure GetDockDims(var rc : TRect);
{$ELSE}
function GetDockDims : TRect;
{$ENDIF}
// Sets the AppBar's docked dimensions
procedure SetDockDims(rc : TRect);
// Gets the AppBar's floating rectangle
{$IFDEF BUILDER_USED}
procedure GetFloatRect(var rc : TRect);
{$ELSE}
function GetFloatRect : TRect;
{$ENDIF}
// Sets the AppBar's floating rectangle
procedure SetFloatRect(rc : TRect);
// Constructs an AppBar
constructor Create(Owner : TComponent); override;
// Destroys a previously created AppBar
destructor Destroy; override;
// Forces the AppBar's visual appearance to match its internal state
procedure UpdateBar;
// If AppBar is Autohide and docked, shows/hides the AppBar
procedure ShowHiddenAppBar(bShow : Boolean); virtual;
property AutoHideIsVisible : boolean read FbAutoHideIsVisible;
{$IFNDEF BUILDER_USED}
// Dimensions when docked on left, top, right and bottom
property DockDims : TRect read GetDockDims write SetDockDims;
// AppBar rectangle when floating
property FloatRect : TRect read GetFloatRect write SetFloatRect;
{$ENDIF}
published
{ Properties }
property Active: Boolean read FActive write SetActive default false;
// Allowed dockable edges
property Flags : TAppBarFlags read FabFlags write SetFlags;
// Horizontal size increment
property HorzSizeInc : LongInt read GetHorzInc write SetHorzInc;
// Vertical size increment
property VertSizeInc : LongInt read GetVertInc write SetVertInc;
// Edge to dock on
property Edge : TAppBarEdge read GetEdge write SetEdge;
// Auto-hide On/Off
property AutoHide : Boolean read IsAutoHide write SetAutoHide;
// Always On Top On/Off
property AlwaysOnTop : Boolean read IsAlwaysOnTop write SetAlwaysOnTop;
// AppBar MinMax dimensions when floating
property MinWidth : LongInt read FABS.nMinWidth write FABS.nMinWidth;
property MinHeight : LongInt read FABS.nMinHeight write FABS.nMinHeight;
property MaxWidth : LongInt read FABS.nMaxWidth write FABS.nMaxWidth;
property MaxHeight : LongInt read FABS.nMaxHeight write FABS.nMaxHeight;
// AppBar behavior in the Window Taskbar
property TaskEntry : TElAppBarTaskEntry read FABS.abTaskEntry write FABS.abTaskEntry;
// If set, the window won't be stretched when docked, and will keep it's size
property KeepSize : Boolean read FKeepSize write SetKeepSize;
// if set, the window will always be kept inside of viewable area (of cause, except when hidden or auto-hide bar)
property PreventOffScreen : Boolean read FPreventOffScreen write SetPreventOffScreen default false;
property OnEdgeChanged : TNotifyEvent read FOnEdgeChanged write FOnEdgeChanged;
property OnForcedToDocked: TNotifyEvent read FOnForcedToDocked write
FOnForcedToDocked;
end;
implementation
{ Internal implementation functions }
// TElAppBar.AppBarMessage //////////////////////////////////////////////////////
function TElAppBar.AppBarMessage(abMessage : TAppBarMessage;
abEdge : TAppBarEdge;
lParam : LPARAM;
bRect : Boolean;
var rc : TRect) : UINT;
var
abd : TAppBarData;
AForm : TForm;
begin
AForm := GetOwnerForm(Self);
// Initialize an APPBARDATA structure
abd.cbSize := sizeof(abd);
abd.hWnd := AForm.Handle;
abd.uCallbackMessage := WM_APPBARNOTIFY;
abd.uEdge := Ord(abEdge);
if bRect then
abd.rc := rc
else
abd.rc := Rect(0, 0, 0, 0);
abd.lParam := lParam;
Result := SHAppBarMessage(Ord(abMessage), abd);
// If the caller passed a rectangle, return the updated rectangle
if bRect then
rc := abd.rc;
end;
// TElAppBar.AppBarMessage1 /////////////////////////////////////////////////////
function TElAppBar.AppBarMessage1(abMessage : TAppBarMessage) : UINT;
var
rc : TRect;
begin
Result := AppBarMessage(abMessage, abeFloat, 0, False, rc);
end;
// TElAppBar.AppBarMessage2 /////////////////////////////////////////////////////
function TElAppBar.AppBarMessage2(abMessage : TAppBarMessage;
abEdge : TAppBarEdge) : UINT;
var
rc : TRect;
begin
Result := AppBarMessage(abMessage, abEdge, 0, False, rc);
end;
// TElAppBar.AppBarMessage3 /////////////////////////////////////////////////////
function TElAppBar.AppBarMessage3(abMessage : TAppBarMessage;
abEdge : TAppBarEdge;
lParam : LPARAM) : UINT;
var
rc : TRect;
begin
Result := AppBarMessage(abMessage, abEdge, lParam, False, rc);
end;
// TElAppBar.AppBarMessage4 /////////////////////////////////////////////////////
function TElAppBar.AppBarMessage4(abMessage : TAppBarMessage;
abEdge : TAppBarEdge;
lParam : LPARAM;
var rc : TRect) : UINT;
begin
Result := AppBarMessage(abMessage, abEdge, lParam, True, rc);
end;
// TElAppBar.CalcProposedState //////////////////////////////////////////////////
function TElAppBar.CalcProposedState(var pt : TSmallPoint) : TAppBarEdge;
var
bForceFloat : Boolean;
begin
// Force the AppBar to float if the user is holding down the Ctrl key
// and the AppBar's style allows floating
bForceFloat := ((GetKeyState(VK_CONTROL) and $8000) <> 0) and
(abfAllowFloat in FabFlags);
if bForceFloat then
Result := abeFloat
else
Result := GetEdgeFromPoint(FabFlags, pt);
end;
// TElAppBar.GetRect ////////////////////////////////////////////////////////////
procedure TElAppBar.GetRect(abEdgeProposed : TAppBarEdge; var rcProposed : TRect);
var
P : TPoint;
begin
// This function finds the x, y, cx, cy of the AppBar window
if abEdgeProposed <> abeFloat then
begin
// The AppBar is docked or auto-hide
// Set dimensions to full screen
with rcProposed do
begin
Left := 0;
Top := 0;
Right := GetSystemMetrics(SM_CXSCREEN);
Bottom := GetSystemMetrics(SM_CYSCREEN);
if KeepSize then
begin
GetCursorPos(P);
case abEdgeProposed of
abeTop :
begin
Left := P.x;
Dec(Left, FDraggingOffset.X);
end;
abeBottom :
begin
Left := P.x;
Dec(Left, FDraggingOffset.X);
Top := Bottom - (FABS.rcFloat.Bottom - FABS.rcFloat.Top);
end;
abeLeft :
begin
Top := P.Y;
Dec(Top, FDraggingOffset.Y);
end;
abeRight :
begin
Top := P.Y;
Dec(Top, FDraggingOffset.Y);
Left := Right - (FABS.rcFloat.Right - FABS.rcFloat.Left);
end;
end;
Right := Left + FABS.rcFloat.Right - FABS.rcFloat.Left;
Bottom := Top + FABS.rcFloat.Bottom - FABS.rcFloat.Top;
end;
end;
// Subtract off what we want from the full screen dimensions
if not IsAutohide then
// Ask the shell where we can dock
AppBarMessage4(abmQueryPos, abEdgeProposed, LPARAM(False), rcProposed);
if KeepSize then
begin
case abEdgeProposed of
abeLeft :
rcProposed.Right := rcProposed.Left + (FABS.rcFloat.Right - FABS.rcFloat.Left);
abeTop :
rcProposed.Bottom := rcProposed.Top + (FABS.rcFloat.Bottom - FABS.rcFloat.Top);
abeRight :
rcProposed.Left := rcProposed.Right - (FABS.rcFloat.Right - FABS.rcFloat.Left);
abeBottom :
rcProposed.Top := rcProposed.Bottom - (FABS.rcFloat.Bottom - FABS.rcFloat.Top);
end; // end of case
end
else
begin
case abEdgeProposed of
abeLeft :
rcProposed.Right := rcProposed.Left + FABS.rcDockDims.Left;
abeTop :
rcProposed.Bottom := rcProposed.Top + FABS.rcDockDims.Top;
abeRight :
rcProposed.Left := rcProposed.Right - FABS.rcDockDims.Right;
abeBottom :
rcProposed.Top := rcProposed.Bottom - FABS.rcDockDims.Bottom;
end; // end of case
end;
end;
end;
// TElAppBar.AdjustLocationForAutohide //////////////////////////////////////////
function TElAppBar.AdjustLocationForAutohide(bShow : Boolean;
var rc : TRect) : Boolean;
var
x, y : Integer;
cxVisibleBorder, cyVisibleBorder : Integer;
AForm : TForm;
begin
AForm := GetOwnerForm(Self);
if ((GetEdge = abeUnknown) or (GetEdge = abeFloat) or
(not FABS.bAutohide)) then
begin
// If we are not docked on an edge OR we are not auto-hidden, there is
// nothing for us to do; just return
Result := False;
Exit;
end;
// Keep a part of the AppBar visible at all times
cxVisibleBorder := 2 * GetSystemMetrics(SM_CXBORDER);
cyVisibleBorder := 2 * GetSystemMetrics(SM_CYBORDER);
if not FKeepSize then
begin
// Showing/hiding doesn't change our size; only our position
x := 0;
y := 0; // Assume a position of (0, 0)
if bShow then
// If we are on the right or bottom, calculate our visible position
case GetEdge of
abeRight :
x := GetSystemMetrics(SM_CXSCREEN) - (rc.Right - rc.Left);
abeBottom :
y := GetSystemMetrics(SM_CYSCREEN) - (rc.Bottom - rc.Top);
end
else
// Calculate our x or y coordinate so that only the border is visible
case GetEdge of
abeLeft :
x := -((rc.Right - rc.Left) - cxVisibleBorder);
abeRight :
x := GetSystemMetrics(SM_CXSCREEN) - cxVisibleBorder;
abeTop :
y := -((rc.Bottom - rc.Top) - cyVisibleBorder);
abeBottom :
y := GetSystemMetrics(SM_CYSCREEN) - cyVisibleBorder;
end;
end
else
begin
x := AForm.Left;
y := AForm.Top;
if bShow then
case GetEdge of
abeTop : y := 0;
abeBottom : y := GetSystemMetrics(SM_CYSCREEN) - (rc.Bottom - rc.Top);
abeLeft : x := 0;
abeRight : x := GetSystemMetrics(SM_CXSCREEN) - (rc.Right - rc.Left);
end
else
case GetEdge of
abeTop : y := -((rc.Bottom - rc.Top) - cyVisibleBorder);
abeBottom : y := GetSystemMetrics(SM_CYSCREEN) - cyVisibleBorder;
abeLeft : x := -((rc.Right - rc.Left) - cxVisibleBorder);
abeRight : x := GetSystemMetrics(SM_CXSCREEN) - cxVisibleBorder;
end;
end;
with rc do
begin
Right := x + (Right - Left);
Bottom := y + (Bottom - Top);
Left := x;
Top := y;
end;
Result := True;
end;
// TElAppBar.ShowHiddenAppBar ///////////////////////////////////////////////////
procedure TElAppBar.ShowHiddenAppBar(bShow : Boolean);
var
rc : TRect;
AForm : TForm;
begin
AForm := GetOwnerForm(Self);
//if bShow = FbAutoHideIsVisible then exit;
// Get our window location in screen coordinates
GetWindowRect(AForm.Handle, rc);
// Assume that we are visible
FbAutoHideIsVisible := True;
if AdjustLocationForAutohide(bShow, rc) then
begin
// the rectangle was adjusted, we are an autohide bar
// Rememebr whether we are visible or not
FbAutoHideIsVisible := bShow;
// Slide window in from or out to the edge
SlideWindow(rc);
end;
end;
// TElAppBar.SlideWindow ////////////////////////////////////////////////////////
procedure TElAppBar.SlideWindow(var rcEnd : TRect);
var
bFullDragOn : LongBool;
rcStart : TRect;
dwTimeStart, dwTimeEnd, dwTime : DWORD;
x, y, w, h : Integer;
AForm : TForm;
begin
AForm := GetOwnerForm(Self);
// Only slide the window if the user has FullDrag turned on
SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0, @bFullDragOn, 0);
// Get the current window position
GetWindowRect(AForm.Handle, rcStart);
if (FABS.bSlideEffect and bFullDragOn and
((rcStart.Left <> rcEnd.Left) or
(rcStart.Top <> rcEnd.Top) or
(rcStart.Right <> rcEnd.Right) or
(rcStart.Bottom <> rcEnd.Bottom))) then
begin
// Get our starting and ending time
dwTimeStart := GetTickCount;
{$WARNINGS OFF}
dwTimeEnd := dwTimeStart + FABS.nTimerInterval;
{$WARNINGS ON}
dwTime := dwTimeStart;
while (dwTime < dwTimeEnd) do
begin
// While we are still sliding, calculate our new position
x := rcStart.Left - (rcStart.Left - rcEnd.Left)
* Integer(dwTime - dwTimeStart) div FABS.nTimerInterval;
y := rcStart.Top - (rcStart.Top - rcEnd.Top)
* Integer(dwTime - dwTimeStart) div FABS.nTimerInterval;
w := (rcStart.Right - rcStart.Left)
- ((rcStart.Right - rcStart.Left) - (rcEnd.Right - rcEnd.Left))
* Integer(dwTime - dwTimeStart) div FABS.nTimerInterval;
h := (rcStart.Bottom - rcStart.Top)
- ((rcStart.Bottom - rcStart.Top) - (rcEnd.Bottom - rcEnd.Top))
* Integer(dwTime - dwTimeStart) div FABS.nTimerInterval;
// Show the window at its changed position
SetWindowPos(AForm.Handle, 0, x, y, w, h,
SWP_NOZORDER or SWP_NOACTIVATE or SWP_DRAWFRAME);
UpdateWindow(AForm.Handle);
dwTime := GetTickCount;
end;
end;
// Make sure that the window is at its final position
AForm.SetBounds(rcEnd.Left, rcEnd.Top, rcEnd.Right - rcEnd.Left, rcEnd.Bottom - rcEnd.Top);
end;
// TElAppBar.GetAutohideEdge ////////////////////////////////////////////////////
function TElAppBar.GetAutohideEdge : TAppBarEdge;
var AForm : TForm;
begin
AForm := GetOwnerForm(Self);
if AForm.Handle = AppBarMessage2(abmGetAutoHideBar, abeLeft) then
Result := abeLeft
else
if AForm.Handle = AppBarMessage2(abmGetAutoHideBar, abeTop) then
Result := abeTop
else
if AForm.Handle = AppBarMessage2(abmGetAutoHideBar, abeRight) then
Result := abeRight
else
if AForm.Handle = AppBarMessage2(abmGetAutoHideBar, abeBottom) then
Result := abeBottom
else
// NOTE: If AppBar is docked but not auto-hidden, we return ABE_UNKNOWN
Result := abeUnknown;
end;
// TElAppBar.GetMessagePosition /////////////////////////////////////////////////
function TElAppBar.GetMessagePosition : TSmallPoint;
var
pt : TSmallPoint;
dw : DWORD;
begin
dw := GetMessagePos;
pt.X := SHORT(dw);
pt.Y := SHORT((dw and $FFFF0000) shr 16);
Result := pt;
end;
{ Property selector functions }
// TElAppBar.GetEdge ////////////////////////////////////////////////////////////
function TElAppBar.GetEdge : TAppBarEdge;
begin
if FabEdgeProposedPrev <> abeUnknown then
Result := FabEdgeProposedPrev
else
Result := FABS.abEdge;
end;
// TElAppBar.SetEdge ////////////////////////////////////////////////////////////
procedure TElAppBar.SetEdge(abEdge : TAppBarEdge);
var
abCurrentEdge : TAppBarEdge;
currentRect : TRect;
rc : TRect;
hWnd : THandle;
ex : boolean;
AForm : TForm;
begin
AForm := GetOwnerForm(Self);
if IsRectEmpty(FABS.rcFloat) then
FABS.rcFloat := AForm.BoundsRect;
// Do not set the edge to non-allowed
ex := false;
case abEdge of //
abeUnknown : ex := false;
abeBottom : ex := not (abfAllowBottom in Flags);
abeFloat : ex := not (abfAllowFloat in Flags);
abeRight : ex := not (abfAllowRight in Flags);
abeLeft : ex := not (abfAllowLeft in Flags);
abeTop : ex := not (abfAllowTop in Flags);
end; // case
if ex then exit;
// If the AppBar is registered as auto-hide, unregister it
abCurrentEdge := GetAutohideEdge;
if abCurrentEdge <> abeUnknown then
// Our AppBar is auto-hidden, unregister it
AppBarMessage3(abmSetAutoHideBar, abCurrentEdge, LPARAM(False));
// Save the new requested state
//fOldEdge := FABS.abEdge;
FABS.abEdge := abEdge;
{if FForceRehide and (fOldEdge <> FABS.abEdge) then
FABS.bAutohide := true;}
case abEdge of
abeUnknown :
// We are being completely unregistered.
// Probably, the AppBar window is being destroyed.
// If the AppBar is registered as NOT auto-hide, unregister it
AppBarMessage1(abmRemove);
abeFloat :
begin
// We are floating and therefore are just a regular window.
// Tell the shell that the docked AppBar should be of 0x0 dimensions
// so that the workspace is not affected by the AppBar
currentRect := Rect(0, 0, 0, 0);
AppBarMessage4(abmSetPos, abEdge, LPARAM(False), currentRect);
with FABS.rcFloat do
AForm.SetBounds(Left, Top, Right - Left, Bottom - Top);
end;
else
begin
if IsAutohide and (AppBarMessage3(abmSetAutoHideBar, GetEdge, LPARAM(True)) = 0) then
begin
FABS.bAutohide := False; // We couldn't set the AppBar on a new edge, let's dock it instead
// Call a virtual function to let derived classes know that the AppBar
// changed from auto-hide to docked
DoForcedToDocked;
end;
GetRect(GetEdge, rc);
if IsAutohide then
begin
currentRect := Rect(0, 0, 0, 0);
AppBarMessage4(abmSetPos, abeLeft, LPARAM(False), currentRect);
end
else
AppBarMessage4(abmSetPos, abEdge, LPARAM(False), rc); // Tell the shell where the AppBar is
AdjustLocationForAutohide(FbAutoHideIsVisible, rc);
// Slide window in from or out to the edge
SlideWindow(rc);
end; // end of else
end; // end of case
// Set the AppBar's z-order appropriately
hWnd := HWND_NOTOPMOST; // Assume normal Z-Order
if FABS.bAlwaysOnTop then
begin
// If we are supposed to be always-on-top, put us there
hWnd := HWND_TOPMOST;
if FbFullScreenAppOpen then
// But, if a full-screen window is opened, put ourself at the bottom
// of the z-order so that we don't cover the full-screen window
hWnd := HWND_BOTTOM;
end;
SetWindowPos(AForm.Handle, hWnd, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE);
// Make sure that any auto-hide appbars stay on top of us after we move
// even though our activation state has not changed
AppBarMessage1(abmActivate);
if not (csDesigning in ComponentState) then
begin
// Show or hide the taskbar entry depending on AppBar position
case FABS.abTaskEntry of
abtShow :
ShowWindow(Application.Handle, SW_SHOW);
abtHide :
ShowWindow(Application.Handle, SW_HIDE);
abtFloatDependent :
case abEdge of
abeFloat :
ShowWindow(Application.Handle, SW_SHOW);
abeLeft, abeTop, abeRight, abeBottom :
ShowWindow(Application.Handle, SW_HIDE);
end;
end;
end;
end;
// TElAppBar.IsAutoHide /////////////////////////////////////////////////////////
function TElAppBar.IsAutoHide : Boolean;
begin
Result := FABS.bAutohide;
end;
// TElAppBar.SetAutoHide ////////////////////////////////////////////////////////
procedure TElAppBar.SetAutoHide(bAutoHide : Boolean);
begin
FABS.bAutohide := bAutoHide;
if Edge <> abeFloat then UpdateBar;
end;
// TElAppBar.IsAlwaysOnTop //////////////////////////////////////////////////////
function TElAppBar.IsAlwaysOnTop : Boolean;
begin
Result := FABS.bAlwaysOnTop;
end;
// TElAppBar.SetAlwaysOnTop /////////////////////////////////////////////////////
procedure TElAppBar.SetAlwaysOnTop(bAlwaysOnTop : Boolean);
begin
FABS.bAlwaysOnTop := bAlwaysOnTop;
if Edge <> abeFloat then UpdateBar;
end;
// TElAppBar.GetFloatRect ///////////////////////////////////////////////////////
{$IFDEF BUILDER_USED}
procedure TElAppBar.GetFloatRect(var rc : TRect);
begin
rc := FABS.rcFloat;
end;
{$ELSE}
function TElAppBar.GetFloatRect : TRect;
begin
Result := FABS.rcFloat;
end;
{$ENDIF}
// TElAppBar.SetFloatRect ///////////////////////////////////////////////////////
procedure TElAppBar.SetFloatRect(rc : TRect);
begin
FABS.rcFloat := rc;
end;
// TElAppBar.GetDockDims ////////////////////////////////////////////////////////
{$IFDEF BUILDER_USED}
procedure TElAppBar.GetDockDims(var rc : TRect);
begin
rc := FABS.rcDockDims;
end;
{$ELSE}
function TElAppBar.GetDockDims : TRect;
begin
Result := FABS.rcDockDims;
end;
{$ENDIF}
// TElAppBar.SetDockDims ////////////////////////////////////////////////////////
procedure TElAppBar.SetDockDims(rc : TRect);
begin
FABS.rcDockDims := rc;
end;
procedure TElAppBar.SetFlags(newValue : TAppBarFlags);
var
ex : boolean;
begin
fabFlags := newValue;
ex := false;
case Edge of //
abeUnknown : ex := false;
abeBottom : ex := not (abfAllowBottom in Flags);
abeFloat : ex := not (abfAllowFloat in Flags);
abeRight : ex := not (abfAllowRight in Flags);
abeLeft : ex := not (abfAllowLeft in Flags);
abeTop : ex := not (abfAllowTop in Flags);
end; // case
if ex then
begin
if abfAllowFloat in fabFlags then
Edge := abeFloat
else
begin
if abfAllowLeft in fabFlags then
Edge := abeLeft
else if abfAllowTop in fabFlags then
Edge := abeTop
else if abfAllowBottom in fabFlags then
Edge := abeBottom
else if abfAllowRight in fabFlags then
Edge := abeRight
else
Edge := abeUnknown;
end;
end;
end;
{ Overridable functions }
// TElAppBar.OnAppBarForcedToDockedDoForcedToDocked /////////////////////////////////////////////
procedure TElAppBar.DoForcedToDocked;
begin
FForceRehide := true;
if assigned(FOnForcedToDocked) then FOnForcedToDocked(Self);
end;
// TElAppBar.OnABNFullScreenApp /////////////////////////////////////////////////
procedure TElAppBar.OnABNFullScreenApp(bOpen : Boolean);
begin
// This function is called when a FullScreen window is openning or
// closing. A FullScreen window is a top-level window that has its caption
// above the top of the screen allowing the entire screen to be occupied
// by the window's client area.
// If the AppBar is a topmost window when a FullScreen window is activated,
// we need to change our window to a non-topmost window so that the AppBar
// doesn't cover the FullScreen window's client area.
// If the FullScreen window is closing, we need to set the AppBar's
// Z-Order back to when the user wants it to be.
FbFullScreenAppOpen := bOpen;
UpdateBar;
end;
// TElAppBar.OnABNPosChanged ////////////////////////////////////////////////////
procedure TElAppBar.OnABNPosChanged;
begin
// The TaskBar or another AppBar has changed its size or position
if (GetEdge <> abeFloat) and (not FABS.bAutohide) then
// If we're not floating and we're not auto-hidden, we have to
// reposition our window
UpdateBar;
end;
// TElAppBar.OnABNWindowArrange /////////////////////////////////////////////////
procedure TElAppBar.OnABNWindowArrange(bBeginning : Boolean);
begin
// This function intentionally left blank
end;
{ Message handlers }
// TElAppBar.OnAppBarCallbackMsg ////////////////////////////////////////////////
procedure TElAppBar.OnAppBarCallbackMsg(var Msg : TMessage);
begin
case Msg.WParam of
ABN_FULLSCREENAPP :
OnABNFullScreenApp(Msg.LParam <> 0);
ABN_POSCHANGED :
OnABNPosChanged;
ABN_WINDOWARRANGE :
OnABNWindowArrange(Msg.LParam <> 0);
end;
end;
// TElAppBar.WmCreate ///////////////////////////////////////////////////////////
procedure TElAppBar.WMCreate(var Msg : TWMCreate);
begin
inherited;
ActivateAppBar;
end;
// TElAppBar.OnDestroy //////////////////////////////////////////////////////////
procedure TElAppBar.WMDestroy(var Msg : TWMDestroy);
begin
DeactivateAppBar;
inherited;
end;
// TElAppBar.WMWindowPosChanged /////////////////////////////////////////////////
procedure TElAppBar.WMWindowPosChanged(var Msg : TWMWindowPosChanged);
begin
if FInPosChanged then
exit;
inherited;
// When our window changes position, tell the Shell so that any
// auto-hidden AppBar on our edge stays on top of our window making it
// always accessible to the user
AppBarMessage1(abmWindowPosChanged);
if (Msg.WindowPos.hwndInsertAfter <> HWND_TOPMOST) and (FAbs.bAlwaysOnTop) then
begin
FInPosChanged := true;
SetWindowPos(GetOwnerForm(Self).Handle, hwnd_TopMost, 0, 0, 0, 0, swp_NoMove + swp_NoSize + swp_NoActivate);
FInPosChanged := false;
end;
end;
// TElAppBar.WMActivate /////////////////////////////////////////////////////////
procedure TElAppBar.WMActivate(var Msg : TWMActivate);
begin
inherited;
if Msg.Active = WA_INACTIVE then
// Hide the AppBar if we are docked and auto-hidden
ShowHiddenAppBar(False);
// When our window changes position, tell the Shell so that any
// auto-hidden AppBar on our edge stays on top of our window making it
// always accessible to the user.
AppBarMessage1(abmActivate);
end;
// TElAppBar.OnAppBarTimer //////////////////////////////////////////////////////
procedure TElAppBar.OnAppBarTimer(Sender : TObject);
var
pt : TSmallPoint;
rc : TRect;
AForm : TForm;
begin
AForm := GetOwnerForm(Self);
if (GetActiveWindow <> AForm.Handle) or (GetForegroundWindow <> AForm.Handle) then
begin
// Possibly hide the AppBar if we are not the active window
// Get the position of the mouse and the AppBar's position
// Everything must be in screen coordinates
pt := GetMessagePosition;
GetWindowRect(AForm.Handle, rc);
// Add a little margin around the AppBar
InflateRect(rc,
2 * GetSystemMetrics(SM_CXDOUBLECLK),
2 * GetSystemMetrics(SM_CYDOUBLECLK));
if not PtInRect(rc, SmallPointToPoint(pt)) then
// If the mouse is NOT over the AppBar, hide the AppBar
ShowHiddenAppBar(False);
end;
inherited;
end;
// TElAppBar.WMNCMouseMove //////////////////////////////////////////////////////
procedure TElAppBar.WMNCMouseMove(var Msg : TMessage);
begin
// If we are a docked, auto-hidden AppBar, shown us
// when the user moves over our non-client area
ShowHiddenAppBar(True);
inherited;
end;
// TElAppBar.WMNCHitTest ////////////////////////////////////////////////////////
procedure TElAppBar.WMNCHitTest(var Msg : TWMNCHitTest);
var
u : UINT;
bPrimaryMouseBtnDown : Boolean;
rcClient : TRect;
pt : TPoint;
vKey : Integer;
AForm : TForm;
begin
// Find out what the system thinks is the hit test code
inherited;
AForm := GetOwnerForm(Self);
{$ifdef D_6_UP}
if (csDesigning in ComponentState) then exit;
{$endif}
u := Msg.Result;
if (Edge <> abeFloat) and KeepSize then exit;
// NOTE: If the user presses the secondary mouse button, pretend that the
// user clicked on the client area so that we get WM_CONTEXTMENU messages
if GetSystemMetrics(SM_SWAPBUTTON) <> 0 then
vKey := VK_RBUTTON
else
vKey := VK_LBUTTON;
bPrimaryMouseBtnDown := ((GetAsyncKeyState(vKey) and $8000) <> 0);
if (u = HTCLIENT) and bPrimaryMouseBtnDown then
// User clicked in client area, allow AppBar to move. We get this
// behavior by pretending that the user clicked on the caption area
u := HTCAPTION;
// If the AppBar is floating and the hittest code is a resize code...
if ((GetEdge = abeFloat) and
(HTSIZEFIRST <= u) and (u <= HTSIZELAST)) then
begin
case u of
HTLEFT, HTRIGHT :
if FszSizeInc.cx = 0 then u := HTBORDER;
HTTOP, HTBOTTOM :
if FszSizeInc.cy = 0 then u := HTBORDER;
HTTOPLEFT :
if (FszSizeInc.cx = 0) and (FszSizeInc.cy = 0) then
u := HTBORDER
else if (FszSizeInc.cx = 0) and (FszSizeInc.cy <> 0) then
u := HTTOP
else if (FszSizeInc.cx <> 0) and (FszSizeInc.cy = 0) then
u := HTLEFT;
HTTOPRIGHT :
if (FszSizeInc.cx = 0) and (FszSizeInc.cy = 0) then
u := HTBORDER
else if (FszSizeInc.cx = 0) and (FszSizeInc.cy <> 0) then
u := HTTOP
else if (FszSizeInc.cx <> 0) and (FszSizeInc.cy = 0) then
u := HTRIGHT;
HTBOTTOMLEFT :
if (FszSizeInc.cx = 0) and (FszSizeInc.cy = 0) then
u := HTBORDER
else if (FszSizeInc.cx = 0) and (FszSizeInc.cy <> 0) then
u := HTBOTTOM
else if (FszSizeInc.cx <> 0) and (FszSizeInc.cy = 0) then
u := HTLEFT;
HTBOTTOMRIGHT :
if (FszSizeInc.cx = 0) and (FszSizeInc.cy = 0) then
u := HTBORDER
else if (FszSizeInc.cx = 0) and (FszSizeInc.cy <> 0) then
u := HTBOTTOM
else if (FszSizeInc.cx <> 0) and (FszSizeInc.cy = 0) then
u := HTRIGHT;
end;
end;
// When the AppBar is docked, the user can resize only one edge.
// This next section determines which edge the user can resize.
// To allow resizing, the AppBar window must have the WS_THICKFRAME style
// If the AppBar is docked and the hittest code is a resize code...
if ((GetEdge <> abeFloat) and (GetEdge <> abeUnknown) and
(HTSIZEFIRST <= u) and (u <= HTSIZELAST)) then
begin
if (IsEdgeLeftOrRight(GetEdge) and (FszSizeInc.cx = 0)) or
(not IsEdgeLeftOrRight(GetEdge) and (FszSizeInc.cy = 0)) then
begin
// If the width/height size increment is zero, then resizing is NOT
// allowed for the edge that the AppBar is docked on
u := HTBORDER; // Pretend that the mouse is not on a resize border
end
else
begin
// Resizing IS allowed for the edge that the AppBar is docked on
// Get the location of the appbar's client area in screen coordinates
rcClient := AForm.ClientRect;
pt.X := rcClient.Left;
pt.Y := rcClient.Top;
pt := AForm.ClientToScreen(pt);
rcClient.Left := pt.X;
rcClient.Top := pt.Y;
pt.X := rcClient.Right;
pt.Y := rcClient.Bottom;
pt := AForm.ClientToScreen(pt);
rcClient.Right := pt.X;
rcClient.Bottom := pt.Y;
u := HTBORDER; // Assume that we can't resize
case GetEdge of
abeLeft :
if Msg.XPos > rcClient.Right then
u := HTRIGHT;
abeTop :
if Msg.YPos > rcClient.Bottom then
u := HTBOTTOM;
abeRight :
if Msg.XPos < rcClient.Left then
u := HTLEFT;
abeBottom :
if Msg.YPos < rcClient.Top then
u := HTTOP;
end; // end of case
end; // end of else
end;
// Return the hittest code
Msg.Result := u;
end;
// TElAppBar.OnEnterSizeMove ////////////////////////////////////////////////////
procedure TElAppBar.WMEnterSizeMove(var Msg : TMessage);
var AForm : TForm;
begin
AForm := GetOwnerForm(Self);
// The user started moving/resizing the AppBar, save its current state
FabEdgeProposedPrev := GetEdge;
GetCursorPos(FDraggingOffset);
Dec(FDraggingOffset.X, AForm.Left);
Dec(FDraggingOffset.Y, AForm.Top);
end;
// TElAppBar.OnExitSizeMove /////////////////////////////////////////////////////
procedure TElAppBar.WMExitSizeMove(var Msg : TMessage);
var
p : TPoint;
abEdgeProposedPrev: TAppBarEdge;
rc, rcWorkArea : TRect;
w, h : Integer;
AForm : TForm;
begin
AForm := GetOwnerForm(Self);
// The user stopped moving/resizing the AppBar, set the new state
// Save the new proposed state of the AppBar
abEdgeProposedPrev := FabEdgeProposedPrev;
// Set the proposed state back to unknown. This causes GetState
// to return the current state rather than the proposed state
FabEdgeProposedPrev := abeUnknown;
// Get the location of the window in screen coordinates
GetWindowRect(AForm.Handle, rc);
// If the AppBar's state has changed...
if GetEdge = abEdgeProposedPrev then
case GetEdge of
abeLeft :
// Save the new width of the docked AppBar
FABS.rcDockDims.Left := rc.Right - rc.Left;
abeTop :
// Save the new height of the docked AppBar
FABS.rcDockDims.Top := rc.Bottom - rc.Top;
abeRight :
// Save the new width of the docked AppBar
FABS.rcDockDims.Right := rc.Right - rc.Left;
abeBottom :
// Save the new height of the docked AppBar
FABS.rcDockDims.Bottom := rc.Bottom - rc.Top;
end;
// Always save the new position of the floating AppBar
if abEdgeProposedPrev = abeFloat then
begin
// If AppBar was floating and keeps floating...
if GetEdge = abeFloat then
begin
FABS.rcFloat := rc;
// If AppBar was docked and is going to float...
end
else
begin
// Propose width and height depending on the current window position
w := rc.Right - rc.Left;
h := rc.Bottom - rc.Top;
// Adjust width and height
SystemParametersInfo(SPI_GETWORKAREA, 0, @rcWorkArea, 0);
if (w >= (rcWorkArea.Right - rcWorkArea.Left)) or
(h >= (rcWorkArea.Bottom - rcWorkArea.Top)) then
begin
w := FABS.rcFloat.Right - FABS.rcFloat.Left;
h := FABS.rcFloat.Bottom - FABS.rcFloat.Top;
end;
// Save new floating position
if FKeepSize then
begin
GetCursorPos(P);
FABS.rcFloat.Left := P.x - FDraggingOffset.X;
FABS.rcFloat.Top := P.y - FDraggingOffset.Y;
FABS.rcFloat.Right := FABS.rcFloat.Left + w;
FABS.rcFloat.Bottom := FABS.rcFloat.Top + h;
end
else
begin
FABS.rcFloat.Left := rc.Left;
FABS.rcFloat.Top := rc.Top;
FABS.rcFloat.Right := rc.Left + w;
FABS.rcFloat.Bottom := rc.Top + h;
end;
end;
end;
if FKeepSize and (abEdgeProposedPrev <> abeFloat) and (Edge <> abeFloat) then
begin
GetWindowRect(AForm.Handle, rc);
FABS.rcFloat.Right := FABS.rcFloat.Left + rc.Right - rc.Left;
FABS.rcFloat.Bottom := FABS.rcFloat.Top + rc.Bottom - rc.Top;
end;
// After setting the dimensions, set the AppBar to the proposed state
SetEdge(abEdgeProposedPrev);
DoEdgeChanged;
if (Edge = abeFloat) and PreventOffScreen then
begin
Rc := AForm.BoundsRect;
with Rc do
begin
if Top < 0 then OffsetRect(Rc, 0, -Top);
if Bottom > GetSystemMetrics(SM_CYSCREEN) then OffsetRect(Rc, 0, GetSystemMetrics(SM_CYSCREEN) - Bottom);
if Left < 0 then OffsetRect(Rc, -Left, 0);
if Right > GetSystemMetrics(SM_CXSCREEN) then OffsetRect(Rc, GetSystemMetrics(SM_CXSCREEN) - Right, 0);
AForm.BoundsRect := Rc;
end;
end;
end;
// TElAppBar.OnMoving ///////////////////////////////////////////////////////////
procedure TElAppBar.WMMoving(var Msg : TMessage);
var
prc : PRect;
pt : TSmallPoint;
abEdgeProposed : TAppBarEdge;
w, h : Integer;
begin
// We control the moving of the AppBar. For example, if the mouse moves
// close to an edge, we want to dock the AppBar
// The lParam contains the window's position proposed by the system
prc := PRect(Msg.LParam);
// Get the location of the mouse cursor
pt := GetMessagePosition;
// Where should the AppBar be based on the mouse position?
abEdgeProposed := CalcProposedState(pt);
if ((FabEdgeProposedPrev <> abeFloat) and (abEdgeProposed = abeFloat)) then
begin
// While moving, the user took us from a docked/autohidden state to
// the float state. We have to calculate a rectangle location so that
// the mouse cursor stays inside the window.
prc^ := FABS.rcFloat;
if FKeepSize then
begin
w := prc.Right - prc.Left { + 1};
h := prc.Bottom - prc.Top { + 1};
with prc^ do
begin
Left := pt.X - FDraggingOffset.X;
Top := pt.Y - FDraggingOffset.Y;
Right := Left + w;
Bottom := Top + h;
end;
end
else
begin
w := prc^.Right - prc^.Left;
h := prc^.Bottom - prc^.Top;
with prc^ do
begin
Left := pt.X - w div 2;
Top := pt.Y;
Right := pt.X - w div 2 + w;
Bottom := pt.Y + h;
end;
end;
end;
// Remember the most-recently proposed state
FabEdgeProposedPrev := abEdgeProposed;
// Tell the system where to move the window based on the proposed state
GetRect(abEdgeProposed, prc^);
end;
// TElAppBar.OnSizing ///////////////////////////////////////////////////////////
procedure TElAppBar.WMSizing(var Msg : TMessage);
var
prc : PRect;
rcBorder : TRect;
nWidthNew, nHeightNew : Integer;
AForm : TForm;
begin
AForm := GetOwnerForm(Self);
// We control the sizing of the AppBar. For example, if the user re-sizes
// an edge, we want to change the size in descrete increments.
// The lParam contains the window's position proposed by the system
prc := PRect(Msg.LParam);
// Get the minimum size of the window assuming it has no client area.
// This is the width/height of the window that must always be present
rcBorder := Rect(0, 0, 0, 0);
AdjustWindowRectEx(rcBorder,
GetWindowLong(AForm.Handle, GWL_STYLE),
False,
GetWindowLong(AForm.Handle, GWL_EXSTYLE));
// We force the window to resize in discrete units set by the FszSizeInc
// member. From the new, proposed window dimensions passed to us, round
// the width/height to the nearest discrete unit
if FszSizeInc.cx <> 0 then
nWidthNew := ((prc^.Right - prc^.Left) - (rcBorder.Right - rcBorder.Left)
+ FszSizeInc.cx div 2) div FszSizeInc.cx * FszSizeInc.cx
+ (rcBorder.Right - rcBorder.Left)
else
nWidthNew := prc^.Right - prc^.Left;
if FszSizeInc.cy <> 0 then
nHeightNew := ((prc^.Bottom - prc^.Top) - (rcBorder.Bottom - rcBorder.Top)
+ FszSizeInc.cy div 2) div FszSizeInc.cy * FszSizeInc.cy
+ (rcBorder.Bottom - rcBorder.Top)
else
nHeightNew := prc^.Bottom - prc^.Top;
// Adjust the rectangle's dimensions
case Msg.wParam of
WMSZ_LEFT :
prc^.Left := prc^.Right - nWidthNew;
WMSZ_TOP :
prc^.Top := prc^.Bottom - nHeightNew;
WMSZ_RIGHT :
prc^.Right := prc^.Left + nWidthNew;
WMSZ_BOTTOM :
prc^.Bottom := prc^.Top + nHeightNew;
WMSZ_BOTTOMLEFT :
begin
prc^.Bottom := prc^.Top + nHeightNew;
prc^.Left := prc^.Right - nWidthNew;
end;
WMSZ_BOTTOMRIGHT :
begin
prc^.Bottom := prc^.Top + nHeightNew;
prc^.Right := prc^.Left + nWidthNew;
end;
WMSZ_TOPLEFT :
begin
prc^.Left := prc^.Right - nWidthNew;
prc^.Top := prc^.Bottom - nHeightNew;
end;
WMSZ_TOPRIGHT :
begin
prc^.Top := prc^.Bottom - nHeightNew;
prc^.Right := prc^.Left + nWidthNew;
end;
end; // end of case
end;
// TElAppBar.OnGetMinMaxInfo ////////////////////////////////////////////////////
procedure TElAppBar.WMGetMinMaxInfo(var Msg : TWMGetMinMaxInfo);
begin
if GetEdge = abeFloat then
with Msg.MinMaxInfo^ do
begin
ptMinTrackSize.X := FABS.nMinWidth;
ptMinTrackSize.Y := FABS.nMinHeight;
ptMaxTrackSize.X := FABS.nMaxWidth;
ptMaxTrackSize.Y := FABS.nMaxHeight;
end
else
with Msg.MinMaxInfo^ do
begin
ptMinTrackSize.X := 0;
ptMinTrackSize.Y := 0;
ptMaxTrackSize.X := GetSystemMetrics(SM_CXSCREEN);
ptMaxTrackSize.Y := GetSystemMetrics(SM_CYSCREEN);
if (not IsEdgeTopOrBottom(GetEdge)) and (not KeepSize) then
ptMaxTrackSize.X := ptMaxTrackSize.X div 2;
if (not IsEdgeLeftOrRight(GetEdge)) and (not KeepSize) then
ptMaxTrackSize.Y := ptMaxTrackSize.Y div 2;
end;
end;
{ AppBar-specific helper functions }
// TElAppBar.IsEdgeLeftOrRight //////////////////////////////////////////////////
function TElAppBar.IsEdgeLeftOrRight(abEdge : TAppBarEdge) : Boolean;
begin
Result := (abEdge in [abeLeft, abeRight]);
end;
// TElAppBar.IsEdgeTopOrBottom //////////////////////////////////////////////////
function TElAppBar.IsEdgeTopOrBottom(abEdge : TAppBarEdge) : Boolean;
begin
Result := (abEdge in [abeTop, abeBottom]);
end;
// TElAppBar.IsFloating /////////////////////////////////////////////////////////
function TElAppBar.IsFloating(abEdge : TAppBarEdge) : Boolean;
begin
Result := (abEdge = abeFloat);
end;
// TElAppBar.IsDockable /////////////////////////////////////////////////////////
function TElAppBar.IsDockable(abFlags : TAppBarFlags) : Boolean;
begin
Result := ((abFlags * [abfAllowLeft..abfAllowBottom]) <> []);
end;
// TElAppBar.IsDockableVertically ///////////////////////////////////////////////
function TElAppBar.IsDockableVertically(abFlags : TAppBarFlags) : Boolean;
begin
Result := ((abFlags * [abfAllowLeft, abfAllowRight]) <> []);
end;
// TElAppBar.IsDockableHorizontally /////////////////////////////////////////////
function TElAppBar.IsDockableHorizontally(abFlags : TAppBarFlags) : Boolean;
begin
Result := ((abFlags * [abfAllowTop, abfAllowBottom]) <> []);
end;
// TElAppBar.ResetSystemKnowledge ///////////////////////////////////////////////
procedure TElAppBar.ResetSystemKnowledge;
{$IFDEF DEBUG}
var
abd : TAppBarData;
begin
abd.cbSize := sizeof(abd);
abd.hWnd := 0;
SHAppBarMessage(ABM_REMOVE, abd);
end;
{$ELSE}
begin
// nothing to do when not in debug mode
end;
{$ENDIF}
// TElAppBar.GetEdgeFromPoint ///////////////////////////////////////////////////
function TElAppBar.GetEdgeFromPoint(abFlags : TAppBarFlags;
pt : TSmallPoint) : TAppBarEdge;
var
rc : TRect;
cxScreen : Integer;
cyScreen : Integer;
ptCenter : TSmallPoint;
ptOffset : TSmallPoint;
bIsLeftOrRight : Boolean;
abSubstEdge : TAppBarEdge;
begin
// Let's get floating out of the way first
if abfAllowFloat in abFlags then
begin
// Get the rectangle that bounds the size of the screen
// minus any docked (but not-autohidden) AppBars
SystemParametersInfo(SPI_GETWORKAREA, 0, @rc, 0);
// Leave a 1/2 width/height-of-a-scrollbar gutter around the workarea
InflateRect(rc,
-GetSystemMetrics(SM_CXVSCROLL),
-GetSystemMetrics(SM_CYHSCROLL));
// If the point is in the adjusted workarea OR no edges are allowed
if PtInRect(rc, SmallPointToPoint(pt)) or
not IsDockable(abFlags) then
begin
// The AppBar should float
Result := abeFloat;
Exit;
end;
end;
// If we get here, the AppBar should be docked; determine the proper edge
// Get the dimensions of the screen
cxScreen := GetSystemMetrics(SM_CXSCREEN);
cyScreen := GetSystemMetrics(SM_CYSCREEN);
// Find the center of the screen
ptCenter.X := cxScreen div 2;
ptCenter.Y := cyScreen div 2;
// Find the distance from the point to the center
ptOffset.X := pt.X - ptCenter.X;
ptOffset.Y := pt.Y - ptCenter.Y;
// Determine if the point is farther from the left/right or top/bottom
bIsLeftOrRight :=
((Abs(ptOffset.Y) * cxScreen) <= (Abs(ptOffset.X) * cyScreen));
// Propose an edge
if bIsLeftOrRight then
begin
if 0 <= ptOffset.X then
Result := abeRight
else
Result := abeLeft;
end
else
begin
if 0 <= ptOffset.Y then
Result := abeBottom
else
Result := abeTop;
end;
// Calculate an edge substitute
if abfAllowFloat in abFlags then
abSubstEdge := abeFloat
else
abSubstEdge := FABS.abEdge;
// Check if the proposed edge is allowed. If not, return the edge substitute
case Result of
abeLeft :
if not (abfAllowLeft in abFlags) then Result := abSubstEdge;
abeTop :
if not (abfAllowTop in abFlags) then Result := abSubstEdge;
abeRight :
if not (abfAllowRight in abFlags) then Result := abSubstEdge;
abeBottom :
if not (abfAllowBottom in abFlags) then Result := abSubstEdge;
end;
end;
{ Public member functions }
// TElAppBar.Create /////////////////////////////////////////////////////////////
constructor TElAppBar.Create(Owner : TComponent);
begin
inherited;
FHook := TElHook.Create(nil);
FHook.Control := GetOwnerForm(Owner);
FHook.OnBeforeProcess := OnHook;
FHook.OnAfterProcess := OnAfterHook;
// Force the shell to update its list of AppBars and the workarea.
// This is a precaution and is very useful when debugging. If you create
// an AppBar and then just terminate the application, the shell still
// thinks that the AppBar exists and the user's workarea is smaller than
// it should be. When a new AppBar is created, calling this function
// fixes the user's workarea.
ResetSystemKnowledge;
// Set default state of AppBar to float with no width & height
FABS.abEdge := abeFloat;
FABS.bAutohide := False;
FABS.bAlwaysOnTop := false;
FABS.nTimerInterval := SLIDE_DEF_TIMER_INTERVAL;
FABS.bSlideEffect := True;
FABS.rcDockDims.Left := AB_DEF_DOCK_DIM;
FABS.rcDockDims.Top := AB_DEF_DOCK_DIM;
FABS.rcDockDims.Right := AB_DEF_DOCK_DIM;
FABS.rcDockDims.Bottom := AB_DEF_DOCK_DIM;
FABS.rcFloat.Left := 0;
FABS.rcFloat.Top := 0;
FABS.rcFloat.Right := 0;
FABS.rcFloat.Bottom := 0;
FABS.nMinWidth := 0;
FABS.nMinHeight := 0;
FABS.nMaxWidth := GetSystemMetrics(SM_CXSCREEN);
FABS.nMaxHeight := GetSystemMetrics(SM_CYSCREEN);
FABS.abTaskEntry := abtHide;
FabFlags := [abfAllowLeft..abfAllowFloat];
FszSizeInc.cx := AB_DEF_SIZE_INC;
FszSizeInc.cy := AB_DEF_SIZE_INC;
FabEdgeProposedPrev := abeUnknown;
FbFullScreenAppOpen := False;
FbAutoHideIsVisible := False;
FPreventOffScreen := false;
end;
// TElAppBar.Destroy ////////////////////////////////////////////////////////////
destructor TElAppBar.Destroy;
begin
ResetSystemKnowledge;
FHook.Free;
inherited;
end;
// TElAppBar.UpdateBar //////////////////////////////////////////////////////////
procedure TElAppBar.UpdateBar;
begin
SetEdge(GetEdge);
end;
// TAppBar.SetSlideTime ///////////////////////////////////////////////////////
procedure TElAppBar.SetSlideTime(nInterval : Integer);
begin
FABS.nTimerInterval := nInterval;
FTimer.Interval := nInterval;
end;
procedure TElAppBar.SetKeepSize(newValue : Boolean);
begin
if (FKeepSize <> newValue) then
begin
if abfAllowFloat in Flags then
begin
FKeepSize := newValue;
if GetEdge <> abeFloat then UpdateBar;
end;
end; {if}
end;
procedure TElAppBar.SetPreventOffScreen(newValue : Boolean);
begin
if (FPreventOffScreen <> newValue) then
begin
FPreventOffScreen := newValue;
UpdateBar;
end; {if}
end;
procedure TElAppBar.SetHorzInc(newValue : integer);
begin
FszSizeInc.cx := newValue;
end;
procedure TElAppBar.SetVertInc(newValue : integer);
begin
FszSizeInc.cy := newValue;
end;
function TElAppBar.GetVertInc : integer;
begin
result := FszSizeInc.cy;
end;
function TElAppBar.GetHorzInc : integer;
begin
result := FszSizeInc.cx;
end;
procedure TElAppBar.DoEdgeChanged;
begin
if Assigned (FOnEdgeChanged) then FOnEdgeChanged(Self);
end;
procedure TElAppBar.WMMouseMove(var Msg : TMessage);
begin
ShowHiddenAppBar(True);
inherited;
end; { OnMouseMove }
procedure TElAppBar.OnHook(Sender : TObject; var Msg : TMessage; var Handled : boolean);
type PWMDestroy = ^TWMDestroy;
begin
case Msg.Msg of
WM_APPBARNOTIFY :
begin
OnAppBarCallbackMsg(Msg);
Handled := true;
end;
WM_DESTROY:
begin
WMDestroy(PWMDestroy(@Msg)^);
Handled := false;
end;
end;
end;
procedure TElAppBar.OnAfterHook(Sender : TObject; var Msg : TMessage; var Handled : boolean);
type PWMCreate = ^TWMCreate;
PWMActivate = ^TWMActivate;
PWMNCHitTest = ^TWMNCHitTest;
PWMWindowPosChanged = ^TWMWindowPosChanged;
PWMGetMinMaxInfo = ^TWMGetMinMaxInfo;
begin
case Msg.Msg of
WM_CREATE:
begin
WMCreate(PWMCreate(@Msg)^);
Handled := true;
end;
WM_ACTIVATE:
begin
WMActivate(PWMActivate(@Msg)^);
Handled := false;
end;
WM_NCHITTEST:
begin
WMNCHitTest(PWMNCHitTest(@Msg)^);
Handled := false;
end;
WM_WINDOWPOSCHANGED:
begin
WMWindowPosChanged(PWMWindowPosChanged(@Msg)^);
Handled := false;
end;
WM_NCMOUSEMOVE:
begin
WMNCMouseMove(Msg);
Handled := false;
end;
WM_MOUSEMOVE:
begin
WMMouseMove(Msg);
Handled := false;
end;
WM_ENTERSIZEMOVE:
begin
WMEnterSizeMove(Msg);
Handled := false;
end;
WM_EXITSIZEMOVE:
begin
WMExitSizeMove(Msg);
Handled := false;
end;
WM_MOVING:
begin
WMMoving(Msg);
Handled := false;
end;
WM_SIZING:
begin
WMSizing(Msg);
Handled := false;
end;
WM_GETMINMAXINFO:
begin
WMGetMinMaxInfo(PWMGetMinMaxInfo(@Msg)^);
Handled := false;
end;
end;
end;
procedure TElAppBar.SetActive(Value: Boolean);
begin
if FActive <> Value then
begin
FActive := Value;
if not (csDesigning in ComponentState) then
begin
if not FActive then DeactivateAppBar;
FHook.Active := FActive;
if FActive then
begin
ActivateAppBar;
AdjustWindowStyles;
end;
end;
end;
end;
procedure TElAppBar.AdjustWindowStyles;
var
dwAdd, dwRemove, dwAddEx, dwRemoveEx : DWORD;
Style, ExStyle : DWORD;
AForm : TForm;
begin
AForm := GetOwnerForm(Self);
// Call the inherited first
// Styles to be added
dwAdd := WS_POPUP or WS_THICKFRAME;
dwAddEx := WS_EX_TOOLWINDOW;
// Styles to be removed
dwRemove := WS_SYSMENU or WS_MAXIMIZEBOX or WS_MINIMIZEBOX;
dwRemoveEx := WS_EX_APPWINDOW;
Style := GetWindowLong(AForm.Handle, GWL_STYLE);
ExStyle := GetWindowLong(AForm.Handle, GWL_EXSTYLE);
// Modify style flags
Style := Style and (not dwRemove);
Style := Style or dwAdd;
ExStyle := ExStyle and (not dwRemoveEx);
ExStyle := ExStyle or dwAddEx;
SetWindowLong(AForm.Handle, GWL_STYLE, Style);
SetWindowLong(AForm.Handle, GWL_EXSTYLE, ExStyle);
end;
procedure TElAppBar.ActivateAppBar;
var
hMenu : THandle;
AForm : TForm;
begin
AForm := GetOwnerForm(Self);
// Associate a timer with the AppBar. The timer is used to determine
// when a visible, inactive, auto-hide AppBar should be re-hidden
FTimer := TElTimer.Create;
with FTimer do
begin
Interval := FABS.nTimerInterval;
OnTimer := OnAppBarTimer;
Enabled := True;
end;
// Save the initial position of the floating AppBar
FABS.rcFloat.Left := AForm.Left;
FABS.rcFloat.Top := AForm.Top;
// Register our AppBar window with the Shell
AppBarMessage1(abmNew);
// Update AppBar internal state
//UpdateBar;
// Save the initial size of the floating AppBar
PostMessage(AForm.Handle, WM_ENTERSIZEMOVE, 0, 0);
PostMessage(AForm.Handle, WM_EXITSIZEMOVE, 0, 0);
// Remove system menu
hMenu := GetSystemMenu(AForm.Handle, False);
DeleteMenu(hMenu, SC_RESTORE, MF_BYCOMMAND);
DeleteMenu(hMenu, SC_MINIMIZE, MF_BYCOMMAND);
DeleteMenu(hMenu, SC_MAXIMIZE, MF_BYCOMMAND);
end;
procedure TElAppBar.DeactivateAppBar;
begin
// Free the Autohide timer
FTimer.Enabled := False;
FTimer.Free;
FTimer := nil;
// Unregister our AppBar window with the Shell
SetEdge(abeUnknown);
end;
end.
|
(* SortPgm: XX, 16.01.2019 *)
(* ------- *)
(* some sorting algorithms with tests *)
(*===============================================*)
PROGRAM SortPgm;
USES
Timer;
CONST
maxArrLen = 20;
TYPE
ArrayType = ARRAY[1..maxArrLen] OF INTEGER;
SortStatistics = RECORD
comp: LONGINT; (*number of comparisons*)
ass: LONGINT; (*number of assignments*)
END; (*SortStatistics*)
VAR
ss: SortStatistics;
(* --- statistcs support --- *)
PROCEDURE InitStatistics;
BEGIN
ss.comp := 0;
ss.ass := 0;
END;
PROCEDURE WriteStatistics(name: STRING);
BEGIN
WriteLn('Statistics for sort algorithm ', name);
WriteLn(' number of comparisons: ', ss.comp);
WriteLn(' number of assignments: ', ss.ass);
END; (*WriteStatistics*)
PROCEDURE Assign(VAR dest: INTEGER; src: INTEGER);
BEGIN
dest:= src;
ss.ass := ss.ass + 1;
END; (*Assign*)
FUNCTION LT(k1, k2: INTEGER): BOOLEAN; (*less than*)
BEGIN
LT := k1 < k2;
ss.comp := ss.comp + 1;
END;
FUNCTION GT(k1, k2: INTEGER): BOOLEAN; (*greater than*)
BEGIN
GT := k1 > k2;
ss.comp := ss.comp + 1;
END;
PROCEDURE Swap(VAR k1, k2: INTEGER);
VAR
h: INTEGER;
BEGIN
h := k1;
k1 := k2;
k2 := h;
ss.ass := ss.ass + 3;
END; (*Swap*)
(*FillArray:
---
mode
1: ascending
2: descending
3: random number in the range of 0 to 1000
--- *)
PROCEDURE FillArray(VAR a: ArrayType; mode: INTEGER);
VAR
i: INTEGER;
BEGIN
CASE mode OF
1: BEGIN
FOR i := 1 TO maxArrLen DO BEGIN
a[i] := i;
END; (*FOR*)
END;
2: BEGIN
FOR i := 1 TO maxArrLen DO BEGIN
a[i] := maxArrLen-i;
END; (*FOR*)
END;
3: BEGIN
FOR i := 1 TO maxArrLen DO BEGIN
a[i] := Random(1000);
END; (*FOR*)
END;
END; (*CASE*)
END; (*FillArray*)
PROCEDURE CopyArray(VAR src, dest: ArrayType);
VAR
i: INTEGER;
BEGIN
FOR i := 1 TO maxArrLen DO BEGIN
dest[i] := src[i];
END; (*FOR*)
END; (*CopyArray*)
PROCEDURE WriteArray(a: ArrayType);
VAR
i: INTEGER;
BEGIN
FOR i := 1 TO maxArrLen DO BEGIN
Write(a[i], ' ');
END; (*FOR*)
WriteLn;
END;
(* ================================================ *)
(* selection sort *)
PROCEDURE SelectionSort(VAR a: ArrayType; lft,rgt: INTEGER);
VAR
i,j: INTEGER;
minPos, minKey, minValue: INTEGER; (* minKey value to be compared *)
BEGIN
FOR i := lft TO rgt-1 DO BEGIN
minPos := i;
minKey := a[minPos];
FOR j := minPos + 1 TO rgt DO BEGIN
IF LT(a[j],minKey) THEN BEGIN
minPos := j;
Assign(minValue,a[minPos]);
END;
END;
Swap(a[i],a[minPos]);
END;
END;
PROCEDURE InsertionSort(VAR a: ArrayType; lft,rgt: INTEGER);
VAR
i,j: INTEGER;
h : INTEGER;
BEGIN
FOR i := lft TO rgt-1 DO BEGIN
Assign(h,a[i+1]);
j := i;
WHILE (j >= lft) AND LT(h,a[j]) DO BEGIN
Assign(a[j+1], a[j]);
j := j - 1;
END;
Assign(a[j+1],h);
END;
END;
PROCEDURE ShellSort1(VAR a: ArrayType; lft,rgt: INTEGER);
VAR
n,m,i,j: INTEGER; (* n... number of elements, m ... steps size *)
h : INTEGER;
BEGIN
n := rgt - lft + 1;
m := n DIV 2;
WHILE m > 0 DO BEGIN
FOR i := lft TO rgt-m DO BEGIN
Assign(h,a[i+m]);
j := i;
WHILE (j >= lft) AND LT(h,a[j]) DO BEGIN
Assign(a[j+m], a[j]);
j := j - m;
END;
Assign(a[j+m],h);
END;
m := m DIV 2;
END;
END;
PROCEDURE BubbleSort1(VAR a: ArrayType; lft,rgt: INTEGER);
VAR
i,j: INTEGER;
BEGIN
FOR i := rgt DOWNTO lft + 1 DO BEGIN
FOR j := lft TO i-1 DO BEGIN
IF GT(a[j],a[j+1]) THEN
Swap(a[j],a[j+1]);
END;
END;
END;
PROCEDURE BubbleSort2(VAR a: ArrayType; lft,rgt:INTEGER);
VAR
i,j: INTEGER;
noswap: BOOLEAN;
BEGIN
REPEAT
noswap := TRUE;
FOR i := lft TO rgt-1 DO BEGIN
IF GT(a[i],a[i+1]) THEN BEGIN
Swap(a[i],a[i+1]);
noswap := FALSE;
END;
END;
//rgt := rgt - 1
UNTIL (noswap);
END;
PROCEDURE QucikSort(VAR a: ArrayType; lft,rgt: INTEGER);
PROCEDURE Partition(l,r: INTEGER);
VAR
i,j: INTEGER;
pivot: INTEGER;
BEGIN
i := l;
j := r;
pivot := a[(l+r) DIV 2];
REPEAT
WHILE LT(a[i],pivot) DO BEGIN
i := i + 1;
END;
WHILE LT(pivot, a[j]) DO BEGIN
j := j - 1;
END;
IF i <= j THEN BEGIN
IF i <> j THEN BEGIN
Swap(a[i],a[j]);
END;
i := i + 1;
j := j - 1;
END;
UNTIL i > j;
IF l < j THEN
Partition(l, j);
IF i < r THEN
Partition(i,r);
END;
BEGIN
Partition(lft,rgt);
END;
VAR
a, aOrigAsc, aOrigDesc, aOrigRand: ArrayType;
i: INTEGER;
BEGIN
WriteLn('Testing Sort Algorithms');
(*Fill test arrays - will be reused for all tests*)
FillArray(aOrigAsc, 1);
(*SelectionSort*)
(*array sorted ascending*)
InitStatistics;
CopyArray(aOrigAsc, a);
WriteArray(a);
StartTimer;
ShellSort1(a, 1, maxArrLen);
StopTimer;
WriteLn('ElapsedTime: ', ElapsedSecs);
WriteArray(a);
WriteStatistics('SelectionSort (sorted ascending)');
WriteLn;
WriteLn('Testing Sort Algorithms');
(*Fill test arrays - will be reused for all tests*)
FillArray(aOrigDesc, 2);
(*SelectionSort*)
(*array sorted ascending*)
InitStatistics;
CopyArray(aOrigDesc, a);
WriteArray(a);
StartTimer;
ShellSort1(a, 1, maxArrLen);
StopTimer;
WriteLn('ElapsedTime: ', ElapsedSecs);
WriteArray(a);
WriteStatistics('SelectionSort (sorted ascending)');
WriteLn;
WriteLn('Testing Sort Algorithms');
(*Fill test arrays - will be reused for all tests*)
FillArray(aOrigRand, 3);
(*SelectionSort*)
(*array sorted ascending*)
InitStatistics;
CopyArray(aOrigRand, a);
WriteArray(a);
StartTimer;
QucikSort(a, 1, maxArrLen);
StopTimer;
WriteLn('ElapsedTime: ', ElapsedSecs);
WriteArray(a);
WriteStatistics('SelectionSort (sorted ascending)');
WriteLn;
END. (*SortPgm*) |
unit uSettings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Buttons, Registry;
type
TfSettings = class(TForm)
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
Panel1: TPanel;
edFileName: TEdit;
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
procedure Load;
procedure Save;
public
class function Settings: TModalResult;
end;
implementation
{$R *.dfm}
const
RegPath = 'Software\Barbaris\Starter';
procedure TfSettings.Save;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey(RegPath, true) then
begin
Reg.WriteString('FileName', edFileName.Text);
end;
Reg.CloseKey;
finally
Reg.Free;
end;
end;
procedure TfSettings.Load;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKeyReadOnly(RegPath) then
begin
edFileName.Text := Reg.ReadString('FileName');
end;
Reg.CloseKey;
finally
Reg.Free;
end;
end;
class function TfSettings.Settings(): TModalResult;
var
fSettings: TfSettings;
begin
fSettings := TfSettings.Create(nil);
try
fSettings.Load;
fSettings.ShowModal;
if fSettings.ModalResult = mrOk then
begin
fSettings.Save;
end;
finally
FreeAndNil(fSettings);
end;
end;
procedure TfSettings.Button1Click(Sender: TObject);
var
dlg: TOpenDialog;
begin
dlg := TOpenDialog.Create(Self);
try
if dlg.Execute then
begin
edFileName.Text := dlg.FileName;
end;
finally
FreeAndNil(dlg);
end;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2017 Kike Pérez
Unit : Quick.Base64
Description : Base64 functions
Author : Kike Pérez
Version : 1.1
Created : 08/11/2017
Modified : 14/08/2018
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Base64;
{$i QuickLib.inc}
interface
uses
System.SysUtils,
{$IFDEF DELPHIXE7_UP}
System.NetEncoding;
{$ELSE}
IdCoderMIME,
IdGlobal;
{$ENDIF}
function Base64Encode(const Input: string): string;
function Base64Decode(const Input: string): string;
{$IFDEF DELPHIXE7_UP}
function Base64DecodeFromBinary(const Input: string) : string;
function Base64DecodeToBytes(const Input: string) : TBytes;
{$ENDIF}
implementation
function Base64Encode(const Input: string): string;
begin
{$IFDEF DELPHIXE7_UP}
Result := TNetEncoding.Base64.Encode(Input);
{$ELSE}
Result := TIdEncoderMIME.EncodeString(Input,IndyTextEncoding_OSDefault);
{$ENDIF}
end;
function Base64Decode(const Input: string): string;
begin
{$IFDEF DELPHIXE7_UP}
Result := TNetEncoding.Base64.Decode(Input);
{$ELSE}
Result := TIdDecoderMIME.DecodeString(Input,IndyTextEncoding_OSDefault);
{$ENDIF}
end;
{$IFDEF DELPHIXE7_UP}
function Base64DecodeFromBinary(const Input: string) : string;
var
b : TBytes;
begin
b := TNetEncoding.Base64.DecodeStringToBytes(Input);
Result := TEncoding.ANSI.GetString(b);
end;
function Base64DecodeToBytes(const Input: string) : TBytes;
begin
Result := TNetEncoding.Base64.DecodeStringToBytes(Input);
end;
{$ENDIF}
end.
|
unit Pessoa;
interface
uses RttiUtils;
type
TOnSalvar = procedure (Sender : TObject) of object;
TPessoa = class
private
FIdade: Integer;
FNome: String;
FSalvar: TOnSalvar;
FEndereco: String;
procedure SetIdade(const Value: Integer);
procedure SetNome(const Value: String);
procedure SetSalvar(const Value: TOnSalvar);
procedure SetEndereco(const Value: String);
public
[Form(tcEdit, 'Nome', 350)]
property Nome : String read FNome write SetNome;
[Form(tcEdit, 'Idade', 350)]
property Idade : Integer read FIdade write SetIdade;
[Form(tcMemo, 'Endereco', 350)]
property Endereco : String read FEndereco write SetEndereco;
[Form(tcButton, 'Salvar', 350)]
property Salvar : TOnSalvar read FSalvar write SetSalvar;
end;
implementation
{ TPessoa }
procedure TPessoa.SetEndereco(const Value: String);
begin
FEndereco := Value;
end;
procedure TPessoa.SetIdade(const Value: Integer);
begin
FIdade := Value;
end;
procedure TPessoa.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TPessoa.SetSalvar(const Value: TOnSalvar);
begin
FSalvar := Value;
end;
end.
|
unit TestCommonsU;
interface
uses
DUnitX.TestFramework;
type
TTestCommons = class(TTestCase)
private
FirstRec: Integer;
LastRec: Integer;
ExpectedFirstRec: Integer;
ExpectedLastRec: Integer;
Page: Integer;
published
procedure TestGetLimitByPagePage0;
procedure TestGetLimitByPagePage1;
procedure TestGetLimitByPagePage2;
procedure TestGetLimitByPagePage3;
end;
implementation
{ TTestCommons }
uses CommonsU;
procedure TTestCommons.TestGetLimitByPagePage0;
begin
Page := 0;
ExpectedException := EWrongPage;
GetLimitByPage(Page, FirstRec, LastRec);
end;
procedure TTestCommons.TestGetLimitByPagePage1;
begin
Page := 1;
ExpectedFirstRec := 1;
ExpectedLastRec := 10;
GetLimitByPage(Page, FirstRec, LastRec);
CheckEquals(ExpectedFirstRec, FirstRec, 'FirstRec');
CheckEquals(ExpectedLastRec, LastRec, 'LastRec');
end;
procedure TTestCommons.TestGetLimitByPagePage2;
begin
Page := 2;
ExpectedFirstRec := 11;
ExpectedLastRec := 20;
GetLimitByPage(Page, FirstRec, LastRec);
CheckEquals(ExpectedFirstRec, FirstRec, 'FirstRec');
CheckEquals(ExpectedLastRec, LastRec, 'LastRec');
end;
procedure TTestCommons.TestGetLimitByPagePage3;
begin
Page := 3;
ExpectedFirstRec := 21;
ExpectedLastRec := 30;
GetLimitByPage(Page, FirstRec, LastRec);
CheckEquals(ExpectedFirstRec, FirstRec, 'FirstRec');
CheckEquals(ExpectedLastRec, LastRec, 'LastRec');
end;
initialization
// Register any test cases with the test runner
DUnitX.RegisterTestFixture(TTestCommons);
end.
|
unit uRunCmd;
interface
uses
System.SysUtils, System.Classes, System.Generics.Collections, System.Types,
System.DateUtils,
Winapi.Windows
//
;
const
CMD_READ_INTERVAL = 1000;
type
TRunCmd = class(TThread)
private
FCmd: string;
FProcess: THandle;
FStdOutBuf: AnsiString;
FStdOutList: TStringList;
FStrOutNewLine: Boolean;
function StartCmd: Boolean;
procedure AddStrOut(const ABuf: AnsiString);
public
constructor Create(const ACmd: string; const AOnDone: TNotifyEvent);
destructor Destroy; override;
property StdOut: TStringList read FStdOutList;
protected
procedure Execute; override;
end;
implementation
uses
System.Math,
//
// System.AnsiStrings,
AcedCommon, AcedStrings,
//
uStringUtils, uGlobalFunctions;
function StrReadLn(var ABuf: AnsiString; out AOutLine: AnsiString): Boolean;
begin
Result := (ABuf <> '') and (ABuf[Length(ABuf)] = #10);
AOutLine := StrCut(ABuf, [#10]);
Result := Result or (ABuf <> '')
end;
{ TSshThread }
constructor TRunCmd.Create(const ACmd: string; const AOnDone: TNotifyEvent);
begin
FCmd := ACmd;
inherited Create(True);
FStdOutBuf := '';
FStdOutList := TStringList.Create;
FStrOutNewLine := True;
OnTerminate := AOnDone
end;
destructor TRunCmd.Destroy;
begin
FStdOutList.Free;
inherited;
end;
procedure TRunCmd.AddStrOut(const ABuf: AnsiString);
var z: AnsiString;
procedure AddLine;
var s,ss: string;
begin
s := string(z);
s := s.TrimRight([#13]);
if FStrOutNewLine then
begin
FStdOutList.Add(s)
end
else
begin
if FStdOutList.Count = 0 then
begin
FStdOutList.Add(s)
end
else
begin
ss := FStdOutList[FStdOutList.Count - 1] + s;
FStdOutList[FStdOutList.Count - 1] := ss;
end;
end;
end;
begin
FStdOutBuf := FStdOutBuf + ABuf;
while StrReadLn(FStdOutBuf, z) do
begin
AddLine();
FStrOutNewLine := True
end;
if z <> '' then
begin
AddLine();
FStrOutNewLine := False
end
end;
procedure TRunCmd.Execute;
begin
StartCmd()
end;
function TRunCmd.StartCmd: Boolean;
const
CReadBuffer = 900;
var
saSecurity: TSecurityAttributes;
hRead: THandle;
hWrite: THandle;
suiStartup: TStartupInfo;
piProcess: TProcessInformation;
pBuffer: array[0..CReadBuffer] of AnsiChar;
dRead: DWord;
dRunning: DWord;
l_bol: BOOL;
begin
Result := False;
FProcess := INVALID_HANDLE_VALUE;
saSecurity.nLength := SizeOf(TSecurityAttributes);
saSecurity.bInheritHandle := True;
saSecurity.lpSecurityDescriptor := nil;
if CreatePipe(hRead, hWrite, @saSecurity, 0) then
begin
try
FillChar(suiStartup, SizeOf(TStartupInfo), #0);
suiStartup.cb := SizeOf(TStartupInfo);
suiStartup.hStdInput := hRead;
suiStartup.hStdOutput := hWrite;
suiStartup.hStdError := hWrite;
suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
suiStartup.wShowWindow := SW_HIDE;
l_bol := CreateProcess(nil, PChar(FCmd), @saSecurity,
@saSecurity, True, NORMAL_PRIORITY_CLASS,
nil, nil, suiStartup, piProcess);
try
if l_bol then
begin
FProcess := piProcess.hProcess;
repeat
dRunning := WaitForSingleObject(piProcess.hProcess, CMD_READ_INTERVAL);
if Terminated then
Break;
repeat
if Terminated then
Break;
dRead := 0;
if not PeekNamedPipe(hRead, nil, 0, nil, @dRead, nil) then
Break;
if dRead = 0 then
Break;
if dRead > CReadBuffer then
dRead := CReadBuffer;
ReadFile(hRead, pBuffer[0], dRead, dRead, nil);
pBuffer[dRead] := #0;
OemToAnsi(pBuffer, pBuffer);
AddStrOut(PAnsiChar(@pBuffer[0]));
until (dRead < CReadBuffer);
until (dRunning <> WAIT_TIMEOUT) or (Terminated);
AddStrOut(#10);
TerminateProcess(piProcess.hProcess, 0);
FProcess := INVALID_HANDLE_VALUE;
Result := True;
end
finally
CloseHandle(piProcess.hProcess);
CloseHandle(piProcess.hThread);
end
finally
CloseHandle(hRead);
CloseHandle(hWrite);
end;
end;
end;
end.
|
unit GX_GxUtils;
{ This unit encapsulates a few utility routines that are
specific to GExperts.
Other units, such as GX_GenericUtils and GX_IdeUtils,
contain routines that do not make use of any GExperts-
specific functionality.
}
interface
{$I GX_CondDefine.inc}
uses
Graphics,
{$IFNDEF GX_VER170_up}GXHtmlHelp,{$ENDIF}
Controls;
// Returns True if the binary this function is called from
// has been linked against various packages; at this time,
// these packages are VCL, VCLX, DESIGNIDE, etc.
function BuiltWithPackages: Boolean;
// Show a message box notifying the user that an application
// has not been built with packages.
procedure ShowNoPackagesError;
// Load bitmap with name FileName from disk; returns True
// if loading was successful ; False otherwise with TargetBitmap
// being undefined.
function GxLoadBitmapForExpert(const BitmapFile: string; var TargetBitmap: Graphics.TBitmap): Boolean;
function GxLoadBitmapFromResource(const ResName: string; var TargetBitmap: Graphics.TBitmap): Boolean;
function GxLoadBitmapFromFile(FileName: string; var TargetBitmap: Graphics.TBitmap): Boolean;
procedure GxContextHelp(const HelpOwner: TWinControl; const ContextID: Integer);
procedure GxContextHelpContents(const HelpOwner: TWinControl);
procedure GxSetDefaultFont(Control: TControl);
// Determine what runtime features are available to be exposed or disabled
// These are dependent on the IDE version, etc.
function ComponentPaletteAvailable: Boolean;
function MultilineTabDockHostPossible: Boolean;
function EditorEnhancementsPossible: Boolean;
const
GXTransparencyColor = $00FF00FF; // Defines the background of some bitmaps
implementation
uses
Windows, SysUtils, Forms,
DdeMan, // Needed to test for linking against VCLX package.
GX_VerDepConst, GX_GenericUtils, GX_ConfigurationInfo, GX_IdeUtils;
function BuiltWithPackages: Boolean;
var
IsNotInInstance: Boolean;
begin
Result := True;
IsNotInInstance := (LongWord(FindClassHInstance(TForm)) <> HINSTANCE); // VCL and VisualClx
Result := Result and IsNotInInstance;
IsNotInInstance := (LongWord(FindClassHInstance(TDdeServerConv)) <> HINSTANCE); // VCLX
Result := Result and IsNotInInstance;
end;
procedure ShowNoPackagesError;
resourcestring
SGxBuildError = 'GExperts build error';
SNotBuiltWithRequiredPackages =
'GExperts has not been built with the required runtime packages ' + sLineBreak +
sLineBreak +
RequiredPackageText + sLineBreak +
sLineBreak +
'Please add these packages to the list of used runtime packages, '+
'check the "Build with runtime packages" box, and rebuild GExperts.' + sLineBreak +
sLineBreak +
'GExperts will not be installed into the IDE until this has been done.';
begin
Windows.MessageBox(0, PChar(SNotBuiltWithRequiredPackages),
PChar(SGxBuildError), MB_OK or MB_ICONERROR);
end;
function GxLoadBitmapForExpert(const BitmapFile: string; var TargetBitmap: Graphics.TBitmap): Boolean;
begin
Result := GxLoadBitmapFromFile(BitmapFile, TargetBitmap);
if not Result then
Result := GxLoadBitmapFromResource(BitmapFile, TargetBitmap);
if not Result then
FreeAndNil(TargetBitmap);
end;
function GxLoadBitmapFromResource(const ResName: string; var TargetBitmap: Graphics.TBitmap): Boolean;
begin
Result := False;
try
FreeAndNil(TargetBitmap);
TargetBitmap := Graphics.TBitmap.Create;
TargetBitmap.LoadFromResourceName(HInstance, ResName);
Result := True;
except //FI:W501
// Swallow exceptions and report the failure
end;
end;
function GxLoadBitmapFromFile(FileName: string; var TargetBitmap: Graphics.TBitmap): Boolean;
begin
Result := False;
try
FileName := AddSlash(ConfigInfo.GExpertsPath) +
AddSlash('Icons') + FileName;
if ExtractFileExt(FileName) = '' then
FileName := ChangeFileExt(FileName, '.bmp');
if FileExists(FileName) then
begin
FreeAndNil(TargetBitmap);
TargetBitmap := Graphics.TBitmap.Create;
TargetBitmap.LoadFromFile(FileName);
Result := True;
end;
except //FI:W501
// Swallow exceptions and report the failure
end;
end;
procedure CallWinHelp(const Command, ContextID: Integer; const HelpOwner: TWinControl);
begin
if FileExists(ConfigInfo.HelpFile) then
// The 0 allows the help to drop behind the IDE
HtmlHelp(0, PChar(ConfigInfo.HelpFile), Command, ContextID)
else
raise Exception.Create('The configured help file is missing: ' + ConfigInfo.HelpFile);
end;
procedure GxContextHelpContents(const HelpOwner: TWinControl);
begin
CallWinHelp(HH_DISPLAY_INDEX, 0, HelpOwner);
end;
procedure GxContextHelp(const HelpOwner: TWinControl; const ContextID: Integer);
begin
CallWinHelp(HH_HELP_CONTEXT, ContextID, HelpOwner);
end;
function ComponentPaletteAvailable: Boolean;
begin
Result := not RunningDelphi8OrGreater;
end;
function MultilineTabDockHostPossible: Boolean;
begin
Result := not RunningDelphi8OrGreater;
end;
function EditorEnhancementsPossible: Boolean;
begin
{$IFDEF GX_EditorEnhancements}
Result := True;
{$ELSE not GX_EditorEnhancements}
Result := False;
{$ENDIF}
end;
type
TControlCracker = class(TControl);
procedure GxSetDefaultFont(Control: TControl);
begin
if ConfigInfo.EnableCustomFont then
TControlCracker(Control).Font.Assign(ConfigInfo.CustomFont)
else
SetDefaultFont(Control);
end;
end.
|
unit Constants;
interface
uses Classes, IdGlobal, SysUtils;
type
MsgType = (
MsgTypeInvalid = 0, //Недопустимый тип пакета
MsgTypePing = 1,
MsgTypePong,
MsgTypeConfirm,
MsgTypeHello, //Запрос соединения
MsgTypeError, //Ошибка
MsgTypeBadSession, //Неактивная сессия
MsgTypeAccept, //- принятие запроса на соединение с сервером
MsgTypeLogon, //принятие логина и пароля
MsgTypeNoLogon, //отклонение логина и пароля
MsgTypeCommand, // Комманда
MsgTypeVersionErr, //не допустимая версия клиента
MsgTypeEvent, //Событие
MsgTypeCount, // кол-во частей строки
MsgTypeSetKopState,
MsgTypeSetZoneState,
MsgTypeSetZonesStates,
MsgTypeGetHistory,
MsgTypeDataPack,
MsgTypeLastPacket
);
type TAlarmTypes = (
// типы тревог
AtAlarm,
AtAlarmForce,
AtNoTest,
AtDrawDown,
AtDmgDevice,
AtDmgLink,
AtDmgPower,
AtLast
);
type TDevSourses = (
PrdSrc = 1, //Передатчик
PpkSrc, //ППКОП
ZoneSrc, //Зона
SysSrc, //Система
PultSrc); //Пульт
type TDamageTypes = (
DmgTypeLink, // авария связи
DmgTypePwr, // авария питания
DmgTypeDev); // авария оборудования
// DmgTypeBody = 4; // авария корпуса
// DmgTypeTest = 5; // пропуск теста
type TEventTypes = (
EvTypeArm, //тип события Взят
EvTypeDisArm, //тип события Снят
EvTypeAlarm, //тип события Тревога
EvTypeMessage, //тип события Сообщение
EvTypeError, //тип события Ошибка
EvTypeAttention, //тип события Внимание
EvTypeDamage, //тип события Авария
EvTypeRepair, //тип события Устранение аварии
EvTypeTestDown, //тип события Пропуск теста
EvTypeTestUp, //тип события Тест
EvTypePreAlarm, //тип события Сработка
EvTypeCommand, //тип события команда
EvTypeDropAlarm, //тип события сброс тревоги
EvTypePatrol, //тип события патруль
EvTypeQueryToArm, //тип события запрос на взятие
EvTypeQueryToDisArm, //тип события запрос на снятие
EvTypeLast);
// EvTypeForceAlarm = 16; //тип события тревога принуждение
// EvTypeDisarmByRequest= 18; //Снят при опросе
// EvTypeArmByRequest = 19; //Взят при опросе
// EvTypeAlarmPanic = 20; //Тревожная кнопка
// EvTypeAlarmFire = 21; //Пожар
// EvTypeArmByCmd = 22; //Взят после команды
// EvTypeDisArmByCmd = 23; //Снят после команды
// EvTypeAlarmByRequest = 24; //Тревога при опросе
type TEventSet = set of TEventTypes;
type CmdTypesToApp = ( // типы команд приложению
CmdFirst = 0,
CmdReloadData, // перегрузка данных
CmdResetConn, // переподключиться к серверу
CmdCloseApp,
CmdBackStart,
CmdDelAlarm,
CmdAddAlarm,
CmdLast); // завершить работу
type SysCodes = (
EventTypeNone,
EventTypeSystemStart, //Сброс процессора(при загрузке)
EventTypeConfigChanged, //Изменены настройки
EventTypeFirmwareUpdated, //Обновлена прошивка
EventTypeChanellChanged, //Переключение канала связи
EventTypePowerSwitchToBackup, //переход на АКБ
EventTypePowerSwitchToMain, //переход на основное питание
EventTypeGuardSensorSet, //Взят шлейф
EventTypeGuardSensorUnset, //Снят шлейф
EventTypeGuardSensorAlarm, //Тревога шлейф
EventTypeGuardSensorNoSetAlarm, //Тревога не взят
EventTypeGuardSensorNoSet, //Не взят
EventTypeGuardSensorNoUnset, //Не снят
EventTypeAlarmSensorAlarm, //Тревога шлейфа
EventTypeAlarmSensorRestore, //Восстановление шлейфа
EventTypeAlarmPowerOn, //Тревога включения питания
EventTypeFireSensorDefectShort, //Неисправность КЗ пожарного шлейфа
EventTypeFireSensorDefectBreak, //Неисправность Обрыв пожарного шлейфа
EventTypeSmokeSensorAlarm, //Срабатывание дымового датчика
EventTypeFireSensorAlarm, //Срабатывание пожарного датчика
EventTypeFireShort, //Пожар КЗ
EventTypeFireBreak, //Пожар обрыв
EventTypeFireRestore, //Восстановление пожарного датчика
EventTypeSensorBadReset, //Неудачное перевзятие шлейфа
EventTypeSensorSetNotAvailable, //Не взят (не доступно)
EventTypeSensorUnsetNotAvailable, //Не снят (не доступно)
EventTypeCaseOpened, //Корпус вскрыт
EventTypeCaseClosed, //Корпус закрыт
EventTypePatrulAlarm, //Срабатывание датчика отметки патруля
EventTypePatrulRestore, //Восстановление датчика отметки патруля
EventTypeOutputShort, //Обрыв выхода
EventTypeOutputRestore, //Восстановление выхода
EventTypeBackupChanellError, //Ошибка проверки резервного канала
EventTypeArmed, //Взят
EventTypeDisArmed, //Снят
EventTypeAlarm, //Тревога
EventTypeDamageSensor, //Неисправность ШС
EventTypeAlarmForce, //Тревога принуждение
EventTypeDamageBattery, //Разряд АКБ
EventTypeRestoreBattery, //Восстановление АКБ
EventTypeDamagePower, //Отключение 220
EventTypeRestorePower, //Восстановление 220
EventTypeTest, //Тест периодический
EventTypeTestLoss, //Пропуск теста
EventTypeAttention, //Внимание
EventTypePatrol, //Отметка наряда
EventTypeNotice, //Извещение
EventTypeError, //Ошибка
EventTypeCaution, //Предупреждение
EventTypeCommand, //Команда
EventTypeDamageDevice, //Авария оборудования
EventTypeRestoreDevice, //Устранение аварии оборудования
EventTypeDamageLink, //Авария связи
EventTypeRestoreLink, //Устранение аварии связи
EventTypeArmedByDuty, //Взят оператором
EventTypeDisArmedByDuty, //Снят оператором
EventTypeConnectPC, //Подключился АРМ
EventTypeDisConnectPC, //Отключился АРМ
EventTypeArmedByQuery, //Взят при опросе
EventTypeDisArmedByQuery, //Снят при опросе
EventTypeAlarmByQuery, //Тревога при опросе
EventTypeDamageByQuery, //Авария при опросе
EventTypeDrawDown, //Сработка
EventTypeArmQueryDenied, //Запрос на взятие отклонен
EventTypeDisarmQueryDenied, //Запрос на снятие отклонен
EventTypeCmdArm, //Взять под охрану
EventTypeCmdDisArm, //Снять с охраны
EventTypeCmdQueryStatus, //Запросить состояние
EventTypeCmdNotExecute, //Команда не выполнена
EventTypeSessionStart, //Старт сессии
EventTypeIPChange, //Смена IP адреса
EventTypeAlarmDroped, //Сброс тревоги
EventTypeDamageDeviceDroped, //Сброс аварии оборудования
EventTypeDamageLinkDroped, //Сброс аварии связи
EventTypeDamagePowerDroped, //Сброс аварии питания
EventTypeTestLossDroped, //Сброс пропуска теста
EventTypeCmdAlarmDrop, //Сбросить тревогу/аварию
EventTypeDeviceNotActive, //Прибор не активен
EventTypeQueryToArm, //Запрос на взятие
EventTypeQueryToDisarm, //Запрос на снятие
EventTypeStatusGet, //Получено состояние
EventTypeKeyNotFound, //Идентификатор не опознан
EventTypeCmdChangeSim, //Команда сменить СИМ
EventTypeServiceMessage, //Служебное
EventTypeAlarmToLong, //Перевод тревоги в долговременную
EventTypeChangeDB, //Изменение БД
EventTypeTechnologyRestore, //Восстановление технологического ШС
EventTypeTechnologyAlarm //Нарушение технологического ШС
);
type DevClasses = (
DevClassNone,
DevClassPrd,
DevClassPpk,
DevClassZone,
DevClassRelay,
DevClassControl,
DevClassSystem,
DevClassGroup,
DevClassApplication,
DevClassSection,
DevClassDriverGSM,
DevClassDriverInet,
DevClassDriverMobilDevice,
DevClassDriverOrion,
DevClassDriverRadio,
DevClassRadioPcn,
DevClassRadioRX,
DevClassCore);
const
InvalidID = -1;
BadSession = 0;
UnixStartDate: TDateTime = 25569.0;
PcnStateDown = 0;
PcnStateWork = 1;
PcnStateUnknow = 3;
tbADRESES = 'ADRESES';
tbALARMS = 'ALARMS';
tbCOLORS = 'COLORS';
tbCOMBINE = 'COMBINE';
tbRX = 'CONTROLS';
tbCUST = 'CUST';
tbDEVICES = 'DEVICES';
tbDEV_TYPES = 'DEV_TYPES';
tbDISTRICTS = 'DISTRICTS';
tbEVENT_CODES = 'EVENT_CODES';
tbGROUPS = 'GROUPS';
tbLARS_CODES = 'LARS_CODES';
tbLOCALS = 'LOCALS';
tbOBJ_EVENTS = 'OBJ_EVENTS';
tbOBJ_LINKS = 'OBJ_LINKS';
tbORGS = 'ORGS';
tbPHONES = 'PHONES';
tbREPORTS = 'REPORTS';
tbSCRIPTS = 'SCRIPTS';
tbSCRIPTS_CMD = 'SCRIPTS_CMD';
tbSECTIONS = 'SECTIONS';
tbSECTION_ZONES = 'SECTION_ZONES';
tbSETTINGS = 'SETTINGS';
tbSTREETS = 'STREETS';
tbTEST = 'TESTS';
tbTIMESPACES = 'TIMESPACES';
tbXO = 'XO';
tbXO_KEYS = 'XO_KEYS';
tbXO_USERS = 'XO_USERS';
tbZONE_TIMESPACES = 'ZONE_TIMESPACES';
tbZONE_XO = 'ZONE_XO';
tbZONE_XO_KEYS = 'ZONE_XO_KEYS';
tbDEV_STATES = 'DEV_STATES';
PultTypeRadioDriver = 400;
PultTypeGSM = 401;
PultTypeInet = 402;
PultTypePcnProton = 403;
PultTypePcnLars = 404;
PultTypeRadioProton = 405;
PultTypeRadioProtonOnLars = 406;
PultTypeRadioLars = 407;
AppTypeCore = 600;
AppTypeDPCO = 601;
AppTypeRaport = 602;
AppTypeCoordinator = 603;
AppTypeAnyPcnDriver = 604;
IoModeWrite = 1;
IoModeRead = 0;
PCN_TYPE_FRIGATE = 0;
PCN_TYPE_PRITOK = 1;
PCN_TYPE_PROTON = 2;
ORG_TYPE_ORG = 0;
ORG_TYPE_KONTR = 1;
ORG_TYPE_SUPPORT = 2;
TrueBit = 1;
FalseBit = 0;
StateOff = 0;
StateOnn = 1;
MESSAGE_NONE = 'none';
MESSAGE_HELLO = 'hello';
MESSAGE_GOODBYE = 'goodbye';
MESSAGE_PING = 'ping';
MESSAGE_PONG = 'pong';
MESSAGE_SETDATA = 'setdata';
MESSAGE_ERROR = 'error';
MESSAGE_NOTREADY = 'not_ready';
MESSAGE_CONFIRM = 'confirm';
MESSAGE_ACCEPT = 'accept';
MESSAGE_EVENT = 'event';
MESSAGE_ADD_ALARM = 'add_alarm';
MESSAGE_DEL_ALARM = 'del_alarm';
MESSAGE_UP_STATE = 'up_state';
MESSAGE_SEND_MAIL = 'send_mail';
MESSAGE_RESET = 'reset';
KEY_REC_COUNT = 'rec_count';
KEY_ARRAY = 'array';
KEY_UID = 'uid';
KEY_MES_TYPE = 'mes_type';
KEY_MES_TEXT = 'mes_text';
KEY_CLIENT_TYPE = 'client_type';
KEY_DATAVERS = 'data_vers';
KEY_USER_ID = 'user_id';
KEY_DATA = 'data';
KEY_DEV_CLASS = 'dev_class';
KEY_DEV_TYPE = 'dev_type';
KEY_DEV_ID = 'dev_id';
KEY_RX_TYPE = 'rx_type';
KEY_RX_ID = 'rx_id';
KEY_ADD_INFO = 'add_info';
KEY_COMMANDS = 'commands';
KEY_EVENTS = 'events';
KEY_MAIN = 'main';
KEY_NAME = 'name';
KEY_ID = 'id';
KEY_ID_CUST = 'id_cust';
KEY_XO_ID = 'xo_id';
KEY_SYS_MES = 'sys_mes';
KEY_SIGNAL = 'signal';
KEY_DATE_TIME = 'date_time';
KEY_CHANGES = 'changes';
KEY_COM_PORT = 'com_port';
KEY_RATE = 'rate';
CLIENT_MONITOR = '1c_monitor';
CLIENT_RAPORT = '1c_raport';
CLIENT_RADIODRV = 'radio_drv';
CLIENT_INETDRV = 'inet_drv';
CLIENT_GSMDRV = 'gsm_drv';
CLIENT_OPER = '1c_oper';
CLIENT_COORDINATOR = '1c_coordinator';
implementation
end.
|
unit mdprottypes;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, mdTypes;
type
{ funciton structures }
PMD_BEGIN = ^TMD_BEGIN;
TMD_BEGIN = record
dev: TMD_DEVICE_ID;
cmd: word;
len: word;
end;
{ function md_stop_all_rotors }
PMD_STOP_ALL_ROTORS_REQ = ^TMD_STOP_ALL_ROTORS_REQ;
TMD_STOP_ALL_ROTORS_REQ = record
rBegin: TMD_BEGIN;
rApp: TMD_APP_ID;
aEmpty: array [0..2] of byte;
bXor: byte;
end;
PMD_STOP_ALL_ROTORS_ANS = ^TMD_STOP_ALL_ROTORS_ANS;
TMD_STOP_ALL_ROTORS_ANS = record
rBegin: TMD_BEGIN;
wEmpty: word;
bState: byte;
bXor: byte;
end;
{ function md_stop_rotor }
PMD_STOP_ROTOR_REQ = ^TMD_STOP_ROTOR_REQ;
TMD_STOP_ROTOR_REQ = record
rBegin: TMD_BEGIN;
rApp: TMD_APP_ID;
wEmpty: word;
bRotor: byte;
bXor: byte;
end;
PMD_STOP_ROTOR_ANS = ^TMD_STOP_ROTOR_ANS;
TMD_STOP_ROTOR_ANS = record
rBegin: TMD_BEGIN;
bEmpty: byte;
bRotor: byte;
bState: byte;
bXor: byte;
end;
PMD_LOGON_REQ = ^TMD_LOGON_REQ;
TMD_LOGON_REQ = record
rBegin: TMD_BEGIN;
rApp: TMD_APP_ID;
aEmpty: array [0..2] of byte;
bXor: byte;
end;
PMD_LOGON_ANS = ^TMD_LOGON_ANS;
TMD_LOGON_ANS = record
rBegin: TMD_BEGIN;
wEmpty: word;
bState: byte;
bXor: byte;
end;
PMD_GET_CONFIG_REQ = ^TMD_GET_CONFIG_REQ;
TMD_GET_CONFIG_REQ = record
rBegin: TMD_BEGIN;
aReserved: array [0..2] of byte;
bXOR: byte;
end;
PMD_GET_CONFIG_ANS = ^TMD_GET_CONFIG_ANS;
TMD_GET_CONFIG_ANS = record
rBegin: TMD_BEGIN;
rConfig: TMD_CONFIG;
wReserved: word;
bState: byte;
bXOR: byte;
end;
PMD_SET_CONFIG_REQ = ^TMD_SET_CONFIG_REQ;
TMD_SET_CONFIG_REQ = record
rBegin: TMD_BEGIN;
rApp: TMD_APP_ID;
rConfig: TMD_CONFIG;
bReserved: byte;
bXOR: byte;
end;
PMD_SET_CONFIG_ANS = ^TMD_SET_CONFIG_ANS;
TMD_SET_CONFIG_ANS = record
rBegin: TMD_BEGIN;
wReserved: word;
bState: byte;
bXOR: byte;
end;
PMD_GET_MOTOR_CONFIG_REQ = ^TMD_GET_MOTOR_CONFIG_REQ;
TMD_GET_MOTOR_CONFIG_REQ = record
rBegin: TMD_BEGIN;
rotorIx: word;
bReserved: byte;
bXOR: byte;
end;
PMD_GET_MOTOR_CONFIG_ANS = ^TMD_GET_MOTOR_CONFIG_ANS;
TMD_GET_MOTOR_CONFIG_ANS = record
rBegin: TMD_BEGIN;
rConfig: TMD_ROTOR_CONFIG;
rotorIx: word;
bState: byte;
bXOR: byte;
end;
PMD_SET_MOTOR_CONFIG_REQ = ^TMD_SET_MOTOR_CONFIG_REQ;
TMD_SET_MOTOR_CONFIG_REQ = record
rBegin: TMD_BEGIN;
rApp: TMD_APP_ID;
rConfig: TMD_ROTOR_CONFIG;
rotorIx: word;
bReserved: byte;
bXOR: byte;
end;
PMD_SET_MOTOR_CONFIG_ANS = ^TMD_SET_MOTOR_CONFIG_ANS;
TMD_SET_MOTOR_CONFIG_ANS = record
rBegin: TMD_BEGIN;
rotorIx: word;
bState: byte;
bXOR: byte;
end;
PMD_GET_ROTOR_ANGLE_REQ = ^TMD_GET_ROTOR_ANGLE_REQ;
TMD_GET_ROTOR_ANGLE_REQ = record
rBegin: TMD_BEGIN;
rotorIx: word;
bReserved: byte;
bXOR: byte;
end;
PMD_GET_ROTOR_ANGLE_ANS = ^TMD_GET_ROTOR_ANGLE_ANS;
TMD_GET_ROTOR_ANGLE_ANS = record
rBegin: TMD_BEGIN;
angle: single;
rotorIx: word;
bState: byte;
bXOR: byte;
end;
PMD_SET_ROTOR_ANGLE_REQ = ^TMD_SET_ROTOR_ANGLE_REQ;
TMD_SET_ROTOR_ANGLE_REQ = record
rBegin: TMD_BEGIN;
rApp: TMD_APP_ID;
angle: single;
rotorIx: word;
bCalibration: byte;
bXOR: byte;
end;
PMD_SET_ROTOR_ANGLE_ANS = ^TMD_SET_ROTOR_ANGLE_ANS;
TMD_SET_ROTOR_ANGLE_ANS = record
rBegin: TMD_BEGIN;
wReserved: word;
bState: byte;
bXOR: byte;
end;
PMD_GET_ROTORS_ANGLES_REQ = ^TMD_GET_ROTORS_ANGLES_REQ;
TMD_GET_ROTORS_ANGLES_REQ = record
rBegin: TMD_BEGIN;
startMotorIx: word;
bReserved: byte;
bXOR: byte;
end;
PMD_GET_ROTORS_ANGLES_ANS = ^TMD_GET_ROTORS_ANGLES_ANS;
TMD_GET_ROTORS_ANGLES_ANS = record
rBegin: TMD_BEGIN;
angles: array[0..1] of single;
startMotorIx: word;
bState: byte;
bXOR: byte;
end;
PMD_SET_ROTORS_ANGLES_REQ = ^TMD_SET_ROTORS_ANGLES_REQ;
TMD_SET_ROTORS_ANGLES_REQ = record
rBegin: TMD_BEGIN;
rApp: TMD_APP_ID;
angles: array [0..1] of single;
startMotorIx: word;
bCalibration: byte;
bXOR: byte;
end;
PMD_SET_ROTORS_ANGLES_ANS = ^TMD_SET_ROTORS_ANGLES_ANS;
TMD_SET_ROTORS_ANGLES_ANS = record
rBegin: TMD_BEGIN;
wReserved: word;
bState: byte;
bXOR: byte;
end;
PMD_EL_MAP_REQ = ^TMD_EL_MAP_REQ;
TMD_EL_MAP_REQ = record
rBegin: TMD_BEGIN;
fromAngle: word;
toAngle: word;
aReserved: array[0..2] of byte;
bXOR: byte;
end;
PMD_EL_MAP_ANS = ^TMD_EL_MAP_ANS;
TMD_EL_MAP_ANS = record
rBegin: TMD_BEGIN;
fromAngle: word;
toAngle: word;
data: byte;
end;
const
{ COMMANDS }
MD_CMD_LOGIN = 1;
MD_CMD_LOGOUT = 2;
MD_CMD_GET_ROTOR_CONFIG = 3;
MD_CMD_SET_ROTOR_CONFIG = 4;
MD_CMD_GET_EL_MAP = 5;
MD_CMD_SET_EL_MAP = 6;
MD_CMD_GET_CONFIG = 9;
MD_CMD_SET_CONFIG = 10;
MD_CMD_GET_ROTOR_POS = 11;
MD_CMD_SET_ROTOR_POS = 12;
MD_CMD_GET_ALL_ROTOR_POS = 13;
MD_CMD_SET_ALL_ROTOR_POS = 14;
MD_CMD_STOP_ROTOR = 15;
MD_CMD_STOP_ALL_ROTORS = 16;
{ DEVICE ERRORS }
MD_DEV_NO_ERROR = 0;
MD_DEV_BUSY = 1;
MD_DEV_BAD_PARAMS = 2;
MD_DEV_XOR_ERROR = 3;
MD_DEV_CMD_NOT_SUPPORTED = 4;
implementation
end.
|
{
This is one of my favorite design patterns. To use it you provide prototype
instances during construction. These will then be used to create clones in the
factory. This provides extensibility where you have no access to the code
(like a user-defined extension or plug-in).
}
unit Prototype;
interface
uses
system.generics.collections;
type
IMaze = interface
function Clone: IMaze;
// rest of definition not important for illustration
end;
IWall = interface
function Clone: IWall;
// rest of definition not important for illustration
end;
IRoom = interface
function Clone: IRoom;
// rest of definition not important for illustration
end;
IDoor = interface
function Clone: IDoor;
procedure Initialize(AFromRoom, AToRoom: IRoom); // mutator
// rest of definition not important for illustration
end;
TMazePrototypeFactory = Class
private
FProtoMaze: IMaze;
FProtoWall: IWall;
FProtoRoom: IRoom;
FProtoDoor: IDoor;
public
constructor Create(AMaze: IMaze; AWall: IWall; ARoom: IRoom; ADoor: IDoor);
function MakeMaze: IMaze;
function MakeWall: IWall;
function MakeRoom(ANumber: integer): TList<IRoom>;
function MakeDoor(AFromRoom, AToRoom: IRoom): IDoor;
end;
// We can pass the factory as a parameter for example
// MazeGame.CreateMaze(AFactory);
// The game in turn can create the maze in an abstract way.
implementation
constructor TMazePrototypeFactory.Create(AMaze: IMaze; AWall: IWall; ARoom: IRoom; ADoor: IDoor);
begin
inherited Create;
FProtoMaze := AMaze;
FProtoWall := AWall;
FProtoRoom := ARoom;
FProtoDoor := ADoor;
end;
function TMazePrototypeFactory.MakeMaze: IMaze;
begin
result := FProtoMaze.Clone;
end;
function TMazePrototypeFactory.MakeWall: IWall;
begin
result := FProtoWall.Clone;
end;
function TMazePrototypeFactory.MakeRoom(ANumber: integer): TList<IRoom>;
var
I: Integer;
begin
for I := 1 to ANumber do
begin
Result.Add(FProtoRoom.Clone);
end;
end;
function TMazePrototypeFactory.MakeDoor(AFromRoom: IRoom; AToRoom: IRoom): IDoor;
begin
//Result := IDoor.Clone;
Result.Initialize(AFromRoom, AToRoom);
end;
end.
|
unit uClasse.Veiculo.Aereo.Helicoptero;
interface
uses
uClasse.Veiculo.Aereo, System.SysUtils, System.DateUtils;
type
THelicoptero = class(TAereo)
private
public
qtd_helices: integer;
possui_turbina: boolean; //tipo_aplicacao: militar/civil/resgate
function RetornaAplicacaoUso: string; override;
function RetornarProximaTrocaOleo: TDateTime; override;
end;
implementation
{ THelicoptero }
function THelicoptero.RetornaAplicacaoUso: string;
begin
result:= 'Veiculo Helicóptero: Aplicação Aéreo';
end;
function THelicoptero.RetornarProximaTrocaOleo: TDateTime;
begin
if DiasMaximoProximaTrocaOleo > 0 then
result:= StrToDateTime(FormatDateTime('dd.mm.yyyy', incDay(DataUltimaTrocaOleo, DiasMaximoProximaTrocaOleo)))
else
begin
raise Exception.Create('Quantidade de dias para próxima troca de óleo deve ser maior do que 0.');
abort;
end;
end;
end.
|
{-----------------------------------------------------------------------------
-----------------------回调函数转消息的基类和监控器---------------------------
-----------------------------------------------------------------------------}
unit VMsgMonitor;
interface
uses
Windows, Messages, SysUtils, Classes, Contnrs, TypInfo, SyncObjs;
type
//所有消息的基类
TVMsg = class(TPersistent)
private
FHandled: Boolean;
FNeedFree: Boolean;
FReturn: Integer;
public
constructor Create; virtual;
procedure Assign(Source: TPersistent); override;
function Clone: TVMsg;
published
property Handled: Boolean read FHandled write FHandled;
property NeedFree: Boolean read FNeedFree write FNeedFree;
property Return: Integer read FReturn write FReturn;
end;
//所有Stream消息的基类
TBaseStreamVMsg = class(TVMsg)
private
FStream: TMemoryStream;
function GetDataLen: Integer;
function GetDataMem: Pointer;
public
constructor Create; override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure WriteData(ADataMem: Pointer; ADataLen: Integer);
property DataLen: Integer read GetDataLen;
property DataMem: Pointer read GetDataMem;
end;
TUploadFileMsg = class (TVMsg)
private
FFileId:Integer;
public
property FileId: Integer read FFileId write FFileId;
end;
//所有具有附加对象的Stream消息的基类
TBaseAttachObjectStreamVMsg = class(TBaseStreamVMsg)
private
FAttachedObject: TObject;
FOwnsObject: Boolean;
public
destructor Destroy; override;
procedure AttachObject(AObject: TObject; AOwnsObject: Boolean);
property AttachedObject: TObject read FAttachedObject;
end;
TVMsgClass = class of TVMsg;
TVMsgHandlerEvent = procedure(Sender: TObject; AMsg: TVMsg) of object;
//消息处理函数类
TVMsgHandler = class(TObject)
private
FEvent: TVMsgHandlerEvent;
FOwner: TObject;
FOwnerClassName: WideString;
public
constructor Create(AOwner: TObject);
procedure Execute(AMsg: TVMsg);
property Owner: TObject read FOwner;
property OwnerClassName: WideString read FOwnerClassName;
property Event: TVMsgHandlerEvent read FEvent write FEvent;
end;
//消息处理函数对象列表
TVMsgHandlerList = class(TObjectList)
private
function GetItems(Index: Integer): TVMsgHandler;
public
procedure Execute(AMsg: TVMsg);
function FindOrNew(AOwner: TObject): TVMsgHandler;
function IndexOfOwner(AOwner: TObject): Integer;
procedure RemoveOwner(AOwner: TObject);
property Items[Index: Integer]: TVMsgHandler read GetItems; default;
end;
//消息监听器(一个消息下可以挂多个消息处理函数)
TVMsgListener = class(TObject)
private
FHandlerList: TVMsgHandlerList;
FVMsgClass: TVMsgClass;
public
constructor Create(AMsgClass: TVMsgClass);
destructor Destroy; override;
procedure DispatchMsg(AMsg: TVMsg; AOwner: TObject = nil);
property HandlerList: TVMsgHandlerList read FHandlerList;
property VMsgClass: TVMsgClass read FVMsgClass;
end;
//消息监听器列表
TVMsgListenerList = class(TObjectList)
private
function FindOrNew(AClass: TVMsgClass): TVMsgListener;
function GetItems(Index: Integer): TVMsgListener;
protected
procedure DispatchMsg(AMsg: TVMsg; AOwner: TObject = nil);
public
procedure RegMsg(AOwner: TObject; AClass: TVMsgClass;
AEvent: TVMsgHandlerEvent);
destructor Destroy; override;
function IndexOfVMsgClass(AClass: TClass): Integer;
procedure RemoveOwner(AOwner: TObject; AClass: TVMsgClass = nil);
property Items[Index: Integer]: TVMsgListener read GetItems; default;
end;
TLogTypeEnum = (
lteSend,
lteRecv
);
TLogEvent = procedure(Sender: TObject; AType: TLogTypeEnum;
const AText: WideString; ADataMem: Pointer; ADataLen: Integer) of object;
TVMsgMonitor = class(TObject)
private
FInterWindow: HWND;
FListenerList: TVMsgListenerList;
FLock: TCriticalSection;
FMessageID: Cardinal;
FOnLog: TLogEvent;
FRecvMsgsStoped: Boolean;
procedure DoLog(AType: TLogTypeEnum; const AText: WideString;
ADataMem: Pointer; ADataLen: Integer);
protected
procedure InterWindowProc(var AMsg: TMessage);
public
constructor Create;
destructor Destroy; override;
procedure LogRecv(const S: WideString; ADataMem: Pointer = nil;
ADataLen: Integer = 0);
procedure LogSend(const S: WideString; ADataMem: Pointer = nil;
ADataLen: Integer = 0);
procedure PostVMsg(AMsg: TVMsg); overload;
procedure PostVMsg(AMsgClass: TVMsgClass); overload;
procedure RegMsg(AOwner: TObject; AClass: TVMsgClass;
AEvent: TVMsgHandlerEvent);
procedure RemoveOwner(AOwner: TObject);
function SendVMsg(AMsg: TVMsg): Integer;
procedure StopRecvMsgs;
published
property OnLog: TLogEvent read FOnLog write FOnLog;
end;
function GlobalVMsgMonitor: TVMsgMonitor;
implementation
const
conVMsgMessageIDString = '{2373A24F-386A-444F-9FC3-F7BE3C1B89DF}';
var
gVMsgMonitor: TVMsgMonitor;
{-----------------------------------------------------------------------------
---------------------------全局消息监听器列表---------------------------------
-----------------------------------------------------------------------------}
function GlobalVMsgMonitor: TVMsgMonitor;
begin
if gVMsgMonitor = nil then
gVMsgMonitor := TVMsgMonitor.Create;
Result := gVMsgMonitor;
end;
{ TVMsg }
constructor TVMsg.Create;
begin
FHandled := False;
FReturn := 0;
FNeedFree := True;
end;
{-----------------------------------------------------------------------------
---------------基类实现复制即可, 派生类可以少写很多实现复制的代码-------------
-----------------------------------------------------------------------------}
procedure TVMsg.Assign(Source: TPersistent);
var
I, nCount: Integer;
PropList: PPropList;
PropInfo: PPropInfo;
strValueW: WideString;
nValue: Integer;
dValue: Extended;
nValue64: Int64;
strPropName: WideString;
begin
if not (Source is TVMsg) then
begin
inherited Assign(Source);
Exit;
end;
nCount := GetTypeData(Self.ClassInfo)^.PropCount;
if nCount > 0 then
begin
GetMem(PropList, nCount * SizeOf(Pointer));
try
GetPropInfos(Self.ClassInfo, PropList);
for I := 0 to nCount - 1 do
begin
PropInfo := PropList^[I];
if PropInfo = nil then
Continue;
if (PropInfo^.PropType^.Kind <> tkClass) and (PropInfo^.SetProc = nil) then
Continue;
{$WARNINGS OFF}
strPropName := PropInfo^.Name;
{$WARNINGS ON}
if not IsPublishedProp(Source, strPropName) then Continue;
case PropInfo^.PropType^.Kind of
tkClass: //对象
begin
Assert(False);
end;
tkInteger, tkChar, tkWChar: //整型
begin
nValue := GetOrdProp(Source, strPropName);
SetOrdProp(Self, PropInfo, nValue);
end;
tkEnumeration: //枚举
begin
strValueW := GetEnumProp(Source, strPropName);
SetEnumProp(Self, PropInfo, strValueW);
end;
tkSet: //集合
begin
strValueW := GetSetProp(Source, strPropName);
SetSetProp(Self, PropInfo, strValueW);
end;
tkFloat: //浮点型
begin
dValue := GetFloatProp(Source, strPropName);
SetFloatProp(Self, PropInfo, dValue);
end;
tkString, tkLString: //Ansi字符串
begin
strValueW := GetStrProp(Source, strPropName);
SetStrProp(Self, PropInfo, strValueW);
end;
{$IFDEF UNICODE}
tkUString:
begin
strValueW := GetUnicodeStrProp(Source, strPropName);
SetUnicodeStrProp(Self, PropInfo, strValueW);
end;
{$ENDIF}
tkWString: //宽字符串
begin
strValueW := GetWideStrProp(Source, strPropName);
TypInfo.SetWideStrProp(Self, PropInfo, strValueW);
end;
tkInt64: //64位整型
begin
nValue64 := GetInt64Prop(Source, strPropName);
SetInt64Prop(Self, PropInfo, nValue64);
end;
tkMethod:
begin
//DoNoting;
end;
else
Assert(False);
end;
end;
finally
FreeMem(PropList, nCount * SizeOf(Pointer));
end;
end;
end;
{-----------------------------------------------------------------------------
----------------------------------克隆一个消息--------------------------------
-----------------------------------------------------------------------------}
function TVMsg.Clone: TVMsg;
begin
Result := TVMsg(Self.ClassType.NewInstance);
Result.Create;
Result.Assign(Self);
end;
{ TVMsgHandler }
constructor TVMsgHandler.Create(AOwner: TObject);
begin
FOwner := AOwner;
Assert(FOwner <> nil);
FOwnerClassName := FOwner.ClassName;
end;
procedure TVMsgHandler.Execute(AMsg: TVMsg);
begin
if Assigned(FEvent) then
FEvent(Self, AMsg);
end;
{-----------------------------------------------------------------------
----------------------------------分派消息------------------------------
-----------------------------------------------------------------------}
procedure TVMsgHandlerList.Execute(AMsg: TVMsg);
var
oListBk: TObjectList;
I, nIndex: Integer;
begin
oListBk := TObjectList.Create(False);
try
for I := 0 to Self.Count - 1 do
oListBk.Add(Self[I]);
for I := 0 to oListBk.Count - 1 do
begin
nIndex := Self.IndexOf(oListBk[I]);
if nIndex <> -1 then
begin
Self.Items[nIndex].Execute(AMsg);
if AMsg.Handled then
Break;
end;
end;
finally
oListBk.Free;
end;
end;
{-----------------------------------------------------------------------------
---------------根据拥有者查找,如果没有找到,则自动新建一个---------------------
-----------------------------------------------------------------------------}
function TVMsgHandlerList.FindOrNew(AOwner: TObject): TVMsgHandler;
var
nIndex: Integer;
begin
nIndex := IndexOfOwner(AOwner);
if nIndex = -1 then
begin
Result := TVMsgHandler.Create(AOwner);
Self.Add(Result);
end
else
Result := Items[nIndex];
end;
function TVMsgHandlerList.GetItems(Index: Integer): TVMsgHandler;
begin
Result := TVMsgHandler(inherited Items[Index]);
end;
{-----------------------------------------------------------------------------
---------------------------------根据拥有者索引-------------------------------
-----------------------------------------------------------------------------}
function TVMsgHandlerList.IndexOfOwner(AOwner: TObject): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if Items[I].Owner = AOwner then
begin
Result := I;
Break;
end;
end;
{-----------------------------------------------------------------------------
----------------------------移除拥有者----------------------------------------
-----------------------------------------------------------------------------}
procedure TVMsgHandlerList.RemoveOwner(AOwner: TObject);
var
nIndex: Integer;
begin
nIndex := IndexOfOwner(AOwner);
if nIndex <> -1 then
Delete(nIndex);
end;
{ TVMsgListener }
constructor TVMsgListener.Create(AMsgClass: TVMsgClass);
begin
FHandlerList := TVMsgHandlerList.Create(True);
FVMsgClass := AMsgClass;
end;
destructor TVMsgListener.Destroy;
begin
FreeAndNil(FHandlerList);
inherited;
end;
{-----------------------------------------------------------------------------
--------------------------分派消息命令----------------------------------------
-----------------------------------------------------------------------------}
procedure TVMsgListener.DispatchMsg(AMsg: TVMsg; AOwner: TObject = nil);
var
nIndex: Integer;
oHandler: TVMsgHandler;
begin
if AOwner <> nil then
begin
nIndex := HandlerList.IndexOfOwner(AOwner);
if nIndex <> -1 then
begin
oHandler := HandlerList[nIndex];
oHandler.Execute(AMsg);
end;
end
else begin
HandlerList.Execute(AMsg);
end;
end;
destructor TVMsgListenerList.Destroy;
{$IFDEF DebugMode}
var
I, J: Integer;
S, strText: WideString;
oList: TStrings;
{$ENDIF}
begin
{$IFDEF DebugMode}
oList := TStringList.Create;
try
for I := 0 to Self.Count - 1 do
for J := 0 to Items[I].HandlerList.Count - 1 do
begin
S := Items[I].HandlerList[J].OwnerClassName;
if oList.IndexOf(S) = -1 then
oList.Add(S);
end;
if oList.Count > 0 then
begin
strText := WideFormat('在 %s 中以下类没有 RemoveOwner:'#13#10#13#10'%s',
[Self.ClassName, oList.Text]);
MessageBoxW(0, PWChar(strText), '警告', MB_ICONWARNING or MB_OK);
end;
finally
oList.Free;
end;
{$ENDIF}
inherited;
end;
{-----------------------------------------------------------------------------
------------------分发消息命令到指定的拥有者的消息命令处理函数----------------
-----------------------------------------------------------------------------}
procedure TVMsgListenerList.DispatchMsg(AMsg: TVMsg; AOwner: TObject = nil);
var
nIndex: Integer;
oListener: TVMsgListener;
begin
nIndex := IndexOfVMsgClass(AMsg.ClassType);
if nIndex <> -1 then
begin
oListener := Items[nIndex];
oListener.DispatchMsg(AMsg, AOwner);
end;
end;
{ TVMsgListenerList }
{-----------------------------------------------------------------------------
---------------根所消息命令类查找,如果没找到,则自动创建一个-------------------
-----------------------------------------------------------------------------}
function TVMsgListenerList.FindOrNew(AClass: TVMsgClass): TVMsgListener;
var
nIndex: Integer;
begin
nIndex := IndexOfVMsgClass(AClass);
if nIndex = -1 then
begin
Result := TVMsgListener.Create(AClass);
Self.Add(Result);
end
else
Result := Items[nIndex];
end;
function TVMsgListenerList.GetItems(Index: Integer): TVMsgListener;
begin
Result := TVMsgListener(inherited Items[Index]);
end;
{-----------------------------------------------------------------------------
------------------------------根据消息命令类索引------------------------------
-----------------------------------------------------------------------------}
function TVMsgListenerList.IndexOfVMsgClass(AClass: TClass): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if Items[I].VMsgClass = AClass then
begin
Result := I;
Break;
end;
end;
{ TVMsgHandlerList }
{-----------------------------------------------------------------------------
------------------------注册消息命令处理函数----------------------------------
-----------------------------------------------------------------------------}
procedure TVMsgListenerList.RegMsg(AOwner: TObject; AClass: TVMsgClass;
AEvent: TVMsgHandlerEvent);
var
oListener: TVMsgListener;
oHandler: TVMsgHandler;
begin
oListener := FindOrNew(AClass);
oHandler := oListener.HandlerList.FindOrNew(AOwner);
oHandler.Event := AEvent;
end;
{-----------------------------------------------------------------------------
--------------------从所有的消息命令中移除拥有者------------------------------
-----------------------------------------------------------------------------}
procedure TVMsgListenerList.RemoveOwner(AOwner: TObject;
AClass: TVMsgClass = nil);
var
I: Integer;
oListener: TVMsgListener;
begin
for I := Count - 1 downto 0 do
begin
oListener := Items[I];
if AClass <> nil then
begin
if oListener.VMsgClass <> AClass then
Continue;
end;
oListener.HandlerList.RemoveOwner(AOwner);
if oListener.HandlerList.Count = 0 then
Delete(I);
end;
end;
constructor TVMsgMonitor.Create;
begin
inherited;
FListenerList := TVMsgListenerList.Create;
FInterWindow := Classes.AllocateHWnd(InterWindowProc);
FMessageID := RegisterWindowMessageW(conVMsgMessageIDString);
FLock := TCriticalSection.Create;
IsMultiThread := True;
end;
{ TCallbackRecvForm }
destructor TVMsgMonitor.Destroy;
begin
Classes.DeallocateHWnd(FInterWindow);
FInterWindow := 0;
FreeAndNil(FLock);
FreeAndNil(FListenerList);
inherited;
end;
procedure TVMsgMonitor.DoLog(AType: TLogTypeEnum; const AText: WideString;
ADataMem: Pointer; ADataLen: Integer);
begin
if Assigned(FOnLog) then
FOnLog(Self, AType, 'Live3t.' + AText, ADataMem, ADataLen);
end;
{-----------------------------------------------------------------------------
--------------------------内部隐藏窗口的窗口过程------------------------------
-----------------------------------------------------------------------------}
procedure TVMsgMonitor.InterWindowProc(var AMsg: TMessage);
var
oMsg: TVMsg;
begin
if AMsg.Msg = FMessageID then
begin
if not FRecvMsgsStoped then
begin
oMsg := TVMsg(AMsg.LParam);
try
FListenerList.DispatchMsg(oMsg);
AMsg.Result := oMsg.Return;
finally
if oMsg.NeedFree then
oMsg.Free;
end;
end;
end
else begin
AMsg.Result := DefWindowProcW(FInterWindow, AMsg.Msg, AMsg.WParam, AMsg.LParam);
end;
end;
procedure TVMsgMonitor.LogRecv(const S: WideString; ADataMem: Pointer;
ADataLen: Integer);
begin
FLock.Enter;
try
DoLog(lteRecv, S, ADataMem, ADataLen);
finally
FLock.Leave;
end;
end;
procedure TVMsgMonitor.LogSend(const S: WideString; ADataMem: Pointer = nil;
ADataLen: Integer = 0);
begin
FLock.Enter;
try
DoLog(lteSend, S, ADataMem, ADataLen);
finally
FLock.Leave;
end;
end;
procedure TVMsgMonitor.PostVMsg(AMsg: TVMsg);
begin
FLock.Enter;
try
if FRecvMsgsStoped then
begin
AMsg.Free;
Exit;
end;
PostMessageW(FInterWindow, FMessageID, 0, Integer(AMsg));
finally
FLock.Leave;
end;
end;
procedure TVMsgMonitor.PostVMsg(AMsgClass: TVMsgClass);
var
oMsg: TVMsg;
begin
oMsg := TVMsg(AMsgClass.NewInstance).Create;
Self.PostVMsg(oMsg);
end;
procedure TVMsgMonitor.RegMsg(AOwner: TObject; AClass: TVMsgClass;
AEvent: TVMsgHandlerEvent);
begin
FListenerList.RegMsg(AOwner, AClass, AEvent);
end;
procedure TVMsgMonitor.RemoveOwner(AOwner: TObject);
begin
FListenerList.RemoveOwner(AOwner);
end;
function TVMsgMonitor.SendVMsg(AMsg: TVMsg): Integer;
begin
FLock.Enter;
try
Result := 0;
if FRecvMsgsStoped then Exit;
AMsg.NeedFree := False;
Result := SendMessageW(FInterWindow, FMessageID, 0, Integer(AMsg));
finally
FLock.Leave;
end;
end;
procedure TVMsgMonitor.StopRecvMsgs;
begin
FRecvMsgsStoped := True;
end;
{ TVMsg }
constructor TBaseStreamVMsg.Create;
begin
inherited;
FStream := TMemoryStream.Create;
end;
destructor TBaseStreamVMsg.Destroy;
begin
FreeAndNil(FStream);
inherited;
end;
procedure TBaseStreamVMsg.Assign(Source: TPersistent);
var
oSource: TBaseStreamVMsg;
begin
inherited;
if Source is TBaseStreamVMsg then
begin
oSource := TBaseStreamVMsg(Source);
Self.WriteData(oSource.DataMem, oSource.DataLen);
end;
end;
function TBaseStreamVMsg.GetDataLen: Integer;
begin
Result := FStream.Size;
end;
function TBaseStreamVMsg.GetDataMem: Pointer;
begin
Result := FStream.Memory;
end;
procedure TBaseStreamVMsg.WriteData(ADataMem: Pointer; ADataLen: Integer);
begin
FStream.Clear;
if (ADataMem <> nil) and (ADataLen > 0) then
FStream.Write(PAnsiChar(ADataMem)^, ADataLen);
end;
destructor TBaseAttachObjectStreamVMsg.Destroy;
begin
if FOwnsObject then
FreeAndNil(FAttachedObject);
inherited;
end;
{ TBaseAttachObjectStreamVMsg }
procedure TBaseAttachObjectStreamVMsg.AttachObject(AObject: TObject;
AOwnsObject: Boolean);
begin
if FOwnsObject then
FreeAndNil(FAttachedObject);
FAttachedObject := AObject;
FOwnsObject := AOwnsObject;
end;
initialization
finalization
FreeAndNil(gVMsgMonitor);
end.
|
unit uSupportLib;
interface
uses
Windows, DBClient, Classes, DB, Provider, SysUtils, DateUtils;
const
CrLf = #13#10;
function AppendMsg(var AMsg: String; const AStr: String): boolean;
function FillZeroesLeft(Str: string; Count: integer; Chr: Char) : string;
function GetComponentFromName(AOwner: TComponent; AName: String): TComponent;
function GetDataSetFromClientDataSet(ACds: TClientDataSet): TDataSet;
function GetMachineName: string;
function YearFirstDate(ADate: TDatetime): TDatetime;
procedure Split(StrBuf,Delimiter: string; var MyStrList: TStringList);
implementation
function AppendMsg(var AMsg: String; const AStr: String): boolean;
begin
if AMsg = '' then
AMsg := AStr
else
AMsg := AMsg + CrLf + AStr;
Result := True;
end;
function FillZeroesLeft(Str: string; Count: integer; Chr: Char) : string;
begin
Result := StringOfChar(Chr, Count - Length(Str)) + Str;
end;
function GetComponentFromName(AOwner: TComponent; AName: String): TComponent;
var
i : integer;
begin
Result := nil;
for i := 0 to AOwner.ComponentCount - 1 do
if AnsiUpperCase(AOwner.Components[i].Name) = ANSIUpperCase(AName) then
begin
Result := AOwner.Components[i];
Break;
end;
end;
function GetDataSetFromClientDataSet(ACds: TClientDataSet): TDataSet;
var
AuxProvider : TDataSetProvider;
begin
Result := nil;
if ACds.ProviderName <> '' then
begin
AuxProvider := TDataSetProvider(GetComponentFromName(ACds.Owner, ACds.ProviderName));
if Assigned(AuxProvider) and
Assigned(AuxProvider.DataSet) then
Result := AuxProvider.DataSet;
end;
end;
function GetMachineName: string;
var
Buffer: array[0..255] of Char;
Size: DWord;
begin
Size := 256;
if GetComputerName(Buffer, Size) then
Result := Buffer
else
Result := '';
end;
procedure Split(StrBuf,Delimiter: string; var MyStrList: TStringList);
var
TmpBuf: string;
LoopCount: integer;
begin
LoopCount := 0;
repeat
if StrBuf[LoopCount] = Delimiter then
begin
MyStrList.Add(TmpBuf);
TmpBuf := '';
end;
TmpBuf := TmpBuf + StrBuf[LoopCount];
inc(LoopCount);
until LoopCount > Length(StrBuf);
MyStrList.Add(TmpBuf);
end;
function YearFirstDate(ADate: TDatetime): TDateTime;
var
Year, Month, Day: Word;
begin
DecodeDate(Date, Year, Month, Day);
Result := EncodeDate(Year, 1, 1);
end;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Description: TMWDataSet component and TMWTable component
Creation: March 20, 1998
Version: 7.00
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list midware@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 1998-2010 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software and or any
derived or altered versions for any purpose, excluding commercial
applications. You can use this software for personal use only.
You may distribute it freely untouched.
The following restrictions applies:
1. The origin of this software must not be misrepresented, you
must not claim that you wrote the original software.
2. If you use this software in a product, an acknowledgment in
the product documentation and displayed on screen is required.
The text must be: "This product is based on MidWare. Freeware
source code is available at http://www.overbyte.be."
3. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
4. This notice may not be removed or altered from any source
distribution and must be added to the product documentation.
Data layout:
+-----------------------------------------------------------------+
| I N T E R N A L R E C O R D B U F F E R |
+-------------------------------------+----------+-------+--------+
| P H Y S I C A L R E C O R D | | | |
+-------------------------------------+ | | |
| |CALCULATED| EXTRA |BOOKMARK|
| ACCESSIBLE PHYSICAL FIELDS | FIELDS |RECINFO| DATA |
+-------------------------------------+----------+-------+--------+
FCalcFieldOffset ----------------^
FExtraRecInfoOffset ------------------------^
FBookMarkOffset ------------------------------------^
<----------- FRecBufSize ----------------------------------------->
<----------- FRecSize ---------------->
Memo fields are stored in separately allocated memory. The record contains
the pointer to the allocated memory and the length as an integer.
Updates:
Mar 23, 1998 V1.01 Added a byte for the nul terminating byte in each field
May 13, 1998 V1.02 Changed IsSequenced to return FALSE. This solve the scroll
bar problem in DBGrids.
Changed GetFieldData to copy just the required number of byte
regarding the datasize (this bug caused field concatenation).
May 23, 1998 V1.03 Added comments.
Jun 01, 1998 V1.04 Removed beta status. Changed "legal stuff" to prohibe
commercial applications whithout an agreement.
Added property editor for FieldLayout.
Jun 14, 1998 V1.05 Moved TFieldLayout in this source file
Jun 20, 1998 V1.06 Implemented field types
Jun 27, 1998 V1.07 Added a notification function
Added code to protect from FData not assigned
Added code to check for table active when setting fieldlayout
Added AppSrvClient, Params and FunctionCode properties to
allow design time data population. Need an upgraded TWSocket.
Jun 28, 1998 V1.08 Added full parsing for Params property to build a full
request TWBuffer.
Jul 08, 1998 V1.09 Adapted for Delphi 4
SetFieldLayout doesn't raise an exception if value not changed
Jul 10, 1998 V1.10 Added memo support
Jul 13, 1998 V1.11 Renamed DataSet component to TMWDataSet
Added EMWDataSetException class, TMWTable.ExecuteRequest,
TMWTable.OnRequestDone, TMWTable.SendRequest
Added checks for FAppSrvClient being assigned and consistency
between TMWTable.Data and FAppSrvClient.Answer assignement,
silently correcting the link when needed.
Added some comments.
Added some conditional compile for Delphi2 and BCB1 to be able
to compile a dummy component.
Jul 17, 1998 V1.12 Added intermediate TMWCustomTable class.
Jul 23, 1998 V1.13 Added DataEvent triggering for blobfields.
Jul 23, 1998 V1.14 Checked for nul length in AppendData
Aug 02, 1998 V1.15 Corrected field len for floats and currency
Aug 19, 1998 V1.16 Added ftBlob and ftGraphic
Aug 20, 1998 V1.17 Corrected a bug ("not Assigned(FData)") in Locate method.
Aug 24, 1998 V1.18 Added FData.Seek in GetRecord
Sep 02, 1998 V1.19 Verify that State in dsWriteModes in SetFieldData
Sep 08, 1998 V1.20 Properly initialize FInternalCurrent in InternalOpen
Sep 27, 1998 V1.21 Added checks in SetFieldData for ReadOnly fields
Added a call in SetFieldData to field's Validate.
Oct 17, 1998 V1.22 Adjusted memory allocation in TMWBlobStream.Write
Nov 27, 1998 V1.23 Replaced FieldCount by MWBufferFieldCount because it masked
the inherited FieldCount property from TDataSet.
Dec 23, 1998 V1.24 Cleared TWBlobStream buffer content when opened for writing.
Optimized TMWBuffer reallocation: reallocate only when
buffer is too small.
Append data in CopyToCurrentRecord. I'm not sure I must do it
like that !
Dec 30, 1998 V1.25 Corrected a bug in date/time handling in SetFieldData
Jan 16, 1999 V1.26 Corrected a bug in ftDate and ftTime field width.
Jan 29, 1999 V1.27 Replaced FloatToStr by FloatToStrEx.
Added DoBeforeScroll and DoAfterScroll in Locate.
Jul 21, 1999 V1.27a Corrected CreateBlobStream to set Stream.FModified in
write mode
Corrected a bug for boolean field in GetFieldData. Thanks
to Marchesini Franco <UP@interbusiness.it> for his help.
Added ftSmallInt case in GetFieldData.
Sep 15, 2001 V1.30 Added FieldTypeToString function.
Removed LoProp and PrmProp uses for Delphi 6 issue.
Jul 05, 2002 V1.31 Created MyTimeStampToMSecs to fix a D6 problem found by
Orson Wang <orson@aitc.com.tw>
Jul 15, 2002 V1.32 Adapted for Delphi 7
Aug 06, 2003 V1.33 Added support for ftSmallInt in SetFieldData. Thanks to
Mike <mail@worksmart.co.uk>.
Aug 28, 2004 V1.34 Use MWDefs.inc.
Added ExtractMetaDataLayout function.
Added code for null field support. Thanks to Stefan Frank
<stefan_frank@yahoo.com> for his code.
Apr 14, 2005 V1.35 Fixed ExtractMetaDataLayout for ftWideString. There is a bug
in TField component that returns always 4 for DataSize for
any WideString field, regardless of the actual column width.
May 03, 2005 V1.36 Fixed CopyFromCurrentRecord to correctly copy blob data.
Sep 22, 2005 V1.37 Replaced DELPHI6_UP by COMPILE6_UP when related to 64
streams which are present as well in BCB6.
Oct 03, 2005 V1.38 Use ftWideString for Delphi 4 and up (D3 doesn't support it)
Thanks to Rocco Neri <rocco.neri@corael.it> for his help.
Oct 23, 2005 V1.39 Updated for Delphi 2006 and BCB 2006
Apr 16, 2006 V1.40 Updated DecodeLayout to have datetime field lenght 23 instead
of 20 to allow space for AM/PM and to have boolean field
length = 6 to have space for TRUE/FALSE keywords, and float
field length 21 instead of 20.
Mar 04, 2007 V1.41 Fixed CompareBookmarks.
Aug 01, 2008 V7.00 Update for ICS-V7 and Delphi 2009.
Warning: Unicode not really supported.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteMwDatSet;
interface
{$I OverbyteMwDefs.inc}
{ TMWTable is not compatible with Delphi 2 (VER90) nor BCB 1 (VER93) }
{$IFNDEF COMPILER3_UP}
{$DEFINE NO_TMWTABLE}
{$ENDIF}
{$IFNDEF NO_TMWTABLE}
uses
Windows, Classes, DB, DBConsts, SysUtils, OverbyteRFormat, OverbyteApsCli,
OverbyteIcsLibrary
{ LOProp, PrmProp };
const
MWDataSetVersion = 700;
CopyRight : String = ' TMWDataSet (c) 1998-2008 F. Piette V7.00 ';
type
EMWDataSetException = class(Exception);
TPosition = Integer;
TFieldLayout = String;
TRequestParams = AnsiString;
{$IFNDEF COMPILER12_UP}
TRecordBuffer = PChar;
{$ENDIF}
{ Field data record is used to maintains our own field definitions }
TFieldData = record
FldOffset : Integer;
FldName : String;
FldType : TFieldType;
FldLen : Integer;
FldSize : Integer;
end;
PFieldData = ^TFieldData;
TBookmarkInfo = TPosition; { TMWBuffer.Tell data type }
PBookmarkInfo = ^TBookmarkInfo;
PExtraRecInfo = ^TExtraRecInfo;
TExtraRecInfo = record
BookmarkFlag : TBookmarkFlag; { bfCurrent, bfBOF, bfEOF, bfInserted }
end;
TDisplayInfo = procedure (Sender: TObject; const Msg: String) of Object;
{:TMWDataSet is derived from TDataSet. It had only very few properties,
methods and events. All inherited properties, methods and events are
described in Delphi online help under the TDataSet topic. }
TMWDataSet = class(TDataSet)
private
FBookmarkOffset : LongInt; { Offset to bookmark data in recbuf }
FCalcFieldsOffset : Word; { Offset to calculated fields data }
FExtraRecInfoOffset : Word; { Offset to extra rec info in recbuf }
FCursorOpen : Boolean; { True if cursor is open }
FInternalCurrent : TPosition; { Record Pointer }
FRecSize : Word; { Physical size of record }
FRecBufSize : Word; { Total size of recbuf }
FData : TMWBuffer; { Where the data really resides }
FFieldLayout : TFieldLayout; { FIELD1;TYP1;LEN1;FIELD2;... }
FFieldData : TList; { Decode FieldLayout }
FMWBufferFieldCount : Integer; { How many fields we have }
FOnDisplayInfo : TDisplayInfo;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
{ Basic file reading and navigation }
function AllocRecordBuffer: TRecordBuffer; override;
procedure FreeRecordBuffer(var Buffer: TRecordBuffer); override;
function GetRecord(Buffer: TRecordBuffer; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override;
function GetRecordSize: Word; override;
procedure InternalClose; override;
procedure InternalFirst; override;
procedure InternalLast; override;
procedure InternalOpen; override;
procedure InternalRefresh; override;
function IsCursorOpen: Boolean; override;
{ Bookmarks }
procedure GetBookmarkData(Buffer: TRecordBuffer; Data: Pointer); override;
function GetBookmarkFlag(Buffer: TRecordBuffer): TBookmarkFlag; override;
procedure SetBookmarkData(Buffer: TRecordBuffer; Data: Pointer); override;
procedure SetBookmarkFlag(Buffer: TRecordBuffer; Value: TBookmarkFlag); override;
procedure InternalGotoBookmark(Bookmark: Pointer); override;
procedure InternalSetToRecord(Buffer: TRecordBuffer); override;
{ Basic file modification }
procedure InternalInitRecord(Buffer: TRecordBuffer); override;
procedure InternalEdit; override;
procedure InternalDelete; override;
procedure InternalPost; override;
{ Field component stuff }
procedure InternalInitFieldDefs; override;
procedure SetFieldData(Field: TField; Buffer: Pointer); override;
procedure InternalAddRecord(Buffer: Pointer; Append: Boolean); override;
{ Calculated fields }
procedure ClearCalcFields(Buffer: TRecordBuffer); override;
function FindRecord(Restart, GoForward: Boolean): Boolean; override;
function GetRecordCount: Longint; override;
function GetRecNo: Integer; override;
procedure SetRecNo(Value: Integer); override;
{ Internal things }
procedure CopyFromCurrentRecord(Dst : TRecordBuffer);
procedure CopyToCurrentRecord(Src : TRecordBuffer);
procedure AppendData(Src : TRecordBuffer);
function TellText : String;
procedure CloseBlob(Field: TField); override;
procedure FreeBlobBuffer(Buffer: TRecordBuffer);
public
function IsSequenced: Boolean; override;
function GetCurrentRecord(Buffer: TRecordBuffer): Boolean; override;
function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; override;
function BookmarkValid(Bookmark: TBookmark): Boolean; override;
function CompareBookmarks(Bookmark1, Bookmark2: TBookmark): Integer; override;
function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override;
function Locate(const KeyFields: String; const KeyValues: Variant;
Options: TLocateOptions): Boolean; override;
function Lookup(const KeyFields: String;
const KeyValues: Variant;
const ResultFields: String): Variant; override;
protected
{ Our own custom stuff }
FBufferFromInternalSetToRecord: TRecordBuffer;
function GetFieldOffset(FieldNo : Integer) : Integer;
function GetFieldLen(FieldNo : Integer) : Integer;
function GetFieldType(FieldNo : Integer) : TFieldType;
procedure TriggerDisplayInfo(const Msg: String); virtual;
procedure SetFieldLayout(newValue : TFieldLayout);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{:The data seen thru the component does'nt resides in the component.
They are actually located in a TMWBuffer component. }
property Data : TMWBuffer read FData
write FData;
{:TMWBuffer is organized in records made of fields. There is nothing
to gives field names, nor field sizes as TMWBuffer is a fully variable
structure. The component needs something to give a name and a size to
fields. This is the purpose of the FieldLayout property. This is
simply a string structured a semicolon separated field names and
field length like this: FIRSTNAME;20;LASTNAME;20;AGE;3;AMOUNT;8 }
property FieldLayout : TFieldLayout read FFieldLayout
write SetFieldLayout;
{:The number of fields. Based on FieldLayout property. }
property MWBufferFieldCount : Integer read FMWBufferFieldCount;
{:The record size property gives the size of the record. It is a
readonly computedd value based on the FieldLayout property. Remember
that the data comes from TMWBuffer component which does'nt have fixed
record length as each TMWBuffer record can have a variable number of
fields each one having a variable length. }
property RecordSize: Word read GetRecordSize;
{:Event used to display internal info, for debugging purpose. }
property OnDisplayInfo: TDisplayInfo read FOnDisplayInfo
write FOnDisplayInfo;
end;
TMWCustomTable = class(TMWDataSet)
private
FReadOnly : Boolean;
FParams : TRequestParams;
FFunctionCode : String;
FAppSrvClient : TAppSrvClient;
FRequestDoneFlag : Boolean;
FRequestError : Integer;
FTimeout : Integer;
FBusy : Boolean;
FPSessionID : PChar;
FOnRequestDone : TRequestDone;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetCanModify: Boolean; override;
procedure InternalOpen; override;
procedure AppSrvClientRequestDone(Sender: TObject; Error: Integer); virtual;
procedure AppSrvClientExecuteRequestDone(Sender: TObject; Error: Integer); virtual;
procedure SetFunctionCode(newValue : String);
procedure SetParams(newValue : TRequestParams);
procedure SetAppSrvClient(newValue : TAppSrvClient);
procedure SetTimeout(newValue : Integer);
procedure SendRequest; virtual;
procedure TriggerRequestDone(Error: Integer); virtual;
public
constructor Create(AOwner : TComponent); override;
procedure DesignTimeRequest; virtual;
procedure ExecuteRequest; virtual;
property CanModify: Boolean read GetCanModify;
property OnRequestDone : TRequestDone
read FOnRequestDone
write FOnRequestDone;
property Data;
property FieldLayout;
property ReadOnly: Boolean read FReadOnly
write FReadOnly;
{ Function code used to request data at design time }
property FunctionCode : String read FFunctionCode
write SetFunctionCode;
{ Parameters used to request data at design time }
property Params : TRequestParams read FParams
write SetParams;
{ Component used to request data at design time }
property AppSrvClient : TAppSrvClient read FAppSrvClient
write SetAppSrvClient;
{ Timeout waiting for server to reply }
property Timeout : Integer read FTimeout
write SetTimeout;
property PSessionID : PChar read FPSessionID
write FPSessionID;
end;
TMWTable = class(TMWCustomTable)
published
property Active;
property AutoCalcFields;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property BeforeScroll;
property AfterScroll;
property OnCalcFields;
property OnDeleteError;
property OnEditError;
property OnNewRecord;
property OnPostError;
property OnDisplayInfo;
property OnRequestDone;
property Data;
property FieldLayout;
property ReadOnly;
property FunctionCode;
property Params;
property AppSrvClient;
property Timeout;
end;
// This stream class is designed to be an interface between TDataSet
// and our datastorage for blobs and memos. There is no real data
// storage in the object. Data is directly accessed where it is:
// in the dynamically allocated buffer.
TMWBlobStream = class(TStream)
Field : TField; // The field it refers to
pFldData : PFieldData; // Pointer to internal infos about field
Mode : TBlobStreamMode; // What operation is intended
{$IFDEF COMPILER12_UP}
Buffer : PByte; // Where the data really is
{$ELSE}
Buffer : PChar; // Where the data really is
{$ENDIF}
{$IFDEF COMPILER6_UP}
FSize : Int64; // The data size
{$ELSE}
FSize : LongInt; // The data size
{$ENDIF}
FCurPos : LongInt; // Current position for R/W
FData : TMWDataSet;
FModified : Boolean;
destructor Destroy; override;
function Write(const Value; Count: Longint): Longint; override;
function Read(var Value; Count: Longint): Longint; override;
procedure SetSize(NewSize: Longint); override;
{$IFDEF COMPILER6}
procedure SetSize64(NewSize: Int64);
function GetSize : Int64;
{$ELSE}
{$IFDEF COMPILER7_UP}
procedure SetSize64(NewSize: Int64);
function GetSize : Int64; override;
{$ELSE}
function GetSize : LongInt;
{$ENDIF}
{$ENDIF}
function Seek(Offset: Longint; Origin: Word): Longint; override;
{$IFDEF COMPILER6_UP}
property Size : int64 read GetSize write SetSize64;
{$ELSE}
property Size : LongInt read GetSize write SetSize;
{$ENDIF}
end;
function StringToFieldType(Token : String) : TFieldType;
function FieldTypeToString(FieldType : TFieldType) : String;
procedure ClearFieldData(FieldData : TList);
function DecodeLayout(Layout : TFieldLayout; FieldData : TList) : Integer;
function ExtractMetaDataLayout(DataSet : TDataSet) : String;
//procedure Register;
const
FieldTypesOrdinals : array [0..15] of TFieldType =
(ftString, ftInteger, ftSmallInt, ftWord, ftDateTime,
ftDate, ftTime, ftFloat, ftCurrency, ftBoolean,
ftBlob, ftMemo, ftGraphic,
{$IFDEF COMPILER4_UP}
ftWideString,
{$ENDIF}
ftBCD, ftAutoInc);
FieldTypesNames : array [0..15] of String =
('Char', 'Integer', 'SmallInt', 'Word', 'DateTime',
'Date', 'Time', 'Float', 'Currency', 'Boolean',
'Blob', 'Memo', 'Graphic',
{$IFDEF COMPILER4_UP}
'Char',
{$ENDIF}
'Integer', 'AutoInc');
implementation
uses Forms;
type
PPChar = ^PChar;
PInteger = ^Integer;
PPByte = ^PByte;
{$IFDEF NEVER}
const
TraceCount : Integer = 0;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure Trace(Msg : String);
begin
Inc(TraceCount);
if IsConsole then
Writeln(TraceCount, ' ', Msg);
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then begin
if AComponent = FData then
FData := nil;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.TriggerDisplayInfo(const Msg: String);
begin
if Assigned(FOnDisplayInfo) then
FOnDisplayInfo(Self, Msg);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TMWDataSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFieldData := TList.Create;
FInternalCurrent := TPosition(-1);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TMWDataSet.Destroy;
begin
// We must close the table before destroying because we
// need some field infos to free ftMemo or ftBlob fields
Active := FALSE;
if Assigned(FFieldData) then begin
ClearFieldData(FFieldData);
FFieldData.Free;
FFieldData := nil;
end;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.AllocRecordBuffer: TRecordBuffer;
begin
GetMem(Result, FRecBufSize);
FillChar(Result^, FRecBufSize, #0);
TriggerDisplayInfo('AllocRecordBuffer $' + IntToHex(LongInt(Result), 8));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.FreeRecordBuffer(var Buffer: TRecordBuffer);
begin
// writeln('FreeRecordBuffer(' + IntToHex(Integer(Buffer), 8) + ')');
try
TriggerDisplayInfo('FreeRecordBuffer $' + IntToHex(LongInt(Buffer), 8));
// Free the memory allocated for blob fields
FreeBlobBuffer(Buffer);
// Free the memory used for the entire record
FreeMem(Buffer, FRecBufSize);
Buffer := nil;
except
on E:Exception do
TriggerDisplayInfo('FreeRecordBuffer $' + IntToHex(LongInt(Buffer), 8) +
' exception ' + E.Message);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This function returns a PChar pointing to blob data }
{ Blobs (ftBlob, ftMemo and ftGraphic) are not stored in the record buffer. }
{ The record buffer contains the size and a pointer to dynamically }
{ allocated memory to hold the blob. }
{$IFDEF COMPILER12_UP}
function GetBlobDataPtr(Buf : TRecordBuffer; pFldData : PFieldData) : PByte;
begin
Result := PPByte(Buf + pFldData^.FldOffset)^;
end;
{$ELSE}
function GetBlobDataPtr(Buf : TRecordBuffer; pFldData : PFieldData) : PChar;
begin
Result := PPChar(Buf + pFldData^.FldOffset)^;
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This function set the blob data pointer }
{$IFDEF COMPILER12_UP}
procedure SetBlobDataPtr(Buf : TRecordBuffer; pFldData : PFieldData; newValue : PByte);
begin
PPByte(Buf + pFldData^.FldOffset)^ := newValue;
end;
{$ELSE}
procedure SetBlobDataPtr(Buf : TRecordBuffer; pFldData : PFieldData; newValue : PChar);
begin
PPChar(Buf + pFldData^.FldOffset)^ := newValue;
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Retreive the blob field data size }
function GetBlobDataLen(Buf : TRecordBuffer; pFldData : PFieldData) : Integer;
begin
Result := PInteger(Buf + pFldData^.FldOffset + SizeOf(PChar))^;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Set the blob field data size }
procedure SetBlobDataLen(Buf : TRecordBuffer; pFldData : PFieldData; newValue : Integer);
begin
PInteger(Buf + pFldData^.FldOffset + SizeOf(PChar))^ := newValue;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Free memory allocated for all blob fields in a record buffer. }
{ Blobs (ftBlob, ftMemo and ftGraphic) are not stored in the record buffer. }
{ The record buffer contains the size and a pointer to dynamically }
{ allocated memory to hold the blob. }
procedure TMWDataSet.FreeBlobBuffer(Buffer: TRecordBuffer);
var
FldNo : Integer;
pFldData : PFieldData;
{$IFDEF COMPILER12_UP}
pData : PByte;
{$ELSE}
pData : PChar;
{$ENDIF}
Len : Integer;
begin
// writeln('FreeBlobBuffer(' + IntToHex(Integer(Buffer), 8) + ')');
for FldNo := 0 to FMWBufferFieldCount - 1 do begin
pFldData := PFieldData(FFieldData.Items[FldNo]);
if pFldData^.FldType in [ftMemo, ftBlob, ftGraphic] then begin
pData := GetBlobDataPtr(Buffer, pFldData);
Len := GetBlobDataLen(Buffer, pFldData);
// writeln(' pData =' + IntToHex(Integer(pData), 8));
// writeln(' Len =' + IntToStr(Len));
if pData <> nil then begin
FreeMem(pData, Len + 1);
SetBlobDataPtr(Buffer, pFldData, nil);
SetBlobDataLen(Buffer, pFldData, 0);
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalInitRecord(Buffer: TRecordBuffer);
begin
// writeln('InternalInitRecord(' + IntToHex(Integer(Buffer), 8) + ')');
TriggerDisplayInfo('InternalInitRecord $' + IntToHex(LongInt(Buffer), 8));
FreeBlobBuffer(Buffer);
FillChar(Buffer^, FRecBufSize, #0);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.TellText : String;
begin
Result := 'Tell = ' + IntToStr(FData.Tell) +
' DataBufferCount = ' + IntToStr(FData.DataBufferCount);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalOpen;
begin
TriggerDisplayInfo('InternalOpen');
if Assigned(FData) then begin
FData.First;
TriggerDisplayInfo(TellText);
end;
FInternalCurrent := TPosition(-1); { 08/09/98 }
FCursorOpen := True;
InternalInitFieldDefs; { Populate FieldDefs from external dict }
if DefaultFields then
CreateFields; { Populate Fields from FieldDefs }
BindFields(True);
{ Compute offsets to various record buffer segments }
BookmarkSize := SizeOf(TBookmarkInfo);
FCalcFieldsOffset := FRecSize;
FExtraRecInfoOffset := FCalcFieldsOffset + CalcFieldsSize;
FBookmarkOffset := FExtraRecInfoOffset + SizeOf(TExtraRecInfo);
FRecBufSize := FBookmarkOffset + BookmarkSize;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalClose;
begin
TriggerDisplayInfo('InternalClose');
{ Destroy the TField components if no persistent fields }
if DefaultFields then
DestroyFields;
{ InternalClose is called by the Fields Editor in design mode, so }
{ the actual table may not be open. }
FCursorOpen := False;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.GetFieldOffset(FieldNo : Integer) : Integer;
begin
Result := PFieldData(FFieldData.Items[FieldNo])^.FldOffset;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.GetFieldLen(FieldNo : Integer) : Integer;
begin
Result := PFieldData(FFieldData.Items[FieldNo])^.FldLen;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.GetFieldType(FieldNo : Integer) : TFieldType;
begin
Result := PFieldData(FFieldData.Items[FieldNo])^.FldType;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure ClearFieldData(FieldData : TList);
var
I : Integer;
begin
for I := 0 to FieldData.Count - 1 do
Dispose(PFieldData(FieldData.Items[I]));
FieldData.Clear;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function stpblk(PValue : PAnsiChar) : PAnsiChar; overload;
begin
Result := PValue;
while TRUE do begin
case Result^ of
' ', #9, #10, #13: Inc(Result);
else
break;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF COMPILER12_UP}
function stpblk(PValue : PChar) : PChar; overload;
begin
Result := PValue;
while TRUE do begin
case Result^ of
' ', #9, #10, #13: Inc(Result);
else
break;
end;
end;
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function atof(value : AnsiString) : Extended;
begin
if Value = '' then
Result := 0
else begin
try
Result := StrToFloat(String(Value));
except
Result := 0;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function atoi(value : AnsiString) : Integer; overload;
var
i : Integer;
Sign : AnsiChar;
begin
Result := 0;
Sign := '+';
i := 1;
while (i <= Length(Value)) and (Value[i] = ' ') do
i := i + 1;
if (i <= Length(Value)) and ((Value[i] = '+') or (Value[i] = '-')) then begin
Sign := Value[i];
Inc(i);
end;
while (i <= Length(Value)) and (Value[i] >= '0') and (Value[i] <= '9')do begin
Result := Result * 10 + ord(Value[i]) - ord('0');
i := i + 1;
end;
if Sign = '-' then
Result := -Result;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF COMPILER12_UP}
function atoi(Value : String) : Integer; overload;
begin
Result := atoi(AnsiString(Value));
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function UpperCaseAnsiChar(Ch : Ansichar) : AnsiChar;
begin
if (Ch >= 'a') and (Ch <= 'z') then
Result := AnsiChar(Ord(Ch) - (Ord('a') - Ord('A')))
else
Result := Ch;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function GetToken(Src : PChar; var Dst : String; var Delim : Char) : PChar;
begin
Result := StpBlk(Src);
Dst := '';
while TRUE do begin
Delim := Result^;
if (Delim = ';') or (Delim = #0) then
break;
Dst := Dst + UpperCase(Delim);
Inc(Result);
end;
if Delim <> #0 then
Inc(Result);
Result := stpblk(Result);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function FieldTypeToString(FieldType : TFieldType) : String;
var
I : Integer;
begin
for I := Low(FieldTypesNames) to High(FieldTypesNames) do begin
if FieldTypesOrdinals[I] = FieldType then begin
Result := FieldTypesNames[I];
Exit;
end;
end;
raise EMWDataSetException.Create(
'FieldTypeToString: Unsupported field type');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function StringToFieldType(Token : String) : TFieldType;
var
I : Integer;
begin
Token := Trim(Token);
Result := ftUnknown;
if Token > '' then begin
if Length(Token) = 1 then begin
// Support old code !
case UpperCase(Token)[1] of
'C': Result := ftString;
'D': Result := ftDateTime;
'N': Result := ftInteger;
'F': Result := ftFloat;
'L': Result := ftBoolean;
end;
end
else begin
for I := Low(FieldTypesNames) to High(FieldTypesNames) do begin
// if StrIComp(PAnsiChar(Token), PAnsiChar(FieldTypesNames[I])) = 0 then begin
if CompareText(Token, FieldTypesNames[I]) = 0 then begin
Result := FieldTypesOrdinals[I];
Exit;
end;
end;
end;
end;
// ftWord, ftCurrency, ftBCD, ftDate, ftTime, ftDateTime,
// ftBytes, ftVarBytes, ftAutoInc, ftBlob, ftMemo, ftGraphic,
// ftFmtMemo, ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Extract metadata from a TDataSet and format it to be used at client side }
{ with TMWDatSet. }
function ExtractMetaDataLayout(DataSet : TDataSet) : String;
var
Fld : Integer;
begin
Result := 'LAYOUT:';
for Fld := 0 to DataSet.FieldCount - 1 do begin
{$IFDEF COMPILER4_UP} // 03/10/2005
if DataSet.Fields[Fld].DataType = ftWideString then // 14/04/2005
Result := Result +
DataSet.Fields[Fld].FieldName + ';' +
FieldTypeToString(DataSet.Fields[Fld].DataType) +
';' + IntToStr(DataSet.Fields[Fld].Size + 1) + ';'
else
{$ENDIF}
Result := Result +
DataSet.Fields[Fld].FieldName + ';' +
FieldTypeToString(DataSet.Fields[Fld].DataType) +
';' + IntToStr(DataSet.Fields[Fld].DataSize) + ';';
end;
// Remove ending semicolon
SetLength(Result, Length(Result) - 1);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Parse a FieldLayout string and build a field structure list. }
function DecodeLayout(Layout : TFieldLayout; FieldData : TList) : Integer;
type
fdState = (fdName, fdType, fdSize);
var
FldNo : Integer;
p : PChar;
Token : String;
Delim : Char;
State : fdState;
FldName : String;
FldType : TFieldType;
FldLen : Integer;
FldSize : Integer;
pData : PFieldData;
begin
// Free all existing data definition
ClearFieldData(FieldData);
State := fdName;
FldNo := 1;
Result := 0;
FldType := ftUnknown;
FldSize := 0;
p := PChar(Layout);
while (p <> nil) and (p^ <> #0) do begin
p := GetToken(p, Token, Delim);
case State of
fdName:
begin
if Token = '' then
FldName := 'FIELD' + IntToStr(FldNo)
else
FldName := Token;
FldSize := 0;
State := fdType;
end;
fdType:
begin
FldType := StringToFieldType(Token);
State := fdSize;
end;
fdSize:
begin
// We need a field length
FldLen := atoi(Token);
if FldLen <= 0 then
FldLen := 10;
if FldType = ftString then
FldSize := FldLen
else if FldType in [ftDateTime, ftTime, ftDate] then // 16/01/99
FldLen := 23 // 16/04/06 was 20
else if FldType in [ftInteger, ftAutoInc] then
FldLen := 11
else if FldType = ftSmallint then
FldLen := 6
else if FldType = ftFloat then
FldLen := 21 // 16/04/06 was 20
else if FldType = ftCurrency then
FldLen := 20
else if FldType = ftBoolean then
FldLen := 6 // 16/04/06 was 2
else if FldType in [ftMemo, ftBlob, ftGraphic] then
FldLen := SizeOf(Pointer) + SizeOf(Integer);
New(pData);
FieldData.Add(pData);
pData.FldLen := FldLen;
pData.FldSize := FldSize;
pData.FldType := FldType;
pData.FldName := FldName;
pData.FldOffset := Result;
Result := Result + FldLen + 1; { compute our record size }
{ +1 is for NUL byte }
Inc(FldNo);
State := fdName;
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalInitFieldDefs;
var
FldNo : Integer;
pData : PFieldData;
{$IFDEF VER110}
Field : TFieldDef;
{$ENDIF}
begin
TriggerDisplayInfo('InternalInitFieldDefs');
FieldDefs.Clear;
FRecSize := DecodeLayout(FFieldLayout, FFieldData);
FMWBufferFieldCount := FFieldData.Count;
for FldNo := 1 to FFieldData.Count do begin
pData := PFieldData(FFieldData.Items[FldNo - 1]);
{$IFDEF VER110}
FieldDefs.BeginUpdate;
try
Field := FieldDefs.AddFieldDef;
Field.Name := pData.FldName;
Field.DataType := pData.FldType;
Field.Size := pData.FldSize;
Field.Required := FALSE; // FP nov 11, 1998
Field.InternalCalcField := FALSE;
finally
FieldDefs.EndUpdate;
end;
{$ELSE}
TFieldDef.Create(FieldDefs, String(pData.FldName), pData.FldType,
pData.FldSize, FALSE, FldNo); // FP nov 11, 1998
{$ENDIF}
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Position BEFORE the very first record (there will be a get next) }
procedure TMWDataSet.InternalFirst;
begin
TriggerDisplayInfo('InternalFirst');
if Assigned(FData) then
FData.First;
FInternalCurrent := TPosition(-1);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Position AFTER the very last record (there will be a get prior) }
procedure TMWDataSet.InternalLast;
begin
TriggerDisplayInfo('InternalLast');
if Assigned(FData) then
FData.Last;
FInternalCurrent := TPosition(-2);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.AppendData(Src : TRecordBuffer);
var
FldNo : Integer;
//{$IFDEF COMPILER12_UP}
// p : PByte;
// pData : PByte;
//{$ELSE}
p : PAnsiChar;
pData : PAnsiChar;
//{$ENDIF}
pFldData : PFieldData;
Len : Integer;
Value : String;
begin
if not Assigned(FData) then
Exit;
// for FldNo := 0 to FMWBufferFieldCount - 1 do begin
// p := Src + GetFieldOffset(FldNo);
// FData.WriteFields(FldNo = 0, [p]);
// end;
for FldNo := 0 to FMWBufferFieldCount - 1 do begin
pFldData := PFieldData(FFieldData.Items[FldNo]);
if pFldData^.FldType in [ftMemo, ftBlob, ftGraphic] then begin
pData := PAnsiChar(GetBlobDataPtr(Src, pFldData));
Len := GetBlobDataLen(Src, pFldData);
SetLength(Value, Len);
if Len > 0 then
Move(pData^, Value[1], Len);
FData.WriteFields(FldNo = 0, [Value]);
end
else begin
p := PAnsiChar(Src + pFldData^.FldOffset);
FData.WriteFields(FldNo = 0, [p]);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Copy data from the TMWBuffer current record to some TDataSet internal }
{ buffer. }
procedure TMWDataSet.CopyFromCurrentRecord(Dst : TRecordBuffer);
var
FldNo : Integer;
pFldData : PFieldData;
{$IFDEF COMPILER12_UP}
pData : PByte;
{$ELSE}
pData : PAnsiChar;
{$ENDIF}
Len : Integer;
Dummy : TMWFieldType;
begin
for FldNo := 0 to FMWBufferFieldCount - 1 do begin
pFldData := PFieldData(FFieldData.Items[FldNo]);
if pFldData^.FldType in [ftMemo, ftBlob, ftGraphic] then begin
// writeln('CopyFromCurrentRecord(' + IntToHex(Integer(Dst), 8) + ')');
// Memo fields are stored in separate dynamically allocated
// memory. The TDataSet buffer contains only the pointer to this
// allocated memory and the field size.
Len := FData.FieldSize[FldNo];
pData := GetBlobDataPtr(Dst, pFldData);
// writeln(' Len =' + IntToStr(Len));
// writeln(' Old Len =' + IntToStr(GetBlobDataLen(Dst, pFldData)));
// writeln(' Old pData=' + IntToHex(Integer(pData), 8));
ReallocMem(pData, Len + 1);
// writeln(' New pData=' + IntToHex(Integer(pData), 8));
SetBlobDataPtr(Dst, pFldData, pData);
SetBlobDataLen(Dst, pFldData, Len);
TriggerDisplayInfo('Memo in record $' + IntToHex(Integer(Dst), 8));
// Move(PChar(FData.Fields[FldNo])^, pData^, Len);
FData.MoveFieldData(FldNo, pData, Len, Dummy);
pData[Len] := {$IFDEF COMPILER12_UP}0{$ELSE}#0{$ENDIF};
end
else begin
// Any other field type is directly stored in the buffer
StrLCopy(PAnsiChar(Dst) + pFldData^.FldOffset,
PAnsiChar(FData.FieldsA[FldNo]),
pFldData^.FldLen + 1);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.CopyToCurrentRecord(Src : TRecordBuffer);
var
FldNo : Integer;
Value : AnsiString;
pFldData : PFieldData;
{$IFDEF COMPILER12_UP}
pData : PByte;
{$ELSE}
pData : PChar;
{$ENDIF}
Len : Integer;
begin
//Trace('CopyToCurrentRecord ' + IntToHex(Integer(Src), 8));
// if not FData.HasData then begin // 24/12/98 Create all fields
// for FldNo := 0 to FMWBufferFieldCount - 1 do
// FData.WriteFields(FldNo = 0, ['']);
// FData.First;
// end;
for FldNo := 0 to FMWBufferFieldCount - 1 do begin
// if not FData.IsValidFields(FldNo) then
// FData.WriteFields(FALSE, ['']);
pFldData := PFieldData(FFieldData.Items[FldNo]);
if pFldData^.FldType in [ftMemo, ftBlob, ftGraphic] then begin
pData := GetBlobDataPtr(Src, pFldData);
Len := GetBlobDataLen(Src, pFldData);
SetLength(Value, Len);
if Len > 0 then
Move(pData^, Value[1], Len);
end
else
Value := StrPas(PAnsiChar(Src + pFldData^.FldOffset));
FData.FieldsA[FldNo] := Value;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.GetRecord(
Buffer : TRecordBuffer;
GetMode : TGetMode;
DoCheck : Boolean): TGetResult;
begin
Result := grOk;
case GetMode of
gmCurrent:
begin
TriggerDisplayInfo('GetRecord Current into buffer $' +
IntToHex(Integer(Buffer), 8));
if (not Assigned(FData)) or // No data
(FInternalCurrent = TPosition(-1)) or // First
(FInternalCurrent = TPosition(-2)) then // Last
Result := grError
else begin
FInternalCurrent := FData.Tell;
TriggerDisplayInfo(TellText);
CopyFromCurrentRecord(Buffer);
end;
end;
gmNext:
begin
TriggerDisplayInfo('GetRecord Next buffer ' + IntToHex(LongInt(Buffer), 8));
if (not Assigned(FData)) or // No data
(FInternalCurrent = TPosition(-2)) then // On the last
Result := grEof
else begin
if FInternalCurrent <> TPosition(-1) then begin
FData.Seek(FInternalCurrent); // 24/08/98
FData.Next;
end;
if FData.Eof then begin
FInternalCurrent := TPosition(-2);
Result := grEof;
end
else begin
FInternalCurrent := FData.Tell;
TriggerDisplayInfo(TellText);
CopyFromCurrentRecord(Buffer);
end;
end;
end;
gmPrior:
begin
TriggerDisplayInfo('GetRecord Prior buffer ' + IntToHex(LongInt(Buffer), 8));
if (not Assigned(FData)) or // No Data
(FInternalCurrent = TPosition(-1)) then // On the first
Result := grBof
else begin
if FInternalCurrent <> TPosition(-2) then begin
FData.Seek(FInternalCurrent); // 24/08/98
FData.Prior;
end;
if FData.Bof then begin
FInternalCurrent := TPosition(-1);
Result := grBof
end
else begin
FInternalCurrent := FData.Tell;
TriggerDisplayInfo(TellText);
CopyFromCurrentRecord(Buffer);
end;
end;
end;
else
Result := grError;
end;
if Result <> grOk then begin
TriggerDisplayInfo('GetRecord Result <> grOk');
InternalInitRecord(Buffer);
end;
if Result = grOk then begin
GetCalcFields(Buffer);
with PExtraRecInfo(Buffer + FExtraRecInfoOffset)^ do begin
BookmarkFlag := bfCurrent;
SetBookmarkData(Buffer, @FInternalCurrent);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function MyTimeStampToMSecs(const TimeStamp: TTimeStamp): Comp;
var
tsTmp : TTimeStamp;
begin
tsTmp := TimeStamp;
if (tsTmp.Date = 0) and (tsTmp.Time = 0) then begin
tsTmp.Date := 1;
tsTmp.Time := 0;
end;
Result := TimeStampToMSecs(tsTmp);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Get the data for the given field from the active buffer and stick it }
{ in the given buffer. Return False if the field value is null; otherwise }
{ return True. Buffer may be nil if TDataSet is checking for null only. }
function TMWDataSet.GetFieldData(Field: TField; Buffer: Pointer): Boolean;
var
Offset : Integer;
DataSize : Integer;
TimeStamp : TTimeStamp; { TTimeStamp declared in SysUtils }
{$IFDEF COMPILER12_UP}
RecBuf : PByte;
{$ELSE}
RecBuf : PChar;
{$ENDIF}
I : Integer;
Buf : String;
begin
//Trace('TMWDataSet.GetFieldData ' + IntToHex(LongInt(ActiveBuffer), 8));
RecBuf := ActiveBuffer;
if State = dsCalcFields then
RecBuf := CalcBuffer;
if Field.FieldNo <> -1 then begin { a physical field }
{ Check for a null value }
Result := TRUE; { no null value }
Offset := GetFieldOffset(Field.FieldNo - 1); { 29/08/2004 }
{ Check if current field is null. MidWare has not support for null }
{ data in character, strings and blob datatypes. In those cases, }
{ null is equal to null length data. }
{ 29/08/2004 }
if (Field.DataType in [ftInteger, ftSmallInt, ftFloat,
ftDate, ftTime, ftDateTime,
ftAutoInc, ftCurrency, ftBoolean]) and
(Char((RecBuf + OffSet)^) = #0) then
Result := FALSE;
{ If value is not null }
if Result and Assigned(Buffer) then begin
FillChar(Buffer^, Field.DataSize, 0);
DataSize := Field.DataSize;
case Field.DataType of
ftDate, ftTime, ftDateTime:
begin { 29/08/2004 }
TimeStamp := TimeStampFromMWFormat(StrPas(PAnsiChar(RecBuf + OffSet)));
if ((TimeStamp.Date = 0) and (TimeStamp.Time = 0)) or
(TimeStampToDateTime(TimeStamp) = 0) then
Result := FALSE
else begin
case Field.DataType of
ftDate: TDateTimeRec(Buffer^).Date := TimeStamp.Date;
ftTime: TDateTimeRec(Buffer^).Time := TimeStamp.Time;
ftDateTime: TDateTimeRec(Buffer^).DateTime := TimeStampToMSecs(TimeStamp);
else
raise EDatabaseError.Create('unsupported data type');
end;
end;
end;
ftInteger: Integer(Buffer^) := atoi(PAnsiChar(RecBuf + Offset));
ftAutoInc: Integer(Buffer^) := atoi(PAnsiChar(RecBuf + Offset));
ftSmallInt: SmallInt(Buffer^) := atoi(PAnsiChar(RecBuf + Offset));
ftWord: Word(Buffer^) := atoi(PAnsiChar(RecBuf + Offset));
ftFloat: Double(Buffer^) := atof(PAnsiChar(RecBuf + Offset));
ftCurrency: Double(Buffer^) := atof(PAnsiChar(RecBuf + Offset));
ftString: StrLCopy(PAnsiChar(Buffer), PAnsiChar(RecBuf + OffSet), DataSize - 1);
{$IFDEF COMPILER12_UP}
ftBoolean: Boolean(Buffer^) := ((RecBuf[Offset] = Ord('T')) or (RecBuf[Offset] = Ord('1')));
{$ELSE}
ftBoolean: Boolean(Buffer^) := ((RecBuf[Offset] = 'T') or (RecBuf[Offset] = '1'));
{$ENDIF}
ftMemo, ftBlob, ftGraphic:
raise Exception.Create('GetFieldData: program error');
else
raise EDatabaseError.Create('unsupported data type');
end;
end;
end
else begin { a calculated field }
Offset := FCalcFieldsOffset + Field.Offset;
Result := not Boolean(RecBuf[Offset]);
if Result and Assigned(Buffer) then
Move(RecBuf[Offset + 1], Buffer^, Field.DataSize);
end;
Buf := '';
for I := 0 to 19 do begin
if (Buffer <> nil) and (PChar(Buffer)[I] = '') then { SF }
break { SF }
else if (Buffer <> nil) and (Pchar(Buffer)[I] >= ' ') then
Buf := Buf + Pchar(Buffer)[I]
end;
TriggerDisplayInfo('GetFieldData ' + IntToStr(Field.FieldNo) +
' from ActiveBuffer $' + IntToHex(Integer(ActiveBuffer), 8) +
' ''' + Buf + '''');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWBlobStream.Read(var Value; Count: Longint): Longint;
var
{$IFDEF COMPILER12_UP}
pData : PByte;
{$ELSE}
pData : PChar;
{$ENDIF}
Len : Integer;
begin
// Trace('TMWBlobStream.Read ' + IntToHex(LongInt(Buffer), 8));
// Writeln('TMWBlobStream.Read Count=', Count);
if Count < 0 then
raise Exception.Create('TMWBlobStream.Read can''t read negative byte count');
if Count = 0 then begin
Result := 0;
Exit;
end;
// Get data length
Len := GetBlobDataLen(Buffer, pFldData);
if Len <= 0 then begin
Result := 0;
Exit;
end;
// Get data pointer
pData := GetBlobDataPtr(Buffer, pFldData);
// Adjust count to not read more than available data
if (FCurPos + Count) > Len then
Count := Len - FCurPos;
// Check if some more data to read
if Count <= 0 then begin
Result := 0;
Exit;
end;
// Copy data
Move(pData[FCurPos], Value, Count);
// Update current position
FCurPos := FCurPos + Count;
// Return byte count
Result := Count;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWBlobStream.Write(const Value; Count: Longint): Longint;
var
{$IFDEF COMPILER12_UP}
pData : PByte;
{$ELSE}
pData : PChar;
{$ENDIF}
Len : LongInt;
begin
// Trace('TMWBlobStream.Write ' + IntToHex(LongInt(Buffer), 8));
// writeln('TMWBlobStream.Write Count=', Count, ' Buffer=', IntToHex(Integer(Buffer), 8));
if Count < 0 then
raise Exception.Create('TMWBlobStream.Write can''t write negative byte count');
if Count = 0 then begin
Result := 0;
Exit;
end;
// Get data pointer and data length
pData := GetBlobDataPtr(Buffer, pFldData);
Len := GetBlobDataLen(Buffer, pFldData); // 23/12/98
if Len < (FCurPos + Count) then begin // 23/12/98
// Adjust allocated memory (17/10/98)
ReallocMem(pData, FCurPos + Count + 1);
SetBlobDataPtr(Buffer, pFldData, pData);
SetBlobDataLen(Buffer, pFldData, FCurPos + Count);
end;
// Copy data to internal buffer
Move(Value, pData[FCurPos], Count);
// Update current position
FCurPos := FCurPos + Count;
{
// If in edit or insert mode, copy data to TMWBuffer
if FData.State = dsEdit then // 24/12/98
FData.CopyToCurrentRecord(Buffer)
else if FData.State = dsInsert then // 23/12/98
FData.AppendData(Buffer);
}
Result := Count;
FModified := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWBlobStream.SetSize(NewSize: Longint);
begin
FSize := NewSize;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF COMPILER6_UP}
procedure TMWBlobStream.SetSize64(NewSize: Int64);
begin
FSize := NewSize;
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWBlobStream.GetSize :
{$IFDEF COMPILER6_UP} Int64;
{$ELSE} LongInt; {$ENDIF}
begin
Result := FSize;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWBlobStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
case Origin of
soFromBeginning: Result := Offset;
soFromCurrent: Result := FCurPos + Offset;
soFromEnd: Result := FSize - Offset;
else
raise Exception.Create('TMWBlobStream.Seek invalid origin');
end;
FCurPos := Result;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TMWBlobStream.Destroy;
begin
// writeln('TMWBlobStream.Destroy');
if FModified then begin
if Field is TBlobField then
TBlobField(Field).Modified := True;
try
FData.DataEvent(deFieldChange, Longint(Field));
except
Application.HandleException(Self);
end;
end;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.CreateBlobStream(
Field: TField; Mode: TBlobStreamMode): TStream;
var
Stream : TMWBlobStream;
pFldData : PFieldData;
{$IFDEF COMPILER12_UP}
pData : PByte;
{$ELSE}
pData : PChar;
{$ENDIF}
begin
pFldData := PFieldData(FFieldData.Items[Field.FieldNo - 1]);
Stream := TMWBlobStream.Create;
Stream.Field := Field;
Stream.Mode := Mode;
Stream.pFldData := pFldData;
Stream.Buffer := ActiveBuffer;
Stream.FData := Self;
if (Mode = bmRead) {and FData.HasData} and (ActiveBuffer <> nil) then
Stream.SetSize(GetBlobDataLen(ActiveBuffer, pFldData));
// 23/12/98
if (Mode = bmWrite) {and FData.HasData }and (ActiveBuffer <> nil) then begin
// Clear any data already into buffer
pData := GetBlobDataPtr(ActiveBuffer, pFldData);
ReallocMem(pData, 1);
SetBlobDataPtr(ActiveBuffer, pFldData, pData);
SetBlobDataLen(ActiveBuffer, pFldData, 0);
Stream.FModified := TRUE;
end;
Result := Stream;
// writeln('CreateBlobStream Fld=', Field.FieldNo, ' Mode=', ord(Mode), ' Buffer=', IntToHex(Integer(Stream.Buffer), 8), ' Size=', Stream.Size);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.CloseBlob(Field: TField);
begin
inherited CloseBlob(Field);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.ClearCalcFields(Buffer: TRecordBuffer);
begin
FillChar(Buffer[FCalcFieldsOffset], CalcFieldsSize, 0);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.GetCurrentRecord(Buffer: TRecordBuffer): Boolean;
begin
TriggerDisplayInfo('GetCurrentRecord');
Result := False;
if not IsEmpty then begin
Result := True;
Move(ActiveBuffer^, Buffer^, FRecSize); {not sure here, buffer may contain internal data}
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.GetRecordSize: Word;
begin
TriggerDisplayInfo('GetRecordSize');
Result := FRecSize;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalGotoBookmark(Bookmark: Pointer);
begin
FInternalCurrent := TBookmarkInfo(Bookmark^);
if Assigned(FData) then begin
if FInternalCurrent = TPosition(-1) then
FData.First
else if FInternalCurrent = TPosition(-2) then begin
FData.Last;
FData.Next;
end
else
FData.Seek(FInternalCurrent);
end;
TriggerDisplayInfo('InternalGotoBookmark ' +
IntToStr(FInternalCurrent));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalSetToRecord(Buffer: TRecordBuffer);
begin
TriggerDisplayInfo('InternalSetToRecord from buffer ' +
IntToHex(LongInt(Buffer), 8));
FBufferFromInternalSetToRecord := Buffer;
InternalGotoBookmark(Buffer + FBookmarkOffset);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.GetBookmarkData(Buffer: TRecordBuffer; Data: Pointer);
begin
Move(Buffer[FBookmarkOffset], Data^, BookmarkSize);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.SetBookmarkData(Buffer: TRecordBuffer; Data: Pointer);
begin
Move(Data^, Buffer[FBookmarkOffset], BookmarkSize);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.GetBookmarkFlag(Buffer: TRecordBuffer): TBookmarkFlag;
begin
Result := PExtraRecInfo(Buffer + FExtraRecInfoOffset).BookmarkFlag;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.SetBookmarkFlag(Buffer: TRecordBuffer; Value: TBookmarkFlag);
begin
PExtraRecInfo(Buffer + FExtraRecInfoOffset).BookmarkFlag := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.BookmarkValid(Bookmark: TBookmark): Boolean;
var
RecordPointer : TPosition;
begin
{$IFDEF COMPILER12_UP}
// Bookmark is an array of byte
RecordPointer := PBookmarkInfo(@Bookmark[0])^;
{$ELSE}
RecordPointer := TBookmarkInfo(Bookmark^);
{$ENDIF}
TriggerDisplayInfo('BookmarkValid ' + IntToHex(LongInt(RecordPointer), 8));
Result := Assigned(FData);
if Result then begin
CursorPosChanged; { physical position no longer matches logical position }
try
FData.Seek(RecordPointer);
{ check for a deleted record }
Result := TRUE;
except
Result := False;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.CompareBookmarks(Bookmark1, Bookmark2: TBookmark): Integer;
var
B1, B2: Integer;
const
RetCodes: array [Boolean, Boolean] of ShortInt = ((2, -1),(1, 0));
begin
TriggerDisplayInfo('CompareBookmarks');
Result := RetCodes[Bookmark1 = nil, Bookmark2 = nil];
if Result = 2 then begin
try
{$IFDEF COMPILER12_UP}
B1 := PBookmarkInfo(@Bookmark1[0])^;
B2 := PBookmarkInfo(@Bookmark2[1])^;
{$ELSE}
B1 := TBookmarkInfo(Bookmark1^);
B2 := TBookmarkInfo(Bookmark2^);
{$ENDIF}
if B1 = B2 then
Result := 0
else if B1 > B2 then
Result := 1
else
Result := -1;
except
Result := 0;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.SetFieldLayout(newValue : TFieldLayout);
begin
if FFieldLayout = Trim(newValue) then
Exit;
if Active then
raise EMWDataSetException.Create('Can''t change FieldLayout while table is active');
FFieldLayout := Trim(newValue);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalAddRecord(Buffer: Pointer; Append: Boolean);
begin
//Trace('InternalAddRecord');
TriggerDisplayInfo('InternalAddRecord');
{ In our case, is doesn't matter if the record is being appended, }
{ inserts and appends both get written to the end of the file. }
// Move(Buffer^, MyData[FInternalCurrent], FRecSize);
AppendData(Buffer);
CursorPosChanged;
Resync([rmExact, rmCenter]);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalDelete;
begin
TriggerDisplayInfo('InternalDelete ');
if Assigned(FData) then begin
FData.Seek(FInternalCurrent);
FData.Delete;
end;
// Physical position no longer matches logical position
CursorPosChanged;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalEdit;
begin
TriggerDisplayInfo('InternalEdit');
{ Refresh the current record }
if Assigned(FData) then begin
FData.Seek(FInternalCurrent);
CopyFromCurrentRecord(ActiveBuffer);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalPost;
begin
//Trace('InternalPost ' + IntToHex(LongInt(ActiveBuffer), 8));
if not Assigned(FData) then
Exit;
case State of
dsEdit:
begin
TriggerDisplayInfo('InternalPost dsEdit');
FData.Seek(FInternalCurrent);
CopyToCurrentRecord(ActiveBuffer);
end;
dsInsert:
begin
TriggerDisplayInfo('InternalPost dsInsert');
AppendData(ActiveBuffer);
FData.Last;
FInternalCurrent := FData.Tell;
CursorPosChanged;
end;
else
TriggerDisplayInfo('InternalPost Unknown');
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.InternalRefresh;
begin
TriggerDisplayInfo('InternalRefresh');
{ This is where we would refresh any buffers we are using }
{ between the data and TDataSet's internal record buffers. }
Close;
Open;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.IsCursorOpen: Boolean;
begin
Result := FCursorOpen;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Copy data from a TField internal storage to our internal storage }
procedure TMWDataSet.SetFieldData(Field: TField; Buffer: Pointer);
var
Offset : Integer;
DataSize : Integer;
DataLen : Integer;
Value : AnsiString;
TimeStamp : TTimeStamp;
begin
// Trace('TMWDataSet.SetFieldData ' + IntToHex(LongInt(Buffer), 8));
// writeln('TMWDataSet.SetFieldData');
TriggerDisplayInfo('SetFieldData ' + IntToStr(Field.FieldNo));
if not (State in dsWriteModes) then
DatabaseError(SNotEditing); { 02/09/98 }
if Field.FieldNo <> -1 then begin { a physical field }
{ Cannot set fields while in OnCalcFields handler }
if State = dsCalcFields then
DatabaseError(SNotEditing);
{ 27/09/98 }
if Field.ReadOnly and not (State in [dsSetKey, dsFilter]) then
DatabaseErrorFmt(SFieldReadOnly, [Field.DisplayName]);
Field.Validate(Buffer);
{ Offset is the position in our internal storage }
Offset := GetFieldOffset(Field.FieldNo - 1);
{ DataLen is our internal (ascii) storage length }
DataLen := GetFieldLen(Field.FieldNo - 1);
{ DataSize is TField internal (binary) storage size }
DataSize := Field.DataSize;
if not Assigned(Buffer) then
{ If setting field to null, clear the field data }
{ Should I handle Memo, Blob and graphic ?? }
FillChar(ActiveBuffer[Offset], DataSize, #0)
else begin
case Field.DataType of
ftString:
StrLCopy(PAnsiChar(ActiveBuffer + Offset), PAnsiChar(Buffer), DataSize);
ftMemo, ftBlob, ftGraphic:
raise Exception.Create('SetFieldData: program error');
ftDate:
begin
TimeStamp := DateTimeToTimeStamp(0);
TimeStamp.Date := TDateTimeRec(Buffer^).Date; // 30/12/98
Value := TimeStampToMWFormat(TimeStamp);
StrLCopy(PAnsiChar(ActiveBuffer + Offset), @Value[1], DataLen);
end;
ftTime:
begin
TimeStamp := DateTimeToTimeStamp(0);
TimeStamp.Time := TDateTimeRec(Buffer^).Time; // 30/12/98
Value := TimeStampToMWFormat(TimeStamp);
StrLCopy(PAnsiChar(ActiveBuffer + Offset), @Value[1], DataLen);
end;
ftDateTime:
begin
TimeStamp := MSecsToTimeStamp(TDateTimeRec(Buffer^).DateTime);
Value := TimeStampToMWFormat(TimeStamp);
StrLCopy(PAnsiChar(ActiveBuffer + Offset), @Value[1], DataLen);
end;
ftSmallint:
begin
Value := IcsIntToStrA(SmallInt(Buffer^));
StrLCopy(PAnsiChar(ActiveBuffer + Offset), @Value[1], DataLen);
end;
ftInteger, ftAutoInc:
begin
Value := IcsIntToStrA(Integer(Buffer^));
StrLCopy(PAnsiChar(ActiveBuffer + Offset), @Value[1], DataLen);
end;
ftFloat:
begin
Value := FloatToStrEx(Double(Buffer^)); // 29/01/99
StrLCopy(PAnsiChar(ActiveBuffer + Offset), @Value[1], DataLen);
end;
ftCurrency:
begin
Value := FloatToStrEx(Double(Buffer^)); // 29/01/99
StrLCopy(PAnsiChar(ActiveBuffer + Offset), @Value[1], DataLen);
end;
ftBoolean:
begin
if Boolean(Buffer^) then
Value := 'T'
else
Value := 'F';
StrLCopy(PAnsiChar(ActiveBuffer + Offset), @Value[1], DataLen);
end;
else
raise EDatabaseError.Create('unsupported field type');
end;
end;
end
else begin { a calculated field }
Offset := FCalcFieldsOffset + Field.Offset;
if Assigned(Buffer) then
Move(Buffer^, CalcBuffer[Offset + 1], Field.DataSize);
end;
if not (State in [dsCalcFields]) then
DataEvent(deFieldChange, Longint(Field));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.Locate(
const KeyFields: String; // Field list, separated by semi-colon
const KeyValues: Variant;
Options: TLocateOptions): Boolean;
var
p : PChar;
FldName : String;
FldNum : Integer;
Delim : Char;
FldArray : String;
begin
DoBeforeScroll; // 29/01/99
// Physical position no longer matches logical position
CursorPosChanged;
// Convert KeyFields which are fields names separated by semicolon to
// an field number list consisting of a string where each field is
// given by his number (starting from 1) expressed as a char
// (Meaning that Ord(FldArray[I]) - 1 gives the field number
// The 1 offset is there for proper string termination
FldArray := '';
p := PChar(String(KeyFields));
while (p <> nil) and (p^ <> #0) do begin
p := GetToken(p, FldName, Delim);
FldNum := FieldDefs.IndexOf(String(FldName)) + 1; // Zero based
FldArray := FldArray + Char(FldNum);
if Delim <> ';' then
break;
end;
if not Assigned(FData) then begin
Result:= FALSE;
Exit;
end;
Result := FData.Locate(String(FldArray), KeyValues, Options);
if FData.Eof then
FInternalCurrent := TPosition(-2)
else if FData.Bof then
FInternalCurrent := TPosition(-1)
else
FInternalCurrent := FData.Tell;
if Result then
Resync([rmExact, rmCenter]);
DoAfterScroll; // 29/01/99
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.Lookup(
const KeyFields: String;
const KeyValues: Variant;
const ResultFields: String): Variant;
begin
// Result := False;
raise EMWDataSetException.Create('TMWDataSet.Lookup not implemented');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.FindRecord(Restart, GoForward: Boolean): Boolean;
begin
raise EMWDataSetException.Create('TMWDataSet.FindRecord not implemented');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.GetRecordCount: Longint;
begin
Result := -1; // Sequenced, no record count
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.GetRecNo: Integer;
begin
Result := -1; // Sequenced, no record number
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWDataSet.SetRecNo(Value: Integer);
begin
// Sequenced, no record number
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWDataSet.IsSequenced: Boolean;
begin
// We use a sequenced data storage (TMWBuffer). It means that there
// is no record number.
Result := False;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TMWCustomTable.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FTimeout := 10;
FFieldLayout := 'FIELD1;C;10;FIELD2;C;15';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWCustomTable.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then begin
if AComponent = FAppSrvClient then
AppSrvClient := nil;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TMWCustomTable.GetCanModify: Boolean;
begin
Result := not FReadOnly;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWCustomTable.SetFunctionCode(newValue : String);
begin
newValue := Trim(newValue);
if newValue = FFunctionCode then
Exit;
if Active then
raise EMWDataSetException.Create('Can''t change FunctionCode while table is active');
FFunctionCode := newValue;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWCustomTable.SetParams(newValue : TRequestParams);
begin
newValue := IcsTrimA(newValue);
if newValue = FParams then
Exit;
if Active then
raise EMWDataSetException.Create('Can''t change Params while table is active');
FParams := newValue;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWCustomTable.SetAppSrvClient(newValue : TAppSrvClient);
begin
if newValue = FAppSrvClient then
Exit;
if newValue = nil then
Active := FALSE;
if Active then
raise EMWDataSetException.Create('Can''t change AppSrvClient while table is active');
FAppSrvClient := newValue;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWCustomTable.SetTimeout(newValue : Integer);
begin
if newValue <= 0 then
FTimeout := 10
else
FTimeout := newValue;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ SendRequest is here just to be able to override it in descending }
{ component to allow something to be done before actually sending a request }
procedure TMWCustomTable.SendRequest;
begin
FAppSrvClient.Send;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called because DesignTimeRequest was called. }
procedure TMWCustomTable.AppSrvClientRequestDone(
Sender: TObject;
Error: Integer);
begin
FRequestDoneFlag := TRUE;
FRequestError := Error;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TMWCustomTable.TriggerRequestDone(Error: Integer);
begin
if Assigned(FOnRequestDone) then
FOnRequestDone(Self, Error);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This event handler is called because ExecuteRequest was called. }
procedure TMWCustomTable.AppSrvClientExecuteRequestDone(
Sender: TObject;
Error: Integer);
begin
FRequestDoneFlag := TRUE;
FRequestError := Error;
if (Error = 0) and (FAppSrvClient.AnswerStatus = '200') then
Active := TRUE;
TriggerRequestDone(Error);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ ExecuteRequest ask the AppSrvClient object to execute the same request as }
{ it is done at design time. }
{ Be aware that AppSrvClient properties are modified by this call. }
procedure TMWCustomTable.ExecuteRequest;
begin
// Check for missing properties
if not Assigned(FAppSrvClient) then
raise EMWDataSetException.Create('TMWCustomTable.AppSrvClient not assigned');
if not (Assigned(Data) or Assigned(FAppSrvClient.Answer)) then
raise EMWDataSetException.Create('TMWCustomTable.Data not assigned');
if Trim(FFunctionCode) = '' then
raise EMWDataSetException.Create('TMWCustomTable.FunctionCode not assigned');
Active := FALSE;
FAppSrvClient.Request.PSessionID := PSessionID;
FAppSrvClient.Request.Rewrite;
// Parse the FParams string to build the request parameters TMWBuffer
FAppSrvClient.Request.StringToRecords(FParams);
FAppSrvClient.FunctionCode := Trim(FFunctionCode);
FRequestDoneFlag := FALSE;
FRequestError := 0;
FAppSrvClient.OnRequestDone := AppSrvClientExecuteRequestDone;
if Assigned(Data) then
FAppSrvClient.Answer := Data
else
Data := FAppSrvClient.Answer;
SendRequest;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This procedure is called at design time to populate the dataware controls.}
{ To execute the same request at runtime, you should use ExecuteRequest. }
procedure TMWCustomTable.DesignTimeRequest;
var
Timeout : Integer;
OldFunctionCode : String;
OldOnRequestDone : TRequestDone;
ErrMsg : String;
begin
if FBusy then
Exit;
Active := FALSE;
OldFunctionCode := FAppSrvClient.FunctionCode;
OldOnRequestDone := FAppSrvClient.OnRequestDone;
try
FBusy := TRUE;
FAppSrvClient.Request.Rewrite;
// Parse the FParams string to build the request parameters TMWBuffer
FAppSrvClient.Request.StringToRecords(FParams);
FAppSrvClient.FunctionCode := Trim(FFunctionCode);
FRequestDoneFlag := FALSE;
FRequestError := 0;
FAppSrvClient.OnRequestDone := AppSrvClientRequestDone;
if Assigned(Data) then
FAppSrvClient.Answer := Data
else
Data := FAppSrvClient.Answer;
SendRequest;
{ SendRequest is asynchronous, so we must wait until the request }
{ is executed in the background or some timeout elapsed. }
{ This is bad code, but I don't know how to do it otherwise. }
Timeout := Integer(GetTickCount) + FTimeout * 1000;
while (not FRequestDoneFlag) and (Timeout > Integer(GetTickCount)) do begin
Application.ProcessMessages;
Sleep(0);
end;
if not FRequestDoneFlag then
ErrMsg := 'Timeout executing request'
else if FRequestError <> 0 then
ErrMsg := 'Can''t execute request, error #' +
IntToStr(FRequestError)
else if (FAppSrvClient.AnswerStatus <> '200') and
(FAppSrvClient.AnswerStatus <> 'OK') then
{ By convention, we suppose the server either return 'OK' if }
{ successfull, or FTP like result code, '200' meaning OK. }
ErrMsg := String('Server reported error #' +
FAppSrvClient.AnswerStatus +
' while executing request: ') +
FAppSrvClient.Answer.RecordToString
else
ErrMsg := '';
if ErrMsg <> '' then begin
if csDesigning in ComponentState then
FAppSrvClient.Answer.Rewrite
else
raise EMWDataSetException.Create(ErrMsg);
end;
finally
FBusy := FALSE;
FAppSrvClient.FunctionCode := OldFunctionCode;
FAppSrvClient.OnRequestDone := OldOnRequestDone;
FAppSrvClient.Close;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ We override the InternalOpen method to be able to populate data-aware }
{ components at run-time. }
procedure TMWCustomTable.InternalOpen;
begin
if (Assigned(FAppSrvClient) and (Trim(FFunctionCode) > '') and
(csDesigning in ComponentState)) and
(not (csLoading in ComponentState)) then
DesignTimeRequest;
inherited InternalOpen;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
(*
procedure Register;
begin
RegisterComponents('FPiette', [TMWTable]);
end;
*)
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$ELSE}
{ TMWCustomTable is not compatible with Delphi 2 nor BCB 1 }
{ Declare and implement a dummy component. }
uses Windows, Classes;
type TMWCustomTable = class(TComponent);
procedure Register;
implementation
procedure Register;
begin RegisterComponents('FPiette', [TMWTable]); end;
{$ENDIF}
end.
|
unit SelOrdenIB;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Buttons, Db;
type
TOrdenDlg = class(TForm)
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
lbCampos: TListBox;
rgMetodo: TRadioGroup;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BitBtn1Click(Sender: TObject);
private
FDataSet: TDataSet;
ACampos: TStringList;
FCampoSel: string;
FAscendente: boolean;
procedure SetDataSet(const Value: TDataSet);
procedure CargarCampos;
procedure SetCampoSel(const Value: string);
procedure SetAscendente(const Value: boolean);
{ Private declarations }
public
{ Public declarations }
property DataSet: TDataSet read FDataSet write SetDataSet;
property CampoSel: string read FCampoSel write SetCampoSel;
property Ascendente: boolean read FAscendente write SetAscendente;
end;
var
OrdenDlg: TOrdenDlg;
implementation
{$R *.DFM}
{ TOrdenDlg }
procedure TOrdenDlg.CargarCampos;
var
x: integer;
begin
lbCampos.Items.Clear;
if Assigned( FDataSet ) then
for x:=0 to FDataSet.FieldCount-1 do
if FDataSet.Fields[ x ].FieldKind = fkData then
begin
lbCampos.Items.Add( FDataSet.Fields[ x ].DisplayLabel );
ACampos.Add( FDataSet.Fields[ x ].FieldName );
end;
end;
procedure TOrdenDlg.SetDataSet(const Value: TDataSet);
begin
FDataSet := Value;
if Value <> nil then
Self.FreeNotification( Value );
CargarCampos;
end;
procedure TOrdenDlg.FormCreate(Sender: TObject);
begin
ACampos := TStringList.create;
end;
procedure TOrdenDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ACampos.free;
end;
procedure TOrdenDlg.BitBtn1Click(Sender: TObject);
begin
if lbCampos.ItemIndex >= 0 then
begin
FCampoSel := ACampos[ lbCampos.ItemIndex ];
FAscendente := rgMetodo.ItemIndex = 0;
end;
end;
procedure TOrdenDlg.SetCampoSel(const Value: string);
begin
FCampoSel := Value;
end;
procedure TOrdenDlg.SetAscendente(const Value: boolean);
begin
FAscendente := Value;
end;
end.
|
{ //************************************************************// }
{ // // }
{ // Código gerado pelo assistente // }
{ // // }
{ // Projeto MVCBr // }
{ // tireideletra.com.br / amarildo lacerda // }
{ //************************************************************// }
{ // Data: 10/03/2017 19:20:22 // }
{ //************************************************************// }
Unit RestClientSample.ViewModel;
interface
{ .$I ..\inc\mvcbr.inc }
uses Data.DB, MVCBr.Interf, MVCBr.ViewModel, firedac.comp.client, Data.FireDACJsonReflect, RestClientSample.ViewModel.Interf;
Type
/// Object Factory para o ViewModel
TRestClientSampleViewModel = class(TViewModelFactory,
IRestClientSampleViewModel, IViewModelAs<IRestClientSampleViewModel>)
private
function GetDeltas(Banco, Tabela: String;
MemTable: TFDMemTable): TFDJSONDeltas;
public
function ViewModelAs: IRestClientSampleViewModel;
class function new(): IRestClientSampleViewModel; overload;
class function new(const AController: IController)
: IRestClientSampleViewModel; overload;
procedure AfterInit; override;
end;
implementation
function TRestClientSampleViewModel.ViewModelAs: IRestClientSampleViewModel;
begin
result := self;
end;
class function TRestClientSampleViewModel.new(): IRestClientSampleViewModel;
begin
result := new(nil);
end;
/// <summary>
/// New cria uma nova instância para o ViewModel
/// </summary>
/// <param name="AController">
/// AController é o controller ao qual o ViewModel esta
/// ligado
/// </param>
class function TRestClientSampleViewModel.new(const AController: IController)
: IRestClientSampleViewModel;
begin
result := TRestClientSampleViewModel.create;
result.controller(AController);
end;
procedure TRestClientSampleViewModel.AfterInit;
begin
// evento disparado apos a definicao do Controller;
end;
function TRestClientSampleViewModel.GetDeltas(Banco, Tabela : String; MemTable : TFDMemTable) : TFDJSONDeltas;
begin
if MemTable.State in [dsInsert, dsEdit] then
MemTable.Post;
result := TFDJSONDeltas.Create;
TFDJSONDeltasWriter.ListAdd(result, MemTable);
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.0 12/8/2004 10:58:34 AM JPMugaas
PC-NFSD FTP List parser.
Rev 1.0 12/8/2004 10:37:42 AM JPMugaas
Parser for PC-NFS for DOS.
}
unit IdFTPListParsePCNFSD;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdFTPList, IdFTPListParseBase, IdFTPListTypes;
{
This parser is a little more tolarant of stuff than others because of scanty samples.
I only found one second hand and it might not have included a header or footer.
Here's all I had:
prog1 exe 2,563,136 06-10-99 10:00a
temp <dir> 01-27-97 3:41p
That was from the TotalCommander helpfile.
It was part of a PC-NFSD package for MS-DOS which included a FTP Deamon.
}
type
TIdPCNFSDFTPListItem = class(TIdFTPListItem);
TIdFTPLPPCNFSD = class(TIdFTPListBase)
protected
class function CheckLine(const AData : String): Boolean;
class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override;
class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override;
public
class function GetIdent : String; override;
class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override;
end;
// RLebeau 2/14/09: this forces C++Builder to link to this unit so
// RegisterFTPListParser can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdFTPListParsePCNFSD"'*)
implementation
uses
IdException,
IdGlobal, IdFTPCommon, IdGlobalProtocols, IdStrings, SysUtils;
const
DIR = '<dir>'; {Do not translate}
{ TIdFTPLPPC-NFSD }
class function TIdFTPLPPCNFSD.CheckLine(const AData: String): Boolean;
var
s : TStrings;
i : Integer;
LBuf : String;
begin
Result := False;
s := TStringList.Create;
try
SplitColumns(AData, s);
if s.Count > 3 then
begin
//last col -time
i := s.Count - 1;
LBuf := s[i];
if CharIsInSet(LBuf, Length(LBuf), 'ap') then {do not localize}
begin
LBuf := Fetch(LBuf, 'a'); {Do not localize}
LBuf := Fetch(LBuf, 'p'); {Do not localize}
if IsHHMMSS(LBuf, ':') then
begin
Dec(i);
//date
if IsMMDDYY(s[i], '-') then
begin
Dec(i);
// size or dir
if IsNumeric(s[i]) or (s[i] = DIR) then begin
Result := (i = 0) or (i = 1);
end;
end;
end;
end;
end;
finally
FreeAndNil(s);
end;
end;
class function TIdFTPLPPCNFSD.CheckListing(AListing: TStrings;
const ASysDescript: String; const ADetails: Boolean): Boolean;
var
i : Integer;
begin
Result := False;
for i := 0 to AListing.Count -1 do
begin
Result := CheckLine(AListing[i]);
if Result then begin
Break;
end;
end;
end;
class function TIdFTPLPPCNFSD.GetIdent: String;
begin
Result := 'PC-NFSD'; {Do not localize}
end;
class function TIdFTPLPPCNFSD.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem;
begin
Result := TIdPCNFSDFTPListItem.Create(AOwner);
end;
class function TIdFTPLPPCNFSD.ParseLine(const AItem: TIdFTPListItem;
const APath: String): Boolean;
var
LI : TIdPCNFSDFTPListItem;
s : TStrings;
i : Integer;
begin
Result := False;
LI := AItem as TIdPCNFSDFTPListItem;
s := TStringList.Create;
try
SplitColumns(LI.Data, s);
if s.Count > 3 then
begin
LI.FileName := s[0];
//assume filename 8.3 requirements in MS-DOS
if Length(s[1]) < 4 then
begin
LI.FFileName := LI.FFileName + '.' + s[1];
i := 2;
end else begin
i := 1;
end;
//<dir> or size
LI.Size := ExtractNumber(s[i], False);
if (LI.Size <> -1) or (s[i] = DIR) then
begin
if s[i] = DIR then
begin
LI.ItemType := ditDirectory;
LI.SizeAvail := False;
end;
Inc(i);
//date
if IsMMDDYY(s[i], '-') then
begin
LI.ModifiedDate := DateMMDDYY(s[i]);
Inc(i);
//time
if CharIsInSet(s[i], Length(s[i]), 'ap') then {Do not localize}
begin
LI.ModifiedDate := LI.ModifiedDate + TimeHHMMSS(s[i]);
Result := True;
end;
end;
end;
end;
finally
FreeAndNil(s);
end;
end;
initialization
RegisterFTPListParser(TIdFTPLPPCNFSD);
finalization
UnRegisterFTPListParser(TIdFTPLPPCNFSD);
end.
|
unit Engine;
// "engine" of all application.
// It works in the main gui thread. Main logic is here, time to time it checks
// if there are commands to do (look into commands in BaseDevice.pas)
//
// Device will create an interrogation thread and produce data, the engine will
// get use this data to show in gui.
//
// Commands can have gui and interrogation parts, so they need to be processed in
// both threads (interrogation and gui).
//
// Currently there are 2 hardcoded devices - "emulator" and "simple usb device".
interface
uses inputLine, Recorder, Classes, EmulatorDevice, SimpleUsbDevice, BaseDevice, Forms, Windows, MainGui, DeviceWrapper, Graphics,
ExtCtrls, SysUtils, Controls;
type
TEngine = class(TInterfacedObject, IConnectionCallback)
public
Constructor Create(gui : IMainGui);
function GetRecordersNumber() : integer;
function GetRecorder(recorderIndex : integer) : TRecorder;
function GetDevicesNumber() : integer;
function GetDeviceName(deviceIndex : integer) : string;
procedure ChooseDevice(deviceIndex : integer);
procedure AddNewRecorder();
function IsDeviceSelected() : boolean;
procedure ChangeChannelName(channelIndex : integer; newName : string);
function GetInputLinesNumber : integer;
function GetInputLineName(inputLineIndex : integer) : string;
function GetCommandsNumber : integer;
function GetCommandName(commandIndex : integer) : string;
procedure CommandClicked(commandIndex : integer);
function GetInputLineGraphWidth(inputLineIndex : integer) : integer;
procedure SetInputLineGraphWidth(inputLineIndex : integer; newWidth : integer);
function GetInputLineGraphColor(inputLineIndex : integer) : TColor;
procedure SetInputLineGraphColor(inputLineIndex : integer; newColor : TColor);
procedure CheckIfHasData;
function GetCalibrationOffset(inputLineIndex : integer) : double;
function GetCalibrationMultiplier(inputLineIndex : integer) : double;
procedure SetCalibrationOffsetAndMultiplier(inputLineIndex : integer; offset, multiplier : double);
function GetScriptText(inputLineIndex : integer) : string;
procedure SetScriptText(inputLineIndex : integer; scriptText : string);
procedure Disconnect;
procedure CancelConnection;
procedure LoadSheetFromFile(inputLineIndex : integer; filePath : string);
// IConnectionCallback
procedure OnConnected;
procedure OnConnectionStatusMessage(message: string);
procedure OnConnectionProgress(percent: integer);
procedure OnDisconnected;
procedure OnErrorOnConnection;
private
recorders : TList;
currentDevice : TDevice;
devicesList : TList;
mainGui : IMainGui;
reconnectOnDisconnect : boolean;
connectOnTick : integer;
timer : TTimer;
procedure OnTimer(Sender: TObject);
procedure DeleteAllRecorders;
procedure RequestFromRecorderToDelete(Sender: TObject);
end;
implementation
{ TEngine }
const maxChartsWhenDisconnected = 1;
const maxChartsWhenConnected = 10;
procedure TEngine.AddNewRecorder;
var recorder : TRecorder;
begin
if (Assigned(currentDevice) and currentDevice.IsConnected) then
begin
if (recorders.Count = maxChartsWhenConnected) then
exit;
recorder := TRecorder.Create(currentDevice);
recorder.CreateRecorderControl(mainGui.GetForm);
recorder.GetRecorderControl.Parent := mainGui.GetForm;
recorder.RequestToDelete := RequestFromRecorderToDelete;
recorders.Add(recorder);
mainGui.RedrawRecorders;
end;
end;
procedure TEngine.ChangeChannelName(channelIndex: integer;
newName: string);
begin
currentDevice.GetInputLine(channelIndex).SetName(newName);
mainGui.UpdateMenus;
end;
procedure TEngine.ChooseDevice(deviceIndex: integer);
var selectDevice : TDevice;
begin
if ((deviceIndex < 0) or (deviceIndex > devicesList.Count)) then
exit;
selectDevice := TDevice(devicesList[deviceIndex]);
if (selectDevice <> currentDevice) then
begin
if (Assigned(currentDevice)) then
begin
currentDevice.Disconnect;
end;
currentDevice := selectDevice;
mainGui.ShowConnectionForm;
reconnectOnDisconnect := true;
currentDevice.Connect(self);
end;
end;
constructor TEngine.Create(gui : IMainGui);
var device : TDevice;
begin
_AddRef;
connectOnTick := 0;
timer := TTimer.Create(gui.GetForm);
timer.Interval := 500;
timer.Enabled := true;
timer.OnTimer := OnTimer;
recorders := TList.Create;
mainGui := gui;
devicesList := TList.Create;
device := TDevice.Create(TEmulatorDevice.Create(mainGui.GetForm));
devicesList.Add(device);
device := TDevice.Create(TSimpleUsbDevice.Create());
devicesList.Add(device);
AddNewRecorder;
end;
procedure TEngine.DeleteAllRecorders;
begin
recorders.Clear;
end;
function TEngine.GetDeviceName(deviceIndex: integer): string;
begin
Result := (TDevice(devicesList[deviceIndex])).GetName;
end;
function TEngine.GetDevicesNumber: integer;
begin
Result := devicesList.Count;
end;
function TEngine.GetInputLineName(inputLineIndex: integer): string;
begin
Result := currentDevice.GetInputLine(inputLineIndex).GetName;
end;
function TEngine.GetInputLinesNumber: integer;
begin
Result := currentDevice.GetInputLinesNumber;
end;
function TEngine.GetInputLineGraphWidth(inputLineIndex: integer): integer;
begin
Result := currentDevice.GetInputLine(inputLineIndex).GetGraphWidth;
end;
function TEngine.GetRecorder(recorderIndex: integer): TRecorder;
begin
Result := TRecorder(recorders[recorderIndex]);
end;
function TEngine.GetRecordersNumber: integer;
begin
Result := recorders.Count;
end;
function TEngine.IsDeviceSelected: boolean;
begin
Result := Assigned(currentDevice);
end;
procedure TEngine.OnConnected;
begin
mainGui.HideConnectionForm;
DeleteAllRecorders;
AddNewRecorder;
mainGui.UpdateMenus;
currentDevice.SetListeningFlag(true);
end;
procedure TEngine.OnConnectionProgress(percent: integer);
begin
mainGui.SetConnectionProgress(percent);
end;
procedure TEngine.OnConnectionStatusMessage(message: string);
begin
mainGui.ShowConnectionStatusMessage(message);
end;
procedure TEngine.OnDisconnected;
begin
if reconnectOnDisconnect then
InterlockedExchange(connectOnTick, 1);
end;
procedure TEngine.OnErrorOnConnection;
begin
if reconnectOnDisconnect then
InterlockedExchange(connectOnTick, 1);
end;
procedure TEngine.SetInputLineGraphWidth(inputLineIndex, newWidth: integer);
begin
if ((newWidth >= 1) and (newWidth <= 10)) then
currentDevice.GetInputLine(inputLineIndex).SetGraphWidth(newWidth);
end;
function TEngine.GetInputLineGraphColor(inputLineIndex: integer): TColor;
begin
Result := currentDevice.GetInputLine(inputLineIndex).GetGraphColor;
end;
procedure TEngine.SetInputLineGraphColor(inputLineIndex: integer; newColor: TColor);
begin
currentDevice.GetInputLine(inputLineIndex).SetGraphColor(newColor);
end;
procedure TEngine.CheckIfHasData;
// 1. Checks if there are commands that want to show forms
// 2. Checks if there is data from a device to show in gui
var readData : PReadFromInputLineData;
var recorder : TRecorder;
var i : integer;
var commandWrapper : TCommand;
begin
mainGui.ShowStatusText('check');
if (Assigned(currentDevice) and currentDevice.IsConnected) then
begin
commandWrapper := currentDevice.GetInitializedCommand;
if Assigned(commandWrapper) then
begin
if (commandWrapper.ShowForm = MrYes) then
begin
if commandWrapper.Executable then
begin
commandWrapper.SetState(waitingExecution);
currentDevice.AddCommand(commandWrapper);
end
end;
end;
readData := currentDevice.GetReadData;
while Assigned(readData) do
begin
for i := 0 to recorders.Count - 1 do
begin
recorder := TRecorder(recorders[i]);
if (recorder.GetListenLineFlag(readData^.lineIndex)) then
begin
recorder.AddDataFromInputLine(readData^.lineIndex, readData^.timeRead, readData^.data);
end;
end;
readData := currentDevice.GetReadData;
end;
end;
mainGui.ShowStatusText('');
end;
procedure TEngine.RequestFromRecorderToDelete(Sender: TObject);
var i : integer;
begin
for i := 0 to recorders.Count - 1 do
begin
if (recorders[i] = Sender) then
begin
recorders.Delete(i);
(TRecorder(Sender)).UnSubscribeInputLineObservers;
(TRecorder(Sender)).GetRecorderControl.Parent := nil;
(TRecorder(Sender)).GetRecorderControl.SetGuiCallback(nil);
mainGui.RedrawRecorders;
exit;
end;
end;
end;
function TEngine.GetCalibrationMultiplier(inputLineIndex: integer): double;
begin
Result := currentDevice.GetInputLine(inputLineIndex).GetMultiplier;
end;
function TEngine.GetCalibrationOffset(inputLineIndex: integer): double;
begin
Result := currentDevice.GetInputLine(inputLineIndex).GetOffset;
end;
procedure TEngine.Disconnect;
begin
currentDevice.Disconnect;
end;
procedure TEngine.CancelConnection;
begin
reconnectOnDisconnect := false;
InterlockedExchange(connectOnTick, 0);
currentDevice.Disconnect;
mainGui.HideConnectionForm;
end;
procedure TEngine.OnTimer(Sender: TObject);
var wasConnect : integer;
begin
wasConnect := InterlockedExchange(connectOnTick, 0);
if (wasConnect <> 0) then
begin
mainGui.ShowConnectionForm;
currentDevice.Connect(self);
end;
end;
procedure TEngine.SetCalibrationOffsetAndMultiplier(inputLineIndex : integer; offset, multiplier : double);
begin
currentDevice.GetInputLine(inputLineIndex).SetOffsetAndMultiplier(offset, multiplier);
end;
procedure TEngine.LoadSheetFromFile(inputLineIndex : integer; filePath: string);
var sl: TStringList;
i: Integer;
value: string;
fmt: TFormatSettings;
corr : TDoubleArr;
rangeMax, rangeMin : integer;
begin
rangeMin := currentDevice.GetInputLine(inputLineIndex).GetMinInputVal;
rangeMax := currentDevice.GetInputLine(inputLineIndex).GetMaxInputVal;
GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, fmt);
fmt.DecimalSeparator := ',';
sl := TStringList.Create;
try
sl.LoadFromFile(filePath);
sl.NameValueSeparator := ';';
SetLength(corr, rangeMax - rangeMin + 1);
for i := rangeMin to rangeMax do
begin
value := sl.Values[IntToStr(i)];
if value = '' then
begin
MessageBox(0, PAnsiChar(Format('No correspondence for value %d', [i])), 'Error in the map file', MB_OK or MB_ICONERROR);
exit;
end;
try
corr[i] := StrToFloat(value, fmt);
except
on e: EConvertError do
begin
MessageBox(0, PAnsiChar(Format('Error in loading correspondence for value %d', [i])), 'Error in the map file', MB_OK or MB_ICONERROR);
exit;
end;
end;
end;
finally
sl.Free;
end;
currentDevice.GetInputLine(inputLineIndex).SetSheedData(corr);
end;
function TEngine.GetScriptText(inputLineIndex: integer): string;
begin
Result := currentDevice.GetInputLine(inputLineIndex).GetScriptText;
end;
procedure TEngine.SetScriptText(inputLineIndex: integer; scriptText: string);
begin
currentDevice.GetInputLine(inputLineIndex).SetScriptText(scriptText);
end;
procedure TEngine.CommandClicked(commandIndex: integer);
var
commandWrapper : TCommand;
begin
commandWrapper := currentDevice.CreateCommandWrapper(commandIndex);
if (commandWrapper.Initializable) then
begin
currentDevice.AddCommand(commandWrapper);
exit;
end;
if (commandWrapper.ShowForm = MrYes) then
begin
commandWrapper.SetState(waitingExecution);
currentDevice.AddCommand(commandWrapper);
exit;
end;
commandWrapper.Free;
end;
function TEngine.GetCommandName(commandIndex: integer): string;
begin
Result := currentDevice.GetCommandName(commandIndex);
end;
function TEngine.GetCommandsNumber: integer;
begin
Result := currentDevice.GetCommandsNumber;
end;
end.
|
{******************************************************************************}
{ }
{ Library: Fundamentals TLS }
{ File name: flcTLSPRF.pas }
{ File version: 5.02 }
{ Description: TLS PRF (Pseudo Random Function) }
{ }
{ Copyright: Copyright (c) 2008-2020, David J Butler }
{ All rights reserved. }
{ Redistribution and use in source and binary forms, with }
{ or without modification, are permitted provided that }
{ the following conditions are met: }
{ Redistributions of source code must retain the above }
{ copyright notice, this list of conditions and the }
{ following disclaimer. }
{ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND }
{ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED }
{ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED }
{ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A }
{ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL }
{ THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, }
{ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR }
{ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, }
{ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF }
{ USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) }
{ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER }
{ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING }
{ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE }
{ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE }
{ POSSIBILITY OF SUCH DAMAGE. }
{ }
{ Github: https://github.com/fundamentalslib }
{ E-mail: fundamentals.library at gmail.com }
{ }
{ Revision history: }
{ }
{ 2008/01/18 0.01 Initial development. }
{ 2020/05/09 5.02 Create flcTLSPRF unit from flcTLSUtils unit. }
{ }
{******************************************************************************}
{$INCLUDE flcTLS.inc}
unit flcTLSPRF;
interface
uses
{ Utils }
flcStdTypes,
{ TLS }
flcTLSProtocolVersion;
{ }
{ PRFAlgorithm }
{ }
type
TTLSPRFAlgorithm = (
tlspaSHA256
);
{ }
{ PRF (Pseudo-Random Function) }
{ }
function tlsP_MD5(const Secret, Seed: RawByteString; const Size: Integer): RawByteString;
function tlsP_SHA1(const Secret, Seed: RawByteString; const Size: Integer): RawByteString;
function tlsP_SHA256(const Secret, Seed: RawByteString; const Size: Integer): RawByteString;
function tlsP_SHA512(const Secret, Seed: RawByteString; const Size: Integer): RawByteString;
function tls10PRF(const Secret, ALabel, Seed: RawByteString; const Size: Integer): RawByteString;
function tls12PRF_SHA256(const Secret, ALabel, Seed: RawByteString; const Size: Integer): RawByteString;
function tls12PRF_SHA512(const Secret, ALabel, Seed: RawByteString; const Size: Integer): RawByteString;
function TLSPRF(const ProtocolVersion: TTLSProtocolVersion;
const Secret, ALabel, Seed: RawByteString; const Size: Integer): RawByteString;
{ }
{ Test }
{ }
{$IFDEF TLS_TEST}
procedure Test;
{$ENDIF}
implementation
uses
{ Crypto }
flcCryptoHash,
{ TLS }
flcTLSErrors;
{ }
{ P_hash }
{ P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + }
{ HMAC_hash(secret, A(2) + seed) + }
{ HMAC_hash(secret, A(3) + seed) + ... }
{ Where + indicates concatenation. }
{ A() is defined as: }
{ A(0) = seed }
{ A(i) = HMAC_hash(secret, A(i-1)) }
{ }
function tlsP_MD5(const Secret, Seed: RawByteString; const Size: Integer): RawByteString;
var A, P : RawByteString;
L : Integer;
begin
P := '';
L := 0;
A := Seed;
repeat
A := MD5DigestToStrA(CalcHMAC_MD5(Secret, A));
P := P + MD5DigestToStrA(CalcHMAC_MD5(Secret, A + Seed));
Inc(L, 16);
until L >= Size;
if L > Size then
SetLength(P, Size);
Result := P;
end;
function tlsP_SHA1(const Secret, Seed: RawByteString; const Size: Integer): RawByteString;
var A, P : RawByteString;
L : Integer;
begin
P := '';
L := 0;
A := Seed;
repeat
A := SHA1DigestToStrA(CalcHMAC_SHA1(Secret, A));
P := P + SHA1DigestToStrA(CalcHMAC_SHA1(Secret, A + Seed));
Inc(L, 20);
until L >= Size;
if L > Size then
SetLength(P, Size);
Result := P;
end;
function tlsP_SHA256(const Secret, Seed: RawByteString; const Size: Integer): RawByteString;
var A, P : RawByteString;
L : Integer;
begin
P := '';
L := 0;
A := Seed;
repeat
A := SHA256DigestToStrA(CalcHMAC_SHA256(Secret, A));
P := P + SHA256DigestToStrA(CalcHMAC_SHA256(Secret, A + Seed));
Inc(L, 32);
until L >= Size;
if L > Size then
SetLength(P, Size);
Result := P;
end;
function tlsP_SHA512(const Secret, Seed: RawByteString; const Size: Integer): RawByteString;
var A, P : RawByteString;
L : Integer;
begin
P := '';
L := 0;
A := Seed;
repeat
A := SHA512DigestToStrA(CalcHMAC_SHA512(Secret, A));
P := P + SHA512DigestToStrA(CalcHMAC_SHA512(Secret, A + Seed));
Inc(L, 64);
until L >= Size;
if L > Size then
SetLength(P, Size);
Result := P;
end;
{ }
{ PRF }
{ TLS 1.0: }
{ PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR }
{ P_SHA-1(S2, label + seed); }
{ S1 and S2 are the two halves of the secret and each is the same length. }
{ S1 is taken from the first half of the secret, S2 from the second half. }
{ Their length is created by rounding up the length of the overall secret }
{ divided by two; thus, if the original secret is an odd number of bytes }
{ long, the last byte of S1 will be the same as the first byte of S2. }
{ }
{ TLS 1.2: }
{ PRF(secret, label, seed) = P_<hash>(secret, label + seed) }
{ P_SHA-256 }
{ }
procedure tls10PRFSplitSecret(const Secret: RawByteString; var S1, S2: RawByteString);
var L, N : Integer;
begin
N := Length(Secret);
L := N;
if L mod 2 = 1 then
Inc(L);
L := L div 2;
S1 := Copy(Secret, 1, L);
S2 := Copy(Secret, N - L + 1, L);
end;
function tls10PRF(const Secret, ALabel, Seed: RawByteString; const Size: Integer): RawByteString;
var S1, S2 : RawByteString;
P1, P2 : RawByteString;
R : RawByteString;
I : Integer;
begin
tls10PRFSplitSecret(Secret, S1, S2);
P1 := tlsP_MD5(S1, ALabel + Seed, Size);
P2 := tlsP_SHA1(S2, ALabel + Seed, Size);
SetLength(R, Size);
for I := 1 to Size do
R[I] := AnsiChar(Byte(P1[I]) xor Byte(P2[I]));
Result := R;
end;
function tls12PRF_SHA256(const Secret, ALabel, Seed: RawByteString; const Size: Integer): RawByteString;
begin
Result := tlsP_SHA256(Secret, ALabel + Seed, Size);
end;
function tls12PRF_SHA512(const Secret, ALabel, Seed: RawByteString; const Size: Integer): RawByteString;
begin
Result := tlsP_SHA512(Secret, ALabel + Seed, Size);
end;
function TLSPRF(const ProtocolVersion: TTLSProtocolVersion;
const Secret, ALabel, Seed: RawByteString; const Size: Integer): RawByteString;
begin
if IsTLS12OrLater(ProtocolVersion) then
Result := tls12PRF_SHA256(Secret, ALabel, Seed, Size) else
if IsTLS10OrLater(ProtocolVersion) then
Result := tls10PRF(Secret, ALabel, Seed, Size)
else
raise ETLSError.Create(TLSError_InvalidParameter);
end;
{ }
{ Test }
{ }
{$IFDEF TLS_TEST}
{$ASSERTIONS ON}
procedure Test;
begin
// //
// Test vectors from http://www6.ietf.org/mail-archive/web/tls/current/msg03416.html //
// //
Assert(tls12PRF_SHA256(
RawByteString(#$9b#$be#$43#$6b#$a9#$40#$f0#$17#$b1#$76#$52#$84#$9a#$71#$db#$35),
'test label',
RawByteString(#$a0#$ba#$9f#$93#$6c#$da#$31#$18#$27#$a6#$f7#$96#$ff#$d5#$19#$8c), 100) =
#$e3#$f2#$29#$ba#$72#$7b#$e1#$7b +
#$8d#$12#$26#$20#$55#$7c#$d4#$53 +
#$c2#$aa#$b2#$1d#$07#$c3#$d4#$95 +
#$32#$9b#$52#$d4#$e6#$1e#$db#$5a +
#$6b#$30#$17#$91#$e9#$0d#$35#$c9 +
#$c9#$a4#$6b#$4e#$14#$ba#$f9#$af +
#$0f#$a0#$22#$f7#$07#$7d#$ef#$17 +
#$ab#$fd#$37#$97#$c0#$56#$4b#$ab +
#$4f#$bc#$91#$66#$6e#$9d#$ef#$9b +
#$97#$fc#$e3#$4f#$79#$67#$89#$ba +
#$a4#$80#$82#$d1#$22#$ee#$42#$c5 +
#$a7#$2e#$5a#$51#$10#$ff#$f7#$01 +
#$87#$34#$7b#$66);
Assert(tls12PRF_SHA512(
RawByteString(#$b0#$32#$35#$23#$c1#$85#$35#$99#$58#$4d#$88#$56#$8b#$bb#$05#$eb),
'test label',
RawByteString(#$d4#$64#$0e#$12#$e4#$bc#$db#$fb#$43#$7f#$03#$e6#$ae#$41#$8e#$e5), 196) =
#$12#$61#$f5#$88#$c7#$98#$c5#$c2 +
#$01#$ff#$03#$6e#$7a#$9c#$b5#$ed +
#$cd#$7f#$e3#$f9#$4c#$66#$9a#$12 +
#$2a#$46#$38#$d7#$d5#$08#$b2#$83 +
#$04#$2d#$f6#$78#$98#$75#$c7#$14 +
#$7e#$90#$6d#$86#$8b#$c7#$5c#$45 +
#$e2#$0e#$b4#$0c#$1c#$f4#$a1#$71 +
#$3b#$27#$37#$1f#$68#$43#$25#$92 +
#$f7#$dc#$8e#$a8#$ef#$22#$3e#$12 +
#$ea#$85#$07#$84#$13#$11#$bf#$68 +
#$65#$3d#$0c#$fc#$40#$56#$d8#$11 +
#$f0#$25#$c4#$5d#$df#$a6#$e6#$fe +
#$c7#$02#$f0#$54#$b4#$09#$d6#$f2 +
#$8d#$d0#$a3#$23#$3e#$49#$8d#$a4 +
#$1a#$3e#$75#$c5#$63#$0e#$ed#$be +
#$22#$fe#$25#$4e#$33#$a1#$b0#$e9 +
#$f6#$b9#$82#$66#$75#$be#$c7#$d0 +
#$1a#$84#$56#$58#$dc#$9c#$39#$75 +
#$45#$40#$1d#$40#$b9#$f4#$6c#$7a +
#$40#$0e#$e1#$b8#$f8#$1c#$a0#$a6 +
#$0d#$1a#$39#$7a#$10#$28#$bf#$f5 +
#$d2#$ef#$50#$66#$12#$68#$42#$fb +
#$8d#$a4#$19#$76#$32#$bd#$b5#$4f +
#$f6#$63#$3f#$86#$bb#$c8#$36#$e6 +
#$40#$d4#$d8#$98);
end;
{$ENDIF}
end.
|
unit TcpInitUtils;
interface
function ParseAddress(AddressDesc: string): string;
procedure SaveIniAddress(AddressDesc, Address, AIniSection: string);
procedure SaveIniAccount(ABrokeId, Account: string);
implementation
uses
IniFiles, SysUtils;
function ParseAddress(AddressDesc: string): string;
var
tmpPos1, tmpPos2: integer;
begin
Result := AddressDesc;
tmpPos1 := pos('(', AddressDesc);
tmpPos2 := pos(')', AddressDesc);
if (tmpPos1 > 0) and (tmpPos2 > 0) then
begin
if tmpPos1 = 1 then
begin
Result := Copy(AddressDesc, tmpPos2 + 1, maxint);
end else
begin
Result := Copy(AddressDesc, 1, tmpPos1 - 1);
end;
end;
end;
procedure SaveIniAddress(AddressDesc, Address, AIniSection: string);
var
tmpIni: TIniFile;
i: integer;
tmpCount: integer;
tmpIsFind: Boolean;
tmpAddr: string;
begin
if Trim(Address) = '' then
exit;
tmpIsFind := false;
tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
try
tmpCount := 0;
for i := 1 to 100 - 1 do
begin
tmpAddr := tmpIni.ReadString(AIniSection + IntToStr(i), 'addr', '');
if tmpAddr = '' then
Break;
Inc(tmpCount);
if SameText(tmpAddr, Address) then
tmpIsFind := true;
end;
if not tmpIsFind then
begin
Inc(tmpCount);
tmpIni.WriteString(AIniSection + IntToStr(tmpCount), 'addr', Address);
tmpIni.WriteString(AIniSection + IntToStr(tmpCount), 'desc', AddressDesc);
end;
tmpIni.WriteString(AIniSection, 'addr', Address);
tmpIni.WriteString(AIniSection, 'desc', AddressDesc);
finally
tmpIni.Free;
end;
end;
procedure SaveIniAccount(ABrokeId, Account: string);
var
tmpIni: TIniFile;
tmpAnsi: AnsiString;
tmpBrokerId: AnsiString;
tmpUserId: AnsiString;
tmpIsFind: Boolean;
i: integer;
tmpCounter: Integer;
begin
tmpBrokerId := Trim(ABrokeId);
tmpUserId := Trim(Account);
if tmpBrokerId = '' then
exit;
if tmpUserId = '' then
exit;
tmpIni := TIniFile.Create(ChangeFileExt(ParamStr(0), '.ini'));
try
tmpCounter := 0;
tmpIsFind := False;
for i := 1 to 100 do
begin
tmpAnsi := tmpIni.ReadString('acc' + IntToStr(i), 'brokerid', '');
if tmpAnsi = '' then
Break;
Inc(tmpCounter);
if SameText(tmpAnsi, tmpBrokerId) then
begin
tmpAnsi := tmpIni.ReadString('acc' + IntToStr(i), 'userid', '');
if SameText(tmpAnsi, tmpUserId) then
begin
tmpIsFind := true;
end;
end;
end;
if not tmpIsFind then
begin
Inc(tmpCounter);
tmpIni.WriteString('acc' + IntToStr(tmpCounter), 'brokerid', tmpBrokerId);
tmpIni.WriteString('acc' + IntToStr(tmpCounter), 'userid',tmpUserId);
//tmpIni.WriteString('acc' + IntToStr(tmpCounter), 'pwd', Trim(edtPassword.Text));
end;
tmpIni.WriteString('acc', 'brokerid', tmpBrokerId);
tmpIni.WriteString('acc', 'userid', tmpUserId);
//tmpIni.WriteString('acc', 'pwd', Trim(edtPassword.Text));
finally
tmpIni.Free;
end;
end;
end.
|
{ Subroutine SST_R_PAS_SMENT_PROG (STR_PROG_H)
*
* Process PROGRAM_STATEMENT syntax. We assume we stay in this program until
* a new PROGRAM statement. STR_PROG_H is the string handle to the
* PROGRAM_STATEMENT syntax.
}
module sst_r_pas_SMENT_PROG;
define sst_r_pas_sment_prog;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_sment_prog ( {process PROGRAM_STATEMENT syntax}
in str_prog_h: syo_string_t); {string handle to PROGRAM_STATEMENT syntax}
var
tag: sys_int_machine_t; {syntax tag from .syn file}
str_h: syo_string_t; {handle to string for a tag}
sym_p: sst_symbol_p_t; {pointer to program name symbol descriptor}
stat: sys_err_t;
begin
case nest_level of {how deep are we nested in blocks}
0: ; {not in any block, no problem}
1: begin {already in top MODULE or PROGRAM block}
sst_opcode_pos_pop; {this finishes block we are currently in}
sst_scope_old; {pop back to previous scope}
nest_level := nest_level - 1; {should now be above any top block}
end;
otherwise
syo_error (str_prog_h, 'sst_pas_read', 'prog_not_allowed_here', nil, 0);
end;
nest_level := nest_level + 1; {down into this PROGRAM block}
top_block := top_block_prog_k; {indicate top block is a PROGRAM}
syo_level_down; {down into PROGRAM_STATEMENT syntax level}
syo_get_tag_msg ( {get tag for program name}
tag, str_h, 'sst_pas_read', 'statement_prog_bad', nil, 0);
if tag <> 1 then begin {unexpected TAG value}
syo_error_tag_unexp (tag, str_h);
end;
sst_symbol_new ( {add program name to symbol table}
str_h, syo_charcase_down_k, sym_p, stat);
sst_scope_new; {make new scope level for this program}
sym_p^.prog_scope_p := sst_scope_p; {save pointer to program's scope}
syo_error_abort (stat, str_h, '', '', nil, 0);
sym_p^.symtype := sst_symtype_prog_k; {this symbol is a program name}
sym_p^.flags := sym_p^.flags +
[sst_symflag_def_k, sst_symflag_used_k];
sst_scope_p^.symbol_p := sym_p; {point scope to its defining symbol}
sst_opcode_new; {make opcode for this program}
sst_opc_p^.opcode := sst_opc_prog_k; {this opcode is a program}
sst_opc_p^.str_h := str_h; {save source file string handle}
sst_opc_p^.prog_sym_p := sym_p; {point opcode to program symbol}
sst_opcode_pos_push (sst_opc_p^.prog_p); {new opcodes are for this program}
syo_get_tag_msg ( {get next tag in PROGRAM_STATEMENT}
tag, str_h, 'sst_pas_read', 'statement_prog_bad', nil, 0);
if tag <> syo_tag_end_k then begin {there should be no tag here}
syo_error_tag_unexp (tag, str_h);
end;
syo_level_up; {back up from PROGRAM_STATEMENT syntax}
end;
|
unit uFrmCadastrarCliente;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Data.DB,
Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Cliente.controller, Cliente.model,
Cliente.dao;
type
TOperacao = (opNovo, opAlterar, opNavegar);
TFrmCadastrarCliente = class(TForm)
pnlRodape: TPanel;
btnFechar: TButton;
pgcPrincipal: TPageControl;
tbPesquisa: TTabSheet;
tbDados: TTabSheet;
pnlFiltro: TPanel;
btnPesquisar: TButton;
edtPesquisar: TLabeledEdit;
DBGrid1: TDBGrid;
dsPesquisar: TDataSource;
edtCodigo: TLabeledEdit;
edtDocumento: TLabeledEdit;
cbxTipo: TComboBox;
edtTelefone: TLabeledEdit;
lblTipo: TLabel;
pnlBtnsPesquisar: TPanel;
btnNovo: TButton;
btnDetalhar: TButton;
BtnExcluir: TButton;
pnlBtnsCadastro: TPanel;
btnListar: TButton;
btnAlterar: TButton;
btnGravar: TButton;
btnCancelar: TButton;
edtNome: TLabeledEdit;
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnFecharClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnDetalharClick(Sender: TObject);
procedure BtnExcluirClick(Sender: TObject);
procedure btnListarClick(Sender: TObject);
procedure btnAlterarClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure DBGrid1DblClick(Sender: TObject);
private
FOperacao : TOperacao;
procedure Novo;
procedure Detalhar;
procedure Excluir;
procedure Configuracoes;
procedure Pesquisar;
procedure CarregarCliente;
procedure Listar;
procedure Alterar;
procedure Inserir;
procedure Gravar;
procedure HabilitarControles(aOperacao: TOperacao);
public
end;
var
FrmCadastrarCliente: TFrmCadastrarCliente;
implementation
{$R *.dfm}
procedure TFrmCadastrarCliente.Alterar;
var
oCliente: TCliente;
oClienteController: TClienteController;
sErro: string;
begin
oCliente := TCliente.Create;
oClienteController := TClienteController.Create;
try
with oCliente do
begin
ID := StrToIntDef(edtCodigo.Text, 0);
Nome := edtNome.Text;
if cbxTipo.ItemIndex = 0 then
Tipo := 'F'
else
if cbxTipo.ItemIndex = 1 then
Tipo := 'J'
else
Tipo := EmptyStr;
Documento := edtDocumento.Text;
Telefone := edtTelefone.Text;
end;
if oClienteController.Alterar(oCliente, sErro) = False then
raise Exception.Create(sErro);
finally
FreeAndNil(oCliente);
FreeAndNil(oClienteController);
end;
end;
procedure TFrmCadastrarCliente.btnAlterarClick(Sender: TObject);
begin
FOperacao := opAlterar;
HabilitarControles(opAlterar);
end;
procedure TFrmCadastrarCliente.btnCancelarClick(Sender: TObject);
begin
HabilitarControles(opNavegar);
end;
procedure TFrmCadastrarCliente.btnDetalharClick(Sender: TObject);
begin
Detalhar;
end;
procedure TFrmCadastrarCliente.BtnExcluirClick(Sender: TObject);
begin
Excluir;
end;
procedure TFrmCadastrarCliente.btnFecharClick(Sender: TObject);
begin
Close;
end;
procedure TFrmCadastrarCliente.btnGravarClick(Sender: TObject);
begin
Gravar;
HabilitarControles(opNavegar);
end;
procedure TFrmCadastrarCliente.btnListarClick(Sender: TObject);
begin
Listar;
HabilitarControles(opNavegar);
end;
procedure TFrmCadastrarCliente.btnNovoClick(Sender: TObject);
begin
Novo;
HabilitarControles(opNovo);
end;
procedure TFrmCadastrarCliente.btnPesquisarClick(Sender: TObject);
begin
Pesquisar;
end;
procedure TFrmCadastrarCliente.CarregarCliente;
var
oCliente: TCliente;
oClienteController: TClienteController;
begin
oCliente := TCliente.Create;
oClienteController := TClienteController.Create;
try
oClienteController.CarregarCliente(oCliente, dsPesquisar.DataSet.FieldByName('id').AsInteger);
edtCodigo.Text := IntToStr(oCliente.ID);
edtNome.Text := oCliente.Nome;
if oCliente.Tipo = 'F' then
cbxTipo.ItemIndex := 0
else
if oCliente.Tipo = 'J' then
cbxTipo.ItemIndex := 1
else
cbxTipo.ItemIndex := -1;
edtDocumento.Text := oCliente.Documento;
edtTelefone.Text := oCliente.Telefone;
finally
FreeAndNil(oCliente);
FreeAndNil(oClienteController);
end;
end;
procedure TFrmCadastrarCliente.Configuracoes;
begin
tbPesquisa.TabVisible := False;
tbDados.TabVisible := False;
pgcPrincipal.ActivePage := tbPesquisa;
end;
procedure TFrmCadastrarCliente.DBGrid1DblClick(Sender: TObject);
begin
Detalhar;
end;
procedure TFrmCadastrarCliente.Detalhar;
begin
CarregarCliente;
HabilitarControles(opNavegar);
FOperacao := opNavegar;
pgcPrincipal.ActivePage := tbDados;
end;
procedure TFrmCadastrarCliente.Excluir;
var
oClienteController: TClienteController;
sErro: string;
begin
oClienteController := TClienteController.Create;
try
if (DmCliente.cdsPesquisar.Active) and (DmCliente.cdsPesquisar.RecordCount > 0) then
begin
if MessageDlg('Deseja realmente excluir esse cliente',mtConfirmation,[mbYes, mbNo], 0) = IDYES then
begin
if oClienteController.Excluir(DmCliente.cdsPesquisarID.AsInteger, sErro) = False then
raise Exception.Create(sErro);
oClienteController.Pesquisar(edtPesquisar.Text);
end;
end
else
raise Exception.Create('Não há registro para ser excluído');
finally
FreeAndNil(oClienteController);
end;
end;
procedure TFrmCadastrarCliente.FormCreate(Sender: TObject);
begin
DmCliente := TDmCliente.Create(nil);
end;
procedure TFrmCadastrarCliente.FormDestroy(Sender: TObject);
begin
FreeAndNil(DmCliente);
end;
procedure TFrmCadastrarCliente.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
Key := #0;
Perform(WM_NEXTDLGCTL, 0, 0);
end;
end;
procedure TFrmCadastrarCliente.FormShow(Sender: TObject);
begin
Configuracoes;
end;
procedure TFrmCadastrarCliente.Gravar;
var
oClienteController: TClienteController;
begin
oClienteController := TClienteController.Create;
try
case FOperacao of
opNovo: Inserir;
opAlterar: Alterar;
end;
oClienteController.Pesquisar(edtPesquisar.Text);
finally
FreeAndNil(oClienteController);
end;
end;
procedure TFrmCadastrarCliente.HabilitarControles(aOperacao: TOperacao);
begin
case aOperacao of
opNovo, opAlterar:
begin
edtNome.Enabled := True;
cbxTipo.Enabled := True;
edtDocumento.Enabled := True;
edtTelefone.Enabled := True;
btnListar.Enabled := False;
btnFechar.Enabled := False;
btnAlterar.Enabled := False;
btnGravar.Enabled := True;
btnCancelar.Enabled := True;
end;
opNavegar:
begin
edtNome.Enabled := False;
cbxTipo.Enabled := False;
edtDocumento.Enabled := False;
edtTelefone.Enabled := False;
btnListar.Enabled := True;
btnFechar.Enabled := True;
btnAlterar.Enabled := True;
btnGravar.Enabled := False;
btnCancelar.Enabled := False;
end;
end;
end;
procedure TFrmCadastrarCliente.Inserir;
var
oCliente: TCliente;
oClienteController: TClienteController;
sErro: string;
begin
oCliente := TCliente.Create;
oClienteController := TClienteController.Create;
try
with oCliente do
begin
ID := 0;
Nome := edtNome.Text;
if cbxTipo.ItemIndex = 0 then
Tipo := 'F'
else
if cbxTipo.ItemIndex = 1 then
Tipo := 'J'
else
Tipo := EmptyStr;
Documento := edtDocumento.Text;
Telefone := edtTelefone.Text;
end;
if oClienteController.Inserir(oCliente, sErro) = False then
raise Exception.Create(sErro);
finally
FreeAndNil(oCliente);
FreeAndNil(oClienteController);
end;
end;
procedure TFrmCadastrarCliente.Listar;
begin
pgcPrincipal.ActivePage := tbPesquisa;
end;
procedure TFrmCadastrarCliente.Novo;
begin
FOperacao := opNovo;
pgcPrincipal.ActivePage := tbDados;
edtNome.SetFocus;
end;
procedure TFrmCadastrarCliente.Pesquisar;
var
oClienteController: TClienteController;
begin
oClienteController := TClienteController.Create;
try
oClienteController.Pesquisar(edtPesquisar.Text);
finally
FreeAndNil(oClienteController);
end;
end;
end.
|
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
{*
Returns a matrix containing a copy of all the values in the given rows.
*}
function GetRows(const Mat:T2DByteArray; FromRow, ToRow:Int32): T2DByteArray; overload;
var y,wid:Int32;
begin
if Length(Mat) = 0 then NewException('Matrix must be initalized');
Wid := Length(Mat[0]);
ToRow := Min(ToRow, High(Mat));
SetLength(Result, ToRow-FromRow+1);
for y:=FromRow to ToRow do
begin
SetLength(Result[y-FromRow],Wid);
Move(Mat[y,0], Result[y-FromRow,0], Wid*SizeOf(Byte));
end;
end;
function GetRows(const Mat:T2DIntArray; FromRow, ToRow:Int32): T2DIntArray; overload;
var y,wid:Int32;
begin
if Length(Mat) = 0 then NewException('Matrix must be initalized');
Wid := Length(Mat[0]);
ToRow := Min(ToRow, High(Mat));
SetLength(Result, ToRow-FromRow+1);
for y:=FromRow to ToRow do
begin
SetLength(Result[y-FromRow],Wid);
Move(Mat[y,0], Result[y-FromRow,0], Wid*SizeOf(Int32));
end;
end;
function GetRows(const Mat:T2DFloatArray; FromRow, ToRow:Int32): T2DFloatArray; overload;
var y,wid:Int32;
begin
if Length(Mat) = 0 then NewException('Matrix must be initalized');
Wid := Length(Mat[0]);
ToRow := Min(ToRow, High(Mat));
SetLength(Result, ToRow-FromRow+1);
for y:=FromRow to ToRow do
begin
SetLength(Result[y-FromRow],Wid);
Move(Mat[y,0], Result[y-FromRow,0], Wid*SizeOf(Single));
end;
end;
function GetRows(const Mat:T2DDoubleArray; FromRow, ToRow:Int32): T2DDoubleArray; overload;
var y,wid:Int32;
begin
if Length(Mat) = 0 then NewException('Matrix must be initalized');
Wid := Length(Mat[0]);
ToRow := Min(ToRow, High(Mat));
SetLength(Result, ToRow-FromRow+1);
for y:=FromRow to ToRow do
begin
SetLength(Result[y-FromRow],Wid);
Move(Mat[y,0], Result[y-FromRow,0], Wid*SizeOf(Double));
end;
end;
function GetRows(const Mat:T2DExtArray; FromRow, ToRow:Int32): T2DExtArray; overload;
var y,wid:Int32;
begin
if Length(Mat) = 0 then NewException('Matrix must be initalized');
Wid := Length(Mat[0]);
ToRow := Min(ToRow, High(Mat));
SetLength(Result, ToRow-FromRow+1);
for y:=FromRow to ToRow do
begin
SetLength(Result[y-FromRow],Wid);
Move(Mat[y,0], Result[y-FromRow,0], Wid*SizeOf(Extended));
end;
end;
|
{Part 7 of regression test for SPECFUND unit (c) 2013 W.Ehrhardt}
unit t_sfd7;
{$i STD.INC}
{$ifdef BIT16}
{$N+}
{$ifndef Windows}
{$O+}
{$endif}
{$endif}
interface
procedure test_agm;
procedure test_bernpoly;
procedure test_lambertw;
procedure test_lambertw1;
procedure test_debye;
procedure test_li_inv;
procedure test_RiemannR;
procedure test_cosint;
procedure test_sinint;
procedure test_fibpoly;
procedure test_lucpoly;
procedure test_catalan;
procedure test_kepler;
implementation
uses
DAMath, SpecFunD, t_sfd0;
{---------------------------------------------------------------------------}
procedure test_agm;
var
y,f: double;
cnt, failed: integer;
const
NE = 1;
begin
cnt := 0;
failed := 0;
writeln('Function: ','agm');
y := agm(MinDouble, Sqrt_MaxDbl);
f := 1.97815801598132823e151;
testrel( 1, NE, y, f, cnt,failed);
y := agm(1, Sqrt_MaxDbl);
f := 5.91138270923603144e151;
testrel( 2, 2, y, f, cnt,failed);
y := agm(MinDouble, 1);
f := 0.0022130664755015594768;
testrel( 3, NE, y, f, cnt,failed);
y := agm(0, 1);
f := 0;
testabs( 4, 0, y, f, cnt,failed);
y := agm(1, 0);
f := 0;
testabs( 5, 0, y, f, cnt,failed);
y := agm(1, 1e-100);
f := 0.0067810557455754508824;
testrel( 5, NE, y, f, cnt,failed);
y := agm(1, 1e-10);
f := 0.064344870476013322929;
testrel( 7, NE, y, f, cnt,failed);
y := agm(1, 1e-5);
f := 0.12177452186538904490;
testrel( 8, NE, y, f, cnt,failed);
y := agm(1, 0.125);
f := 0.45196952219967034359;
testrel( 9, NE, y, f, cnt,failed);
y := agm(1, 0.5);
f := 0.72839551552345343459;
testrel(10, NE, y, f, cnt,failed);
y := agm(1, 1);
f := 1;
testrel(11, 0, y, f, cnt,failed);
y := agm(1, 1000);
f := 189.38830240995087556;
testrel(12, NE, y, f, cnt,failed);
y := agm(1, 1e20);
f := 3311261967046375735.6;
testrel(13, NE, y, f, cnt,failed);
y := agm(1, 1e100);
f := 6.7810557455754508824e97;
testrel(14, NE, y, f, cnt,failed);
y := agm(1, 1e150);
f := 4.52974001126015639814e147;
testrel(15, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_lambertw;
var
x,y,f: double;
cnt, failed: integer;
i: integer;
const
NE = 2;
NA = 2;
begin
cnt := 0;
failed := 0;
writeln('Function: ','LambertW');
x := -exp(-1);
y := LambertW(x);
f := -1;
testrel( 1, NE, y, f, cnt,failed);
x := -6027/16384.0;
y := LambertW(x);
f := -0.9894660903569092419;
testrel( 2, 16, y, f, cnt,failed);
x := -3013/8192.0;
y := LambertW(x);
f := -0.9790854111351907084;
testrel( 3, 8, y, f, cnt,failed);
x := -753/2048;
y := LambertW(x);
f := -0.9670887700916448631;
testrel( 4, 8, y, f, cnt,failed);
x := -0.25;
y := LambertW(x);
f := -0.3574029561813889031;
testrel( 5, NE, y, f, cnt,failed);
x := -0.125;
y := LambertW(x);
f := -0.1444213531375097292;
testrel( 6, NE, y, f, cnt,failed);
x := -0.0009765625;
y := LambertW(x);
f := -0.977517573730222695e-3;
testrel( 7, NE, y, f, cnt,failed);
x := -1e-10;
y := LambertW(x);
f := -0.1000000000100000000e-9;
testrel( 8, NE, y, f, cnt,failed);
x := 0.0;
y := LambertW(x);
f := 0;
testrel( 9, 1, y, f, cnt,failed);
x := 1e-10;
y := LambertW(x);
f := 0.9999999999000000000e-10;
testrel(10, NE, y, f, cnt,failed);
x := 0.0009765625;
y := LambertW(x);
f := 0.9756102202467530500e-3;
testrel(11, NE, y, f, cnt,failed);
x := 0.125;
y := LambertW(x);
f := 0.1117801089327885068;
testrel(12, NE, y, f, cnt,failed);
x := 0.25;
y := LambertW(x);
f := 0.2038883547022401644;
testrel(13, NE, y, f, cnt,failed);
x := 1;
y := LambertW(x);
f := +0.5671432904097838730;
testrel(14, NE, y, f, cnt,failed);
x := 3.125;
y := LambertW(x);
f := 1.070918030310010008;
testrel(15, NE, y, f, cnt,failed);
x := 10;
y := LambertW(x);
f := 1.745528002740699383;
testrel(16, NE, y, f, cnt,failed);
x := 100;
y := LambertW(x);
f := 3.385630140290050185;
testrel(17, NE, y, f, cnt,failed);
x := 1e4;
y := LambertW(x);
f := 7.231846038093372706;
testrel(18, NE, y, f, cnt,failed);
x := 1e10;
y := LambertW(x);
f := 20.02868541330495078;
testrel(19, NE, y, f, cnt,failed);
x := MaxDouble; {2^1024}
y := LambertW(x);
f := 703.2270331047701870;
testrel(20, NE, y, f, cnt,failed);
x := 1e-300;
y := LambertW(x);
f := x;
testrel(21, NE, y, f, cnt,failed);
x := MaxDouble;
i := 1000;
while x>1e-200 do begin
y := LambertW(x);
f := ln(x/y);
if y>=0.5 then testrel(i, NE, y, f, cnt,failed)
else testabs(i, NA, y, f, cnt,failed);
x := 0.125*x;
inc(i);
end;
x := -exp(-1);
i := 10000;
while x<-MinDouble do begin
y := LambertW(x);
f := ln(x/y);
if y>=0.5 then testrel(i, NE, y, f, cnt,failed)
else testabs(i, NA, y, f, cnt,failed);
if x < -1e-7 then x := 0.95*x
else x := 0.01*x;
inc(i);
end;
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_lambertw1;
var
x,y,f: double;
cnt, failed: integer;
i: integer;
const
NE = 2;
begin
cnt := 0;
failed := 0;
writeln('Function: ','LambertW1');
x := -exp(-1);
y := LambertW1(x);
f := -1;
testrel( 1, NE, y, f, cnt,failed);
x := -6027/16384.0;
y := LambertW1(x);
f := -1.010608408692175856;
testrel( 2, 16, y, f, cnt,failed);
x := -3013/8192.0;
y := LambertW1(x);
f := -1.021210331605726089434;
testrel( 3, 8, y, f, cnt,failed);
x := -753/2048;
y := LambertW1(x);
f := -1.033649565301978476;
testrel( 4, 8, y, f, cnt,failed);
x := -0.25;
y := LambertW1(x);
f := -2.153292364110349649;
testrel( 5, NE, y, f, cnt,failed);
x := -0.125;
y := LambertW1(x);
f := -3.261685684576488777;
testrel( 6, NE, y, f, cnt,failed);
x := -0.0009765625;
y := LambertW1(x);
f := -9.144639686625083192;
testrel( 7, NE, y, f, cnt,failed);
x := -1e-10;
y := LambertW1(x);
f := -26.29523881924692569;
testrel( 8, NE, y, f, cnt,failed);
x := -1e-100;
y := LambertW1(x);
f := -235.7211588756853137;
testrel( 9, NE, y, f, cnt,failed);
x := -1e-299;
y := LambertW1(x);
f := -695.0168789367294442;
testrel(10, NE, y, f, cnt,failed);
x := -exp(-1);
i := 1000;
while x<-MinDouble do begin
y := LambertW1(x);
f := ln(x/y);
testrel(i, 2, y, f, cnt,failed);
if x < -1e-7 then x := 0.95*x
else
x := 0.01*x;
inc(i);
end;
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_debye;
var
x,y,f: double;
cnt, failed: integer;
const
NE = 4;
NE2 = 10;
NE3 = 25;
begin
cnt := 0;
failed := 0;
writeln('Function: ','debye');
{Test values debye(n,x), n=1,3,4 from MISCFUN [22]}
x := 1/512;
y := debye(1,x);
f := 0.99951182471380889183;
testrel( 1, NE, y, f, cnt,failed);
x := 1/32;
y := debye(1,x);
f := 0.99221462647120597836;
testrel( 2, NE, y, f, cnt,failed);
x := 1/8;
y := debye(1,x);
f := 0.96918395997895308324;
testrel( 3, NE, y, f, cnt,failed);
x := 1/2;
y := debye(1,x);
f := 0.88192715679060552968;
testrel( 4, NE, y, f, cnt,failed);
x := 1.0;
y := debye(1,x);
f := 0.77750463411224827642;
testrel( 5, NE, y, f, cnt,failed);
x := 2.0;
y := debye(1,x);
f := 0.60694728460981007205;
testrel( 6, NE, y, f, cnt,failed);
x := 3.0;
y := debye(1,x);
f := 0.48043521957304283829;
testrel( 7, NE, y, f, cnt,failed);
x := 4.0;
y := debye(1,x);
f := 0.38814802129793784501;
testrel( 8, NE, y, f, cnt,failed);
x := 17/4;
y := debye(1,x);
f := 0.36930802829242526815;
testrel( 9, NE, y, f, cnt,failed);
x := 5.0;
y := debye(1,x);
f := 0.32087619770014612104;
testrel(10, NE, y, f, cnt,failed);
x := 11/2;
y := debye(1,x);
f := 0.29423996623154246701;
testrel(11, NE, y, f, cnt,failed);
x := 6.0;
y := debye(1,x);
f := 0.27126046678502189985;
testrel(12, NE, y, f, cnt,failed);
x := 8.0;
y := debye(1,x);
f := 0.20523930310221503723;
testrel(13, NE, y, f, cnt,failed);
x := 10.0;
y := debye(1,x);
f := 0.16444346567994602563;
testrel(14, NE, y, f, cnt,failed);
x := 20.0;
y := debye(1,x);
f := 0.82246701178200016086e-1;
testrel(15, NE, y, f, cnt,failed);
x := 50.0;
y := debye(1,x);
f := 0.32898681336964528729e-1;
testrel(16, NE, y, f, cnt,failed);
x := 1/512;
y := debye(3,x);
f := 0.99926776885985461940;
testrel(17, NE, y, f, cnt,failed);
x := 1/32;
y := debye(3,x);
f := 0.98833007755734698212;
testrel(18, NE, y, f, cnt,failed);
x := 1/8;
y := debye(3,x);
f := 0.95390610472023510237;
testrel(19, NE, y, f, cnt,failed);
x := 1/2;
y := debye(3,x);
f := 0.82496296897623372315;
testrel(20, NE, y, f, cnt,failed);
x := 1.0;
y := debye(3,x);
f := 0.67441556407781468010;
testrel(21, NE, y, f, cnt,failed);
x := 2.0;
y := debye(3,x);
f := 0.44112847372762418113;
testrel(22, NE, y, f, cnt,failed);
x := 3.0;
y := debye(3,x);
f := 0.28357982814342246206;
testrel(23, NE, y, f, cnt,failed);
x := 4.0;
y := debye(3,x);
f := 0.18173691382177474795;
testrel(24, NE, y, f, cnt,failed);
x := 17/4;
y := debye(3,x);
f := 0.16277924385112436877;
testrel(25, NE, y, f, cnt,failed);
x := 5.0;
y := debye(3,x);
f := 0.11759741179993396450;
testrel(26, NE, y, f, cnt,failed);
x := 11/2;
y := debye(3,x);
f := 0.95240802723158889887e-1;
testrel(27, NE, y, f, cnt,failed);
x := 6.0;
y := debye(3,x);
f := 0.77581324733763020269e-1;
testrel(28, NE, y, f, cnt,failed);
x := 8.0;
y := debye(3,x);
f := 0.36560295673194845002e-1;
testrel(29, NE, y, f, cnt,failed);
x := 10.0;
y := debye(3,x);
f := 0.19295765690345489563e-1;
testrel(30, NE, y, f, cnt,failed);
x := 20.0;
y := debye(3,x);
f := 0.24352200674805479827e-2;
testrel(31, NE, y, f, cnt,failed);
x := 50.0;
y := debye(3,x);
f := 0.15585454565440389896e-3;
testrel(32, NE, y, f, cnt,failed);
x := 1/512;
y := debye(4,x);
f := 0.99921896192761576256;
testrel(33, NE, y, f, cnt,failed);
x := 1/32;
y := debye(4,x);
f := 0.98755425280996071022;
testrel(34, NE, y, f, cnt,failed);
x := 1/8;
y := debye(4,x);
f := 0.95086788606389739976;
testrel(35, NE, y, f, cnt,failed);
x := 1/2;
y := debye(4,x);
f := 0.81384569172034042516;
testrel(36, NE, y, f, cnt,failed);
x := 1.0;
y := debye(4,x);
f := 0.65487406888673697092;
testrel(37, NE, y, f, cnt,failed);
x := 2.0;
y := debye(4,x);
f := 0.41189273671788528876;
testrel(38, NE, y, f, cnt,failed);
x := 3.0;
y := debye(4,x);
f := 0.25187863642883314410;
testrel(39, NE, y, f, cnt,failed);
x := 4.0;
y := debye(4,x);
f := 0.15185461258672022043;
testrel(40, NE2, y, f, cnt,failed);
x := 17/4;
y := debye(4,x);
f := 0.13372661145921413299;
testrel(41, NE, y, f, cnt,failed);
x := 5.0;
y := debye(4,x);
f := 0.91471377664481164749e-1;
testrel(42, NE, y, f, cnt,failed);
x := 11/2;
y := debye(4,x);
f := 0.71227828197462523663e-1;
testrel(43, NE, y, f, cnt,failed);
x := 6.0;
y := debye(4,x);
f := 0.55676547822738862783e-1;
testrel(44, NE, y, f, cnt,failed);
x := 8.0;
y := debye(4,x);
f := 0.21967566525574960096e-1;
testrel(45, NE, y, f, cnt,failed);
x := 10.0;
y := debye(4,x);
f := 0.96736755602711590082e-2;
testrel(46, NE, y, f, cnt,failed);
x := 20.0;
y := debye(4,x);
f := 0.62214648623965450200e-3;
testrel(47, NE, y, f, cnt,failed);
x := 50.0;
y := debye(4,x);
f := 0.15927210319002161231e-4;
testrel(48, NE, y, f, cnt,failed);
{Rest of test values for n=6,8,12 calculated with Maple }
{f := x->n*int(t^n/(exp(t)-1),t=0..x)/x^n; and Digits:=50}
x := 1/512;
y := debye(6,x);
f := 0.9991631848471384035;
testrel(49, NE, y, f, cnt,failed);
x := 1/32;
y := debye(6,x);
f := 0.9866681772186796587;
testrel(50, NE, y, f, cnt,failed);
x := 1/8;
y := debye(6,x);
f := 0.9474049305411031823;
testrel(51, NE, y, f, cnt,failed);
x := 1/2;
y := debye(6,x);
f := 0.8012874593544054948;
testrel(52, NE, y, f, cnt,failed);
x := 1.0;
y := debye(6,x);
f := 0.6331114258349510759;
testrel(53, NE, y, f, cnt,failed);
x := 2.0;
y := debye(6,x);
f := 0.3804986630746610429;
testrel(54, NE, y, f, cnt,failed);
x := 3.0;
y := debye(6,x);
f := 0.2193992525257245836;
testrel(55, NE, y, f, cnt,failed);
x := 4.0;
y := debye(6,x);
f := 0.1229278562814578228;
testrel(56, NE2, y, f, cnt,failed);
x := 17/4;
y := debye(6,x);
f := 0.1060375248597196031;
testrel(57, NE2, y, f, cnt,failed);
x := 5.0;
y := debye(6,x);
f := 0.6777784974890353731e-1;
testrel(58, NE, y, f, cnt,failed);
x := 11/2;
y := debye(6,x);
f := 0.5020600934448088116e-1;
testrel(59, NE, y, f, cnt,failed);
x := 6.0;
y := debye(6,x);
f := 0.3719333613705515670e-1;
testrel(60, NE, y, f, cnt,failed);
x := 8.0;
y := debye(6,x);
f := 0.1145231921902748610e-1;
testrel(61, NE, y, f, cnt,failed);
x := 10.0;
y := debye(6,x);
f := 0.3793849329461595528e-2;
testrel(62, NE, y, f, cnt,failed);
x := 20.0;
y := debye(6,x);
f := 0.6804635545479456894e-4;
testrel(63, NE, y, f, cnt,failed);
x := 50.0;
y := debye(6,x);
f := 0.2787884082105527120e-6;
testrel(64, NE, y, f, cnt,failed);
x := 1/512;
y := debye(12,x);
f := 0.9990988301706686501;
testrel(65, NE, y, f, cnt,failed);
x := 1/32;
y := debye(12,x);
f := 0.9856466765478185763;
testrel(66, NE, y, f, cnt,failed);
x := 1/8;
y := debye(12,x);
f := 0.9434235095071814036;
testrel(67, NE, y, f, cnt,failed);
x := 1/2;
y := debye(12,x);
f := 0.7870231504611680153;
testrel(68, NE, y, f, cnt,failed);
x := 1.0;
y := debye(12,x);
f := 0.6088700041762235049;
testrel(69, NE, y, f, cnt,failed);
x := 2.0;
y := debye(12,x);
f := 0.3472653175019342084;
testrel(70, NE, y, f, cnt,failed);
x := 3.0;
y := debye(12,x);
f := 0.1872401059320712096;
testrel(71, NE, y, f, cnt,failed);
x := 4.0;
y := debye(12,x);
f := 0.9654143896262086549e-1;
testrel(72, NE2, y, f, cnt,failed);
x := 17/4;
y := debye(12,x);
f := 0.8134774441706960165e-1;
testrel(73, NE, y, f, cnt,failed);
x := 5.0;
y := debye(12,x);
f := 0.4814185645191148541e-1;
testrel(74, NE, y, f, cnt,failed);
x := 11/2;
y := debye(12,x);
f := 0.3367880055948328374e-1;
testrel(75, NE, y, f, cnt,failed);
x := 6.0;
y := debye(12,x);
f := 0.2344811348723500784e-1;
testrel(76, NE, y, f, cnt,failed);
x := 8.0;
y := debye(12,x);
f := 0.5344588786833453221e-2;
testrel(77, NE, y, f, cnt,failed);
x := 10.0;
y := debye(12,x);
f := 0.1198815360618837356e-2;
testrel(78, NE, y, f, cnt,failed);
x := 20.0;
y := debye(12,x);
f := 0.1348750701799345211e-5;
testrel(79, NE, y, f, cnt,failed);
x := 50.0;
y := debye(12,x);
f := 0.2354677578932315411e-10;
testrel(80, NE, y, f, cnt,failed);
{D(n,20) n=20..200}
x := 20;
f := 0.2045985597891880435e-6;
y := debye(20,x);
testrel(81, NE, y, f, cnt,failed);
f := 0.6521968411709099410e-7;
y := debye(50,x);
testrel(82, NE, y, f, cnt,failed);
f := 0.5964824507515076368e-7;
y := debye(60,x);
testrel(83, NE, y, f, cnt,failed);
f := 0.5378148028857494088e-7;
y := debye(80,x);
testrel(84, NE, y, f, cnt,failed);
f := 0.5074077974146328750e-7;
y := debye(100,x);
testrel(85, NE, y, f, cnt,failed);
f := 0.4714758392337898263e-7;
y := debye(150,x);
testrel(86, NE, y, f, cnt,failed);
f := 0.4552275137444157216e-7;
y := debye(200,x);
testrel(87, NE, y, f, cnt,failed);
{D(n,5) n=100..10000}
x := 5;
f := 0.3532560165653401053e-1;
y := debye(100,x);
testrel(88, NE, y, f, cnt,failed);
f := 0.34193472837210103295e-1;
y := debye(500,x);
testrel(89, NE2, y, f, cnt,failed);
f := 0.3410139487334168171e-1;
y := debye(750,x);
testrel(90, NE3, y, f, cnt,failed);
f := 0.3405548547450571961e-1;
y := debye(1000,x);
testrel(91, NE3, y, f, cnt,failed);
f := 0.3398678310287432440e-1;
y := debye(2000,x);
testrel(92, NE2, y, f, cnt,failed);
f := 0.3393196075652582305e-1;
y := debye(10000,x);
testrel(93, NE3, y, f, cnt,failed);
{Test after fix for large x}
y := debye(1, 100000.0);
f := 0.1644934066848226436e-4;
testrel(94, NE, y, f, cnt,failed);
x := 20000.0;
y := debye(2, x);
f := 0.1202056903159594285e-7;
testrel(95, NE, y, f, cnt,failed);
y := debye(7, x);
f := 0.2767488213020584085e-25;
testrel(96, NE2, y, f, cnt,failed);
y := debye(10, x);
f := 0.3545501280865848353e-35;
testrel(97, NE, y, f, cnt,failed);
y := debye(8, 30000.0);
f := 0.4926197640450862355e-30;
testrel(98, NE, y, f, cnt,failed);
y := debye(20, 12000);
f := 0.12691995186452421609e-61;
testrel(99, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_RiemannR;
var
y,f: double;
cnt, failed: integer;
const
NE = 2;
NE2 = 8;
begin
cnt := 0;
failed := 0;
writeln('Function: ','RiemannR');
y := RiemannR(ldexpd(1,1023));
f := 1.269399252238138694e305;
testrel( 1, NE, y, f, cnt,failed);
y := RiemannR(1e100);
f := 4.361971987140703159e97;
testrel( 2, NE, y, f, cnt,failed);
y := RiemannR(1e30);
f := 0.1469239889772043272e29;
testrel( 3, NE, y, f, cnt,failed);
y := RiemannR(1e24);
f := 0.18435599767347541878e23;
testrel( 4, NE, y, f, cnt,failed);
y := RiemannR(1e20);
f := 0.2220819602556027015e19;
testrel( 5, NE, y, f, cnt,failed);
y := RiemannR(1e19);
f := 0.2340576673002289402e18;
testrel( 6, NE, y, f, cnt,failed);
y := RiemannR(1e18);
f := 0.2473995428423949440e17;
testrel( 7, NE, y, f, cnt,failed);
y := RiemannR(1e16);
f := 0.2792383413609771872e15;
testrel( 8, NE, y, f, cnt,failed);
y := RiemannR(1e6);
f := 78527.39942912770486;
testrel( 9, NE, y, f, cnt,failed);
y := RiemannR(1000);
f := 168.3594462811673481;
testrel(10, NE2, y, f, cnt,failed);
y := RiemannR(100);
f := 25.66163326692418259;
testrel(11, NE, y, f, cnt,failed);
y := RiemannR(10);
f := 4.564583141005090240;
testrel(12, NE, y, f, cnt,failed);
y := RiemannR(8);
f := 3.901186044934149947;
testrel(13, NE, y, f, cnt,failed);
y := RiemannR(4);
f := 2.426657752706807136;
testrel(14, NE, y, f, cnt,failed);
y := RiemannR(2);
f := 1.541009016187131883;
testrel(15, NE, y, f, cnt,failed);
y := RiemannR(1);
f := 1;
testrel(16, NE, y, f, cnt,failed);
y := RiemannR(0.5);
f := 0.6635262381124574212;
testrel(17, NE, y, f, cnt,failed);
y := RiemannR(0.1);
f := 0.2790883528560020161;
testrel(18, NE, y, f, cnt,failed);
y := RiemannR(0.125);
f := 0.3124612249259569001;
testrel(19, NE, y, f, cnt,failed);
y := RiemannR(0.0625);
f := 0.2216077332920197402;
testrel(20, NE2, y, f, cnt,failed);
y := RiemannR(1e15);
f := 2.98445704958869274e13; {mpmath}
testrel(21, NE2, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_li_inv;
var
y,f: double;
cnt, failed: integer;
const
NE = 1;
NE1 = 2;
begin
cnt := 0;
failed := 0;
writeln('Function: ','li_inv');
y := li_inv(0);
f := 1.0 + 0.4513692348833810503;
testrel(1, NE, y, f, cnt,failed);
y := li_inv(0.25);
f := 1.552800837242485188;
testrel(2, NE, y, f, cnt,failed);
y := li_inv(0.5);
f := 1.671930573009875373;
testrel(3, NE, y, f, cnt,failed);
y := li_inv(0.75);
f := 1.810255009236505581;
testrel(4, NE, y, f, cnt,failed);
y := li_inv(1);
f := 1.969047489224750850;
testrel(5, NE, y, f, cnt,failed);
y := succd(1);
y := li_inv(y);
f := 1.969047489224751001;
testrel(6, NE, y, f, cnt,failed);
y := li_inv(2);
f := 2.825187152005826843;
testrel(7, NE, y, f, cnt,failed);
y := li_inv(3);
f := 4.045118486231030200;
testrel(8, NE, y, f, cnt,failed);
y := li_inv(3.5);
f := 4.786319700881971309;
testrel(9, NE, y, f, cnt,failed);
y := li_inv(4);
f := 5.609276693050890355;
testrel(10, NE, y, f, cnt,failed);
y := li_inv(5);
f := 7.480870261577641432;
testrel(11, NE1, y, f, cnt,failed);
y := li_inv(8);
f := 14.58290311807629198;
testrel(12, NE1, y, f, cnt,failed);
y := li_inv(10);
f := 20.284365456596612497;
testrel(13, NE1, y, f, cnt,failed);
y := li_inv(20);
f := 56.07960987414566197;
testrel(14, NE1, y, f, cnt,failed);
y := li_inv(100);
f := 488.8719098528075319;
testrel(15, NE, y, f, cnt,failed);
y := li_inv(1000);
f := 7762.986220174737687;
testrel(16, NE, y, f, cnt,failed);
y := li_inv(-0.25);
f := 1.365970426374257461;
testrel(17, NE, y, f, cnt,failed);
y := li_inv(-0.5);
f := 1.294838891062147533;
testrel(18, NE, y, f, cnt,failed);
y := li_inv(-0.75);
f := 1.236183126594032207;
testrel(19, NE, y, f, cnt,failed);
y := li_inv(-1);
f := 1.188256066274325355;
testrel(20, NE, y, f, cnt,failed);
y := li_inv(-10);
f := 1.000025489896249632;
testrel(21, NE, y, f, cnt,failed);
y := li_inv(-15);
f := 1.0 + 0.1717517441415356666e-6;
testrel(22, NE, y, f, cnt,failed);
y := li_inv(-40);
f := 1.0 + 0.238528e-17;
testrel(23, NE, y, f, cnt,failed);
y := li_inv(-43.5);
f := 1 + 0.72e-19;
testrel(24, NE, y, f, cnt,failed);
y := li_inv(1e10);
f := 0.2520971600140342078e12;
testrel(25, NE, y, f, cnt,failed);
y := li_inv(1e100);
f := 0.2347125735865764178e103;
testrel(26, NE, y, f, cnt,failed);
y := li_inv(1e300);
f := 0.6963198968074983689e303;
testrel(27, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_bernpoly;
var
x,y,f: double;
cnt, failed: integer;
const
NE = 4;
NE1 = 6;
NE2 = 12;
begin
cnt := 0;
failed := 0;
writeln('Function: ','bernpoly');
y := bernpoly(1,-1);
f := -3/2;
testrel(1, NE, y, f, cnt,failed);
y := bernpoly(7,-1);
f := -7;
testrel(2, NE, y, f, cnt,failed);
y := bernpoly(8,-1);
f := 239/30;
testrel(3, NE, y, f, cnt,failed);
y := bernpoly(1,1);
f := 0.5;
testrel(4, NE, y, f, cnt,failed);
y := bernpoly(7,1);
f := 0;
testrel(5, NE, y, f, cnt,failed);
y := bernpoly(8,1);
f := -0.3333333333333333333e-1;
testrel(6, NE, y, f, cnt,failed);
{some 'normal' case}
y := bernpoly(10,-0.75);
f := 0.7507730252815015388;
testrel(7, NE, y, f, cnt,failed);
y := bernpoly(12,1/3);
f := 0.1265560621400686431;
testrel(8, NE, y, f, cnt,failed);
y := bernpoly(11,-0.125);
f := -0.9375500085297971964e-1;
testrel(9, NE, y, f, cnt,failed);
y := bernpoly(20, 0.375);
f := 374.14698287953266697;
testrel(10, NE, y, f, cnt,failed);
y := bernpoly(15,-1.25);
f := -343.8455539522692561;
testrel(11, NE, y, f, cnt,failed);
y := bernpoly(12,2.5);
f := 1038.229552462511447;
testrel(12, NE, y, f, cnt,failed);
x := 10000+1/3;
y := bernpoly(15,x);
f := 0.9997499416835207086e60;
testrel(13, NE1, y, f, cnt,failed);
y := bernpoly(10,x);
f := 0.9998333083377781148e40;
testrel(14, NE, y, f, cnt,failed);
x := sqrt(1e21);
y := bernpoly(15,x);
f := 0.3162277659418379332e158;
testrel(15, NE, y, f, cnt,failed);
x := sqrt(1e21);
y := bernpoly(10,x);
f := 0.9999999998418861170e105;
testrel(16, NE, y, f, cnt,failed);
y := bernpoly(256,0.5);
f := 0.7950212504588525285e303;
testrel(17, NE, y, f, cnt,failed);
y := bernpoly(100,0.5);
f := 2.838224957069370696e78;
testrel(18, NE, y, f, cnt,failed);
x := -987654321.0/65536.0; {=15070.4089508056641}
y := bernpoly(70,x);
f := 0.2949584500818898822e293;
testrel(19, NE, y, f, cnt,failed);
x := 1e-5;
y := bernpoly(7,x);
f := 0.1666666665500000000e-5;
testrel(20, NE, y, f, cnt,failed);
x := 1e-5;
y := bernpoly(6,x);
f := 0.2380952375952380955e-1;
testrel(21, NE, y, f, cnt,failed);
x := 0.5e-5;
y := bernpoly(6,x);
f := 0.2380952379702380953e-1;
testrel(22, NE, y, f, cnt,failed);
x := 1e-11;
y := bernpoly(2,x);
f := 0.1666666666566666667;
testrel(23, NE, y, f, cnt,failed);
y := bernpoly(3,x);
f := 0.4999999999850000000e-11;
testrel(24, NE, y, f, cnt,failed);
y := bernpoly(4,x);
f := -0.3333333333333333333e-1;
testrel(25, NE, y, f, cnt,failed);
y := bernpoly(5,x);
f := -0.1666666666666666667e-11;
testrel(26, NE, y, f, cnt,failed);
x := 1e-12;
y := bernpoly(15,x);
f := 0.175e-10;
testrel(27, NE, y, f, cnt,failed);
x := 1e-10;
y := bernpoly(15,x);
f := 0.175e-8;
testrel(28, NE, y, f, cnt,failed);
x := 1e-10;
y := bernpoly(20,x);
f := -529.1242424242424241;
testrel(29, NE, y, f, cnt,failed);
x := 2e-10;
y := bernpoly(51,x);
f := 0.7650884080998503652e17;
testrel(30, NE, y, f, cnt,failed);
x := 1e-5;
y := bernpoly(51,x);
f := 0.3825442037982211854e22;
testrel(31, NE, y, f, cnt,failed);
x := 1e-5;
y := bernpoly(101,x);
f := -0.2866607204753912463e76;
testrel(32, NE, y, f, cnt,failed);
x := 3e5;
y := bernpoly(16,x);
f := 0.4304557309700593800e88;
testrel(33, NE, y, f, cnt,failed);
x := -100;
y := bernpoly(2,x);
f := 10100.16666666666667;
testrel(34, NE, y, f, cnt,failed);
x := -Pi;
y := bernpoly(15,x);
f := -0.1374730009236393778e9;
testrel(35, NE, y, f, cnt,failed);
x := sqrt(10);
y := bernpoly(20,x);
f := 46168783.47767854148;
testrel(36, NE, y, f, cnt,failed);
y := bernpoly(15,x);
f := 732699.8879814299995;
testrel(37, NE, y, f, cnt,failed);
x := 1/4;
y := bernpoly(68,x);
f := 0.8896458292761226510e22;
testrel(38, NE2, y, f, cnt,failed);
x := 2/3;
y := bernpoly(70,x);
f := -0.1606254105135901626e45;
testrel(39, NE2, y, f, cnt,failed);
x := -1.75;
y := bernpoly(75,x);
f := 0.6794407537645821705e50;
testrel(40, NE2, y, f, cnt,failed);
x := 4.75;
y := bernpoly(120,x);
f := 0.2450175593271593322e71;
testrel(41, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_cosint;
var
y,f: double;
cnt, failed: integer;
const
NE = 4;
NE2 = 6;
NE3 = 10;
begin
cnt := 0;
failed := 0;
writeln('Function: ','cosint');
{special case}
y := cosint(10000,0);
f := 0;
testrel(1, NE, y, f, cnt,failed);
f := -1234.5;
y := cosint(0,f);
testrel(2, NE, y, f, cnt,failed);
y := cosint(1,-1234.5);
f := -0.1453956505229364208;
testrel(3, NE, y, f, cnt,failed);
{------------------------------}
y := cosint(10,4);
f := 1.158627877632916986;
testrel(4, NE, y, f, cnt,failed);
y := cosint(10,5);
f := 1.159689565748002596;
testrel(5, NE2, y, f, cnt,failed);
y := cosint(10,Pi);
f := 0.7731263170943631798;
testrel(6, NE, y, f, cnt,failed);
y := cosint(10,Pi_2);
f := 0.3865631585471815899;
testrel(7, NE3, y, f, cnt,failed);
y := cosint(10,19*Pi_2);
f := 7.344700012396450208;
testrel(8, NE2, y, f, cnt,failed);
y := cosint(10,-19*Pi_2);
f := -7.344700012396450208;
testrel(9, NE2, y, f, cnt,failed);
y := cosint(10,100);
f := 24.38341351832059336;
testrel(10, NE2, y, f, cnt,failed);
y := cosint(5,1);
f := 0.5286328129112155881;
testrel(11, NE, y, f, cnt,failed);
y := cosint(17,Pi_2);
f := 32768/109395;
testrel(12, NE, y, f, cnt,failed);
y := cosint(20,1.25);
f := 0.2767696820752703606;
testrel(13, NE, y, f, cnt,failed);
y := cosint(20,10);
f := 1.935371243364068614;
testrel(14, NE, y, f, cnt,failed);
y := cosint(99,TwoPi);
f := 0;
testabs(15, 2, y, f, cnt,failed);
y := cosint(99,4);
f := -0.1256451290185490101;
testrel(16, NE2, y, f, cnt,failed);
y := cosint(9,30);
f := -0.4063492055789358166;
testrel(17, NE, y, f, cnt,failed);
y := cosint(200,10000);
f := 563.5558003428517485;
testrel(18, NE, y, f, cnt,failed);
y := cosint(600,100000);
f := 3255.962631924894514;
testrel(19, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_sinint;
var
y,f: double;
cnt, failed: integer;
const
NE = 4;
NE2 = 8;
NE3 = 16;
begin
cnt := 0;
failed := 0;
writeln('Function: ','sinint');
{special case}
y := sinint(10000,0);
f := 0;
testrel(1, NE, y, f, cnt,failed);
f := -1234.5;
y := sinint(0,f);
testrel(2, NE, y, f, cnt,failed);
y := sinint(1,-1234.5);
f := 1.989373592132422007;
testrel(3, NE, y, f, cnt,failed);
{------------------------------}
y := sinint(6,0.5);
f := 0.9185547761246106100e-3;
testrel(4, NE, y, f, cnt,failed);
y := sinint(6,1.5);
f := 0.4204309461889264874;
testrel(5, NE, y, f, cnt,failed);
y := sinint(6,2.5);
f := 0.9771099714670822183;
testrel(6, NE, y, f, cnt,failed);
y := sinint(6,3.0);
f := 0.9817475437693720085;
testrel(7, NE, y, f, cnt,failed);
y := sinint(6,5.0);
f := 1.737945254534703918;
testrel(18, NE, y, f, cnt,failed);
y := sinint(6,8.0);
f := 2.597326791887639688;
testrel(9, NE, y, f, cnt,failed);
y := sinint(6,11.0);
f := 3.440542590614796164;
testrel(10, NE, y, f, cnt,failed);
y := sinint(6,-4.0);
f := -1.009340246947754459;
testrel(11, NE, y, f, cnt,failed);
y := sinint(6,-20.0);
f := -6.025751555775555279;
testrel(12, NE, y, f, cnt,failed);
y := sinint(5,0.5);
f := 0.2226985853239443664e-2;
testrel(13, NE, y, f, cnt,failed);
y := sinint(5,1.5);
f := 0.4628317450440416392;
testrel(14, NE, y, f, cnt,failed);
y := sinint(5,2.5);
f := 1.057683460168249835;
testrel(15, NE, y, f, cnt,failed);
y := sinint(5,3.5);
f := 1.066340666683688580;
testrel(16, NE, y, f, cnt,failed);
y := sinint(5,4.5);
f := 0.7379679184068533471;
testrel(17, NE, y, f, cnt,failed);
y := sinint(5,5.5);
f := 0.2618445135450898748e-1;
testrel(18, NE, y, f, cnt,failed);
y := sinint(5,6.5);
f := 0.16811939182727524784e-4;
testrel(19, NE, y, f, cnt,failed);
y := sinint(10,Pi_2);
f := 0.3865631585471815899;
testrel(20, NE, y, f, cnt,failed);
y := sinint(10,Pi);
f := 0.7731263170943631798;
testrel(21, NE, y, f, cnt,failed);
y := sinint(10,-13*Pi_2);
f := -5.025321061113360669;
testrel(22, NE2, y, f, cnt,failed);
y := sinint(9,Pi_2);
f := 0.4063492063492063492;
testrel(23, NE, y, f, cnt,failed);
y := sinint(9,Pi);
f := 0.8126984126984126984;
testrel(24, NE, y, f, cnt,failed);
y := sinint(9,-TwoPi);
f := 0;
testrel(25, NE, y, f, cnt,failed);
y := sinint(9,-13*Pi_2);
f := 0.4063492063492063492;
testrel(26, NE3, y, f, cnt,failed);
y := sinint(99,0.5);
f := 0.1341426041012494184e-33;
testrel(27, NE2, y, f, cnt,failed);
y := sinint(99,2);
f := 0.2512885482248272477;
testrel(28, NE, y, f, cnt,failed);
y := sinint(99,Pi_2);
f := 0.1256451290185490101;
testrel(29, NE, y, f, cnt,failed);
y := sinint(100,0.5);
f := 0.6367642770299571293e-34;
testrel(30, NE, y, f, cnt,failed);
y := sinint(100,2);
f := 0.2500354235665634526;
testrel(31, NE, y, f, cnt,failed);
y := sinint(100,Pi_2);
f := 0.1250184817401874538;
testrel(32, NE2, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_fibpoly;
var
x,y,f,r: double;
cnt, failed, k,n: integer;
const
NE = 4;
{$ifdef FPC}
NE1 = 540; {32-Bit/SSE2 only}
{$else}
NE1 = 420;
{$endif}
{$ifdef BIT16}
const
tol=5;
{$else}
const
tol=2;
{$endif}
{Values directly from Maple, note that the 16-bit compilers are inaccurate}
{for some literals of length > 19, therefore the tolerance is increased !}
const
fp15: array[-10..10] of double = (
-450359962737049.599999999999998,
14073748835532.8000000000000113,
-439804651110.399999999999636200,
13743895347.2000000000116415321,
-429496729.599999999627470970153,
13421772.8000000119209289550781,
-419430.0 - 0.3999996185302734375, {16 Bit!}
13107.20001220703125,
-409.599609375,
12.8125,
0,
12.8125,
409.599609375,
13107.20001220703125,
419430.0 + 0.3999996185302734375, {16 Bit!}
13421772.8000000119209289550781,
429496729.599999999627470970153,
13743895347.2000000000116415321,
439804651110.399999999999636200,
14073748835532.8000000000000113,
450359962737049.599999999999998);
fm25: array[-10..10] of double = (
17491671035336584642638.2191390,
92899200757966079853.9563808855,
493392625783670135.494300316212,
2620434634437155.42014947329880,
13917268549466.5442822966724634,
73915357907.6294983029365539548,
392568420.6778049468994140625,
2084951.0 + 0.88653564453125, {16 Bit!}
11073.291015625,
58.8125,
0,
58.8125,
-11073.291015625,
2084951.0 + 0.88653564453125, {16 Bit!}
-392568420.6778049468994140625,
73915357907.6294983029365539548,
-13917268549466.5442822966724634,
2620434634437155.42014947329880,
-493392625783670135.494300316212,
92899200757966079853.9563808855,
-17491671035336584642638.2191390);
begin
{pari: fib(n,x) = ([x,1;1,0]^(n-1))[1,1]}
cnt := 0;
failed := 0;
writeln('Function: ','fibpoly');
y := fibpoly(10,1.5);
f := 409.599609375;
testrel(1, NE, y, f, cnt,failed);
y := fibpoly(15,-Pi);
f := 0.2909849191767565688e8; {Fib(15, asd(Pi))}
testrel(2, NE, y, f, cnt,failed);
y := fibpoly(123,1.5);
f := 0.4253529586511730793e37;
testrel(3, NE, y, f, cnt,failed);
y := fibpoly(123,-1.5);
f := 0.4253529586511730793e37;
testrel(4, NE, y, f, cnt,failed);
y := fibpoly(-123,1.5);
f := 0.4253529586511730793e37;
testrel(5, NE, y, f, cnt,failed);
y := fibpoly(-123,-1.5);
f := 0.4253529586511730793e37;
testrel(6, NE, y, f, cnt,failed);
y := fibpoly(234,1.5);
f := 0.1104279415486490206e71;
testrel(7, NE, y, f, cnt,failed);
y := fibpoly(234,-1.5);
f := -0.1104279415486490206e71;
testrel(8, NE, y, f, cnt,failed);
y := fibpoly(-234,1.5);
f := -0.1104279415486490206e71;
testrel(9, NE, y, f, cnt,failed);
y := fibpoly(-234,-1.5);
f := 0.1104279415486490206e71;
testrel(10, NE, y, f, cnt,failed);
{Max n for F(n) = fibpoly(n,1) is 23601, 1476 for double}
y := fibpoly(1476, 1);
f := 0.1306989223763399318e309;
testrel(11, NE, y, f, cnt,failed);
y := fibpoly(32000, 1/32);
f := 6.875799035044984665e216;
testrel(12, NE1, y, f, cnt,failed);
x := 1.5;
for k:=-10 to 10 do begin
inc(cnt);
n := 5*k;
y := fibpoly(n,x);
f := fp15[k];
if f=0.0 then r := y-f
else r := 1.0-y/f;
if abs(r) > tol*eps_d then begin
inc(failed);
writeln('Test failed: n,x,err= ',n:4, x:8:2, r:30);
end;
end;
x := -2.5;
for k:=-10 to 10 do begin
inc(cnt);
n := 5*k;
y := fibpoly(n,x);
f := fm25[k];
if f=0.0 then r := y-f
else r := 1.0-y/f;
if abs(r) > tol*eps_d then begin
inc(failed);
writeln('Test failed: n,x,err= ',n:4, x:8:2, r:30);
end;
end;
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_lucpoly;
var
y,f: double;
cnt, failed: integer;
const
NE = 4;
begin
{Pari: luc(n,x) = trace([x,1;1,0]^n) }
{Maple: luc := (n,x) -> fibonacci(n+1,x) + fibonacci(n-1,x); }
cnt := 0;
failed := 0;
writeln('Function: ','lucpoly');
y := lucpoly(0,0);
f := 2;
testrel(1, NE, y, f, cnt,failed);
y := lucpoly(1,0);
f := 0;
testabs(2, 0, y, f, cnt,failed);
y := lucpoly(2,0);
f := 2;
testrel(3, NE, y, f, cnt,failed);
y := lucpoly(3,0);
f := 0;
testabs(4, 0, y, f, cnt,failed);
y := lucpoly(-1,0);
f := 0;
testabs(5, 0, y, f, cnt,failed);
y := lucpoly(-2,0);
f := 2;
testrel(6, NE, y, f, cnt,failed);
y := lucpoly(-3,0);
f := 0;
testabs(7, 0, y, f, cnt,failed);
y := lucpoly(1,1.5);
f := 1.5;
testrel(8, NE, y, f, cnt,failed);
y := lucpoly(2,1.5);
f := 4.25;
testrel(9, NE, y, f, cnt,failed);
y := lucpoly(9,1.5);
f := 511.998046875;
testrel(10, NE, y, f, cnt,failed);
y := lucpoly(9,-1.5);
f := -511.998046875;
testrel(11, NE, y, f, cnt,failed);
y := lucpoly(-9,1.5);
f := -511.998046875;
testrel(12, NE, y, f, cnt,failed);
y := lucpoly(-9,-1.5);
f := 511.998046875;
testrel(13, NE, y, f, cnt,failed);
y := lucpoly(10,1.5);
f := 1024.0009765625;
testrel(14, NE, y, f, cnt,failed);
y := lucpoly(10,-1.5);
f := 1024.0009765625;
testrel(15, NE, y, f, cnt,failed);
y := lucpoly(-10,1.5);
f := 1024.0009765625;
testrel(16, NE, y, f, cnt,failed);
y := lucpoly(-10,-1.5);
f := 1024.0009765625;
testrel(17, NE, y, f, cnt,failed);
y := lucpoly(125,1.5);
f := 0.4253529586511730793e38;
testrel(18, NE, y, f, cnt,failed);
y := lucpoly(125,-1.5);
f := -0.4253529586511730793e38;
testrel(19, NE, y, f, cnt,failed);
y := lucpoly(-125,1.5);
f := -0.4253529586511730793e38;
testrel(20, NE, y, f, cnt,failed);
y := lucpoly(-125,-1.5);
f := 0.4253529586511730793e38;
testrel(21, NE, y, f, cnt,failed);
y := lucpoly(234,1.5);
f := 0.2760698538716225515e71;
testrel(22, NE, y, f, cnt,failed);
y := lucpoly(234,-1.5);
f := 0.2760698538716225515e71;
testrel(23, NE, y, f, cnt,failed);
y := lucpoly(-234,1.5);
f := 0.2760698538716225515e71;
testrel(24, NE, y, f, cnt,failed);
y := lucpoly(-234,-1.5);
f := 0.2760698538716225515e71;
testrel(25, NE, y, f, cnt,failed);
y := lucpoly(-123,4.5);
f := -6.407383962038300961e82; {Wolfram Alpha}
testrel(26, NE, y, f, cnt,failed);
{Max n for L(n) = lucpoly(n,1) is 23599, 1474 for double}
y := lucpoly(1474,1);
f := 1.116302065883468286e308;
testrel(27, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_catalan;
var
y,f: double;
cnt, failed: integer;
const
NE = 2;
NE1 = 4;
begin
cnt := 0;
failed := 0;
writeln('Function: ','catalan');
y := catalan(0);
f := 1;
testrel(1, NE, y, f, cnt,failed);
y := catalan(1e-9);
f := 1.999999998000000005*0.5;
testrel(2, NE1, y, f, cnt,failed); {'large' error for arg 1e-9}
y := catalan(0.125);
f := 0.4542281453407636314 * 2;
testrel(3, NE, y, f, cnt,failed);
y := catalan(0.5);
f := 0.8488263631567751241;
testrel(4, NE, y, f, cnt,failed);
y := catalan(2.5);
f := 3.104279270973349025;
testrel(5, NE, y, f, cnt,failed);
y := catalan(21);
f := 24466267020.0;
testrel(6, NE, y, f, cnt,failed);
y := catalan(35);
{$ifdef BIT16}
f := 0.38953568686341265775e18 * 8;
{$else}
f := 3116285494907301262.0;
{$endif}
testrel(7, NE, y, f, cnt,failed);
y := catalan(100);
f := 0.8965199470901314967e57;
testrel(8, NE, y, f, cnt,failed);
y := catalan(500);
f := 0.5394974869170390609e297;
testrel(9, NE, y, f, cnt,failed);
y := catalan(-1);
f := -0.5;
testrel(10, NE, y, f, cnt,failed);
y := catalan(-1.25);
f := -0.3934468663386987420;
testrel(11, NE1, y, f, cnt,failed); {D18/64 on AMD}
y := catalan(-12.375);
f := -0.1218624678667657878e-8;
testrel(12, NE1, y, f, cnt,failed);
y := catalan(-45.625);
f := 0.1538947487306520572e-29;
testrel(13, NE, y, f, cnt,failed);
y := catalan(-123.875);
f := 0.4497289298048582343e-78;
testrel(14, NE, y, f, cnt,failed);
y := catalan(-456.75);
f := 0.5916664229531300294e-279;
testrel(15, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
{---------------------------------------------------------------------------}
procedure test_kepler;
var
y,f: double;
cnt, failed: integer;
const
NE = 2;
{$ifdef BIT64}
NE2 = 2;
{$else}
NE2 = 10;
{$endif}
begin
cnt := 0;
failed := 0;
writeln('Function: ','kepler');
{elliptic, Maple: kepler := (m,e) -> fsolve(y-e*sin(y) = m, y=Pi);}
y := kepler(1, 0.5);
f := 1.498701133517848314;
testrel(1, NE, y, f, cnt,failed);
y := kepler(-1000, 0.5);
f := -1000.497514775673146;
testrel(2, NE, y, f, cnt,failed);
y := kepler(Pi_2, 0.75);
f := 2.184106679498448926;
testrel(3, NE, y, f, cnt,failed);
y := kepler(0.5, 0.125);
f := 0.5671542538034771510;
testrel(4, NE, y, f, cnt,failed);
y := kepler(0.125, 0.9375);
f := 0.7928034322756140260;
testrel(5, NE, y, f, cnt,failed);
y := kepler(1.5, 0.9375);
f := 2.237023829054169401;
testrel(6, NE, y, f, cnt,failed);
y := kepler(10.125, 0.9375);
f := 9.790088287071411171;
testrel(7, NE, y, f, cnt,failed);
y := kepler(0.125, 0.99609375);
f := 0.9136395753855342618;
testrel(8, NE, y, f, cnt,failed);
{in difficult region m near 0, e near 1}
y := 1-ldexpd(1,-15);
y := kepler(1/512, y);
f := 0.2270684928814436695;
testrel(9, NE2, y, f, cnt,failed);
{arguments from literature, somewhat inexact with binary}
y := kepler(0.2, 0.99);
f := 1.066997365281563186;
testrel(10, NE, y, f, cnt,failed);
y := kepler(0.06, 0.6);
f := 0.1491710835982268287;
testrel(11, NE, y, f, cnt,failed);
y := kepler(1, 0.9);
f := 1.862086686874532255;
testrel(12, NE, y, f, cnt,failed);
{hyperbolic, Maple: kepler_hyp := (m,e) -> fsolve(e*sinh(x) - x - m, x = signum(m)*ln(2*abs(m)/e + 1.8));}
y := kepler(-1000, 10);
f := -5.303631719539061703;
testrel(13, NE, y, f, cnt,failed);
y := kepler(1, 2);
f := 0.8140967963021331692;
testrel(14, NE, y, f, cnt,failed);
y := kepler(6,2);
f := 2.107689797681256377;
testrel(15, NE, y, f, cnt,failed);
y := kepler(0.5,1.5);
f := 0.7673431749540970103;
testrel(16, NE, y, f, cnt,failed);
y := kepler(Maxdouble,1.5);
f := 710.07039496583577777;
testrel(17, NE, y, f, cnt,failed);
y := kepler(10,6);
f := 1+0.3978298998186000144;
testrel(18, NE, y, f, cnt,failed);
y := kepler(10000,20);
f := 6.9084468837654158448;
testrel(19, NE, y, f, cnt,failed);
y := kepler(1,20);
f := 0.5260603476886937829e-1;
testrel(20, NE, y, f, cnt,failed);
y := kepler(0,2);
f := 0;
testrel(21, NE, y, f, cnt,failed);
y := kepler(1e-6,1.5);
f := 0.1999999999996000000e-5;
testrel(22, NE, y, f, cnt,failed);
{parabolic, Maple: kepler_para := m -> fsolve(x + x^3/3 = m, x = m^(1/3));}
y := kepler(2, 1);
f := 1.287909750704127236;
testrel(23, NE, y, f, cnt,failed);
y := kepler(1, 1);
f := 0.8177316738868235061;
testrel(24, NE, y, f, cnt,failed);
y := kepler(0.5,1.0);
f := 0.4662205239107734274;
testrel(25, NE, y, f, cnt,failed);
y := kepler(0.125, 1);
f := 0.124358923863462980055;
testrel(26, NE, y, f, cnt,failed);
y := kepler(1/1024, 1);
f := 0.9765621895594378539e-3;
testrel(27, NE, y, f, cnt,failed);
y := kepler(-1000, 1);
f := -14.35316011237345298;
testrel(28, NE, y, f, cnt,failed);
y := kepler(sqrt_epsh,1.0);
f := 0.1053671212772350756e-7;
testrel(29, NE, y, f, cnt,failed);
y := kepler(1.25e25,1.0);
f := 0.33471647504108475795e9;
testrel(30, NE, y, f, cnt,failed);
y := kepler(Maxdouble, 1.0);
f := 0.8139772587397598764e103;
testrel(31, NE, y, f, cnt,failed);
y := kepler(0.25*Maxdouble, 1.0);
f := 0.5127735412109745435e103;
testrel(32, NE, y, f, cnt,failed);
if failed>0 then writeln('*** failed: ',failed,' of ',cnt)
else writeln(cnt:4, ' tests OK');
inc(total_cnt, cnt);
inc(total_failed, failed);
end;
end.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.FlipView.Types;
interface
{$SCOPEDENUMS ON}
uses
System.Classes, FMX.Filter.Effects, FGX.Types;
type
{ TfgFlipViewSlideOptions }
/// <summary>Direction of switching images in [Sliding] mode</summary>
TfgSlideDirection = (Horizontal, Vertical);
/// <summary>Way of switching image slides</summary>
/// <remarks>
/// <list type="bullet">
/// <item><c>Effects</c> - switching slides by transition effects</item>
/// <item><c>Sliding</c> - switching slides by shifting of images</item>
/// <item><c>Custom</c> - user's way. Requires implementation a presentation with name <b>FlipView-Custom</b></item>
/// </list>
/// </remarks>
TfgFlipViewMode = (Effects, Sliding, Custom);
/// <summary>Direction of sliding</summary>
TfgDirection = (Forward, Backward);
TfgChangingImageEvent = procedure (Sender: TObject; const NewItemIndex: Integer) of object;
IfgFlipViewNotifications = interface
['{0D4A9AF7-4B56-4972-8EF2-5693AFBD2857}']
procedure StartChanging;
procedure FinishChanging;
end;
/// <summary>Settings of slider in [Sliding] mode</summary>
TfgFlipViewSlideOptions = class(TfgPersistent)
public const
DefaultDirection = TfgSlideDirection.Horizontal;
DefaultDuration = 0.4;
private
FDirection: TfgSlideDirection;
FDuration: Single;
procedure SetSlideDirection(const Value: TfgSlideDirection);
procedure SetDuration(const Value: Single);
function IsDurationStored: Boolean;
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(AOwner: TComponent); override;
function IsDefaultValues: Boolean; override;
published
property Direction: TfgSlideDirection read FDirection write SetSlideDirection default DefaultDirection;
property Duration: Single read FDuration write SetDuration stored IsDurationStored nodefault;
end;
{ TfgEffectSlidingOptions }
TfgImageFXEffectClass = class of TImageFXEffect;
TfgTransitionEffectKind = (Random, Blind, Line, Crumple, Fade, Ripple, Dissolve, Circle, Drop, Swirl, Magnify, Wave,
Blood, Blur, Water, Wiggle, Shape, RotateCrumple, Banded, Saturate, Pixelate);
/// <summary>Settings of slider in [Effect] mode</summary>
TfgFlipViewEffectOptions = class(TfgPersistent)
public const
DefaultKind = TfgTransitionEffectKind.Random;
DefaultDuration = 0.4;
private
FKind: TfgTransitionEffectKind;
FDuration: Single;
procedure SetKind(const Value: TfgTransitionEffectKind);
procedure SetDuration(const Value: Single);
function GetTransitionEffectClass: TfgImageFXEffectClass;
function IsDurationStored: Boolean;
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(AOwner: TComponent); override;
function IsDefaultValues: Boolean; override;
property TransitionEffectClass: TfgImageFXEffectClass read GetTransitionEffectClass;
published
property Kind: TfgTransitionEffectKind read FKind write SetKind default DefaultKind;
property Duration: Single read FDuration write SetDuration stored IsDurationStored nodefault;
end;
{ TfgFlipViewSlideShowOptions }
TfgFlipViewSlideShowOptions = class(TfgPersistent)
public const
DefaultEnabled = False;
DefaultDuration = 4;
private
FEnabled: Boolean;
FDuration: Integer;
procedure SetDuration(const Value: Integer);
procedure SetEnabled(const Value: Boolean);
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(AOwner: TComponent); overload; override;
function IsDefaultValues: Boolean; override;
published
property Duration: Integer read FDuration write SetDuration default DefaultDuration;
property Enabled: Boolean read FEnabled write SetEnabled default DefaultEnabled;
end;
implementation
uses
System.Math, FGX.Consts, FGX.Asserts;
const
TRANSITION_EFFECTS: array [TfgTransitionEffectKind] of TfgImageFXEffectClass = (nil, TBlindTransitionEffect,
TLineTransitionEffect, TCrumpleTransitionEffect, TFadeTransitionEffect, TRippleTransitionEffect,
TDissolveTransitionEffect, TCircleTransitionEffect, TDropTransitionEffect, TSwirlTransitionEffect,
TMagnifyTransitionEffect, TWaveTransitionEffect, TBloodTransitionEffect, TBlurTransitionEffect,
TWaterTransitionEffect, TWiggleTransitionEffect, TShapeTransitionEffect, TRotateCrumpleTransitionEffect,
TBandedSwirlTransitionEffect, TSaturateTransitionEffect, TPixelateTransitionEffect);
{ TfgSlidingOptions }
procedure TfgFlipViewSlideOptions.AssignTo(Dest: TPersistent);
begin
AssertIsNotNil(Dest);
if Dest is TfgFlipViewSlideOptions then
begin
TfgFlipViewSlideOptions(Dest).Direction := Direction;
TfgFlipViewSlideOptions(Dest).Duration := Duration;
end
else
inherited AssignTo(Dest);
end;
constructor TfgFlipViewSlideOptions.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDirection := DefaultDirection;
FDuration := DefaultDuration;
end;
function TfgFlipViewSlideOptions.IsDefaultValues: Boolean;
begin
Result := (Direction = DefaultDirection) and not IsDurationStored;
end;
function TfgFlipViewSlideOptions.IsDurationStored: Boolean;
begin
Result := not SameValue(Duration, DefaultDuration, EPSILON_SINGLE);
end;
procedure TfgFlipViewSlideOptions.SetDuration(const Value: Single);
begin
Assert(Value >= 0);
if not SameValue(Value, Duration, EPSILON_SINGLE) then
begin
FDuration := Max(0, Value);
DoInternalChanged;
end;
end;
procedure TfgFlipViewSlideOptions.SetSlideDirection(const Value: TfgSlideDirection);
begin
if Direction <> Value then
begin
FDirection := Value;
DoInternalChanged;
end;
end;
{ TfgEffectSlidingOptions }
procedure TfgFlipViewEffectOptions.AssignTo(Dest: TPersistent);
var
DestOptions: TfgFlipViewEffectOptions;
begin
AssertIsNotNil(Dest);
if Dest is TfgFlipViewEffectOptions then
begin
DestOptions := TfgFlipViewEffectOptions(Dest);
DestOptions.Kind := Kind;
DestOptions.Duration := Duration;
end
else
inherited AssignTo(Dest);
end;
constructor TfgFlipViewEffectOptions.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FKind := DefaultKind;
FDuration := DefaultDuration;
end;
function TfgFlipViewEffectOptions.GetTransitionEffectClass: TfgImageFXEffectClass;
var
RandomEffectKind: TfgTransitionEffectKind;
begin
if Kind = TfgTransitionEffectKind.Random then
begin
RandomEffectKind := TfgTransitionEffectKind(Random(Integer(High(TfgTransitionEffectKind))) + 1);
Result := TRANSITION_EFFECTS[RandomEffectKind];
end
else
Result := TRANSITION_EFFECTS[Kind];
AssertIsNotNil(Result, 'TfgFlipViewEffectOptions.GetTransitionEffectClass must return class of effect.');
end;
function TfgFlipViewEffectOptions.IsDefaultValues: Boolean;
begin
Result := not IsDurationStored and (Kind = DefaultKind);
end;
function TfgFlipViewEffectOptions.IsDurationStored: Boolean;
begin
Result := not SameValue(Duration, DefaultDuration, EPSILON_SINGLE);
end;
procedure TfgFlipViewEffectOptions.SetKind(const Value: TfgTransitionEffectKind);
begin
if Kind <> Value then
begin
FKind := Value;
DoInternalChanged;
end;
end;
procedure TfgFlipViewEffectOptions.SetDuration(const Value: Single);
begin
Assert(Value >= 0);
if not SameValue(Value, Duration, EPSILON_SINGLE) then
begin
FDuration := Max(0, Value);
DoInternalChanged;
end;
end;
{ TfgFlipViewSlideShowOptions }
procedure TfgFlipViewSlideShowOptions.AssignTo(Dest: TPersistent);
var
DestOptions: TfgFlipViewSlideShowOptions;
begin
AssertIsNotNil(Dest);
if Dest is TfgFlipViewSlideShowOptions then
begin
DestOptions := TfgFlipViewSlideShowOptions(Dest);
DestOptions.Enabled := Enabled;
DestOptions.Duration := Duration;
end
else
inherited AssignTo(Dest);
end;
constructor TfgFlipViewSlideShowOptions.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEnabled := DefaultEnabled;
FDuration := DefaultDuration;
end;
function TfgFlipViewSlideShowOptions.IsDefaultValues: Boolean;
begin
Result := (Duration = DefaultDuration) and (Enabled = DefaultEnabled);
end;
procedure TfgFlipViewSlideShowOptions.SetDuration(const Value: Integer);
begin
Assert(Value >= 0);
if Duration <> Value then
begin
FDuration := Max(0, Value);
DoInternalChanged;
end;
end;
procedure TfgFlipViewSlideShowOptions.SetEnabled(const Value: Boolean);
begin
if Enabled <> Value then
begin
FEnabled := Value;
DoInternalChanged;
end;
end;
end.
|
unit uServerMethods;
interface
uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth,
System.JSON, uClienteCRUD, uCidades;
type
{$METHODINFO ON}
TServerMethods1 = class(TComponent)
private
{ Private declarations }
vloCliente : TClienteCRUD;
vloCidade : TCidades;
public
{ Public declarations }
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
function Ping: String;
function fncValidaLogin(psUsuarioSenha: String) : TJSONObject;
function fncGravarCliente(psDadosCliente: String): TJSONObject;
function fncExcluiCliente(psCodigo: String): TJSONObject;
function fncConsultaCliente(psCodigo: String): TJSONObject;
function fncConsultaCidades(psCidades: String): TJSONObject;
function fncRetornaUltimoCliente: Integer;
function fncPing: TJSONObject;
end;
{$METHODINFO OFF}
implementation
uses System.StrUtils, uServidor, FireDAC.Comp.Client, uDMServer;
function TServerMethods1.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods1.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
function TServerMethods1.fncConsultaCidades(psCidades: String): TJSONObject;
var
vlJsonObject, vlPropertyJson : TJSONObject;
vlJsonList:TJsonArray;
FoCidades : TFDQuery;
begin
vlJsonObject := TJSONObject.Create;
vlJsonList := TJsonArray.Create;
vloCidade := TCidades.Create(DMServer.FDConexao);
try
try
FoCidades := vloCidade.fncRetornaCidades;
FoCidades.First;
FoCidades.FetchAll;
while not FoCidades.Eof do
begin
if TRim(FoCidades.FieldByName('CID_DESCRICAO').AsString) <> '' then
begin
vlPropertyJson := TJSONObject.Create;
vlPropertyJson.AddPair('CID_DESCRICAO', FoCidades.FieldByName('CID_DESCRICAO').AsString);
vlJsonList.AddElement(vlPropertyJson);
end;
FoCidades.Next;
end;
vlJsonObject.AddPair('Cidades', vlJsonList);
Result := vlJsonObject;
except
on E:Exception do
begin
FServidor.pcdMensagemLOG(E.Message);
end;
end;
finally
FreeAndNil(vloCidade);
FreeAndNil(FoCidades);
end;
end;
function TServerMethods1.fncConsultaCliente(psCodigo: String): TJSONObject;
var
vlJsonObject, vlPropertyJson : TJSONObject;
vlJsonList:TJsonArray;
vliCLI_CODIGO : TJSONValue;
vloClientes : TFDQuery;
vlbUnicoCliente : Boolean;
begin
vlbUnicoCliente := False;
vlJsonList := TJsonArray.Create;
vlJsonObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(psCodigo), 0) as TJSONObject;
vliCLI_CODIGO := vlJsonObject.GetValue('CLI_CODIGO') as TJSONValue;
vloCliente := TClienteCRUD.Create(DMServer.FDConexao);
try
vloCliente.CLI_CODIGO := StrToInt(vliCLI_CODIGO.Value);
try
vloClientes := vloCliente.fncConsultaClientes;
if vloCliente.CLI_CODIGO <> 0 then
vlbUnicoCliente := True;
vloClientes.First;
vloClientes.FetchAll;
while not vloClientes.Eof do
begin
if TRim(vloClientes.FieldByName('CLI_RAZAO').AsString) <> '' then
begin
vlPropertyJson := TJSONObject.Create;
if not vlbUnicoCliente then
begin
vlPropertyJson.AddPair('CLI_CODIGO', vloClientes.FieldByName('CLI_CODIGO').AsString);
vlPropertyJson.AddPair('CLI_RAZAO', vloClientes.FieldByName('CLI_RAZAO').AsString);
end
else
begin
vlPropertyJson.AddPair('CLI_CODIGO', vloClientes.FieldByName('CLI_CODIGO').AsString);
vlPropertyJson.AddPair('CLI_RAZAO', vloClientes.FieldByName('CLI_RAZAO').AsString);
vlPropertyJson.AddPair('CLI_TELEFONE', vloClientes.FieldByName('CLI_TELEFONE').AsString);
vlPropertyJson.AddPair('CLI_TIPOPESSOA', vloClientes.FieldByName('CLI_TIPOPESSOA').AsString);
vlPropertyJson.AddPair('CLI_CNPJCPF', vloClientes.FieldByName('CLI_CNPJCPF').AsString);
vlPropertyJson.AddPair('CLI_RETAGUARDA', vloClientes.FieldByName('CLI_RETAGUARDA').AsString);
vlPropertyJson.AddPair('CLI_PDV', vloClientes.FieldByName('CLI_PDV').AsString);
vlPropertyJson.AddPair('CLI_EMAIL', vloClientes.FieldByName('CLI_EMAIL').AsString);
vlPropertyJson.AddPair('CLI_ENDERECO', vloClientes.FieldByName('CLI_ENDERECO').AsString);
vlPropertyJson.AddPair('CLI_NUMERO', vloClientes.FieldByName('CLI_NUMERO').AsString);
vlPropertyJson.AddPair('CLI_CIDADE', vloClientes.FieldByName('CLI_CIDADE').AsString);
vlPropertyJson.AddPair('CID_DESCRICAO', vloClientes.FieldByName('CID_DESCRICAO').AsString);
vlPropertyJson.AddPair('CLI_ESTADO', vloClientes.FieldByName('CLI_ESTADO').AsString);
vlPropertyJson.AddPair('CLI_CEP', vloClientes.FieldByName('CLI_CEP').AsString);
vlPropertyJson.AddPair('CLI_IE', vloClientes.FieldByName('CLI_IE').AsString);
vlPropertyJson.AddPair('CLI_REVENDA', vloClientes.FieldByName('CLI_REVENDA').AsString);
vlPropertyJson.AddPair('CLI_BAIRRO', vloClientes.FieldByName('CLI_BAIRRO').AsString);
vlPropertyJson.AddPair('CLI_DATACADASTRO', vloClientes.FieldByName('CLI_DATACADASTRO').AsString);
vlPropertyJson.AddPair('CLI_TIPOLICENCA', vloClientes.FieldByName('CLI_TIPOLICENCA').AsString);
end;
vlJsonList.AddElement(vlPropertyJson);
end;
vloClientes.Next;
end;
FreeAndNil(vlJsonObject);
vlJsonObject := TJSONObject.Create;
vlJsonObject.AddPair('Clientes', vlJsonList);
Result := vlJsonObject;
except
on E:Exception do
begin
FServidor.pcdMensagemLOG(E.Message);
end;
end;
finally
FreeAndNil(vloCliente);
FreeAndNil(vloClientes);
end;
end;
function TServerMethods1.fncExcluiCliente(psCodigo: String): TJSONObject;
var
vlJsonObject, vlJsonResult : TJSONObject;
vliCLI_CODIGO : TJSONValue;
begin
vlJsonObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(psCodigo), 0) as TJSONObject;
vlJsonResult := TJSONObject.Create;
vliCLI_CODIGO := vlJsonObject.GetValue('CLI_CODIGO') as TJSONValue;
vloCliente := TClienteCRUD.Create(DMServer.FDConexao);
try
vloCliente.CLI_CODIGO := StrToInt(vliCLI_CODIGO.Value);
try
vloCliente.pcdExluirCliente;
vlJsonResult.AddPair('Retorno', 'Ok');
except
on E:Exception do
begin
FServidor.pcdMensagemLOG(E.Message);
vlJsonResult.AddPair('Retorno', E.Message);
end;
end;
finally
FreeAndNil(vloCliente);
Result := vlJsonResult;
end;
end;
function TServerMethods1.fncGravarCliente(psDadosCliente: String): TJSONObject;
var
vlsCLI_ENDERECO, vlsCLI_ESTADO, vlsCLI_TELEFONE, vlsCLI_RAZAO,
vlsCLI_TIPOPESSOA, vlsCLI_BAIRRO, vlsCLI_EMAIL, vlsCLI_TIPOLICENCA,
vlsCLI_CEP, vlsCLI_CNPJCPF, vlsCLI_IE, vlsCLI_NUMERO, vlsCLI_CIDADE,
vlsCLI_DATACADASTRO: TJSONString;
vliCLI_RETAGUARDA, vliCLI_REVENDA, vliCLI_CODIGO, vliCLI_PDV: TJSONValue;
vlJsonObject, vlJsonResult : TJSONObject;
begin
vlJsonObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(psDadosCliente), 0) as TJSONObject;
vlJsonResult := TJSONObject.Create;
vliCLI_CODIGO := vlJsonObject.GetValue('CLI_CODIGO') as TJSONValue;
vlsCLI_RAZAO := vlJsonObject.GetValue('CLI_RAZAO') as TJSONString;
vlsCLI_TELEFONE := vlJsonObject.GetValue('CLI_TELEFONE') as TJSONString;
vlsCLI_TIPOPESSOA := vlJsonObject.GetValue('CLI_TIPOPESSOA') as TJSONString;
vlsCLI_CNPJCPF := vlJsonObject.GetValue('CLI_CNPJCPF') as TJSONString;
vliCLI_RETAGUARDA := vlJsonObject.GetValue('CLI_RETAGUARDA') as TJSONValue;
vliCLI_PDV := vlJsonObject.GetValue('CLI_PDV') as TJSONValue;
vlsCLI_EMAIL := vlJsonObject.GetValue('CLI_EMAIL') as TJSONString;
vlsCLI_ENDERECO := vlJsonObject.GetValue('CLI_ENDERECO') as TJSONString;
vlsCLI_NUMERO := vlJsonObject.GetValue('CLI_NUMERO') as TJSONString;
vlsCLI_BAIRRO := vlJsonObject.GetValue('CLI_BAIRRO') as TJSONString;
vlsCLI_CIDADE := vlJsonObject.GetValue('CLI_CIDADE') as TJSONString;
vlsCLI_ESTADO := vlJsonObject.GetValue('CLI_ESTADO') as TJSONString;
vlsCLI_CEP := vlJsonObject.GetValue('CLI_CEP') as TJSONString;
vlsCLI_IE := vlJsonObject.GetValue('CLI_IE') as TJSONString;
vliCLI_REVENDA := vlJsonObject.GetValue('CLI_REVENDA') as TJSONValue;
vlsCLI_DATACADASTRO := vlJsonObject.GetValue('CLI_DATACADASTRO') as TJSONString;
vlsCLI_TIPOLICENCA := vlJsonObject.GetValue('CLI_TIPOLICENCA') as TJSONString;
if not Assigned(vloCliente) then
vloCliente := TClienteCRUD.Create(DMServer.FDConexao);
try
if ((vliCLI_CODIGO.Value = '0') or (vliCLI_CODIGO.Value = '')) then
vloCliente.CLI_CODIGO := fncRetornaUltimoCliente
else
vloCliente.CLI_CODIGO := StrToInt(vliCLI_CODIGO.ToString);
vloCliente.CLI_RAZAO := StringReplace(vlsCLI_RAZAO.Value, '+', ' ', [rfReplaceAll]);
vloCliente.CLI_TELEFONE := vlsCLI_TELEFONE.Value;
vloCliente.CLI_TIPOPESSOA := vlsCLI_TIPOPESSOA.Value;
vloCliente.CLI_CNPJCPF := vlsCLI_CNPJCPF.Value;
vloCliente.CLI_RETAGUARDA := StrToInt(vliCLI_RETAGUARDA.Value);
vloCliente.CLI_PDV := StrToInt(vliCLI_PDV.Value);
vloCliente.CLI_EMAIL := vlsCLI_EMAIL.Value;
vloCliente.CLI_ENDERECO := StringReplace(vlsCLI_ENDERECO.Value, '+', ' ', [rfReplaceAll]);
vloCliente.CLI_NUMERO := vlsCLI_NUMERO.Value;
vloCliente.CLI_BAIRRO := StringReplace(vlsCLI_BAIRRO.Value, '+', ' ', [rfReplaceAll]);
vloCliente.psCidadeDescricao := StringReplace(vlsCLI_CIDADE.Value, '+', ' ', [rfReplaceAll]);
vloCliente.CLI_ESTADO := vlsCLI_ESTADO.Value;
vloCliente.CLI_CEP := vlsCLI_CEP.Value;
vloCliente.CLI_IE := vlsCLI_IE.Value;
vloCliente.CLI_REVENDA := StrToInt(vliCLI_REVENDA.Value);
vloCliente.CLI_DATACADASTRO := Date();
vloCliente.CLI_TIPOLICENCA := vlsCLI_TIPOLICENCA.Value;
try
vloCliente.pcdGravarCliente;
vlJsonResult.AddPair('Retorno', 'Ok');
except
on E:Exception do
begin
FServidor.pcdMensagemLOG(E.Message);
vlJsonResult.AddPair('Retorno', E.Message);
end;
end;
finally
FreeAndNil(vloCliente);
Result := vlJsonResult;
end;
end;
function TServerMethods1.fncPing: TJSONObject;
var
vlJsonResult : TJSONObject;
begin
vlJsonResult := TJSONObject.Create;
vlJsonResult.AddPair('Retorno', 'Ok');
Result := vlJsonResult;
end;
function TServerMethods1.fncRetornaUltimoCliente: Integer;
var
vloQuery : TFDQuery;
begin
Result := 0;
vloQuery := TFDQuery.Create(nil);
try
vloQuery.Close;
vloQuery.Connection := DMServer.FDConexao;
vloQuery.SQL.Clear;
vloQuery.SQL.Add('SELECT MAX(CLI_CODIGO) AS ULTIMO FROM CLIENTE');
vloQuery.Open();
Result := vloQuery.FieldByName('ULTIMO').AsInteger + 1;
FServidor.pcdMensagemLOG('Retorno da função fncRetornaUltimoCliente: ' + Result.ToString);
finally
FreeAndNil(vloQuery);
end;
end;
function TServerMethods1.fncValidaLogin(psUsuarioSenha: String): TJSONObject;
var
vlsUsuario, vlsSenha: TJSONString;
vlJsonObject, vlJsonResult : TJSONObject;
vloQuery : TFDQuery;
begin
vlJsonObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(psUsuarioSenha), 0) as TJSONObject;
vlJsonResult := TJSONObject.Create;
vlsUsuario := vlJsonObject.GetValue('REP_CODIGO') as TJSONString;
vlsSenha := vlJsonObject.GetValue('REP_SENHA') as TJSONString;
vloQuery := TFDQuery.Create(nil);
try
vloQuery.Close;
vloQuery.Connection := DMServer.FDConexao;
vloQuery.SQL.Clear;
vloQuery.SQL.Add('SELECT REP_CODIGO FROM REPRESENTANTE WHERE REP_CODIGO = :CODIGO AND REP_SENHA = :SENHA');
vloQuery.ParamByName('CODIGO').AsString := vlsUsuario.Value;
vloQuery.ParamByName('SENHA').AsString := vlsSenha.Value;
vloQuery.Open();
if not vloQuery.IsEmpty then
begin
vlJsonResult.AddPair('Retorno', 'Ok');
vloQuery.Close;
vloQuery.Connection := DMServer.FDConexao;
vloQuery.SQL.Clear;
vloQuery.SQL.Add('SELECT REP_DESCRICAO FROM REPRESENTANTE WHERE REP_CODIGO = :CODIGO');
vloQuery.ParamByName('CODIGO').AsString := vlsUsuario.Value;
vloQuery.Open();
vlJsonResult.AddPair('NOME_REVENDA', vloQuery.FieldByName('REP_DESCRICAO').AsString);
FServidor.pcdMensagemLOG('Usuário: ' + vlsUsuario.Value + ' localizado com sucesso!');
end
else
begin
vlJsonResult.AddPair('Retorno', '');
vlJsonResult.AddPair('NOME_REVENDA', '');
FServidor.pcdMensagemLOG('Usuário: ' + vlsUsuario.Value + ' não localizado ou senha não confere!');
end;
finally
FreeAndNil(vloQuery);
Result := vlJsonResult;
end;
end;
function TServerMethods1.Ping: String;
begin
FServidor.pcdMensagemLOG('Teste de Conexão na função Ping');
Result := 'Ok';
end;
end.
|
namespace Sugar.Test;
interface
uses
Sugar,
Sugar.Collections,
Sugar.RegularExpressions,
RemObjects.Elements.EUnit;
type
RegularExpressionsTest = public class (Test)
private
const ContactNumbers: String = "Voice: (425) 555-1234. Fax: (206) 555-5678.";
const PhoneNumberPattern: String = "\((\d{3})\) (\d{3}-\d{4})";
const PhoneNumberTypePattern: String = "([a-zA-Z]+):";
public
method FindMatchesSequentially;
method FindMatchesAllAtOnce;
method IgnoreCase;
method IgnoreWhitespace;
method Multiline;
method ReplaceMatches;
method Singleline;
end;
implementation
method RegularExpressionsTest.FindMatchesSequentially;
begin
var FirstMatch: Match := new Regex(PhoneNumberPattern).FindFirstMatch(ContactNumbers);
Assert.IsNotNil(FirstMatch);
Assert.AreEqual(FirstMatch.Start, 7);
Assert.AreEqual(FirstMatch.End, 20);
Assert.AreEqual(FirstMatch.Length, 14);
Assert.AreEqual(FirstMatch.Text, "(425) 555-1234");
Assert.AreEqual(FirstMatch.Groups.Count, 2);
Assert.AreEqual(FirstMatch.Groups.Item[0].Start, 8);
Assert.AreEqual(FirstMatch.Groups.Item[0].End, 10);
Assert.AreEqual(FirstMatch.Groups.Item[0].Length, 3);
Assert.AreEqual(FirstMatch.Groups.Item[0].Text, "425");
Assert.AreEqual(FirstMatch.Groups.Item[1].Start, 13);
Assert.AreEqual(FirstMatch.Groups.Item[1].End, 20);
Assert.AreEqual(FirstMatch.Groups.Item[1].Length, 8);
Assert.AreEqual(FirstMatch.Groups.Item[1].Text, "555-1234");
var SecondMatch: Match := FirstMatch.FindNext();
Assert.IsNotNil(SecondMatch);
Assert.AreEqual(SecondMatch.Start, 28);
Assert.AreEqual(SecondMatch.End, 41);
Assert.AreEqual(SecondMatch.Length, 14);
Assert.AreEqual(SecondMatch.Text, "(206) 555-5678");
Assert.AreEqual(SecondMatch.Groups.Count, 2);
Assert.AreEqual(SecondMatch.Groups.Item[0].Start, 29);
Assert.AreEqual(SecondMatch.Groups.Item[0].End, 31);
Assert.AreEqual(SecondMatch.Groups.Item[0].Length, 3);
Assert.AreEqual(SecondMatch.Groups.Item[0].Text, "206");
Assert.AreEqual(SecondMatch.Groups.Item[1].Start, 34);
Assert.AreEqual(SecondMatch.Groups.Item[1].End, 41);
Assert.AreEqual(SecondMatch.Groups.Item[1].Length, 8);
Assert.AreEqual(SecondMatch.Groups.Item[1].Text, "555-5678");
Assert.IsNil(SecondMatch.FindNext());
end;
method RegularExpressionsTest.FindMatchesAllAtOnce;
begin
var Matches: List<Match> := new Regex(PhoneNumberTypePattern).FindMatches(ContactNumbers);
Assert.AreEqual(Matches.Count, 2);
Assert.AreEqual(Matches.Item[0].Start, 0);
Assert.AreEqual(Matches.Item[0].End, 5);
Assert.AreEqual(Matches.Item[0].Length, 6);
Assert.AreEqual(Matches.Item[0].Text, "Voice:");
Assert.AreEqual(Matches.Item[0].Groups.Count, 1);
Assert.AreEqual(Matches.Item[0].Groups.Item[0].Start, 0);
Assert.AreEqual(Matches.Item[0].Groups.Item[0].End, 4);
Assert.AreEqual(Matches.Item[0].Groups.Item[0].Length, 5);
Assert.AreEqual(Matches.Item[0].Groups.Item[0].Text, "Voice");
Assert.AreEqual(Matches.Item[1].Start, 23);
Assert.AreEqual(Matches.Item[1].End, 26);
Assert.AreEqual(Matches.Item[1].Length, 4);
Assert.AreEqual(Matches.Item[1].Text, "Fax:");
Assert.AreEqual(Matches.Item[1].Groups.Count, 1);
Assert.AreEqual(Matches.Item[1].Groups.Item[0].Start, 23);
Assert.AreEqual(Matches.Item[1].Groups.Item[0].End, 25);
Assert.AreEqual(Matches.Item[1].Groups.Item[0].Length, 3);
Assert.AreEqual(Matches.Item[1].Groups.Item[0].Text, "Fax");
end;
method RegularExpressionsTest.IgnoreCase;
const
Pattern: String = "FAX: (" + PhoneNumberPattern + ")";
begin
var CaseSensitiveRegex := new Regex(Pattern);
Assert.IsFalse(CaseSensitiveRegex.IsMatch(ContactNumbers));
var CaseInsensitiveRegex := new Regex(Pattern, RegexOptions.IgnoreCase);
Assert.IsTrue(CaseInsensitiveRegex.IsMatch(ContactNumbers));
end;
method RegularExpressionsTest.IgnoreWhitespace;
begin
var RegexWithWhitespace := new Regex(PhoneNumberPattern);
Assert.IsTrue(RegexWithWhitespace.IsMatch(ContactNumbers));
Assert.IsFalse(RegexWithWhitespace.IsMatch(ContactNumbers.Replace(" ", "")));
var RegexWithoutWhitespace := new Regex(PhoneNumberPattern, RegexOptions.IgnoreWhitespace);
Assert.IsFalse(RegexWithoutWhitespace.IsMatch(ContactNumbers));
Assert.IsTrue(RegexWithoutWhitespace.IsMatch(ContactNumbers.Replace(" ", "")));
end;
method RegularExpressionsTest.Multiline;
const
DelimitedPhoneNumberPattern: String = "^" + PhoneNumberPattern + "$";
begin
var MultilineContactNumbers: String := ContactNumbers.Replace(": ", ":"#10).Replace(". ", #10);
var NonMultilineRegex := new Regex(DelimitedPhoneNumberPattern);
Assert.IsFalse(NonMultilineRegex.IsMatch(ContactNumbers));
Assert.IsFalse(NonMultilineRegex.IsMatch(MultilineContactNumbers));
var MultilineRegex := new Regex(DelimitedPhoneNumberPattern, RegexOptions.Multiline);
Assert.IsFalse(MultilineRegex.IsMatch(ContactNumbers));
Assert.IsTrue(MultilineRegex.IsMatch(MultilineContactNumbers));
end;
method RegularExpressionsTest.ReplaceMatches;
const
FaxPattern: String = "Fax:";
VoicePattern: String = "Voice:";
begin
var FaxRegex: Regex := new Regex(FaxPattern);
var VoiceRegex: Regex := new Regex(VoicePattern);
var AlteredContactNumbers: String := VoiceRegex.ReplaceMatches(ContactNumbers, FaxPattern);
Assert.AreEqual(FaxRegex.FindMatches(ContactNumbers).Count, 1);
Assert.AreEqual(VoiceRegex.FindMatches(ContactNumbers).Count, 1);
Assert.AreEqual(FaxRegex.FindMatches(AlteredContactNumbers).Count, 2);
Assert.AreEqual(VoiceRegex.FindMatches(AlteredContactNumbers).Count, 0);
end;
method RegularExpressionsTest.Singleline;
begin
var MultilineContactNumbers: String := ContactNumbers.Replace(": ", ":"#10).Replace(". ", #10);
var NonSinglelineRegex := new Regex(PhoneNumberTypePattern + ".");
Assert.IsTrue(NonSinglelineRegex.IsMatch(ContactNumbers));
Assert.IsFalse(NonSinglelineRegex.IsMatch(MultilineContactNumbers));
var SinglelineRegex := new Regex(PhoneNumberTypePattern + ".", RegexOptions.Singleline);
Assert.IsTrue(SinglelineRegex.IsMatch(ContactNumbers));
Assert.IsTrue(SinglelineRegex.IsMatch(MultilineContactNumbers));
end;
end.
|
unit KM_Hand;
interface
uses
Windows, System.SysUtils,
KM_Consts, KM_HandAI_Ext, ExtAIInfo;
type
// Game class for Hand. It hides the ExtAI inside of it
TKMHand = class
private
fHandIndex: TKMHandIndex;
fAIExt: THandAI_Ext;
public
constructor Create(aHandIndex: TKMHandIndex); reintroduce;
destructor Destroy; override;
property AIExt: THandAI_Ext read fAIExt;
property HandIndex: TKMHandIndex read fHandIndex;
// KP sets AI type after init
procedure SetAIType(aExtAI: TExtAIInfo);
procedure UpdateState(aTick: Cardinal);
end;
implementation
uses
ExtAILog;
{ TKMHand }
constructor TKMHand.Create(aHandIndex: TKMHandIndex);
begin
Inherited Create;
fHandIndex := aHandIndex;
fAIExt := nil;
gLog.Log('THand-Create: HandIndex = %d', [fHandIndex]);
end;
destructor TKMHand.Destroy;
begin
FreeAndNil(fAIExt);
gLog.Log('THand-Destroy: HandIndex = %d', [fHandIndex]);
Inherited;
end;
procedure TKMHand.SetAIType(aExtAI: TExtAIInfo);
begin
fAIExt := THandAI_Ext.Create(fHandIndex, aExtAI);
end;
procedure TKMHand.UpdateState(aTick: Cardinal);
begin
if (fAIExt <> nil) then
fAIExt.UpdateState(aTick);
end;
end.
|
(******************************************************************)
(* Structures for DelZip v1.7 *)
(* Copyright (C)1997-2004 E. W. Engler, C. Vleghert, M. Stephany *)
(* *)
(* written by Markus Stephany *)
(* mailto:delphizip@mirkes.de *)
(* http://delphizip.mirkes.de *)
(* *)
(* last changed: 12/21/2003 *)
(* *)
(******************************************************************)
(************************************************************************
Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht,
Eric W. Engler and Chris Vleghert.
This file is part of TZipMaster Version 1.9.
TZipMaster is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TZipMaster is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with TZipMaster. If not, see <http://www.gnu.org/licenses/>.
contact: problems@delphizip.org (include ZipMaster in the subject).
updates: http://www.delphizip.org
DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip
************************************************************************)
unit ZMSFXStructs19;
{
this unit contains definitions of records and signatures used
in zipfiles.
}
interface
uses
Windows;
{$I '..\ZipVers19.inc'}
const
FS_FAT: Integer = 0;
FS_HPFS: Integer = 6;
FS_NTFS: Integer = 11;
FLAG_UTF8_BIT = $0800;
Zip64_data_tag = $0001; // Zip64 extra field tag
NTFS_STAMP_TAG = $000A; // NTFS time stamps
UPath_Data_Tag = $7075; // Info-Zip UTF8 path field
UCmnt_Data_Tag = $6375; // Info-Zip UTF8 comment field
// Tag - 2 byte
// total size - 2 byte
// version - 1 byte = 1
// crc -4 bytes = crc of orig field
// utf8 string - total size - 9
type
XNTFSData = packed record
MTime: Int64;
ATime: Int64;
CTime: Int64;
end;
PXNTFData = ^XNTFSData;
type
PUString_Data_Header = ^UString_Data_Header;
UString_Data_Header = packed record
tag: word;
totsiz: word;
version: byte;
origcrc: DWORD;
end;
type
// local file header entry
PZipLocalHeader = ^TZipLocalHeader;
TZipLocalHeader = packed record
HeaderSig: LongWord;
VersionNeed: Word;
Flag: Word;
ComprMethod: Word;
ModifTime: Word;
ModifDate: Word;
CRC32: LongWord;
ComprSize: LongWord;
UnComprSize: LongWord;
FileNameLen: Word;
ExtraLen: Word;
end;
// ZipLocalHeader = TZipLocalHeader;
// central directory entry
PZipCentralHeader = ^TZipCentralHeader;
TZipCentralHeader = packed record //fixed part size : 42 bytes
HeaderSig: LongWord; // hex: 02014B50(4)
VersionMadeBy0: Byte; //version made by(1)
VersionMadeBy1: Byte; //host number(1)
VersionNeed: Word; // version needed to extract(2)
Flag: Word; //generalPurpose bitflag(2)
ComprMethod: Word; //compression method(2)
ModifTime: Word; // modification time(2)
ModifDate: Word; // modification date(2)
CRC32: LongWord; //Cycling redundancy check (4)
ComprSize: LongWord; //compressed file size (4)
UnComprSize: LongWord; //uncompressed file size (4)
FileNameLen: Word; //(2)
ExtraLen: Word; //(2)
FileComLen: Word; //(2)
DiskStart: Word; //starts on disk number xx(2)
IntFileAtt: Word; //internal file attributes(2)
ExtFileAtt: LongWord; //external file attributes(4)
RelOffLocal: LongWord; //relative offset of local file header(4)
// not used as part of this record structure:
// filename, extra data, file comment
end;
// ZipCentralHeader = TZipCentralHeader;
pZ64CentralEntry = ^TZ64CentralEntry;
TZ64CentralEntry = packed record // used internally
HeaderSig: LongWord; // hex: 02014B50(4)
VersionMadeBy0: Byte; //version made by(1)
VersionMadeBy1: Byte; //host number(1)
VersionNeed: Word; // version needed to extract(2)
Flag: Word; //generalPurpose bitflag(2)
ComprMethod: Word; //compression method(2)
ModifTime: Word; // modification time(2)
ModifDate: Word; // modification date(2)
CRC32: LongWord; //Cycling redundancy check (4)
ComprSize: Int64; //compressed file size (4)
UnComprSize: Int64; //uncompressed file size (4)
FileNameLen: Word; //(2)
ExtraLen: Word; //(2)
FileComLen: Word; //(2)
DiskStart: Word; //starts on disk number xx(2)
IntFileAtt: Word; //internal file attributes(2)
ExtFileAtt: LongWord; //external file attributes(4)
RelOffLocal: Int64; //relative offset of local file header(4)
MTime: Int64; // ntfs modified time - only if data available
ATime: Int64; // ntfs accessed time - only if data available
CTime: Int64; // ntfs created time - only if data available
// not used as part of this record structure:
// filename, extra data, file comment
end;
// end of central directory record
PZipEndOfCentral = ^TZipEndOfCentral;
TZipEndOfCentral = packed record //Fixed part size : 22 bytes
HeaderSig: LongWord; //(4) hex=06054B50
ThisDiskNo: Word; //(2)This disk's number
CentralDiskNo: Word; //(2)Disk number central directory start
CentralEntries: Word; //(2)Number of central directory entries on this disk
TotalEntries: Word; //(2)Number of entries in central dir
CentralSize: LongWord; //(4)Size of central directory
CentralOffSet: LongWord; //(4)offsett of central directory on 1st disk
ZipCommentLen: Word; //(2)
// not used as part of this record structure:
// ZipComment
end;
// ZipEndOfCentral = TZipEndOfCentral;
// ext local header (for spanning ?)
PZipExtLocalHeader = ^TZipExtLocalHeader;
TZipExtLocalHeader = packed record
DataDescSig: LongWord; // Should be 0x08074B50
CRC32: LongWord;
ComprSize: LongWord;
UnComprSize: LongWord;
end;
// ZipExtLocalHeader = TZipExtLocalHeader;
// ZipDataDescriptor = TZipExtLocalHeader;
type
// must be same disk as EOC
pZip64EOCLocator = ^TZip64EOCLocator;
TZip64EOCLocator = packed record
LocSig: Longword; // (4) Should be 0x07064B50
EOC64DiskStt: Longword; // (4)
EOC64RelOfs: Int64; // (8) relative to start of it's disk
NumberDisks: Longword; // (4) total disks
end;
// pZip64EOCLocator = ^TZip64EOCLocator;
type
pZipEOC64 = ^TZipEOC64;
TZipEOC64 = packed record
EOC64Sig: LongWord; // (4) should be 0x06064b50
vsize: Int64; // (8) size of variable part
// variable part - fields as needed? (old field = 0XFFFF or 0XFF)
VersionMade: Word; // (2)
VersionNeed: Word; // (2)
ThisDiskNo: LongWord; // (4)
CentralDiskNo: LongWord; // (4)
CentralEntries: Int64; // (8) Number of central dir entries on this disk
TotalEntries: Int64; // (8) Number of entries in central dir
CentralSize: Int64; // (8) Size of central directory
CentralOffSet: Int64; // (8) offsett of central dir on 1st disk
// zip64 extensible data sector (variable size)
end;
type
TZipCentralDigitSignature = packed record
CenDigSig: LongWord; // (4) should be 0x05054b50
vsize: Word; // (2)
// data[vsize]
end;
var { these are stored in reverse order }
// xyz-1: avoid zip structure signatures in the sfx code
// zipdll.dll doesn't like them...
ZipLocalHeaderSig: DWORD = $04034B50-1; { 'PK'34 (in file: 504b0304) }
ZipCentralHeaderSig: DWORD = $02014B50-1; { 'PK'12 }
ZipEndOfCentralSig: DWORD = $06054B50-1; { 'PK'56 }
ZipExtLocalHeaderSig: DWORD = $08074B50-1; { 'PK'78 }
ZipEndCentral64Sig: DWORD = $06064B50-1; { 'PK'66 }
ZipEOC64LocatorSig: DWORD = $07064B50-1; { 'PK'67 }
// buffer stuff (not anymore public in zipmstr.pas)
const
SFXBufSize = 8192;
// Zip64_data_tag = $0001; // zip64 extra field tag
MAX_UNSIGNED:DWORD = $FFFFFFFF;
MAX_WORD:WORD = $FFFF;
MAX_BYTE:BYTE = $FF;
type
PSFXBuffer = ^TSFXBuffer;
TSFXBuffer = array[0..SFXBufSize - 1] of Byte;
implementation
initialization
// adjust the signatures
Inc(ZipLocalHeaderSig);
Inc(ZipCentralHeaderSig);
Inc(ZipEndOfCentralSig);
Inc(ZipExtLocalHeaderSig);
Inc(ZipEndCentral64Sig);
Inc(ZipEOC64LocatorSig);
end.
|
{
redis command
}
unit uRedisCommand;
interface
uses
Classes, SysUtils;
type
TRedisCommand = class
private
FCommandList: TStrings;
public
constructor Create(); virtual;
destructor Destroy; override;
function Clear(): TRedisCommand;
function Add(aValue: String): TRedisCommand; overload;
function Add(aValue: Integer): TRedisCommand; overload;
function ToRedisCommand: TBytes;
end;
implementation
const
//回车换行
C_CRLF = #$0D#$0A;
{ TRedisCommand }
function TRedisCommand.Add(aValue: String): TRedisCommand;
begin
FCommandList.Add(aValue);
Result := Self;
end;
function TRedisCommand.Add(aValue: Integer): TRedisCommand;
begin
FCommandList.Add(IntToStr(aValue));
Result := Self;
end;
function TRedisCommand.Clear: TRedisCommand;
begin
FCommandList.Clear;
Result := Self;
end;
constructor TRedisCommand.Create;
begin
inherited;
FCommandList := TStringList.Create;
end;
destructor TRedisCommand.Destroy;
begin
FCommandList.Free;
inherited;
end;
{
发送命令:
*<参数数量> CR LF
$<参数 1 的字节数量> CR LF
<参数 1 的数据> CR LF
...
$<参数 N 的字节数量> CR LF
<参数 N 的数据> CR LF
}
function TRedisCommand.ToRedisCommand: TBytes;
var
aCmd: string;
i, aLen: Integer;
begin
//参数个数
aCmd := '*' + IntToStr(FCommandList.Count) + C_CRLF;
//params
for i := 0 to FCommandList.Count - 1 do
begin
//string len
aLen := TEncoding.UTF8.GetByteCount(FCommandList.Strings[i]);
aCmd := aCmd + '$' + IntToStr(aLen) + C_CRLF
+ FCommandList.Strings[i] + C_CRLF;
end;
Result := TEncoding.UTF8.GetBytes(aCmd);
end;
end.
|
unit evEditControl;
{* Базовый класс поля редактора }
// Модуль: "w:\common\components\gui\Garant\Everest\qf\evEditControl.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevEditControl" MUID: (48D2409102B7)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, evControl
, evQueryCardInt
, evEditorControlList
, l3Interfaces
, nevTools
, nevBase
;
type
TevEditControl = class(TevControl, IevEditorControlField)
{* Базовый класс поля редактора }
private
f_ChildList: TevEditorControlList;
{* Список дочерних виджетов }
f_ErrorColor: Boolean;
{* Цвет ошибочного кода }
f_IsOtherFieldInited: Boolean;
protected
procedure DoSynchronizeSelectedValueWithText; virtual;
function GetHasOtherField: Boolean; virtual;
procedure AfterSetText(const Value: Il3CString); virtual;
function GetSelectAllOnFocus: Boolean; virtual;
function GetIsClear: Boolean; virtual;
procedure DoInitOtherField(const aValue: IevEditorControl;
aIsStart: Boolean); virtual;
procedure DoClearText; virtual;
procedure DoCheckDataText; virtual;
function DoAnalyzeString(const aValue: Il3CString;
aPos: Integer;
out aRslt: Il3CString): Boolean; virtual;
function GetIsFieldEmpty: Boolean; virtual;
procedure CheckDataText;
{* Проверяет введенный текст на корректность. }
function AnalyzeString(const aValue: Il3CString;
aPos: Integer;
out aRslt: Il3CString): Boolean;
{* Анализ добавленной строки, если нужно, то убирает лишние символы или разбивает строку на несколько. }
function IsClear: Boolean;
{* Функция возвращает призна того, что поле пустое (вынесено специально
для обновления кнопок!). Для реквизитов дат проверяет оба поля дат! }
procedure InitOtherField(const aValue: IevEditorControl;
aIsStart: Boolean = True);
{* Для реквизитов с двумя полями. Используется для полей дат. }
function IsFieldEmpty: Boolean;
{* Проверяет является ли поле пустым (или содержит значение по умолчанию). }
function FindButton(aButtonType: TevButtonType): IevEditorControlButton;
{* Возвращает кнопку для поля. }
procedure ClearText;
{* Очищает поле редактора. }
function SelectAllOnFocus: Boolean;
{* Надо ли выделять поле при фокусировании. }
function Get_Text: Il3CString;
procedure Set_Text(const aValue: Il3CString);
function Get_ErrorColor: Boolean;
procedure Set_ErrorColor(aValue: Boolean);
function Get_Valid: Boolean;
procedure Set_Valid(aValue: Boolean);
function Get_ChildList: IevEditorControlList;
function DoLMouseBtnUp(const aView: InevControlView;
const aTextPara: InevPara;
const aPt: TnevPoint;
const Keys: TevMouseState;
anInPara: Boolean): Boolean; override;
function DoLMouseBtnDown(const aView: InevControlView;
const aTextPara: InevPara;
const aPt: TnevPoint;
const Keys: TevMouseState;
anInPara: Boolean;
const aMap: InevMap): Boolean; override;
procedure SynchronizeSelectedValueWithText;
function HasOtherField: Boolean;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure SetText(const Value: Il3CString); override;
procedure DoTextChange(const aView: InevView;
const aPara: InevPara;
const anOp: InevOp); override;
public
constructor Create(const aPara: InevPara); override;
end;//TevEditControl
implementation
uses
l3ImplUses
, l3Base
, l3String
, k2Tags
, l3Chars
, SysUtils
//#UC START# *48D2409102B7impl_uses*
//#UC END# *48D2409102B7impl_uses*
;
procedure TevEditControl.DoSynchronizeSelectedValueWithText;
//#UC START# *4E93093B00C1_48D2409102B7_var*
//#UC END# *4E93093B00C1_48D2409102B7_var*
begin
//#UC START# *4E93093B00C1_48D2409102B7_impl*
// - ничео не делаем
//#UC END# *4E93093B00C1_48D2409102B7_impl*
end;//TevEditControl.DoSynchronizeSelectedValueWithText
function TevEditControl.GetHasOtherField: Boolean;
//#UC START# *501686490090_48D2409102B7_var*
//#UC END# *501686490090_48D2409102B7_var*
begin
//#UC START# *501686490090_48D2409102B7_impl*
Result := f_IsOtherFieldInited;
//#UC END# *501686490090_48D2409102B7_impl*
end;//TevEditControl.GetHasOtherField
procedure TevEditControl.AfterSetText(const Value: Il3CString);
//#UC START# *48D247CA0077_48D2409102B7_var*
//#UC END# *48D247CA0077_48D2409102B7_var*
begin
//#UC START# *48D247CA0077_48D2409102B7_impl*
Get_Req.UpdateState(Self, nil);
//#UC END# *48D247CA0077_48D2409102B7_impl*
end;//TevEditControl.AfterSetText
function TevEditControl.GetSelectAllOnFocus: Boolean;
//#UC START# *48D249F00054_48D2409102B7_var*
//#UC END# *48D249F00054_48D2409102B7_var*
begin
//#UC START# *48D249F00054_48D2409102B7_impl*
Result := not IsFieldEmpty;
//#UC END# *48D249F00054_48D2409102B7_impl*
end;//TevEditControl.GetSelectAllOnFocus
function TevEditControl.GetIsClear: Boolean;
//#UC START# *48D24A66039B_48D2409102B7_var*
//#UC END# *48D24A66039B_48D2409102B7_var*
begin
//#UC START# *48D24A66039B_48D2409102B7_impl*
Result := IsFieldEmpty;
//#UC END# *48D24A66039B_48D2409102B7_impl*
end;//TevEditControl.GetIsClear
procedure TevEditControl.DoInitOtherField(const aValue: IevEditorControl;
aIsStart: Boolean);
//#UC START# *48D24AA202D1_48D2409102B7_var*
//#UC END# *48D24AA202D1_48D2409102B7_var*
begin
//#UC START# *48D24AA202D1_48D2409102B7_impl*
//#UC END# *48D24AA202D1_48D2409102B7_impl*
end;//TevEditControl.DoInitOtherField
procedure TevEditControl.DoClearText;
//#UC START# *48D24C9F02F5_48D2409102B7_var*
//#UC END# *48D24C9F02F5_48D2409102B7_var*
begin
//#UC START# *48D24C9F02F5_48D2409102B7_impl*
SetText(l3CStr(Get_Req.Para.Attr[k2_tiDefaultText].AsWStr));
Set_Valid(True);
Get_Req.CheckEdit(Self);
//#UC END# *48D24C9F02F5_48D2409102B7_impl*
end;//TevEditControl.DoClearText
procedure TevEditControl.DoCheckDataText;
//#UC START# *48D24F2302F2_48D2409102B7_var*
//#UC END# *48D24F2302F2_48D2409102B7_var*
begin
//#UC START# *48D24F2302F2_48D2409102B7_impl*
//#UC END# *48D24F2302F2_48D2409102B7_impl*
end;//TevEditControl.DoCheckDataText
function TevEditControl.DoAnalyzeString(const aValue: Il3CString;
aPos: Integer;
out aRslt: Il3CString): Boolean;
//#UC START# *48D24F5F02BF_48D2409102B7_var*
//#UC END# *48D24F5F02BF_48D2409102B7_var*
begin
//#UC START# *48D24F5F02BF_48D2409102B7_impl*
Result := true;
//#UC END# *48D24F5F02BF_48D2409102B7_impl*
end;//TevEditControl.DoAnalyzeString
function TevEditControl.GetIsFieldEmpty: Boolean;
//#UC START# *48D24FA901F4_48D2409102B7_var*
//#UC END# *48D24FA901F4_48D2409102B7_var*
begin
//#UC START# *48D24FA901F4_48D2409102B7_impl*
Result := l3EmptyOrAllCharsInCharSet(l3PCharLen(Get_Caption), cc_WhiteSpace);
//#UC END# *48D24FA901F4_48D2409102B7_impl*
end;//TevEditControl.GetIsFieldEmpty
procedure TevEditControl.CheckDataText;
{* Проверяет введенный текст на корректность. }
//#UC START# *47CD7AC60335_48D2409102B7_var*
//#UC END# *47CD7AC60335_48D2409102B7_var*
begin
//#UC START# *47CD7AC60335_48D2409102B7_impl*
DoCheckDataText;
//#UC END# *47CD7AC60335_48D2409102B7_impl*
end;//TevEditControl.CheckDataText
function TevEditControl.AnalyzeString(const aValue: Il3CString;
aPos: Integer;
out aRslt: Il3CString): Boolean;
{* Анализ добавленной строки, если нужно, то убирает лишние символы или разбивает строку на несколько. }
//#UC START# *47CD7AD60335_48D2409102B7_var*
//#UC END# *47CD7AD60335_48D2409102B7_var*
begin
//#UC START# *47CD7AD60335_48D2409102B7_impl*
Result := DoAnalyzeString(aValue, aPos, aRslt);
//#UC END# *47CD7AD60335_48D2409102B7_impl*
end;//TevEditControl.AnalyzeString
function TevEditControl.IsClear: Boolean;
{* Функция возвращает призна того, что поле пустое (вынесено специально
для обновления кнопок!). Для реквизитов дат проверяет оба поля дат! }
//#UC START# *47CD7AFA0334_48D2409102B7_var*
//#UC END# *47CD7AFA0334_48D2409102B7_var*
begin
//#UC START# *47CD7AFA0334_48D2409102B7_impl*
Result := GetIsClear;
//#UC END# *47CD7AFA0334_48D2409102B7_impl*
end;//TevEditControl.IsClear
procedure TevEditControl.InitOtherField(const aValue: IevEditorControl;
aIsStart: Boolean = True);
{* Для реквизитов с двумя полями. Используется для полей дат. }
//#UC START# *47CD7B0F0260_48D2409102B7_var*
//#UC END# *47CD7B0F0260_48D2409102B7_var*
begin
//#UC START# *47CD7B0F0260_48D2409102B7_impl*
f_IsOtherFieldInited := True;
DoInitOtherField(aValue, aIsStart);
//#UC END# *47CD7B0F0260_48D2409102B7_impl*
end;//TevEditControl.InitOtherField
function TevEditControl.IsFieldEmpty: Boolean;
{* Проверяет является ли поле пустым (или содержит значение по умолчанию). }
//#UC START# *47CD7B23002F_48D2409102B7_var*
//#UC END# *47CD7B23002F_48D2409102B7_var*
begin
//#UC START# *47CD7B23002F_48D2409102B7_impl*
Result := GetIsFieldEmpty;
//#UC END# *47CD7B23002F_48D2409102B7_impl*
end;//TevEditControl.IsFieldEmpty
function TevEditControl.FindButton(aButtonType: TevButtonType): IevEditorControlButton;
{* Возвращает кнопку для поля. }
//#UC START# *47CD7B3301BA_48D2409102B7_var*
var
i : Integer;
l_Count : Integer;
l_Control : IevEditorControlButton;
//#UC END# *47CD7B3301BA_48D2409102B7_var*
begin
//#UC START# *47CD7B3301BA_48D2409102B7_impl*
Result := nil;
l_Count := f_ChildList.Count - 1;
for i := l_Count downto 0 do
if Supports(f_ChildList[i], IevEditorControlButton, l_Control) then
try
if l_Control.GetButtonType = aButtonType then
begin
Result := l_Control;
Break;
end;
finally
l_Control := nil;
end;
//#UC END# *47CD7B3301BA_48D2409102B7_impl*
end;//TevEditControl.FindButton
procedure TevEditControl.ClearText;
{* Очищает поле редактора. }
//#UC START# *47CD7B46001C_48D2409102B7_var*
//#UC END# *47CD7B46001C_48D2409102B7_var*
begin
//#UC START# *47CD7B46001C_48D2409102B7_impl*
DoClearText;
//#UC END# *47CD7B46001C_48D2409102B7_impl*
end;//TevEditControl.ClearText
function TevEditControl.SelectAllOnFocus: Boolean;
{* Надо ли выделять поле при фокусировании. }
//#UC START# *47CD7B5401A4_48D2409102B7_var*
//#UC END# *47CD7B5401A4_48D2409102B7_var*
begin
//#UC START# *47CD7B5401A4_48D2409102B7_impl*
Result := GetSelectAllOnFocus;
//#UC END# *47CD7B5401A4_48D2409102B7_impl*
end;//TevEditControl.SelectAllOnFocus
function TevEditControl.Get_Text: Il3CString;
//#UC START# *47CD7B6E0380_48D2409102B7get_var*
//#UC END# *47CD7B6E0380_48D2409102B7get_var*
begin
//#UC START# *47CD7B6E0380_48D2409102B7get_impl*
Result := Get_Caption;
//#UC END# *47CD7B6E0380_48D2409102B7get_impl*
end;//TevEditControl.Get_Text
procedure TevEditControl.Set_Text(const aValue: Il3CString);
//#UC START# *47CD7B6E0380_48D2409102B7set_var*
//#UC END# *47CD7B6E0380_48D2409102B7set_var*
begin
//#UC START# *47CD7B6E0380_48D2409102B7set_impl*
SetText(aValue);
//#UC END# *47CD7B6E0380_48D2409102B7set_impl*
end;//TevEditControl.Set_Text
function TevEditControl.Get_ErrorColor: Boolean;
//#UC START# *47CD7C1F03E3_48D2409102B7get_var*
//#UC END# *47CD7C1F03E3_48D2409102B7get_var*
begin
//#UC START# *47CD7C1F03E3_48D2409102B7get_impl*
Result := f_ErrorColor;
//#UC END# *47CD7C1F03E3_48D2409102B7get_impl*
end;//TevEditControl.Get_ErrorColor
procedure TevEditControl.Set_ErrorColor(aValue: Boolean);
//#UC START# *47CD7C1F03E3_48D2409102B7set_var*
//#UC END# *47CD7C1F03E3_48D2409102B7set_var*
begin
//#UC START# *47CD7C1F03E3_48D2409102B7set_impl*
if f_ErrorColor <> aValue then
begin
f_ErrorColor := aValue;
Set_Valid(not f_ErrorColor);
end;
//#UC END# *47CD7C1F03E3_48D2409102B7set_impl*
end;//TevEditControl.Set_ErrorColor
function TevEditControl.Get_Valid: Boolean;
//#UC START# *47CD7C2E00E2_48D2409102B7get_var*
//#UC END# *47CD7C2E00E2_48D2409102B7get_var*
begin
//#UC START# *47CD7C2E00E2_48D2409102B7get_impl*
Result := Para.AsObject.BoolA[k2_tiValid];
//#UC END# *47CD7C2E00E2_48D2409102B7get_impl*
end;//TevEditControl.Get_Valid
procedure TevEditControl.Set_Valid(aValue: Boolean);
//#UC START# *47CD7C2E00E2_48D2409102B7set_var*
//#UC END# *47CD7C2E00E2_48D2409102B7set_var*
begin
//#UC START# *47CD7C2E00E2_48D2409102B7set_impl*
Para.AsObject.BoolA[k2_tiValid] := aValue;
//#UC END# *47CD7C2E00E2_48D2409102B7set_impl*
end;//TevEditControl.Set_Valid
function TevEditControl.Get_ChildList: IevEditorControlList;
//#UC START# *47CEBBC50272_48D2409102B7get_var*
//#UC END# *47CEBBC50272_48D2409102B7get_var*
begin
//#UC START# *47CEBBC50272_48D2409102B7get_impl*
Result := f_ChildList;
//#UC END# *47CEBBC50272_48D2409102B7get_impl*
end;//TevEditControl.Get_ChildList
function TevEditControl.DoLMouseBtnUp(const aView: InevControlView;
const aTextPara: InevPara;
const aPt: TnevPoint;
const Keys: TevMouseState;
anInPara: Boolean): Boolean;
//#UC START# *48D1461101C6_48D2409102B7_var*
//#UC END# *48D1461101C6_48D2409102B7_var*
begin
//#UC START# *48D1461101C6_48D2409102B7_impl*
Result := True;
//#UC END# *48D1461101C6_48D2409102B7_impl*
end;//TevEditControl.DoLMouseBtnUp
function TevEditControl.DoLMouseBtnDown(const aView: InevControlView;
const aTextPara: InevPara;
const aPt: TnevPoint;
const Keys: TevMouseState;
anInPara: Boolean;
const aMap: InevMap): Boolean;
//#UC START# *48D1464501E8_48D2409102B7_var*
//#UC END# *48D1464501E8_48D2409102B7_var*
begin
//#UC START# *48D1464501E8_48D2409102B7_impl*
Result := False;
//#UC END# *48D1464501E8_48D2409102B7_impl*
end;//TevEditControl.DoLMouseBtnDown
procedure TevEditControl.SynchronizeSelectedValueWithText;
//#UC START# *4E9308B7007B_48D2409102B7_var*
//#UC END# *4E9308B7007B_48D2409102B7_var*
begin
//#UC START# *4E9308B7007B_48D2409102B7_impl*
DoSynchronizeSelectedValueWithText;
//#UC END# *4E9308B7007B_48D2409102B7_impl*
end;//TevEditControl.SynchronizeSelectedValueWithText
function TevEditControl.HasOtherField: Boolean;
//#UC START# *501685F70342_48D2409102B7_var*
//#UC END# *501685F70342_48D2409102B7_var*
begin
//#UC START# *501685F70342_48D2409102B7_impl*
Result := GetHasOtherField;
//#UC END# *501685F70342_48D2409102B7_impl*
end;//TevEditControl.HasOtherField
procedure TevEditControl.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_48D2409102B7_var*
//#UC END# *479731C50290_48D2409102B7_var*
begin
//#UC START# *479731C50290_48D2409102B7_impl*
f_IsOtherFieldInited := False;
l3Free(f_ChildList);
inherited;
//#UC END# *479731C50290_48D2409102B7_impl*
end;//TevEditControl.Cleanup
constructor TevEditControl.Create(const aPara: InevPara);
//#UC START# *47CFE07602FE_48D2409102B7_var*
//#UC END# *47CFE07602FE_48D2409102B7_var*
begin
//#UC START# *47CFE07602FE_48D2409102B7_impl*
inherited;
f_ChildList := TevEditorControlList.Make;
//#UC END# *47CFE07602FE_48D2409102B7_impl*
end;//TevEditControl.Create
procedure TevEditControl.SetText(const Value: Il3CString);
//#UC START# *48D148F7020F_48D2409102B7_var*
var
l_Req : IevReq;
l_Value : Il3CString;
l_Def : Tl3Variant;
//#UC END# *48D148F7020F_48D2409102B7_var*
begin
//#UC START# *48D148F7020F_48D2409102B7_impl*
l_Value := Value;
if l3IsNil(l_Value) then
begin
l_Req := Get_Req;
if (l_Req <> nil) then
begin
l_Def := l_Req.Para.AsObject.Attr[k2_tiDefaultText];
if l_Def.IsValid then
begin
l_Def := l_Def.CloneTag.AsObject;
// - чтобы редактирование не испортило значение по-умолчанию
if not l_Def.Box.QI(Il3CString, l_Value) then
Assert(false);
end;//l_Def.IsValid
end;//l_Req <> nil
end;//l3IsNil(l_Value)
if not l3Same(l_Value, Get_Caption) then
begin
inherited;
AfterSetText(l_Value);
end//not l3Same
else
begin
l_Req := Get_Req;
if (l_Req <> nil) then
l_Req.UpdateState(Self, nil);
end;//not l3Same(l_Value, Get_Caption)
//#UC END# *48D148F7020F_48D2409102B7_impl*
end;//TevEditControl.SetText
procedure TevEditControl.DoTextChange(const aView: InevView;
const aPara: InevPara;
const anOp: InevOp);
//#UC START# *48D14C0E023E_48D2409102B7_var*
//#UC END# *48D14C0E023E_48D2409102B7_var*
begin
//#UC START# *48D14C0E023E_48D2409102B7_impl*
Get_Req.UpdateState(Self, anOp);
Get_Req.TextChange(aView);
//#UC END# *48D14C0E023E_48D2409102B7_impl*
end;//TevEditControl.DoTextChange
end.
|
unit uShapes;
interface
type
IHasArea = interface
function GetArea: Double;
property Area: Double read GetArea;
end;
TRectangle = class(TInterfacedObject, IHasArea)
private
FHeight: Double;
FWidth: Double;
function GetArea: Double;
public
constructor Create(const aHeight, aWidth: Double);
end;
TCircle = class(TInterfacedObject, IHasArea)
private
FRadius: Double;
function GetArea: Double;
public
constructor Create(const aRadius: Double);
end;
TTriangle = class(TInterfacedObject, IHasArea)
private
FBase: Double;
FHeight: Double;
function GetArea: Double;
public
constructor Create(const aBase, aHeight: Double);
end;
TSquare = class(TInterfacedObject, IHasArea)
private
FSide: Double;
function GetArea: Double;
public
constructor Create(const aSide: Double);
end;
implementation
{ TRectangle }
constructor TRectangle.Create(const aHeight, aWidth: Double);
begin
inherited Create;
FHeight := aHeight;
FWidth := aWidth;
end;
function TRectangle.GetArea: Double;
begin
Result := FHeight * FWidth;
end;
{ TCircle }
constructor TCircle.Create(const aRadius: Double);
begin
inherited Create;
FRadius := aRadius;
end;
function TCircle.GetArea: Double;
begin
Result := Pi * FRadius * FRadius;
end;
{ TTriangle }
constructor TTriangle.Create(const aBase, aHeight: Double);
begin
inherited Create;
FBase := aBase;
FHeight := aHeight;
end;
function TTriangle.GetArea: Double;
begin
Result := FBase * FHeight / 2;
end;
{ TSquare }
constructor TSquare.Create(const aSide: Double);
begin
inherited Create;
FSide := aSide;
end;
function TSquare.GetArea: Double;
begin
Result := FSide * FSide;
end;
end.
|
unit BaseExampleUnit;
interface
uses
SysUtils, OutputUnit, IRoute4MeManagerUnit, IConnectionUnit;
type
TBaseExample = class abstract
private
FOutput: IOutput;
protected
Route4MeManager: IRoute4MeManager;
procedure WriteLn(Message: String);
public
destructor Destroy; override;
procedure Init(Output: IOutput; Connection: IConnection);
end;
TBaseExampleClass = class of TBaseExample;
implementation
{ TBaseExample }
uses Route4MeManagerUnit;
destructor TBaseExample.Destroy;
begin
FOutput := nil;
Route4MeManager.Clear;
Route4MeManager := nil;
inherited;
end;
procedure TBaseExample.Init(Output: IOutput; Connection: IConnection);
begin
FOutput := Output;
// Create the manager with the api key
Route4MeManager := TRoute4MeManager.Create(Connection);
end;
procedure TBaseExample.WriteLn(Message: String);
begin
FOutput.Writeln(Message);
end;
end.
|
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Creation: May 01, 2003
Version: 1.00 ALPHA
Description: A console mode application object for ICS
EMail: francois.piette@overbyte.be http://www.overbyte.be
francois.piette@pophost.eunet.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 1996-2010 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
History:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsConApp;
{$I OVERBYTEICSDEFS.INC}
interface
uses
Windows, SysUtils, Classes, Messages;
const
WM_STARTUP = WM_USER + 789; { Must be unique in each application }
type
TKeyboardThread = class (TThread)
protected
FEvent : THandle;
public
ConAppThreadID : Integer;
constructor Create(Suspended : Boolean);
destructor Destroy; override;
procedure Execute; override;
procedure Terminate;
end;
TConApplicationClass = class of TConApplication;
TConApplication = class(TComponent)
private
FThreadID : Integer;
FTerminated : Boolean;
FKbdThread : TKeyboardThread;
FLineMode : Boolean;
FLineBuffer : String;
FLineEcho : Boolean;
FIsInputRedirected : Boolean;
FIsOutputRedirected : Boolean;
protected
procedure Terminate; virtual;
procedure MessageLoop; virtual;
function ProcessMessage: Boolean; virtual;
procedure ProcessMessages; virtual;
procedure WndProc(var Msg: TMsg); virtual;
procedure WMKeyDown(var MsgRec : TMsg); virtual;
procedure WMKeyUp(var MsgRec : TMsg); virtual;
function GetExeName: String;
public
class procedure CreateInstance(AppClass : TConApplicationClass); virtual;
class procedure Run; virtual;
class procedure Done; virtual;
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Execute; virtual;
procedure ConsoleWrite(const S : String); virtual;
procedure ConsoleWriteLn(const S : String); virtual;
procedure DoLineReceived(const Line : String); virtual;
procedure DoCharReceived(Ch : Char); virtual;
property ThreadID : Integer read FThreadID write FThreadID;
property Terminated : Boolean read FTerminated write FTerminated;
property LineMode : Boolean read FLineMode write FLineMode;
property LineEcho : Boolean read FLineEcho write FLineEcho;
property IsInputRedirected : Boolean read FIsInputRedirected;
property IsOutputRedirected : Boolean read FIsOutputRedirected;
property ExeName : String read GetExeName;
end;
var
ConApplication : TConApplication;
implementation
function CtrlHandlerRoutine(CtrlType : DWORD) : DWORD; stdcall; forward;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TConApplication.Create(AOwner: TComponent);
begin
FLineMode := TRUE;
FLineEcho := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TConApplication.Destroy;
begin
FreeAndNil(FKbdThread);
inherited;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class procedure TConApplication.CreateInstance(
AppClass: TConApplicationClass);
var
CMode : DWORD;
begin
FreeAndNil(ConApplication);
ConApplication := AppClass.Create(nil);
ConApplication.FIsInputRedirected := not GetConsoleMode(GetStdHandle(
STD_INPUT_HANDLE), CMode);
ConApplication.FIsOutputRedirected := not GetConsoleMode(GetStdHandle(
STD_OUTPUT_HANDLE), CMode);
ConApplication.FThreadID := GetCurrentThreadID;
ConApplication.FKbdThread := TKeyboardThread.Create(TRUE);
ConApplication.FKbdThread.ConAppThreadID := ConApplication.FThreadID;
SetConsoleCtrlHandler(@CtrlHandlerRoutine, TRUE);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.Execute;
begin
ConsoleWriteLn('Error: You must override TConApplication.Execute !');
Terminate;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.Terminate;
begin
PostThreadMessage(FThreadID, WM_QUIT, 0, 0);
FTerminated := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.MessageLoop;
var
Msg : TMsg;
begin
// If GetMessage retrieves the WM_QUIT, the return value is FALSE and
// the message loop is broken.
while (not FTerminated) and GetMessage(Msg, 0, 0, 0) do
WndProc(Msg);
FTerminated := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TConApplication.ProcessMessage: Boolean;
var
Msg : TMsg;
begin
Result := FALSE;
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin
Result := TRUE;
if Msg.Message = WM_QUIT then
FTerminated := TRUE
else
WndProc(Msg);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.ProcessMessages;
begin
while Self.ProcessMessage do
{ loop };
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class procedure TConApplication.Run;
begin
ConApplication.ProcessMessage; // This will create message queue
PostThreadMessage(ConApplication.FThreadID, WM_STARTUP, 0, 0);
{$if RTLVersion >= 21}
ConApplication.FKbdThread.Start;
{$else}
ConApplication.FKbdThread.Resume;
{$ifend}
ConApplication.MessageLoop;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
class procedure TConApplication.Done;
begin
SetConsoleCtrlHandler(nil, FALSE);
FreeAndNil(ConApplication);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.WndProc(var Msg: TMsg);
begin
if Msg.hwnd = 0 then begin // We process thread's messages
case Msg.message of
WM_STARTUP:
Execute;
WM_KEYDOWN:
WMKeyDown(Msg);
WM_KEYUP:
WMKeyUp(Msg);
else
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end
else begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.ConsoleWrite(const S: String);
begin
Write(S);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.ConsoleWriteLn(const S: String);
begin
WriteLn(S);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
// Console mode applications do not receive keyboard messages as GUI apps.
// We use a thread to wait for keyboard activity and generate keyboard
// messages as in a GUI application.
constructor TKeyboardThread.Create(Suspended: Boolean);
begin
inherited Create(TRUE);
FEvent := CreateEvent(nil, TRUE, FALSE, nil);
if not Suspended then
{$if RTLVersion >= 21}
Start;
{$else}
Resume;
{$ifend}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TKeyboardThread.Destroy;
begin
if FEvent <> 0 then begin
SetEvent(FEvent);
Sleep(0);
CloseHandle(FEvent);
FEvent := 0;
end;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TKeyboardThread.Execute;
var
hConsole : THandle;
Status : DWORD;
InputBuffer : TInputRecord;
KeyEvent : TKeyEventRecord;
Count : DWORD;
Ascii : Char;
I : Integer;
Handles : array [0..1] of THandle;
begin
hConsole := GetStdHandle(STD_INPUT_HANDLE);
Handles[0] := hConsole;
Handles[1] := FEvent;
while not Terminated do begin
Status := MsgWaitForMultipleObjects(2, Handles, FALSE, INFINITE, 0);
if Status = WAIT_FAILED then begin
//WriteLn('WAIT_FAILED');
break; // Wait failed
end
else if Status = WAIT_OBJECT_0 + 1 then begin
//WriteLn('FEvent is signaled');
break; // FEvent is signaled
end
else if Status = WAIT_OBJECT_0 then begin // Console is signaled
if ReadConsoleInput(hConsole, InputBuffer, 1, Count) then begin
if InputBuffer.EventType = KEY_EVENT then begin
{$IFDEF COMPILER4_UP}
{ Starting from Delphi 4 and Bcb4, they changed definition }
KeyEvent := InputBuffer.Event.KeyEvent;
{$ELSE}
KeyEvent := InputBuffer.KeyEvent;
{$ENDIF}
Ascii := Char(KeyEvent.AsciiChar);
for I := 1 to KeyEvent.wRepeatCount do begin
if KeyEvent.bKeyDown then begin
PostThreadMessage(
ConAppThreadID,
WM_KEYDOWN,
Ord(Ascii) + (KeyEvent.wVirtualKeyCode shl 16),
KeyEvent.dwControlKeyState);
end
else begin
PostThreadMessage(
ConAppThreadID,
WM_KEYUP,
Ord(Ascii) + (KeyEvent.wVirtualKeyCode shl 16),
KeyEvent.dwControlKeyState);
end;
end;
end;
end;
end
else begin
WriteLn('Unknown status ', Status);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.WMKeyDown(var MsgRec: TMsg);
var
Ascii : Char;
begin
Ascii := Char(MsgRec.wParam and 255);
// WriteLn('WMKeyDown ' +
// IntToHex(MsgRec.WParam, 8) + ' ' +
// IntToHex(MsgRec.lParam, 8));
if not FLineMode then begin
DoCharReceived(Ascii);
end
else begin
case Ascii of
#0: begin // Not an ASCII char
end;
#9: begin // TabChar
repeat
if FLineEcho then
ConsoleWrite(' ');
FLineBuffer := FLineBuffer + ' ';
until (Length(FLineBuffer) and 7) = 0;
end;
#8: begin // BackSpace
if Length(FLineBuffer) > 0 then begin
if FLineEcho then
ConsoleWrite(#8#32#8);
SetLength(FLineBuffer, Length(FLineBuffer) - 1);
end;
end;
#13: begin // Return
if FLineEcho then
ConsoleWrite(#13#10);
DoLineReceived(FLineBuffer);
FLineBuffer := ''; // Clear line
end;
else
if FLineEcho then
ConsoleWrite(Char(MsgRec.WParam));
FLineBuffer := FLineBuffer + Char(MsgRec.WParam);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.WMKeyUp(var MsgRec: TMsg);
begin
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.DoLineReceived(const Line : String);
begin
// By default: nothing to do
// Todo: Override this method in your derived class
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TConApplication.DoCharReceived(Ch: Char);
begin
// By default: nothing to do
// Todo: Override this method in your derived class
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This is a callback routine called by windows when some events occurs. }
{ We trap those events to close our application. }
function CtrlHandlerRoutine(CtrlType : DWORD) : DWORD; stdcall;
begin
case CtrlType of
CTRL_C_EVENT, // User hit CTRL-C
CTRL_BREAK_EVENT, // User hit CTRL-BREAK
CTRL_LOGOFF_EVENT, // User log off his session
CTRL_CLOSE_EVENT, // Close signal
CTRL_SHUTDOWN_EVENT : // Window shutdown signal
begin
Result := 1;
PostThreadMessage(ConApplication.FThreadID, WM_QUIT, 0, 0);
end;
else
Result := 0;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TKeyboardThread.Terminate;
begin
inherited Terminate;
if FEvent <> 0 then
SetEvent(FEvent);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TConApplication.GetExeName: String;
begin
SetLength(Result, 256);
SetLength(Result, GetModuleFileName(0, @Result[1], Length(Result)));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2016 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit REST.Utils;
interface
uses
System.Classes,
System.SysUtils,
System.Character;
type
TRESTFindDefaultComponent = class
public
class function FindDefaultT<T: TComponent>(AComp: TComponent): T;
class function FindDefaultIntfT<T: IInterface>(AComp: TComponent): T;
class procedure FindAllT<T: TComponent>(AComp: TComponent; ACallback: TProc<T>); overload;
end;
//This URIEncode variant implements an encoding as specified by OAuth mechanisms
function URIEncode(const S: string): string;
function iif(const ACondition: boolean; const BranchTRUE, BranchFALSE: string): string;
procedure ExtractURLSegmentNames(const AString: string; AList: TStrings);
procedure ExtractGetParams(const AUrl: string; var VParams: TStrings);
function RESTComponentIsDesigning(AComp: TComponent): boolean;
implementation
uses System.TypInfo;
const
URL_UNRESERVED_CHARS = ['A' .. 'Z', 'a' .. 'z', '0' .. '9', '-', '_', '.', '~'];
var
GURLUnreservedChars: array of Char;
procedure InitUnreservedChars;
var
c: Char;
i: integer;
begin
SetLength(GURLUnreservedChars, 1024);
i := 0;
for c in URL_UNRESERVED_CHARS do
begin
inc(i);
GURLUnreservedChars[i] := c;
end;
SetLength(GURLUnreservedChars, i);
end;
function URIEncode(const S: string): string;
var
c: Char;
begin
result := '';
for c in S do
if c.IsInArray(GURLUnreservedChars) then
result := result + WideChar(c)
else
result := result + '%' + IntToHex(Ord(c), 2);
end;
function iif(const ACondition: boolean; const BranchTRUE, BranchFALSE: string): string;
begin
if ACondition then
result := BranchTRUE
else
result := BranchFALSE;
end;
function RESTComponentIsDesigning(AComp: TComponent): boolean;
begin
result := ([csDesigning, csLoading] * AComp.ComponentState = [csDesigning]) and
((AComp.Owner = nil) or ([csDesigning, csLoading] * AComp.Owner.ComponentState = [csDesigning]));
end;
procedure ExtractURLSegmentNames(const AString: string; AList: TStrings);
var
LIndex: integer;
LResource: string;
LName: string;
begin
LResource := AString;
LIndex := LResource.IndexOf('{');
while (LIndex >= 0) do
begin
LResource := LResource.Substring(LIndex + 1);
LIndex := LResource.IndexOf('}');
if (LIndex >= 0) then
begin
LName := LResource.Substring(0, LIndex);
if (LName <> '') and (AList.IndexOf(LName) < 0) then
AList.Add(LName);
LResource := LResource.Substring(LIndex + 1);
LIndex := LResource.IndexOf('{');
end;
end;
end;
procedure ExtractGetParams(const AUrl: string; var VParams: TStrings);
var
LTokenPos: integer;
LURI: string;
LParams: string;
begin
LURI := AUrl;
LParams := LURI;
LTokenPos := Pos('://', LURI); { Do not Localize }
if LTokenPos > 0 then
begin
// absolute URI
// remove the protocol
Delete(LURI, 1, LTokenPos + 2);
// separate the path from the parameters
LTokenPos := Pos('?', LURI); { Do not Localize }
if LTokenPos > 0 then
begin
LParams := Copy(LURI, LTokenPos + 1, MaxInt);
// separate the bookmark from the parameters
LTokenPos := Pos('#', LParams); { Do not Localize }
if LTokenPos > 0 then
begin
LParams := Copy(LParams, 1, LTokenPos - 1);
end;
end;
end
else
begin
// received an absolute path, not an URI
LTokenPos := Pos('?', LURI); { Do not Localize }
if LTokenPos > 0 then
begin // The case when there is parameters after the document name
LParams := Copy(LURI, LTokenPos + 1, MaxInt);
// separate the bookmark from the parameters
LTokenPos := Pos('#', LParams); { Do not Localize }
if LTokenPos > 0 then
begin
LParams := Copy(LParams, 1, LTokenPos - 1);
end;
end
else
begin
// separate the bookmark from the path
LTokenPos := Pos('#', LURI); { Do not Localize }
if LTokenPos > 0 then
begin // The case when there is a bookmark after the document name
LParams := Copy(LURI, 1, LTokenPos - 1);
end;
end;
end;
VParams:= TStringList.Create;
VParams.NameValueSeparator := '=';
VParams.Text := LParams;
end;
class function TRESTFindDefaultComponent.FindDefaultT<T>(AComp: TComponent): T;
var
I: Integer;
LRoot: TComponent;
begin
Result := nil;
LRoot := AComp;
if (LRoot <> nil) and (LRoot.Owner <> nil) then
LRoot := LRoot.Owner;
if LRoot <> nil then
for I := 0 to LRoot.ComponentCount - 1 do
if LRoot.Components[I] is T then
if not Assigned(Result) then
Result := T(LRoot.Components[I])
else
Exit(nil);
end;
class function TRESTFindDefaultComponent.FindDefaultIntfT<T>(AComp: TComponent): T;
var
I: Integer;
LRoot: TComponent;
LGuid: TGuid;
LIntf: T;
begin
LGuid := GetTypeData(TypeInfo(T)).Guid;
Result := nil;
LRoot := AComp;
if (LRoot <> nil) and (LRoot.Owner <> nil) then
LRoot := LRoot.Owner;
if LRoot <> nil then
for I := 0 to LRoot.ComponentCount - 1 do
if Supports(LRoot.Components[I], LGuid, LIntf) then
if not Assigned(Result) then
Result := LIntf
else
Exit(nil);
end;
class procedure TRESTFindDefaultComponent.FindAllT<T>(AComp: TComponent; ACallback: TProc<T>);
var
I: Integer;
LRoot: TComponent;
begin
LRoot := AComp;
if (LRoot <> nil) and (LRoot.Owner <> nil) then
LRoot := LRoot.Owner;
if LRoot <> nil then
for I := 0 to LRoot.ComponentCount - 1 do
if LRoot.Components[I] is T then
ACallback(T(LRoot.Components[I]));
end;
initialization
InitUnreservedChars;
end.
|
unit MachineIndustry;
interface
uses
Kernel, Population, WorkCenterBlock, Surfaces, OutputEvaluators;
const
tidGate_LegalServ = 'LegalServ';
tidGate_CompServ = 'CompServ';
tidGate_Metals = 'Metals';
tidGate_Machinery = 'Machinery';
type
TMetaMachineIndustryBlock =
class( TMetaWorkCenter )
public
constructor Create( anId : string;
aCapacities : array of TFluidValue;
aPollResistance : TFluidValue;
aLegalServMax : TFluidValue;
aCompMax : TFluidValue;
aMetalsMax : TFluidValue;
aMachineryMax : TFluidValue;
aMaxBudget : TMoney;
aBlockClass : CBlock );
destructor Destroy; override;
private
fMetaEvaluatorPool : TMetaEvaluatorPool;
end;
TMachineIndustryBlock =
class( TWorkCenter )
protected
constructor Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); override;
destructor Destroy; override;
private
fLegalServ : TInputData;
fCompServ : TInputData;
fMetals : TInputData;
fMachinery : TOutputData;
protected
function GetSurfaceValue( SurfaceId : TSurfaceId ) : TSurfaceValue; override;
protected
function Evaluate : TEvaluationResult; override;
procedure AutoConnect; override;
private
fEvaluatorPool : TEvaluatorPool;
private
fBeautyModifier : TSurfaceModifier;
fPollutionIntegrator : TSurfaceIntegrator;
end;
procedure RegisterBackup;
implementation
uses
StdFluids, ClassStorage, PyramidalModifier, Classes, BackupObjects;
// TMetaElectronicIndustryBlock
constructor TMetaMachineIndustryBlock.Create( anId : string;
aCapacities : array of TFluidValue;
aPollResistance : TFluidValue;
aLegalServMax : TFluidValue;
aCompMax : TFluidValue;
aChemicalsMax : TFluidValue;
aMetalsMax : TFluidValue;
aElectronicsMax : TFluidValue;
aMaxBudget : TMoney;
aBlockClass : CBlock );
var
Sample : TElectronicIndustryBlock;
MetaInput : TMetaInput;
begin
inherited Create( anId, aCapacities, aBlockClass );
Sample := nil;
// Inputs
MetaInputs.Insert(
TMetaInput.Create(
tidGate_LegalServ,
inputZero,
InputData( aLegalServMax, 100, sIlimited ),
InputData( 0, 0, sIlimited ),
aLegalServMax,
TPullInput,
TMetaFluid( TheClassStorage.ClassById[ tidClassFamily_Fluids, tidFluid_LegalServ ]),
5,
[ mgoptCacheable, mgoptEditable ],
Sample.Offset( Sample.fLegalServ ) ) );
MetaInputs.Insert(
TMetaInput.Create(
tidGate_CompServ,
inputZero,
InputData( aCompMax, 100, sIlimited ),
InputData( 0, 0, sIlimited ),
aCompMax,
TPullInput,
TMetaFluid( TheClassStorage.ClassById[ tidClassFamily_Fluids, tidFluid_CompServ ] ),
5,
[ mgoptCacheable, mgoptEditable ],
Sample.Offset( Sample.fCompServ ) ) );
MetaInputs.Insert(
TMetaInput.Create(
tidGate_Metals,
inputZero,
InputData( aMetalsMax, 100, sIlimited ),
InputData( 0, 0, sIlimited ),
aMetalsMax,
TPullInput,
TMetaFluid( TheClassStorage.ClassById[ tidClassFamily_Fluids, tidFluid_Metals ] ),
5,
[ mgoptCacheable, mgoptBasic, mgoptEditable ],
Sample.Offset( Sample.fMetals ) ) );
// Outputs
MetaOutputs.Insert(
TMetaOutput.Create(
tidGate_Machinery,
FluidData( aMachineryMax, 100 ),
TPullOutput,
TMetaFluid( TheClassStorage.ClassById[ tidClassFamily_Fluids, tidFluid_Electronics ] ),
5,
[ mgoptCacheable, mgoptEditable ],
Sample.Offset( Sample.fMachinery ) ) );
// MetaEvaluators
fMetaEvaluatorPool := TMetaEvaluatorPool.Create;
with TMetaOutputEvaluator.Create(
aMaxBudget,
99,
OutputByName[ tidGate_Machinery ],
TOutputEvaluator ) do
begin
RegisterInput(
TMetaInputInfo.Create(
InputByName[ PeopleKindPrefix[ pkHigh ] + tidGate_WorkForce ],
100,
1 ) );
RegisterInput(
TMetaInputInfo.Create(
InputByName[ PeopleKindPrefix[ pkMiddle ] + tidGate_WorkForce ],
3000,
1 ) );
RegisterInput(
TMetaInputInfo.Create(
InputByName[ PeopleKindPrefix[ pkLow ] + tidGate_WorkForce ],
1000,
1 ) );
RegisterInput(
TMetaInputInfo.Create(
InputByName[ tidGate_LegalServ ],
50,
1 ) );
RegisterInput(
TMetaInputInfo.Create(
InputByName[ tidGate_CompServ ],
100,
1 ) );
RegisterInput(
TMetaInputInfo.Create(
InputByName[ tidGate_Metals ],
1000,
1 ) );
RegisterIntegrator(
TIntegratorInfo.Create(
tidEnvironment_Pollution,
aPollResistance,
DecreasingEffect ) );
Register( fMetaEvaluatorPool );
end
end;
destructor TMetaMachineIndustryBlock.Destroy;
begin
fMetaEvaluatorPool.Free;
inherited;
end;
// TElectronicIndustryBlock
constructor TMachineIndustryBlock.Create( aMetaBlock : TMetaBlock; aFacility : TFacility );
begin
inherited;
fEvaluatorPool := TMetaElectronicIndustryBlock( aMetaBlock ).fMetaEvaluatorPool.Instantiate( Self )
end;
destructor TMachineIndustryBlock.Destroy;
begin
fEvaluatorPool.Free;
inherited
end;
function TMachineIndustryBlock.GetSurfaceValue( SurfaceId : TSurfaceId ) : TSurfaceValue;
begin
if SurfaceId <> tidEnvironment_Pollution
then
Result := fPollutionIntegrator.Value
else
Result := inherited GetSurfaceValue( SurfaceId )
end;
function TMachineIndustryBlock.Evaluate : TEvaluationResult;
begin
inherited Evaluate;
if not Facility.CriticalTrouble
then Result := fEvaluatorPool.Evaluate
else Result := evrNormal
end;
procedure TMachineIndustryBlock.AutoConnect;
begin
inherited;
fBeautyModifier :=
TPyramidalModifier.Create(
tidEnvironment_Beauty,
Point( xOrigin, yOrigin ),
MetaBlock.Beauty,
MetaBlock.BeautyStrength );
fPollutionIntegrator :=
TSurfaceIntegrator.Create(
tidEnvironment_Pollution,
GetArea( modPollutionRatio, amdIncludeBlock ) )
end;
procedure RegisterBackup;
begin
BackupObjects.RegisterClass( TMachineIndustryBlock )
end;
end.
|
unit VehicleControl;
interface
uses
Math, TypeControl, CircularUnitControl, VehicleTypeControl, VehicleUpdateControl;
type
TVehicle = class (TCircularUnit)
private
FPlayerId: Int64;
FDurability: LongInt;
FMaxDurability: LongInt;
FMaxSpeed: Double;
FVisionRange: Double;
FSquaredVisionRange: Double;
FGroundAttackRange: Double;
FSquaredGroundAttackRange: Double;
FAerialAttackRange: Double;
FSquaredAerialAttackRange: Double;
FGroundDamage: LongInt;
FAerialDamage: LongInt;
FGroundDefence: LongInt;
FAerialDefence: LongInt;
FAttackCooldownTicks: LongInt;
FRemainingAttackCooldownTicks: LongInt;
FType: TVehicleType;
FAerial: Boolean;
FSelected: Boolean;
FGroups: TLongIntArray;
public
constructor Create(const id: Int64; const x: Double; const y: Double; const radius: Double; const playerId: Int64;
const durability: LongInt; const maxDurability: LongInt; const maxSpeed: Double; const visionRange: Double;
const squaredVisionRange: Double; const groundAttackRange: Double; const squaredGroundAttackRange: Double;
const aerialAttackRange: Double; const squaredAerialAttackRange: Double; const groundDamage: LongInt;
const aerialDamage: LongInt; const groundDefence: LongInt; const aerialDefence: LongInt;
const attackCooldownTicks: LongInt; const remainingAttackCooldownTicks: LongInt; const vehicleType: TVehicleType;
const aerial: Boolean; const selected: Boolean; const groups: TLongIntArray); overload;
constructor Create(const vehicle: TVehicle; const vehicleUpdate: TVehicleUpdate); overload;
function GetPlayerId: Int64;
property PlayerId: Int64 read GetPlayerId;
function GetDurability: LongInt;
property Durability: LongInt read GetDurability;
function GetMaxDurability: LongInt;
property MaxDurability: LongInt read GetMaxDurability;
function GetMaxSpeed: Double;
property MaxSpeed: Double read GetMaxSpeed;
function GetVisionRange: Double;
property VisionRange: Double read GetVisionRange;
function GetSquaredVisionRange: Double;
property SquaredVisionRange: Double read GetSquaredVisionRange;
function GetGroundAttackRange: Double;
property GroundAttackRange: Double read GetGroundAttackRange;
function GetSquaredGroundAttackRange: Double;
property SquaredGroundAttackRange: Double read GetSquaredGroundAttackRange;
function GetAerialAttackRange: Double;
property AerialAttackRange: Double read GetAerialAttackRange;
function GetSquaredAerialAttackRange: Double;
property SquaredAerialAttackRange: Double read GetSquaredAerialAttackRange;
function GetGroundDamage: LongInt;
property GroundDamage: LongInt read GetGroundDamage;
function GetAerialDamage: LongInt;
property AerialDamage: LongInt read GetAerialDamage;
function GetGroundDefence: LongInt;
property GroundDefence: LongInt read GetGroundDefence;
function GetAerialDefence: LongInt;
property AerialDefence: LongInt read GetAerialDefence;
function GetAttackCooldownTicks: LongInt;
property AttackCooldownTicks: LongInt read GetAttackCooldownTicks;
function GetRemainingAttackCooldownTicks: LongInt;
property RemainingAttackCooldownTicks: LongInt read GetRemainingAttackCooldownTicks;
function GetType: TVehicleType;
property VehicleType: TVehicleType read GetType;
function GetAerial: Boolean;
property IsAerial: Boolean read GetAerial;
function GetSelected: Boolean;
property IsSelected: Boolean read GetSelected;
function GetGroups: TLongIntArray;
property Groups: TLongIntArray read GetGroups;
destructor Destroy; override;
end;
TVehicleArray = array of TVehicle;
implementation
constructor TVehicle.Create(const id: Int64; const x: Double; const y: Double; const radius: Double;
const playerId: Int64; const durability: LongInt; const maxDurability: LongInt; const maxSpeed: Double;
const visionRange: Double; const squaredVisionRange: Double; const groundAttackRange: Double;
const squaredGroundAttackRange: Double; const aerialAttackRange: Double; const squaredAerialAttackRange: Double;
const groundDamage: LongInt; const aerialDamage: LongInt; const groundDefence: LongInt; const aerialDefence: LongInt;
const attackCooldownTicks: LongInt; const remainingAttackCooldownTicks: LongInt; const vehicleType: TVehicleType;
const aerial: Boolean; const selected: Boolean; const groups: TLongIntArray);
begin
inherited Create(id, x, y, radius);
FPlayerId := playerId;
FDurability := durability;
FMaxDurability := maxDurability;
FMaxSpeed := maxSpeed;
FVisionRange := visionRange;
FSquaredVisionRange := squaredVisionRange;
FGroundAttackRange := groundAttackRange;
FSquaredGroundAttackRange := squaredGroundAttackRange;
FAerialAttackRange := aerialAttackRange;
FSquaredAerialAttackRange := squaredAerialAttackRange;
FGroundDamage := groundDamage;
FAerialDamage := aerialDamage;
FGroundDefence := groundDefence;
FAerialDefence := aerialDefence;
FAttackCooldownTicks := attackCooldownTicks;
FRemainingAttackCooldownTicks := remainingAttackCooldownTicks;
FType := vehicleType;
FAerial := aerial;
FSelected := selected;
if Assigned(groups) then begin
FGroups := Copy(groups, 0, Length(groups));
end else begin
FGroups := nil;
end;
end;
constructor TVehicle.Create(const vehicle: TVehicle; const vehicleUpdate: TVehicleUpdate);
begin
inherited Create(vehicle.Id, vehicleUpdate.X, vehicleUpdate.Y, vehicle.Radius);
FPlayerId := vehicle.PlayerId;
FDurability := vehicleUpdate.Durability;
FMaxDurability := vehicle.MaxDurability;
FMaxSpeed := vehicle.MaxSpeed;
FVisionRange := vehicle.VisionRange;
FSquaredVisionRange := vehicle.SquaredVisionRange;
FGroundAttackRange := vehicle.GroundAttackRange;
FSquaredGroundAttackRange := vehicle.SquaredGroundAttackRange;
FAerialAttackRange := vehicle.AerialAttackRange;
FSquaredAerialAttackRange := vehicle.SquaredAerialAttackRange;
FGroundDamage := vehicle.GroundDamage;
FAerialDamage := vehicle.AerialDamage;
FGroundDefence := vehicle.GroundDefence;
FAerialDefence := vehicle.AerialDefence;
FAttackCooldownTicks := vehicle.AttackCooldownTicks;
FRemainingAttackCooldownTicks := vehicleUpdate.RemainingAttackCooldownTicks;
FType := vehicle.VehicleType;
FAerial := vehicle.IsAerial;
FSelected := vehicleUpdate.IsSelected;
FGroups := vehicleUpdate.Groups;
end;
function TVehicle.GetPlayerId: Int64;
begin
result := FPlayerId;
end;
function TVehicle.GetDurability: LongInt;
begin
result := FDurability;
end;
function TVehicle.GetMaxDurability: LongInt;
begin
result := FMaxDurability;
end;
function TVehicle.GetMaxSpeed: Double;
begin
result := FMaxSpeed;
end;
function TVehicle.GetVisionRange: Double;
begin
result := FVisionRange;
end;
function TVehicle.GetSquaredVisionRange: Double;
begin
result := FSquaredVisionRange;
end;
function TVehicle.GetGroundAttackRange: Double;
begin
result := FGroundAttackRange;
end;
function TVehicle.GetSquaredGroundAttackRange: Double;
begin
result := FSquaredGroundAttackRange;
end;
function TVehicle.GetAerialAttackRange: Double;
begin
result := FAerialAttackRange;
end;
function TVehicle.GetSquaredAerialAttackRange: Double;
begin
result := FSquaredAerialAttackRange;
end;
function TVehicle.GetGroundDamage: LongInt;
begin
result := FGroundDamage;
end;
function TVehicle.GetAerialDamage: LongInt;
begin
result := FAerialDamage;
end;
function TVehicle.GetGroundDefence: LongInt;
begin
result := FGroundDefence;
end;
function TVehicle.GetAerialDefence: LongInt;
begin
result := FAerialDefence;
end;
function TVehicle.GetAttackCooldownTicks: LongInt;
begin
result := FAttackCooldownTicks;
end;
function TVehicle.GetRemainingAttackCooldownTicks: LongInt;
begin
result := FRemainingAttackCooldownTicks;
end;
function TVehicle.GetType: TVehicleType;
begin
result := FType;
end;
function TVehicle.GetAerial: Boolean;
begin
result := FAerial;
end;
function TVehicle.GetSelected: Boolean;
begin
result := FSelected;
end;
function TVehicle.GetGroups: TLongIntArray;
begin
if Assigned(FGroups) then begin
result := Copy(FGroups, 0, Length(FGroups));
end else begin
result := nil;
end;
end;
destructor TVehicle.Destroy;
begin
inherited;
end;
end.
|
unit K604908954;
{* [Requestlink:604908954] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K604908954.pas"
// Стереотип: "TestCase"
// Элемент модели: "K604908954" MUID: (55D6EC680274)
// Имя типа: "TK604908954"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, RTFtoEVDWriterTest
;
type
TK604908954 = class(TRTFtoEVDWriterTest)
{* [Requestlink:604908954] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK604908954
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *55D6EC680274impl_uses*
//#UC END# *55D6EC680274impl_uses*
;
function TK604908954.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.11';
end;//TK604908954.GetFolder
function TK604908954.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '55D6EC680274';
end;//TK604908954.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK604908954.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
{====================================================}
{ }
{ EldoS Visual Components }
{ }
{ Copyright (c) 1998-2003, EldoS Corporation }
{ }
{====================================================}
{$include elpack2.inc}
{$ifdef ELPACK_SINGLECOMP}
{$I ElPack.inc}
{$else}
{$ifdef LINUX}
{$I ../ElPack.inc}
{$else}
{$I ..\ElPack.inc}
{$endif}
{$endif}
unit ElTreeModalEdit;
interface
uses
Classes,
Messages,
Windows,
Forms,
{$ifdef VCL_6_USED}
Types,
{$endif}
ElHeader,
ElTree;
type
TModalEditExecuteEvent = procedure(Sender : TObject; var Accepted : boolean) of object;
TElTreeInplaceModalEdit = class(TElTreeInplaceEditor)
private
procedure WndProc(var Message : TMessage);
protected
RegMsg: DWORD;
FWnd : HWND;
FInProgress : boolean;
FOnExecute: TModalEditExecuteEvent;
function GetVisible: Boolean; override;
procedure StartOperation; override;
procedure DoStartOperation; override;
procedure Execute(var Accepted : boolean); virtual;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
published
property OnExecute: TModalEditExecuteEvent read FOnExecute write FOnExecute;
end;
implementation
constructor TElTreeInplaceModalEdit.Create(AOwner : TComponent);
begin
inherited;
RegMsg := RegisterWindowMessage('TElTreeInplaceModalEdit.ControlMessage');
FWnd := AllocateHwnd(WndProc);
FTypes := [sftCustom];
end;
destructor TElTreeInplaceModalEdit.Destroy;
begin
DeallocateHwnd(FWnd);
inherited;
end;
procedure TElTreeInplaceModalEdit.WndProc(var Message : TMessage);
begin
if Message.Msg = RegMsg then
begin
CompleteOperation(Message.lParam <> 0);
end
else
with Message do
DefWindowProc(FWnd, Msg, wParam, lParam);
end;
function TElTreeInplaceModalEdit.GetVisible: Boolean;
begin
Result := FInProgress;
end;
procedure TElTreeInplaceModalEdit.StartOperation;
var Accepted : boolean;
DefaultConversion : boolean;
begin
DefaultConversion := true;
TriggerBeforeOperation(DefaultConversion);
FInProgress := true;
Execute(Accepted);
FInProgress := false;
PostMessage(FWnd, WM_NULL, 0, 0);
PostMessage(FWnd, RegMsg, 0, Integer(Accepted));
end;
procedure TElTreeInplaceModalEdit.DoStartOperation;
begin
end;
procedure TElTreeInplaceModalEdit.Execute(var Accepted : boolean);
begin
if Assigned(FOnExecute) then
FOnExecute(Self, Accepted)
else
Accepted := false;
end;
end.
|
unit NTFileSecurity;
{
TNTFileSecurity component for Delphi 4 (version 1.0)
----------------------------------------------------
Copyright (c) 1999 by David A. Bussey
Version Info
------------
v1.0
- Initial release.
There are still a few things that can be improved. If you have any suggestions
for improvements please let me know your ideas. If they are possible, I will
try and include them in later versions.
(you can reach me at dbussey@bluegrass.net)
TNTFileSecurity is FREEWARE. It is supplied as is, without warranty of any kind.
Use it at your own risk. Any components derived from TNTFileSecurity must also be
FREEWARE. You may use TNTFileSecurity in both private and commercial applications
without any fees or royalties. No person/persons may redistribute TNTFileSecurity
as their own or for any profit whatsoever. If you redistribute TNTFileSecurity
you must supply the files in their original un-altered states.
TNTFileSecurity is designed to run in the Windows NT operating system. The
necessary funtions will not work under Windows 95/98 however, software
using TNTFileSecurity can be designed in these operating environments and
should work correctly when installed on a Windows NT machine.
These are the most common error codes that can occur, and their
most likely causes (They are returned by the OnGetSecurity and
OnSetSecurity events):
ERROR_ACL_NOT_SUPPORTED : "The file system does not support Access Control Lists."
The drive or partition in question does not support Access
Control Lists and specific access rights cannot be read or
set by inherent Windows NT methods.
ERROR_CALL_NOT_IMPLEMENTED : "This function is only valid in Win32 mode."
This error occurs when you are not running in the Windows NT
operating environment.
ERROR_NO_SECURITY_INFO : "The object has no security information."
The requested file or directory has an empty Access Control List.
No access rights are specified for any user, group or system account.
ERROR_FILE_NOT_FOUND : "The system cannot find the file specified."
The file or directory specified in TNTFileSecurity.FileName cannot be
located.
ERROR_ACCESS_DENIED : "Access is denied."
Just like it says...
If, by some odd chance, you get this error code...
ERROR_INVALID_NAME : "The filename, directory name, or volume label
syntax is incorrect."
This error will occur when attempting to read file security
when TNTFileSecurity.FileName is an empty string. You should
not get this error, but just in case...
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
{BEGIN OPTIONAL DEFINES}
// If you are working with "Windows 2000" (A.k.a. Windows NT 5.0)
// defining WINVER5 allows TNTFileSecurity to work with NT5's Deny Access
// Control Entries which are unsupported under earlier versions of NT.
// Earlier NT versions assume that which is not specifcally allowed is denied.
// TNTFileSecurity can still use Access Denied ACEs on NT 4 however, the
// operating system will be unable to read the security information.
// I have left this undefined to reduce the risk of accidentally making access
// rights unreadable by NT 4.
{$DEFINE WINVER5}
{END OPTIONAL DEFINES}
const
ACL_REVISION =2;
DNLEN =15; // Domain name length
CNLEN =15; // Computer name length
UNLEN =256; // Maximum user name length
SECURITY_DESCRIPTOR_MAX_LENGTH =65536 + SECURITY_DESCRIPTOR_MIN_LENGTH;
// ACE types
ACCESS_ALLOWED_ACE_TYPE =0;
ACCESS_DENIED_ACE_TYPE =1;
SYSTEM_AUDIT_ACE_TYPE =2;
SYSTEM_ALARM_ACE_TYPE =3;
// ACE inherit flags
OBJECT_INHERIT_ACE =$1;
CONTAINER_INHERIT_ACE =$2;
NO_PROPAGATE_INHERIT_ACE =$4;
INHERIT_ONLY_ACE =$8;
VALID_INHERIT_FLAGS =$F;
SUCCESSFUL_ACCESS_ACE_FLAG =$40;
FAILED_ACCESS_ACE_FLAG =$80;
// Access Types
FILE_READ_DATA =$0001; // file & pipe
FILE_LIST_DIRECTORY =$0001; // directory
FILE_WRITE_DATA =$0002; // file & pipe
FILE_ADD_FILE =$0002; // directory
FILE_APPEND_DATA =$0004; // file
FILE_ADD_SUBDIRECTORY =$0004; // directory
FILE_CREATE_PIPE_INSTANCE =$0004; // named pipe
FILE_READ_EA =$0008; // file & directory
FILE_READ_PROPERTIES =FILE_READ_EA;
FILE_WRITE_EA =$0010; // file & directory
FILE_WRITE_PROPERTIES =FILE_WRITE_EA;
FILE_EXECUTE =$0020; // file
FILE_TRAVERSE =$0020; // directory
FILE_DELETE_CHILD =$0040; // directory
FILE_READ_ATTRIBUTES =$0080; // all
FILE_WRITE_ATTRIBUTES =$0100; // all
FILE_ALL_ACCESS =(STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or $1FF);
FILE_GENERIC_READ =(STANDARD_RIGHTS_READ Or FILE_READ_DATA Or FILE_READ_ATTRIBUTES Or FILE_READ_EA Or SYNCHRONIZE);
FILE_GENERIC_WRITE =(STANDARD_RIGHTS_WRITE Or FILE_WRITE_DATA Or FILE_WRITE_ATTRIBUTES Or FILE_WRITE_EA Or FILE_APPEND_DATA Or SYNCHRONIZE);
FILE_GENERIC_EXECUTE =(STANDARD_RIGHTS_EXECUTE Or FILE_READ_ATTRIBUTES Or FILE_EXECUTE Or SYNCHRONIZE);
GENERIC_NONE =$00000000;
ERROR_NO_SECURITY_INFO =MAXDWORD;
ERROR_ACL_NOT_SUPPORTED =MAXDWORD - 1;
ERROR_NONE =$0000;
ERROR_GET_FILE_SECURITY =$0001;
ERROR_GET_DACL =$0002;
ERROR_GET_ACE_COUNT =$0003;
ERROR_GET_ACE =$0004;
ERROR_GET_ACCOUNT_NAME =$0005;
ERROR_INITIALIZE_ACL =$0006;
ERROR_GET_ACCOUNT_SID =$0007;
ERROR_ADD_ALLOWED_ACE =$0008;
ERROR_ADD_DENIED_ACE =$0009;
ERROR_INITIALIZE_SD =$000A;
ERROR_SET_DACL =$000B;
ERROR_SET_SD =$000C;
ERROR_UNKNOWN_DRIVE_TYPE =$000D;
ERROR_INVALID_ROOT =$000E;
ERROR_RESERVED_1 =$000F;
// Type Definitions
type
TFileAccess = (faRead,
faWrite,
faExecute,
faDelete,
faChangePermissions,
faTakeOwnership,
faAll);
TAccessSet = set of TFileAccess;
type
SecurityEntry = (seNone,
seUser,
seGroup,
seDomain,
seAlias,
seWellKnownGroup,
seDeletedAcount,
seInvalid,
seUnknown);
// ACE Types
type
PACE_HEADER = ^ACE_HEADER;
ACE_HEADER = record
AceType : BYTE;
AceFlags : BYTE;
AceSize : WORD;
end;
type
PACCESS_ALLOWED_ACE = ^ACCESS_ALLOWED_ACE;
ACCESS_ALLOWED_ACE = record
Header: ACE_HEADER;
Mask: ACCESS_MASK;
SidStart: DWORD;
end;
type
PACCESS_DENIED_ACE = ^ACCESS_DENIED_ACE;
ACCESS_DENIED_ACE = record
Header : ACE_HEADER;
Mask : ACCESS_MASK;
SidStart : DWORD;
end;
type
ACL_SIZE_INFORMATION = record
AceCount: DWORD;
AclBytesInUse: DWORD;
AclBytesFree: DWORD;
end;
type
EFileSecurityError = class(Exception);
type
PSecurityListItem = ^TSecurityListItem;
TSecurityListItem = record
Name: string;
ServerName: string;
EntryType: SecurityEntry;
FileAllowed : TAccessSet;
DirectoryAllowed : TAccessSet;
{$IFDEF WINVER5}
FileDenied : TAccessSet;
DirectoryDenied : TAccessSet;
{$ENDIF}
end;
type
TNTFileSecurityEvent = procedure(Sender: TObject; Error, Location: DWORD) of object;
type
TNTFileSecurity = class(TComponent)
private
{ Private declarations }
FACEList: TList;
FEntries: TStrings;
FIsFile: Boolean;
FIsDirectory: Boolean;
FIsRemoteDrive: Boolean;
FFileName: string;
FVolumeName: string;
FFileSystemName: string;
FSystemName: string;
FLocalMachineName: string;
FSerialNumber: DWORD;
FEntryCount: integer;
FOnGetSecurity: TNTFileSecurityEvent;
FOnSetSecurity: TNTFileSecurityEvent;
function CalculateACLSize: DWORD;
procedure ValidateIndex(Index: integer);
function GetEntryName(Index: Integer): string;
function GetServerName(Index: Integer): string;
function GetEntryType(Index: Integer): SecurityEntry;
function GetFileAllowedRights(Index: Integer): TAccessSet;
procedure SetFileAllowedRights(Index: Integer; Value: TAccessSet);
function GetDirAllowedRights(Index: Integer): TAccessSet;
procedure SetDirAllowedRights(Index: Integer; Value: TAccessSet);
procedure SetFileName(Value: string);
{$IFDEF WINVER5}
function GetFileDeniedRights(Index: Integer): TAccessSet;
procedure SetFileDeniedRights(Index: Integer; Value: TAccessSet);
function GetDirDeniedRights(Index: Integer): TAccessSet;
procedure SetDirDeniedRights(Index: Integer; Value: TAccessSet);
{$ENDIF}
protected
{ Protected declarations }
INFO: ^ACL_SIZE_INFORMATION;
function GetACECount(AN_ACL: PACL; var Count: DWORD): DWORD;
function GetACLSize(AN_ACL: PACL; var AclSize: DWORD): DWORD;
procedure RaiseError(Msg: string);
procedure DoOnGetSecurity(ErrorCode, Location: DWORD);
procedure DoOnSetSecurity(ErrorCode, Location: DWORD);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetMessageString(ErrorCode, Location: DWORD): string;
function AddEntry(ServerName, Name: string): Integer;
procedure RemoveEntry(Index: integer);
procedure RefreshSecurity;
procedure SetSecurity;
procedure ClearAll(Index: integer);
procedure GrantAll(Index: integer);
{$IFDEF WINVER5}
procedure DenyAll(Index: integer);
property DeniedDirectoryRights[Index: integer] : TAccessSet read GetDirDeniedRights write SetDirDeniedRights;
property DeniedFileRights[Index: integer] : TAccessSet read GetFileDeniedRights write SetFileDeniedRights;
{$ENDIF}
property FileName : string read FFileName write SetFileName;
property HostName: string read FSystemName;
property VolumeName: string read FVolumeName;
property FileSystemName: string read FFileSystemName;
property LocalMachine: string read FLocalMachineName;
property VolumeSerialNumber: DWORD read FSerialNumber;
property Entries : TStrings read FEntries;
property EntryCount : Integer read FEntryCount;
property EntryName [Index: integer] : string read GetEntryName;
property ServerName[Index: integer] : string read GetServerName;
property EntryType [Index: integer] : SecurityEntry read GetEntryType;
property FileRights[Index: integer] : TAccessSet read GetFileAllowedRights write SetFileAllowedRights;
property DirectoryRights[Index: integer] : TAccessSet read GetDirAllowedRights write SetDirAllowedRights;
published
{ Published declarations }
property Tag;
property OnGetSecurity: TNTFileSecurityEvent read FOnGetSecurity write FOnGetSecurity;
property OnSetSecurity: TNTFileSecurityEvent read FOnSetSecurity write FOnSetSecurity;
end;
procedure Register;
implementation
uses stNetAPI;
procedure Register;
begin
RegisterComponents('Custom', [TNTFileSecurity]);
end;
function DirectoryExists(const Name: string): Boolean;
var
Code: Integer;
begin
Code := GetFileAttributes(PChar(Name));
Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0);
end;
procedure TNTFileSecurity.RaiseError(Msg: string);
begin
raise EFileSecurityError.Create(Msg);
end;
constructor TNTFileSecurity.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FACEList := TList.Create;
FACEList.Capacity := 10;
// Just a general setting... the TList will allocate more as needed
FEntries := TStringList.Create;
end;
destructor TNTFileSecurity.Destroy;
var
x: integer;
NewItem: PSecurityListItem;
begin
for x := Pred(FACEList.Count) downto 0 do begin
NewItem := FACEList.Items[x];
Dispose(NewItem);
FACEList.Delete(x);
end;
FEntries.Free;
FACEList.Free;
inherited Destroy;
end;
function TNTFileSecurity.GetMessageString(ErrorCode, Location: DWORD): string;
var
a: array [0..1023] of Char;
// LocStr: string;
begin
if ErrorCode = 0 then begin
Result := 'Operation was successfull.';
end else begin
case ErrorCode of
ERROR_NO_SECURITY_INFO : StrPCopy(a,'The object has no security information.');
ERROR_ACL_NOT_SUPPORTED : StrPCopy(a,'The file system does not support Access Control Lists.');
ERROR_UNKNOWN_DRIVE_TYPE: StrPCopy(a,'Unable to determine drive type.');
ERROR_INVALID_ROOT : StrPCopy(a,'The root directory does not exist.');
else
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,ErrorCode,0,a,1024,nil);
end;
// case Location of
// ERROR_NONE : LocStr := '';
// ERROR_GET_FILE_SECURITY : LocStr := 'Retrieving file security information.';
// ERROR_GET_DACL : LocStr := 'Retrieving Access Control List.';
// ERROR_GET_ACE_COUNT : LocStr := 'Retrieving number of Access Control Entries.';
// ERROR_GET_ACE : LocStr := 'Retrieving Access Control Entry.';
// ERROR_GET_ACCOUNT_NAME : LocStr := 'Retrieving account name.';
// ERROR_INITIALIZE_ACL : LocStr := 'Initializing Access Control List.';
// ERROR_GET_ACCOUNT_SID : LocStr := 'Retrieving account Security Identifier.';
// ERROR_ADD_ALLOWED_ACE : LocStr := 'Adding Access Allowed ACE.';
// ERROR_ADD_DENIED_ACE : LocStr := 'Adding Access Denied ACE.';
// ERROR_INITIALIZE_SD : LocStr := 'Initializing Security Descriptor.';
// ERROR_SET_DACL : LocStr := 'Setting new Access Control List in Security Descriptor.';
// ERROR_SET_SD : LocStr := 'Adding new Security Descriptor to object.';
// else
// LocStr := 'Unknown function call!';
// end;
Result := StrPas(a){ + '(' + LocStr + ')'};
end;
end;
procedure TNTFileSecurity.DoOnGetSecurity(ErrorCode, Location: DWORD);
begin
if Assigned(FOnGetSecurity) then
FOnGetSecurity(Self, ErrorCode, Location);
end;
procedure TNTFileSecurity.DoOnSetSecurity(ErrorCode, Location: DWORD);
begin
if Assigned(FOnSetSecurity) then
FOnSetSecurity(Self, ErrorCode, Location);
end;
procedure TNTFileSecurity.ValidateIndex(Index: integer);
begin
if (Index < 0) or (Index >= FACEList.Count) then
RaiseError('Index ['+IntToStr(Index)+'] is out of bounds.');
end;
function TNTFileSecurity.GetEntryName(Index: integer) : string;
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
Result := LI^.Name;
end;
function TNTFileSecurity.GetServerName(Index: integer) : string;
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
Result := LI^.ServerName;
end;
function TNTFileSecurity.GetEntryType(Index: integer) : SecurityEntry;
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
Result := LI^.EntryType;
end;
function TNTFileSecurity.GetFileAllowedRights(Index: Integer): TAccessSet;
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
Result := LI^.FileAllowed;
end;
procedure TNTFileSecurity.SetFileAllowedRights(Index: Integer; Value: TAccessSet);
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
if Value <> LI^.FileAllowed then
LI^.FileAllowed := Value;
end;
function TNTFileSecurity.GetDirAllowedRights(Index: Integer): TAccessSet;
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
Result := LI^.DirectoryAllowed;
end;
procedure TNTFileSecurity.SetDirAllowedRights(Index: Integer; Value: TAccessSet);
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
if Value <> LI^.DirectoryAllowed then
LI^.DirectoryAllowed := Value;
end;
{$IFDEF WINVER5}
function TNTFileSecurity.GetFileDeniedRights(Index: Integer): TAccessSet;
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
Result := LI^.FileDenied;
end;
procedure TNTFileSecurity.SetFileDeniedRights(Index: Integer; Value: TAccessSet);
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
if Value <> LI^.FileDenied then
LI^.FileDenied := Value;
end;
function TNTFileSecurity.GetDirDeniedRights(Index: Integer): TAccessSet;
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
Result := LI^.DirectoryDenied;
end;
procedure TNTFileSecurity.SetDirDeniedRights(Index: Integer; Value: TAccessSet);
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
if Value <> LI^.DirectoryDenied then
LI^.DirectoryDenied := Value;
end;
procedure TNTFileSecurity.DenyAll(Index: integer);
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
if FIsDirectory then begin
LI^.DirectoryAllowed := [];
LI^.DirectoryDenied := [faAll];
LI^.FileAllowed := [];
LI^.FileDenied := [faAll];
end else begin
if FIsFile then begin
LI^.FileAllowed := [];
LI^.FileDenied := [faAll];
end;
end;
end;
{$ENDIF}
function ExtractServerName(RootName: PChar): string;
var
Temp: string;
x: integer;
begin
Result := '';
Temp := StrPas(RootName);
for x := 3 to (Length(Temp)-3) do begin
if Temp[x] = '\' then Break
else Result := Result + Temp[x];
end;
end;
procedure TNTFileSecurity.SetFileName(Value: string);
var
Res: NET_API_STATUS;
SInfo: Pointer;
STmp: string;
RP: string;
TempName: array [0..CNLEN] of Char;
VolName, SystemName, RootPath: array [0..255] of Char;
VolNameLen, SerialNo, CompLen, VolFlags,
SysNameLen, RemoteNameLen, dwRes, TempNameLen : DWORD;
DriveType: UINT;
x: integer;
pRemName: Pointer;
NewItem: PSecurityListItem;
RemName: ^REMOTE_NAME_INFO;
begin
if Value <> FFileName then begin
TempNameLen := CNLEN + 1;
GetComputerName(TempName,TempNameLen);
FLocalMachineName := StrPas(TempName);
FSystemName := FLocalMachineName;
FVolumeName := '';
FFileSystemName := '';
FSerialNumber := 0;
FIsFile := False;
FIsDirectory := False;
FIsRemoteDrive := False;
ZeroMemory(@RootPath,SizeOf(RootPath));
ZeroMemory(@VolName,SizeOf(VolName));
ZeroMemory(@SystemName,SizeOf(SystemName));
pRemName := nil;
VolNameLen := SizeOf(VolName);
SysNameLen := SizeOf(SystemName);
RP := ExtractFileDrive(Value);
if RP = Value then
Value := Value + '\';
StrPCopy(RootPath,RP+'\');
DriveType := GetDriveType(RootPath);
case DriveType of
0 : begin
FFileName := '';
DoOnGetSecurity(ERROR_UNKNOWN_DRIVE_TYPE,0);
Exit;
end;
1 : begin
FFileName := '';
DoOnGetSecurity(ERROR_INVALID_ROOT,0);
Exit;
end;
DRIVE_REMOTE : begin
FIsRemoteDrive := True;
if Copy(RP,1,2) <> '\\' then
begin
ReallocMem(pRemName,RemoteNameLen);
try
WNetGetUniversalName(@RootPath,REMOTE_NAME_INFO_LEVEL,
pRemName,RemoteNameLen);
ReallocMem(pRemName,RemoteNameLen);
WNetGetUniversalName(@RootPath,REMOTE_NAME_INFO_LEVEL,
pRemName,RemoteNameLen);
RemName := pRemName;
FSystemName := ExtractServerName(RemName^.lpConnectionName);
StrPCopy(RootPath,StrPas(RemName^.lpConnectionName)+
StrPas(RemName^.lpRemainingPath));
except
end;
ReallocMem(pRemName,0);
end
else
begin
STmp := '\\'+ExtractServerName(PChar(RP));
Res := StNetServerGetInfo(STmp, 100, SInfo);
if Res = NO_ERROR then
begin
FSystemName := WideString(PSERVER_INFO_100(SInfo)^.sv100_name);
end;
end;
end;
end;
if not GetVolumeInformation(RootPath,VolName,VolNameLen,@SerialNo,CompLen,
VolFlags,SystemName,SysNameLen) then begin
dwRes := GetLastError;
FFileName := '';
DoOnGetSecurity(dwRes,0);
Exit;
end;
FSerialNumber := SerialNo;
FVolumeName := StrPas(VolName);
FFileSystemName := StrPas(SystemName);
FIsFile := FileExists(Value);
FIsDirectory := SysUtils.DirectoryExists(Value);
if (VolFlags and FS_PERSISTENT_ACLS) <= 0 then begin
// If there are entries in the list, dispose of them.
if FACEList.Count > 0 then begin
FEntries.Clear;
for x := Pred(FACEList.Count) downto 0 do begin
NewItem := FACEList.Items[x];
Dispose(NewItem);
FACEList.Delete(x);
end;
FACEList.Clear;
end;
FFileName := '';
DoOnGetSecurity(ERROR_ACL_NOT_SUPPORTED,0);
end else
FFileName := Value;
if FFileName <> '' then
RefreshSecurity;
end;
end;
procedure TNTFileSecurity.ClearAll(Index: integer);
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
LI^.DirectoryAllowed := [];
LI^.FileAllowed := [];
{$IFDEF WINVER5}
LI^.DirectoryDenied := [];
LI^.FileDenied := [];
{$ENDIF}
end;
procedure TNTFileSecurity.GrantAll(Index: integer);
var
LI: PSecurityListItem;
begin
ValidateIndex(Index);
LI := FACEList.Items[Index];
if FIsDirectory then begin
LI^.DirectoryAllowed := [faAll];
LI^.FileAllowed := [faAll];
{$IFDEF WINVER5}
LI^.DirectoryDenied := [];
LI^.FileDenied := [];
{$ENDIF}
end else begin
if FIsFile then begin
LI^.FileAllowed := [faAll];
{$IFDEF WINVER5}
LI^.FileDenied := [];
{$ENDIF}
end;
end;
end;
procedure TNTFileSecurity.RemoveEntry(Index: integer);
var
LI: PSecurityListItem;
begin
LI := FACEList.Items[Index];
Dispose(LI);
FACEList.Delete(Index);
FEntries.Delete(Index);
FEntryCount := FACEList.Count;
end;
function TNTFileSecurity.AddEntry(ServerName, Name: string): Integer;
var
LI: PSecurityListItem;
NewSID: PSID;
NewSIDLen, RefDomLen, dwRes: DWORD;
RefDomain: array [0..DNLEN] of Char;
SIDType: SID_NAME_USE;
a: array [0..1023] of Char;
begin
NewSIDLen := 0;
RefDomLen := SizeOf(RefDomain);
if not LookupAccountName(PChar(ServerName),PChar(Name),nil,NewSIDLen,RefDomain,RefDomLen,SIDType) then begin
dwRes := GetLastError;
if dwRes <> ERROR_INSUFFICIENT_BUFFER then begin
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
RaiseError(a);
end;
end;
NewSID := AllocMem(NewSIDLen);
if not LookupAccountName(PChar(ServerName),PChar(Name),NewSID,NewSIDLen,RefDomain,RefDomLen,SIDType) then begin
dwRes := GetLastError;
FreeMem(NewSID);
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
RaiseError(a);
end;
New(LI);
LI^.Name := Name;
if (UpperCase(StrPas(RefDomain)) = 'BUILTIN') or (UpperCase(StrPas(RefDomain)) = '')
or (UpperCase(StrPas(RefDomain)) = 'NT AUTHORITY') then
LI^.ServerName := ServerName
else
LI^.ServerName := StrPas(RefDomain);
case SIDType of
SidTypeUser : LI^.EntryType := seUser;
SidTypeGroup : LI^.EntryType := seGroup;
SidTypeDomain : LI^.EntryType := seDomain;
SidTypeAlias : LI^.EntryType := seAlias;
SidTypeWellKnownGroup : LI^.EntryType := seWellKnownGroup;
SidTypeDeletedAccount : LI^.EntryType := seDeletedAcount;
SidTypeInvalid : LI^.EntryType := seInvalid;
SidTypeUnknown : LI^.EntryType := seUnknown;
end;
LI^.FileAllowed := [];
LI^.DirectoryAllowed := [];
{$IFDEF WINVER5}
LI^.FileDenied := [];
LI^.DirectoryDenied := [];
{$ENDIF}
FreeMem(NewSID);
FEntries.Add(LI^.Name);
FEntryCount := FACEList.Count;
Result := FACEList.Add(LI);
end;
function TNTFileSecurity.GetACECount(AN_ACL: PACL; var Count: DWORD): DWORD;
var
INFO_SIZE: DWORD;
begin
New(INFO);
INFO_SIZE := SizeOf(ACL_SIZE_INFORMATION);
if not GetAclInformation(AN_ACL^,INFO,INFO_SIZE,AclSizeInformation) then begin
Count := 0;
Result := GetLastError;
end else begin
Count := INFO^.AceCount;
Result := ERROR_SUCCESS;
end;
Dispose(INFO);
end;
function TNTFileSecurity.GetACLSize(AN_ACL: PACL; var AclSize: DWORD): DWORD;
var
INFO_SIZE: DWORD;
begin
New(INFO);
INFO_SIZE := SizeOf(ACL_SIZE_INFORMATION);
if not GetAclInformation(AN_ACL^,INFO,INFO_SIZE,AclSizeInformation) then begin
AclSize := 0;
Result := GetLastError;
end else begin
AclSize := INFO^.AclBytesInUse;
Result := ERROR_SUCCESS;
end;
Dispose(INFO);
end;
function GetFileGenericSecurity(Mask: DWORD): TAccessSet;
begin
Result := [];
if Mask = FILE_ALL_ACCESS then
Result := [faAll]
else begin
if (Mask and FILE_GENERIC_READ) = FILE_GENERIC_READ then
Result := Result + [faRead];
if (Mask and FILE_GENERIC_WRITE) = FILE_GENERIC_WRITE then
Result := Result + [faWrite];
if (Mask and FILE_GENERIC_EXECUTE) = FILE_GENERIC_EXECUTE then
Result := Result + [faExecute];
if (Mask and _DELETE) = _DELETE then
Result := Result + [faDelete];
if (Mask and WRITE_DAC) = WRITE_DAC then
Result := Result + [faChangePermissions];
if (Mask and WRITE_OWNER) = WRITE_OWNER then
Result := Result + [faTakeOwnership];
end;
end;
function GetGenericSecurity(Mask: DWORD): TAccessSet;
begin
Result := [];
if Mask = GENERIC_ALL then
Result := [faAll]
else begin
if (Mask and GENERIC_READ) = GENERIC_READ then
Result := Result + [faRead];
if (Mask and GENERIC_WRITE) = GENERIC_WRITE then
Result := Result + [faWrite];
if (Mask and GENERIC_EXECUTE) = GENERIC_EXECUTE then
Result := Result + [faExecute];
if (Mask and _DELETE) = _DELETE then
Result := Result + [faDelete];
if (Mask and WRITE_DAC) = WRITE_DAC then
Result := Result + [faChangePermissions];
if (Mask and WRITE_OWNER) = WRITE_OWNER then
Result := Result + [faTakeOwnership];
end;
end;
procedure TNTFileSecurity.RefreshSecurity;
var
D_ACL: PACL;
TheSID: PSID;
pACE: Pointer;
NewItem: PSecurityListItem;
TheACE : PACCESS_ALLOWED_ACE;
FileSD: PSECURITY_DESCRIPTOR;
x: integer;
LastGroup: string;
SIDType: SID_NAME_USE;
HasDACL,IsDefault: LongBool;
a: array [0..1023] of Char;
RefDom: array [0..DNLEN] of Char;
GroupName: array [0..UNLEN] of Char;
SrvName, FileName : array [0..255] of Char;
AFlag, AMask, TempFlag: DWORD;
dwRes, RefDomLen, GroupLen, ACECount, LenNeeded : DWORD;
begin
if FFileName = '' then begin
DoOnGetSecurity(ERROR_FILE_NOT_FOUND,0);
Exit;
end;
// Initialize a few local vars
D_ACL := nil;
FileSD := nil;
NewItem := nil;
LastGroup := '';
// Clear the list of ACEs, making sure to free the memory of the entries...
if FACEList.Count > 0 then begin
FEntries.Clear;
for x := Pred(FACEList.Count) downto 0 do begin
NewItem := FACEList.Items[x];
Dispose(NewItem);
FACEList.Delete(x);
end;
FACEList.Clear;
end;
// Copy the file name to a PChar...
ZeroMemory(@FileName,SizeOf(FileName));
StrPCopy(FileName,FFileName);
// Retrieve the SECURITY_DESCRIPTOR length from the requested file...
// since the SECURITY_DESCRIPTOR pointer (FileSD) is nil and the
// SECURITY_DESCRIPTOR length is 0, this will force the "Insufficient Buffer"
// error and give us the required size of the SECURITY_DESCRIPTOR in LenNeeded.
if not GetFileSecurity(FileName,DACL_SECURITY_INFORMATION,FileSD,0,LenNeeded) then begin
dwRes := GetLastError;
if dwRes <> ERROR_INSUFFICIENT_BUFFER then begin
DoOnGetSecurity(dwRes,ERROR_GET_FILE_SECURITY);
Exit;
end;
end;
// Allocate the SECURITY_DESCRIPTOR.
FileSD := AllocMem(LenNeeded);
// *Now* retrieve the actual SECURITY_DESCRIPTOR.
if not GetFileSecurity(FileName,DACL_SECURITY_INFORMATION,FileSD,LenNeeded,LenNeeded) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
FreeMem(FileSD);
DoOnGetSecurity(dwRes,ERROR_GET_FILE_SECURITY);
Exit;
end;
// Get the pointer to the Discretionary Access Control List in the
// SECURITY_DESCRIPTOR we just got.
if not GetSecurityDescriptorDACL(FileSD,HasDACL,D_ACL,IsDefault) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
FreeMem(FileSD);
DoOnGetSecurity(dwRes,ERROR_GET_DACL);
Exit;
end;
// Get the number os Access Control Entries in the Access Control List
dwRes := GetACECount(D_ACL, ACECount);
if dwRes <> ERROR_SUCCESS then begin
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
FreeMem(FileSD);
DoOnGetSecurity(dwRes,ERROR_GET_ACE_COUNT);
Exit;
end;
// If there was no error but the ACE count is still zero the object
// has no security information set.
if ACECount = 0 then begin
FreeMem(FileSD);
DoOnGetSecurity(ERROR_NO_SECURITY_INFO,ERROR_GET_ACE_COUNT);
Exit;
end;
// Now we loop through the ACL, gathering required information...
for x := 0 to (ACECount - 1) do begin
if not GetAce(D_ACL^,x,pACE) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
FreeMem(FileSD);
DoOnGetSecurity(dwRes,ERROR_GET_ACE);
Exit;
end else begin
// This is far easier than typecasting a generic pointer each time
// you want to use it.
TheACE := pACE;
// Set the address of the SECURITY_IDENTIFIER the ACE belongs to.
TheSID := PSID(@TheACE.SidStart);
// Initialize a few vars...
RefDomLen := DNLEN + 1;
GroupLen := SizeOf(GroupName);
ZeroMemory(@GroupName,SizeOf(GroupName));
ZeroMemory(@SrvName,SizeOf(SrvName));
StrPCopy(SrvName,FSystemName);
// Lookup the account name that goes with the SECURITY_IDENTIFIER.
if LookupAccountSid(SrvName,TheSID,GroupName,GroupLen,RefDom,RefDomLen,SidType) then begin
if LastGroup <> StrPas(GroupName) then begin
// If the account we just looked up is different than the one
// before it, add it to our security list. I had to do it this
// way because a specific account can have more than one ACE and
// we need to combine the different ACEs for easy viewing and
// editing. This is especially true for directories because they
// store security information for the directory AND the files it
// contains for each account in the Access Control List.
// On the first time through the loop we do not have any security
// information so don't add garbage to the list.
if x <> 0 then begin
FACEList.Add(NewItem);
FEntries.Add(NewItem^.Name);
FEntryCount := FACEList.Count;
end;
// Initialize a new item to add to our list
New(NewItem);
{$IFDEF WINVER5}
NewItem^.DirectoryDenied := [];
NewItem^.FileDenied := [];
{$ENDIF}
NewItem^.DirectoryAllowed := [];
NewItem^.FileAllowed := [];
// Some accounts are built into the OS and therefore they don't
// report the referenced domain name as the local machine name.
if (UpperCase(StrPas(RefDom)) = 'BUILTIN') or (UpperCase(StrPas(RefDom)) = '')
or (UpperCase(StrPas(RefDom)) = 'NT AUTHORITY') then
NewItem^.ServerName := SrvName
else
NewItem^.ServerName := StrPas(RefDom);
// Get the type of account...
case SidType of
SidTypeUser : NewItem^.EntryType := seUser;
SidTypeGroup : NewItem^.EntryType := seGroup;
SidTypeDomain : NewItem^.EntryType := seDomain;
SidTypeAlias : NewItem^.EntryType := seAlias;
SidTypeWellKnownGroup : NewItem^.EntryType := seWellKnownGroup;
SidTypeDeletedAccount : NewItem^.EntryType := seDeletedAcount;
SidTypeInvalid : NewItem^.EntryType := seInvalid;
SidTypeUnknown : NewItem^.EntryType := seUnknown;
end;
end;
// Remember the name of this account for the next time
// through the loop.
LastGroup := StrPas(GroupName);
NewItem^.Name := LastGroup;
end else begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
FreeMem(FileSD);
DoOnGetSecurity(dwRes,ERROR_GET_ACCOUNT_NAME);
Exit;
end;
// Ok... time to decipher the security flags...
// Directories usually have 2 Access Control Entries for an account.
// The *first* entry specifies rights that apply to *files* within the
// directory. The *second* entry specifies rights that apply to the
// *directory* itself. The *first* entry uses a *slightly different*
// set of access flags, thus my use of GetFileGenericSecurity and
// GetGenericSecurity.
AFlag := TheACE.Header.AceFlags;
AMask := TheACE.Mask;
if FIsFile then begin
if TheAce.Header.AceType = ACCESS_ALLOWED_ACE_TYPE then
NewItem^.FileAllowed := GetFileGenericSecurity(AMask);
{$IFDEF WINVER5}
if TheAce.Header.AceType = ACCESS_DENIED_ACE_TYPE then
NewItem^.FileDenied := GetFileGenericSecurity(AMask);
{$ENDIF}
end else begin
if FIsDirectory then begin
TempFlag := AFlag and CONTAINER_INHERIT_ACE;
if TempFlag = CONTAINER_INHERIT_ACE then begin
// This is for the actual directory access and is inherited
// by new subdirectories.
if TheAce.Header.AceType = ACCESS_ALLOWED_ACE_TYPE then
NewItem^.DirectoryAllowed := GetFileGenericSecurity(AMask);
{$IFDEF WINVER5}
if TheAce.Header.AceType = ACCESS_DENIED_ACE_TYPE then
NewItem^.DirectoryDenied := GetFileGenericSecurity(AMask);
{$ENDIF}
end else begin
// This is for file access specified by directory security
// and inherited for new files added to the directory.
if TheAce.Header.AceType = ACCESS_ALLOWED_ACE_TYPE then
NewItem^.FileAllowed := GetGenericSecurity(AMask);
{$IFDEF WINVER5}
if TheAce.Header.AceType = ACCESS_DENIED_ACE_TYPE then
NewItem^.FileDenied := GetGenericSecurity(AMask);
{$ENDIF}
end;
end;
end;
pACE := nil;
end;
end;
// Add the last ACE we read to our list of ACEs...
FACEList.Add(NewItem);
FEntries.Add(NewItem^.Name);
FEntryCount := FACEList.Count;
FreeMem(FileSD);
DoOnGetSecurity(ERROR_SUCCESS,0);
end;
function SetFileGenericSecurity(SecuritySet: TAccessSet): DWORD;
begin
Result := 0;
if SecuritySet = [faAll] then
Result := FILE_ALL_ACCESS
else begin
if (faRead in SecuritySet) then
Result := Result or FILE_GENERIC_READ;
if (faWrite in SecuritySet) then
Result := Result or FILE_GENERIC_WRITE;
if (faExecute in SecuritySet) then
Result := Result or FILE_GENERIC_EXECUTE;
if (faDelete in SecuritySet) then
Result := Result or _DELETE;
if (faChangePermissions in SecuritySet) then
Result := Result or WRITE_DAC;
if (faTakeOwnership in SecuritySet) then
Result := Result or WRITE_OWNER;
end;
end;
function SetGenericSecurity(SecuritySet: TAccessSet): DWORD;
begin
Result := 0;
if SecuritySet = [faAll] then
Result := GENERIC_ALL
else begin
if (faRead in SecuritySet) then
Result := Result or GENERIC_READ;
if (faWrite in SecuritySet) then
Result := Result or GENERIC_WRITE;
if (faExecute in SecuritySet) then
Result := Result or GENERIC_EXECUTE;
if (faDelete in SecuritySet) then
Result := Result or _DELETE;
if (faChangePermissions in SecuritySet) then
Result := Result or WRITE_DAC;
if (faTakeOwnership in SecuritySet) then
Result := Result or WRITE_OWNER;
end;
end;
function TNTFileSecurity.CalculateACLSize: DWORD;
var
x: integer;
AccountSID: PSID;
SIDType: SID_NAME_USE;
LI : PSecurityListItem;
a: array [0..1023] of Char;
RefDom: array [0..DNLEN] of Char;
ServerName: array [0..DNLEN] of Char;
AccountName: array [0..UNLEN] of Char;
SIDTotal, DACEC, AACEC, dwRes, SIDLength, RefDomainLen, AclSize: DWORD;
begin
DACEC := 0;
AACEC := 0;
SIDTotal := 0;
SIDLength := 0;
AccountSID := nil;
AclSize := SizeOf(ACL);
for x := 0 to Pred(FACEList.Count) do begin
LI := FACEList.Items[x];
RefDomainLen := 0;
ZeroMemory(@ServerName,SizeOf(ServerName));
ZeroMemory(@AccountName,SizeOf(AccountName));
ZeroMemory(@RefDom,SizeOf(RefDom));
StrPCopy(AccountName,LI^.Name);
StrPCopy(ServerName,FSystemName);
case LI^.EntryType of
seUser : SIDType := SidTypeUser;
seGroup : SIDType := SidTypeGroup;
seDomain : SIDType := SidTypeDomain;
seAlias : SIDType := SidTypeAlias;
seWellKnownGroup : SIDType := SidTypeWellKnownGroup;
seDeletedAcount : SIDType := SidTypeDeletedAccount;
seInvalid : SIDType := SidTypeInvalid;
seUnknown : SIDType := SidTypeUnknown;
end;
if not LookupAccountName(ServerName,AccountName,AccountSID,SIDLength,RefDom,RefDomainLen,SIDType) then begin
dwRes := GetLastError;
if dwRes <> ERROR_INSUFFICIENT_BUFFER then begin
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
RaiseError(a);
end;
end;
if FIsDirectory then begin
{$IFDEF WINVER5}
if LI^.DirectoryDenied <> [] then begin
Inc(DACEC);
SIDTotal := SIDTotal + SIDLength;
end;
if LI^.FileDenied <> [] then begin
Inc(DACEC);
SIDTotal := SIDTotal + SIDLength;
end;
{$ENDIF}
if LI^.DirectoryAllowed <> [] then begin
Inc(AACEC);
SIDTotal := SIDTotal + SIDLength;
end;
if LI^.FileAllowed <> [] then begin
Inc(AACEC);
SIDTotal := SIDTotal + SIDLength;
end;
end else begin
if FIsFile then begin
{$IFDEF WINVER5}
if LI^.FileDenied <> [] then begin
Inc(DACEC);
SIDTotal := SIDTotal + SIDLength;
end;
{$ENDIF}
if LI^.FileAllowed <> [] then begin
Inc(AACEC);
SIDTotal := SIDTotal + SIDLength;
end;
end;
end;
end;
Result := AclSize + (DACEC * ( SizeOf(ACCESS_DENIED_ACE) - SizeOf(DWORD))) +
(AACEC * ( SizeOf(ACCESS_ALLOWED_ACE) - SizeOf(DWORD))) + SIDTotal;
end;
procedure TNTFileSecurity.SetSecurity;
var
HasDACL,IsDefault: LongBool;
UserSID: PSID;
NEW_ACL: PACL;
TheACE: PACCESS_ALLOWED_ACE;
NewFileSD: PSECURITY_DESCRIPTOR;
CurrentItem : PSecurityListItem;
SIDType: SID_NAME_USE;
FileName, a : array [0..255] of Char;
GroupName: array [0..UNLEN] of Char;
ServerName: array [0..CNLEN] of Char;
RefDom: array [0..DNLEN] of Char;
RefDomLen, SIDLen, ACL_SIZE, SDSize, AMask: DWORD;
x, ACECount: integer;
pACE: Pointer;
dwRes: DWORD;
begin
SDSize := 128;
ACECount := 0;
NEW_ACL := nil;
UserSID := nil;
HasDACL := True;
NewFileSD := nil;
IsDefault:= False;
StrPCopy(FileName,FFileName);
// Set the size of the ACCESS CONTROL LIST
ACL_SIZE := CalculateACLSize;
NEW_ACL := AllocMem(ACL_SIZE);
// Initialize the new ACCESS CONTROL LIST.
if not InitializeACL(NEW_ACL^,ACL_SIZE,ACL_REVISION) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_INITIALIZE_ACL);
Exit;
end;
// Loop through the security list adding ACCESS_DENIED_ACE first as we go.
// Proper ACCESS CONTROL LISTS place ACCESS_DENIED_ACEs before
// ACCESS_ALLOWED_ACEs. This is not a requirement but, it is STRONGLY
// suggested by Microsoft and more secure if it is done this way.
for x := 0 to Pred(FACEList.Count) do begin
// Initialize a few temp variables.
SIDLen := 0;
RefDomLen := 0;
CurrentItem := FACEList.Items[x];
StrPCopy(GroupName,CurrentItem^.Name);
StrPCopy(ServerName,FSystemName);
// Get the entry's SECURITY_IDENTIFIER length.
if not LookupAccountName(ServerName,GroupName,nil,SIDLen,nil,RefDomLen,SIDType) then begin
dwRes := GetLastError;
if dwRes <> ERROR_INSUFFICIENT_BUFFER then begin
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
DoOnSetSecurity(dwRes,ERROR_GET_ACCOUNT_SID);
Exit;
end;
end;
// Allocate memory for the entry's SECURITY_IDENTIFIER.
ReallocMem(UserSID,SIDLen);
// ReallocMem is the same as AllocMem if the pointer is "nil" and size > 0.
// Retrieve the entry's SECURITY_IDENTIFIER.
if not LookupAccountName(ServerName,GroupName,UserSID,SIDLen,RefDom,RefDomLen,SIDType) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
FreeMem(UserSID);
DoOnSetSecurity(dwRes,ERROR_GET_ACCOUNT_SID);
Exit;
end;
// Directories usually have 2 Access Control Entries for an account.
// The *first* entry specifies rights that apply to *files* within the
// directory. The *second* entry specifies rights that apply to the
// *directory* itself. The *first* entry uses a *slightly different*
// set of access flags, thus my use of SetFileGenericSecurity and
// SetGenericSecurity.
if FIsFile then begin
{$IFDEF WINVER5}
if CurrentItem^.FileDenied <> [] then begin
// Determine the file's ACCESS_MASK
AMask := SetFileGenericSecurity(CurrentItem^.FileDenied);
// Add the ACE to the ACCESS CONTROL LIST
if not AddAccessDeniedAce(NEW_ACL^,ACL_REVISION,AMask,UserSID) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_ADD_DENIED_ACE);
Exit;
end;
// Increment the ACE counter by one...
Inc(ACECount);
// Retrieve the ACE we just added
if not GetAce(NEW_ACL^,ACECount - 1,pACE) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_GET_ACE);
Exit;
end;
// Set security inheritence flags for the ACE.
// For actual files this is probably not neccessary but just for practice.
TheACE := pACE;
TheACE^.Header.AceFlags := OBJECT_INHERIT_ACE;
end;
{$ENDIF}
if CurrentItem^.FileAllowed <> [] then begin
// Determine the file's ACCESS_MASK
AMask := SetFileGenericSecurity(CurrentItem^.FileAllowed);
// Add the ACE to the ACCESS CONTROL LIST
if not AddAccessAllowedAce(NEW_ACL^,ACL_REVISION,AMask,UserSID) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_ADD_ALLOWED_ACE);
Exit;
end;
// Increment the ACE counter by one...
Inc(ACECount);
// Retrieve the ACE we just added
if not GetAce(NEW_ACL^,ACECount - 1,pACE) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_GET_ACE);
Exit;
end;
// Set security inheritence flags for the ACE.
// For actual files this is probably not neccessary but just for practice.
TheACE := pACE;
TheACE^.Header.AceFlags := OBJECT_INHERIT_ACE;
end;
end else begin
if FIsDirectory then begin
// Add *FILE* access rights to the directory *FIRST*.
{$IFDEF WINVER5}
if CurrentItem^.FileDenied <> [] then begin
AMask := SetGenericSecurity(CurrentItem^.FileDenied);
if not AddAccessDeniedAce(NEW_ACL^,ACL_REVISION,AMask,UserSID) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_ADD_DENIED_ACE);
Exit;
end;
// Increment the ACE counter by one...
Inc(ACECount);
// Retrieve the ACE we just added
if not GetAce(NEW_ACL^,ACECount - 1,pACE) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_GET_ACE);
Exit;
end;
// Set security inheritence flags for the directory's file ACE.
TheACE := pACE;
TheACE^.Header.AceFlags := INHERIT_ONLY_ACE or OBJECT_INHERIT_ACE;
end;
{$ENDIF}
if CurrentItem^.FileAllowed <> [] then begin
AMask := SetGenericSecurity(CurrentItem^.FileAllowed);
if not AddAccessAllowedAce(NEW_ACL^,ACL_REVISION,AMask,UserSID) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_ADD_ALLOWED_ACE);
Exit;
end;
// Increment the ACE counter by one...
Inc(ACECount);
// Retrieve the ACE we just added
if not GetAce(NEW_ACL^,ACECount - 1,pACE) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_GET_ACE);
Exit;
end;
// Set security inheritence flags for the directory's file ACE.
TheACE := pACE;
TheACE^.Header.AceFlags := INHERIT_ONLY_ACE or OBJECT_INHERIT_ACE;
end;
// Add *DIRECTORY* access rights to the directory itself *NEXT*.
{$IFDEF WINVER5}
if CurrentItem^.DirectoryDenied <> [] then begin
AMask := SetFileGenericSecurity(CurrentItem^.DirectoryDenied);
if not AddAccessDeniedAce(NEW_ACL^,ACL_REVISION,AMask,UserSID) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_ADD_DENIED_ACE);
Exit;
end;
// Increment the ACE counter by one...
Inc(ACECount);
// Retrieve the ACE we just added
if not GetAce(NEW_ACL^,ACECount - 1,pACE) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_GET_ACE);
Exit;
end;
// Set security inheritence flags for the directory's own ACE.
TheACE := pACE;
TheACE^.Header.AceFlags := CONTAINER_INHERIT_ACE;
// Means this security setting is inherited by NEW subdirectories.
// This does NOT set existing subdirectory security.
end;
{$ENDIF}
if CurrentItem^.DirectoryAllowed <> [] then begin
AMask := SetFileGenericSecurity(CurrentItem^.DirectoryAllowed);
if not AddAccessAllowedAce(NEW_ACL^,ACL_REVISION,AMask,UserSID) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_ADD_ALLOWED_ACE);
Exit;
end;
// Increment the ACE counter by one...
Inc(ACECount);
// Retrieve the ACE we just added
if not GetAce(NEW_ACL^,ACECount - 1,pACE) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
DoOnSetSecurity(dwRes,ERROR_GET_ACE);
Exit;
end;
// Set security inheritence flags for the directory's own ACE.
TheACE := pACE;
TheACE^.Header.AceFlags := CONTAINER_INHERIT_ACE;
// Means this security setting is inherited by NEW subdirectories.
// This does NOT set existing subdirectory security.
end;
end;
end;
// Get ready for the next security list entry.
// Dispose of the current entry's SECURITY_IDENTIFIER...
ReallocMem(UserSID,0);
// ReallocMem is the same as FreeMem if the pointer is pointer is not "nil"
// and the size = 0.
end;
// Allocate and Initialize a *NEW* SECURITY_DESCRIPTOR
ReallocMem(NewFileSD,SDSize);
if not InitializeSecurityDescriptor(NewFileSD,SECURITY_DESCRIPTOR_REVISION) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
ReallocMem(NewFileSD,0);
DoOnSetSecurity(dwRes,ERROR_INITIALIZE_SD);
Exit;
end;
// Place the NEW ACCESS CONTROL LIST into the NEW SECURITY_DESCRIPTOR
if not SetSecurityDescriptorDACL(NewFileSD,HasDACL,NEW_ACL,IsDefault) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
ReallocMem(NewFileSD,0);
DoOnSetSecurity(dwRes,ERROR_SET_DACL);
Exit;
end;
// Set the NEW SECURITY_DESCRIPTOR to the file or directory
if not SetFileSecurity(FileName,DACL_SECURITY_INFORMATION,NewFileSD) then begin
dwRes := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,dwRes,0,a,1024,nil);
// Clean up and exit on error...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
ReallocMem(NewFileSD,0);
DoOnSetSecurity(dwRes,ERROR_SET_SD);
Exit;
end;
// Clean up the mess...
ReallocMem(NEW_ACL,0);
ReallocMem(UserSID,0);
ReallocMem(NewFileSD,0);
DoOnSetSecurity(ERROR_SUCCESS,0);
end;
end.
|
unit ScriptRunner;
{
Inno Setup
Copyright (C) 1997-2011 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Script runner
$jrsoftware: issrc/Projects/ScriptRunner.pas,v 1.34 2011/01/11 05:30:39 jr Exp $
}
interface
uses
uPSRuntime, uPSDebugger, uPSUtils;
type
TScriptRunnerOnDllImport = procedure(var DllName: String; var ForceDelayLoad: Boolean);
TScriptRunnerOnDebug = function(const Position: LongInt; var ContinueStepOver: Boolean): Boolean;
TScriptRunnerOnDebugIntermediate = function(const Position: LongInt; var ContinueStepOver: Boolean): Boolean;
TScriptRunnerOnException = procedure(const Exception: AnsiString; const Position: LongInt);
TScriptRunner = class
private
FPSExec: TPSDebugExec;
FClassImporter: TPSRuntimeClassImporter;
FOnDllImport: TScriptRunnerOnDllImport;
FOnDebug: TScriptRunnerOnDebug;
FOnDebugIntermediate: TScriptRunnerOnDebugIntermediate;
FOnException: TScriptRunnerOnException;
procedure RaisePSExecException;
procedure SetPSExecParameters(const Parameters: array of Const; Params: TPSList);
procedure SetPSExecReturnValue(Params: TPSList; BaseType: TPSBaseType; var Res: PPSVariant);
procedure ShowPSExecError(const Error: TPSError);
public
constructor Create;
destructor Destroy; override;
procedure LoadScript(const CompiledScriptText, CompiledScriptDebugInfo: AnsiString);
function FunctionExists(const Name: AnsiString): Boolean;
procedure RunProcedure(const Name: AnsiString; const Parameters: array of Const; const MustExist: Boolean);
function RunBooleanFunction(const Name: AnsiString; const Parameters: array of Const; const MustExist, Default: Boolean): Boolean;
function RunIntegerFunction(const Name: AnsiString; const Parameters: array of Const; const MustExist: Boolean; const Default: Integer): Integer;
function RunStringFunction(const Name: AnsiString; const Parameters: array of Const; const MustExist: Boolean; const Default: String): String;
function EvaluateUsedVariable(const Param1, Param2, Param3: LongInt; const Param4: AnsiString): String;
property OnDllImport: TScriptRunnerOnDllImport read FOnDllImport write FOnDllImport;
property OnDebug: TScriptRunnerOnDebug read FOnDebug write FOnDebug;
property OnDebugIntermediate: TScriptRunnerOnDebugIntermediate read FOnDebugIntermediate write FOnDebugIntermediate;
property OnException: TScriptRunnerOnException read FOnException write FOnException;
end;
implementation
uses
Windows,
Forms, SysUtils,
uPSR_dll,
ScriptClasses_R, ScriptFunc_R;
{---}
{ Note: Originally this unit used String() casts to avoid "Implicit string
cast" warnings on Delphi 2009, but the casts were found to cause non-Unicode
Setup to crash during tooltip variable evaluation due to some kind of code
generation bug in Delphi 2. Removed all casts, and added the following to
simply disable the warning. }
{$IFDEF UNICODE}
{$WARN IMPLICIT_STRING_CAST OFF}
{$ENDIF}
procedure TScriptRunner.ShowPSExecError(const Error: TPSError);
begin
raise Exception.Create('Script error: ' + PSErrorToString(Error, ''));
end;
procedure TScriptRunner.RaisePSExecException;
var
E: TObject;
begin
try
FPSExec.RaiseCurrentException;
except
{ Note: Don't use 'on E: Exception do' since that will also match
'Exception' objects raised from other modules (which we mustn't modify) }
E := ExceptObject;
if E is Exception then begin
Exception(E).Message := Format('Runtime Error (at %d:%d):'#13#10#13#10,
[FPSExec.ExceptionProcNo, FPSExec.ExceptionPos]) + Exception(E).Message;
raise;
end
else begin
{ If we don't see it as an Exception, it was likely raised by another
module }
raise Exception.CreateFmt('Runtime Error (at %d:%d):'#13#10#13#10 +
'Exception "%s" at address %p',
[FPSExec.ExceptionProcNo, FPSExec.ExceptionPos, E.ClassName, ExceptAddr]);
end;
end;
end;
procedure TScriptRunner.SetPSExecParameters(const Parameters: array of Const; Params: TPSList);
var
Param: PPSVariant;
I: Integer;
begin
for I := High(Parameters) downto Low(Parameters) do begin
case Parameters[I].vType of
vtAnsiString:
begin
Param := CreateHeapVariant(FPSExec.FindType2(btString));
PPSVariantAString(Param).Data := AnsiString(Parameters[I].vAnsiString);
end;
{$IFDEF UNICODE}
vtWideString:
begin
Param := CreateHeapVariant(FPSExec.FindType2(btWideString));
PPSVariantWString(Param).Data := WideString(Parameters[I].VWideString);
end;
vtUnicodeString:
begin
Param := CreateHeapVariant(FPSExec.FindType2(btUnicodeString));
PPSVariantUString(Param).Data := UnicodeString(Parameters[I].VUnicodeString);
end;
{$ENDIF}
vtInteger:
begin
Param := CreateHeapVariant(FPSExec.FindType2(btS32));
PPSVariantS32(Param).Data := Parameters[I].vInteger;
end;
vtBoolean:
begin
Param := CreateHeapVariant(FPSExec.FindType2(btU8));
PPSVariantU8(Param).Data := Byte(Parameters[I].vBoolean);
end;
vtPointer:
begin
{ Pointers are assumed to be pointers to Booleans }
Param := CreateHeapVariant(FPSExec.FindType2(btU8));
PPSVariantU8(Param).Data := Byte(Boolean(Parameters[I].VPointer^));
end;
else
raise Exception.Create('TScriptRunner.SetPSExecParameters: Invalid type');
end;
Params.Add(Param);
end;
end;
procedure TScriptRunner.SetPSExecReturnValue(Params: TPSList; BaseType: TPSBaseType; var Res: PPSVariant);
begin
Res := CreateHeapVariant(FPSExec.FindType2(BaseType));
Params.Add(Res);
end;
{---}
{$IFDEF UNICODE}
function EncodeDLLFilename(const Filename: String): AnsiString;
begin
Result := '';
if Filename <> '' then
Result := AnsiString('<utf8>') + UTF8Encode(Filename);
end;
function NewUnloadDLLProc(Caller: TPSExec; Proc: TPSExternalProcRec; Global, Stack: TPSStack): Boolean;
begin
UnloadDLL(Caller, EncodeDLLFilename(Stack.GetString(-1)));
Result := True;
end;
{$ENDIF}
function PSExecOnSpecialProcImport(Sender: TPSExec; p: TPSExternalProcRec; Tag: Pointer): Boolean;
var
ScriptRunner: TScriptRunner;
DllName: AnsiString;
{$IFDEF UNICODE}
UnicodeDllName: String;
{$ENDIF}
I: Integer;
ForceDelayLoad: Boolean;
begin
ScriptRunner := Sender.ID;
ForceDelayLoad := False;
if Assigned(ScriptRunner.FOnDllImport) then begin
DllName := p.Decl;
I := Pos(AnsiString('dll:'), DllName);
if I <> 1 then begin
Result := False;
Exit;
end;
Delete(DllName, 1, Length('dll:'));
I := Pos(AnsiString(#0), DllName);
if I = 0 then begin
Result := False;
Exit;
end;
Delete(DllName, I, MaxInt);
{$IFDEF UNICODE}
UnicodeDllName := String(DllName);
ScriptRunner.FOnDllImport(UnicodeDllName, ForceDelayLoad);
DllName := EncodeDLLFilename(UnicodeDllName);
{$ELSE}
ScriptRunner.FOnDllImport(DllName, ForceDelayLoad);
{$ENDIF}
p.Decl := AnsiString('dll:') + DllName + Copy(p.Decl, Pos(AnsiString(#0), p.Decl), MaxInt);
end;
Result := ProcessDllImportEx(Sender, p, ForceDelayLoad);
end;
procedure PSExecOnSourceLine(Sender: TPSDebugExec; const Name: AnsiString; Position, Row, Col: Cardinal);
var
ScriptRunner: TScriptRunner;
ContinueStepOver, NeedToResume: Boolean;
begin
ScriptRunner := Sender.ID;
ContinueStepOver := False;
if Sender.DebugMode = dmPaused then begin
if Assigned(ScriptRunner.FOnDebug) then
ScriptRunner.FOnDebug(Position, ContinueStepOver);
NeedToResume := True;
end else begin
{ Normally the debugger does not pause when it receives an 'intermediate'
notification. However, it can happen if the user clicks Step Over and
then Pause before the function call being stepped over has returned. }
NeedToResume := False;
if Assigned(ScriptRunner.FOnDebugIntermediate) then
NeedToResume := ScriptRunner.FOnDebugIntermediate(Position, ContinueStepOver);
end;
if NeedToResume then begin
if ContinueStepOver then
Sender.StepOver()
else
Sender.StepInto();
end;
end;
procedure PSExecOnException(Sender: TPSExec; ExError: TPSError; const ExParam: AnsiString; ExObject: TObject; ProcNo, Position: Cardinal);
var
ScriptRunner: TScriptRunner;
begin
ScriptRunner := Sender.ID;
if Assigned(ScriptRunner.FOnException) then
ScriptRunner.FOnException(PSErrorToString(ExError, ExParam), ScriptRunner.FPSExec.TranslatePosition(ProcNo, Position));
{ Clear any previous 'step over' state after an exception. Like Delphi,
when F8 is pressed after an exception it should go to the first line of
the nearest 'except' handler, not to the next line of some higher-level
function that the user was stepping over prior to the exception. }
ScriptRunner.FPSExec.StepInto();
end;
{---}
constructor TScriptRunner.Create();
begin
FPSExec := TPSDebugExec.Create();
FPSExec.ID := Self;
FPSExec.AddSpecialProcImport('dll', @PSExecOnSpecialProcImport, nil);
FPSExec.OnSourceLine := PSExecOnSourceLine;
FPSExec.OnException := PSExecOnException;
{$IFNDEF UNICODE}
RegisterDLLRuntimeEx(FPSExec, False);
{$ELSE}
RegisterDLLRuntimeEx(FPSExec, False, False);
FPSExec.RegisterFunctionName('UNLOADDLL', NewUnloadDLLProc, nil, nil);
{$ENDIF}
FClassImporter := ScriptClassesLibraryRegister_R(FPSExec);
ScriptFuncLibraryRegister_R(FPSExec);
end;
destructor TScriptRunner.Destroy;
begin
FPSExec.Free();
FClassImporter.Free();
end;
procedure TScriptRunner.LoadScript(const CompiledScriptText, CompiledScriptDebugInfo: AnsiString);
begin
if FPSExec.LoadData(CompiledScriptText) then begin
FPSExec.DebugEnabled := CompiledScriptDebugInfo <> '';
if FPSExec.DebugEnabled then
FPSExec.LoadDebugData(CompiledScriptDebugInfo);
FPSExec.StepInto();
end else begin
RaisePSExecException;
{ In the case the above for some reason doesn't raise an exception, raise
our own: }
raise Exception.Create('TScriptRunner.LoadScript failed');
end;
end;
function TScriptRunner.FunctionExists(const Name: AnsiString): Boolean;
begin
Result := FPSExec.GetProc(Name) <> Cardinal(-1);
end;
procedure WriteBackParameters(const Parameters: array of Const; const Params: TPSList);
var
I: Integer;
begin
{ Write back new Boolean values to vtPointer-type parameters }
for I := 0 to High(Parameters) do
if Parameters[I].vType = vtPointer then
Boolean(Parameters[I].VPointer^) := (PPSVariantU8(Params[High(Parameters)-I]).Data = 1);
end;
procedure TScriptRunner.RunProcedure(const Name: AnsiString; const Parameters: array of Const; const MustExist: Boolean);
var
ProcNo: Cardinal;
Params: TPSList;
begin
ProcNo := FPSExec.GetProc(Name);
if ProcNo <> Cardinal(-1) then begin
Params := TPSList.Create();
try
SetPSExecParameters(Parameters, Params);
FPSExec.RunProc(Params, ProcNo);
WriteBackParameters(Parameters, Params);
finally
FreePSVariantList(Params);
end;
RaisePSExecException;
end else begin
if MustExist then
ShowPSExecError(erCouldNotCallProc);
end;
end;
function TScriptRunner.RunBooleanFunction(const Name: AnsiString; const Parameters: array of Const; const MustExist, Default: Boolean): Boolean;
var
ProcNo: Cardinal;
Params: TPSList;
Res: PPSVariant;
begin
Result := Default;
ProcNo := FPSExec.GetProc(Name);
if ProcNo <> Cardinal(-1) then begin
Params := TPSList.Create();
try
SetPSExecParameters(Parameters, Params);
SetPSExecReturnValue(Params, btU8, Res);
FPSExec.RunProc(Params, ProcNo);
WriteBackParameters(Parameters, Params);
RaisePSExecException;
Result := PPSVariantU8(Res).Data = 1;
finally
FreePSVariantList(Params);
end;
end else begin
if MustExist then
ShowPSExecError(erCouldNotCallProc);
end;
end;
function TScriptRunner.RunIntegerFunction(const Name: AnsiString; const Parameters: array of Const; const MustExist: Boolean; const Default: Integer): Integer;
var
ProcNo: Cardinal;
Params: TPSList;
Res: PPSVariant;
begin
Result := Default;
ProcNo := FPSExec.GetProc(Name);
if ProcNo <> Cardinal(-1) then begin
Params := TPSList.Create();
try
SetPSExecParameters(Parameters, Params);
SetPSExecReturnValue(Params, btS32, Res);
FPSExec.RunProc(Params, ProcNo);
WriteBackParameters(Parameters, Params);
RaisePSExecException;
Result := PPSVariantS32(Res).Data;
finally
FreePSVariantList(Params);
end;
end else begin
if MustExist then
ShowPSExecError(erCouldNotCallProc);
end;
end;
function TScriptRunner.RunStringFunction(const Name: AnsiString; const Parameters: array of Const; const MustExist: Boolean; const Default: String): String;
var
ProcNo: Cardinal;
Params: TPSList;
Res: PPSVariant;
begin
Result := Default;
ProcNo := FPSExec.GetProc(Name);
if ProcNo <> Cardinal(-1) then begin
Params := TPSList.Create();
try
SetPSExecParameters(Parameters, Params);
{$IFDEF UNICODE}
SetPSExecReturnValue(Params, btUnicodeString, Res);
{$ELSE}
SetPSExecReturnValue(Params, btString, Res);
{$ENDIF}
FPSExec.RunProc(Params, ProcNo);
WriteBackParameters(Parameters, Params);
RaisePSExecException;
{$IFDEF UNICODE}
Result := PPSVariantUString(Res).Data;
{$ELSE}
Result := PPSVariantAString(Res).Data;
{$ENDIF}
finally
FreePSVariantList(Params);
end;
end else begin
if MustExist then
ShowPSExecError(erCouldNotCallProc);
end;
end;
function TScriptRunner.EvaluateUsedVariable(const Param1, Param2, Param3: LongInt; const Param4: AnsiString): String;
function VariantToString(const p: TPSVariantIFC; const ClassProperties: AnsiString): String;
begin
{$IFDEF UNICODE}
//PSVariantToString isn't Unicode enabled, handle strings ourselves
//doesn't handle more complex types as records, arrays and objects
if p.Dta <> nil then begin
case p.aType.BaseType of
btWideChar: Result := '''' + tbtWideChar(p.Dta^) + '''';
btWideString: Result := '''' + tbtWideString(p.Dta^) + '''';
btUnicodeString: Result := '''' + tbtUnicodeString(p.Dta^) + '''';
else
Result := PSVariantToString(p, ClassProperties);
end;
end else
{$ENDIF}
Result := PSVariantToString(p, ClassProperties);
end;
begin
case TPSVariableType(Param1) of
ivtGlobal:
begin
Result := FPSExec.GlobalVarNames[Param3];
if Param4 <> '' then
Result := Result + '.' + Param4;
Result := Result + ' = ' + VariantToString(NewTPSVariantIFC(FPSExec.GetGlobalVar(Param3), False), Param4);
end;
ivtParam:
begin
if Param2 = LongInt(FPSExec.GetCurrentProcNo) then begin
Result := FPSExec.CurrentProcParams[Param3];
if Param4 <> '' then
Result := Result + '.' + Param4;
Result := Result + ' = ' + VariantToString(NewTPSVariantIFC(FPSExec.GetProcParam(Param3), False), Param4);
end else
Result := '';
end;
ivtVariable:
begin
if Param2 = LongInt(FPSExec.GetCurrentProcNo) then begin
Result := FPSExec.CurrentProcVars[Param3];
if Param4 <> '' then
Result := Result + '.' + Param4;
Result := Result + ' = ' + VariantToString(NewTPSVariantIFC(FPSExec.GetProcVar(Param3), False), Param4);
end else
Result := '';
end;
end;
end;
end.
|
unit TestFeatureParser;
interface
uses
TestFramework, FeatureParser, FeatureParserIntf, dSpec, dSpecIntf, TestBaseClasses;
type
TestTFeatureParser = class(TParseContext)
strict private
FFeatureParser: IFeatureParser;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure DeveriaRetornarUmaFeature;
procedure DeveriaTrazerOsCenariosDaFeature;
procedure DeveriaTrazerOTituloEADescricaoDaFeature;
procedure DeveriaTrazerOTituloDosCenarios;
procedure DeveriaTrazerOsPassosDosCenarios;
procedure DeveriaCarregarOErroDaFeature;
procedure DeveriaIdentificarSePassoContemApenasUmaPalavra;
procedure DeveriaInicializarComAPalavraFuncionalidade;
procedure DeveriaValidarSeExistiOArquivoDaFeature;
procedure DeveriaCarregarOsParametrosDoStep;
end;
implementation
uses
TypeUtils, TestConsts, FeatureIntf, ScenarioIntf, StepIntf, FeatureErrorIntf, Constants, SysUtils;
procedure TestTFeatureParser.DeveriaTrazerOsCenariosDaFeature;
var
LFeature: IFeature;
begin
LFeature := FFeatureParser.Parse;
Specify.That(LFeature.Scenarios.Count).Should.Equal(1);
end;
procedure TestTFeatureParser.DeveriaTrazerOTituloDosCenarios;
var
LFeature: IFeature;
begin
LFeature := FFeatureParser.Parse;
Specify.That((LFeature.Scenarios[0] as IScenario).Titulo).Should.Equal('Primeiros Passos');
end;
procedure TestTFeatureParser.DeveriaTrazerOTituloEADescricaoDaFeature;
var
LFeature: IFeature;
begin
LFeature := FFeatureParser.Parse;
Specify.That(LFeature.Titulo).Should.Equal('Um modelo de teste');
Specify.That(LFeature.Descricao).Should.Equal(DescricaoFeatureTeste);
end;
procedure TestTFeatureParser.DeveriaInicializarComAPalavraFuncionalidade;
var
LError: IFeatureError;
begin
FFeatureParser.FeatureFileName := S(FeatureDir).Mais(FeatureSemFuncionalidade);
FFeatureParser.Parse;
Specify.That(FFeatureParser.Errors.Count).Should.Equal(1);
LError := FFeatureParser.Errors.First as IFeatureError;
Specify.That(LError.Line).Should.Equal(1);
Specify.That(LError.Message).Should.Equal(Format(InvalidFeature, [FFeatureParser.FeatureFileName]));
Specify.That(LError.SugestedAction).Should.Equal('Exemplo: Funcionalidade: Aqui vai o título da sua funcionalidade.');
FFeatureParser.FeatureFileName := S(FeatureDir).Mais(FeatureComPrimeiraLinhaEmBranco);
FFeatureParser.Parse;
Specify.That(FFeatureParser.Errors.Count).Should.Equal(1);
LError := FFeatureParser.Errors.First as IFeatureError;
Specify.That(LError.Line).Should.Equal(1);
Specify.That(LError.Message).Should.Equal(Format(InvalidFeature, [FFeatureParser.FeatureFileName]));
Specify.That(LError.SugestedAction).Should.Equal('Exemplo: Funcionalidade: Aqui vai o título da sua funcionalidade.');
end;
procedure TestTFeatureParser.DeveriaTrazerOsPassosDosCenarios;
var
LFeature: IFeature;
begin
LFeature := FFeatureParser.Parse;
Specify.That((LFeature.Scenarios.First as IScenario).Steps.Count).Should.Equal(3);
Specify.That(((LFeature.Scenarios.First as IScenario).Steps.First as IStep).Descricao).Should.Equal(DescricaoPrimeiroStep)
end;
procedure TestTFeatureParser.SetUp;
begin
FFeatureParser := TFeatureParser.Create;
FFeatureParser.FeatureFileName := S(FeatureDir).Mais(FeatureCenarioSimples);
end;
procedure TestTFeatureParser.TearDown;
begin
FFeatureParser := nil;
end;
procedure TestTFeatureParser.DeveriaValidarSeExistiOArquivoDaFeature;
var
LError: IFeatureError;
begin
FFeatureParser.FeatureFileName := 'InvalidFileName.feature';
FFeatureParser.Parse;
Specify.That(FFeatureParser.Errors.Count).Should.Equal(1);
LError := FFeatureParser.Errors.First as IFeatureError;
Specify.That(LError.Message).Should.Equal('O arquivo que você tentou carregar (InvalidFileName.feature) não existe.');
Specify.That(LError.SugestedAction).Should.Equal('Tente carregar um arquivo que exista :)');
end;
procedure TestTFeatureParser.DeveriaCarregarOErroDaFeature;
var
LError: IFeatureError;
begin
FFeatureParser.FeatureFileName := S(FeatureDir).Mais(FeatureComUmErro);
FFeatureParser.Parse;
Specify.That(FFeatureParser.Errors).Should.Not_.Be.Empty;
LError := FFeatureParser.Errors.First as IFeatureError;
Specify.That(LError.Line).Should.Equal(8);
Specify.That(LError.Message).Should.Equal('A linha 8 começa com uma palavra chave desconhecida (Essa).');
Specify.That(LError.SugestedAction).Should.Equal(SugestedActionToStepError)
end;
procedure TestTFeatureParser.DeveriaCarregarOsParametrosDoStep;
begin
Fail('TODO - criar lista de parâmetros no Scenario.');
end;
procedure TestTFeatureParser.DeveriaIdentificarSePassoContemApenasUmaPalavra;
var
LError: IFeatureError;
begin
FFeatureParser.FeatureFileName := S(FeatureDir).Mais(FeatureComUmErro);
FFeatureParser.Parse;
Specify.That(FFeatureParser.Errors).Should.Not_.Be.Empty;
LError := FFeatureParser.Errors.Last as IFeatureError;
Specify.That(LError.Line).Should.Equal(13);
Specify.That(LError.Message).Should.Equal('O passo da linha 13 deve conter mais do que apenas uma palavra.');
Specify.That(LError.SugestedAction).Should.Equal('Quando... ?!');
end;
procedure TestTFeatureParser.DeveriaRetornarUmaFeature;
var
LFeature: IFeature;
begin
LFeature := FFeatureParser.Parse;
Specify.That(LFeature).Should.Not_.Be.Nil_;
LFeature := nil;
end;
initialization
RegisterSpec(TestTFeatureParser.Suite);
end.
|
unit Unit1;
interface
type
TElem = record
id: integer;
libelle: string[50];
coche: boolean;
end;
TListe = array of TElem;
function ajouter(libelle: string): integer;
procedure modifier(id: integer; libelle: string);
procedure supprimer(id: integer);
procedure cocher(id: integer);
procedure decocher(id: integer);
function estCoché(id: integer): boolean;
function lister: TListe;
implementation
uses system.ioutils;
const
FichName = 'Presentation-RADStudio-Delphi.rcd';
type
TFichier = file of TElem;
var
liste: TListe;
id_max: integer;
liste_modifiee: boolean;
function ajouter(libelle: string): integer;
var
num: integer;
begin
inc(id_max);
num := length(liste);
setlength(liste, num + 1);
liste[num].id := id_max;
liste[num].libelle := libelle;
liste[num].coche := false;
liste_modifiee := true;
end;
procedure modifier(id: integer; libelle: string);
var
num: integer;
begin
num := 0;
while (num < length(liste)) and (liste[num].id <> id) do
inc(num);
if (num < length(liste)) then
begin
liste[num].libelle := libelle;
liste_modifiee := true;
end;
end;
procedure supprimer(id: integer);
var
num: integer;
begin
num := 0;
while (num < length(liste)) and (liste[num].id <> id) do
inc(num);
if (num < length(liste)) then
begin
while (num < length(liste) - 1) do
begin
liste[num] := liste[num + 1];
inc(num);
end;
setlength(liste, length(liste) - 1);
liste_modifiee := true;
end;
end;
procedure cocher(id: integer);
var
num: integer;
begin
num := 0;
while (num < length(liste)) and (liste[num].id <> id) do
inc(num);
if (num < length(liste)) then
begin
liste[num].coche := true;
liste_modifiee := true;
end;
end;
procedure decocher(id: integer);
var
num: integer;
begin
num := 0;
while (num < length(liste)) and (liste[num].id <> id) do
inc(num);
if (num < length(liste)) then
begin
liste[num].coche := false;
liste_modifiee := true;
end;
end;
function estCoché(id: integer): boolean;
var
num: integer;
begin
num := 0;
while (num < length(liste)) and (liste[num].id <> id) do
inc(num);
result := (num < length(liste)) and liste[num].coche;
end;
function lister: TListe;
begin
result := liste;
end;
procedure load;
var
f: TFichier;
path: string;
begin
id_max := 0;
setlength(liste, 0);
path := tpath.Combine(tpath.GetDocumentsPath, FichName);
if (tfile.Exists(path)) then
begin
assignfile(f, path);
reset(f);
while not eof(f) do
begin
setlength(liste, length(liste) + 1);
read(f, liste[length(liste) - 1]);
if (id_max < liste[length(liste) - 1].id) then
id_max := liste[length(liste) - 1].id;
end;
closefile(f);
end;
liste_modifiee := false;
end;
procedure save;
var
f: TFichier;
e: TElem;
begin
assignfile(f, tpath.Combine(tpath.GetDocumentsPath, FichName));
rewrite(f);
for e in liste do
write(f, e);
closefile(f);
liste_modifiee := false;
end;
initialization
id_max := 0;
liste_modifiee := false;
setlength(liste, 0);
load;
finalization
if liste_modifiee then
save;
end.
|
unit ucustomtranslation;
{$MODE Delphi}
interface
uses
SysUtils, Classes, Graphics, Controls, StdCtrls, ExtCtrls, Forms, Buttons,
Grids, MPHexEditor, ComCtrls, ToolWin, Dialogs;
type
TdlgEditCustomTranslation = class(TForm)
Button1: TButton;
Button2: TButton;
MPHexEditor1: TMPHexEditor;
ToolBar1: TToolBar;
btnLoad: TToolButton;
btnSave: TToolButton;
btnAuto: TToolButton;
ToolButton1: TToolButton;
TabSet1: TTabControl;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
pnPos: TPanel;
procedure TabSet1Change(Sender: TObject; NewTab: Integer;
var AllowChange: Boolean);
procedure btnLoadClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnAutoClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FOldIdle: TIdleEvent;
FCustTrans: TMPHCharConv;
procedure ShowTable(Index: Integer);
procedure SetTable(Index: Integer);
// idle handler
procedure AppIdle(Sender: TObject; var Done: Boolean);
end;
var
dlgEditCustomTranslation: TdlgEditCustomTranslation;
// edit custom translation
function EditCustomTranslation: Boolean;
implementation
uses umain, inifiles, LazFileUtils;
{$R *.lfm}
const
STR_ERR_UNKNOWNTABLE = 'Unknown Table Format';
STR_ERR_TABLEVALNOTUSE =
'Byte %2x is not used in the table, so i cannot do an 1:1 translation';
STR_ERR_TABLEVALMULTIPLE =
'Byte %2x is used multiple times, so icannot do an 1:1 translation';
// edit custom translation
function EditCustomTranslation: Boolean;
begin
with TdlgEditCustomTranslation.Create(Application) do
try
FCustTrans := MPHCustomCharConv;
ShowTable(0);
Result := ShowModal = mrok;
if Result then
MPHCustomCharConv := FCustTrans;
finally
Free;
end;
end;
{ TdlgEditCustomTranslation }
procedure TdlgEditCustomTranslation.SetTable(Index: Integer);
begin
if Index = 0 then
MPHexEditor1.ReadBuffer(FCustTrans[cctFromAnsi], 0,
sizeof(FCustTrans[cctFromAnsi]))
else
MPHexEditor1.ReadBuffer(FCustTrans[cctToAnsi], 0,
sizeof(FCustTrans[cctToAnsi]))
end;
procedure TdlgEditCustomTranslation.ShowTable;
var
LIntLoop: Integer;
begin
MPHexEditor1.DataSize := sizeof(TMPHCharConvTable);
if Index = 0 then
MPHexEditor1.WriteBuffer(FCustTrans[cctFromAnsi], 0,
sizeof(FCustTrans[cctFromAnsi]))
else
MPHexEditor1.WriteBuffer(FCustTrans[cctToAnsi], 0,
sizeof(FCustTrans[cctToAnsi]));
for LIntLoop := 0 to 255 do
MPHexEditor1.ByteChanged[LIntLoop] :=
MPHexEditor1.Data[LIntLoop] <> LIntLoop;
MPHexEditor1.Repaint;
end;
procedure TdlgEditCustomTranslation.TabSet1Change(Sender: TObject;
NewTab: Integer; var AllowChange: Boolean);
var
LIntPos: Integer;
LBoolChars: Boolean;
begin
with MPHexEditor1 do
begin
LIntPos := GetCursorPos;
LBoolChars := InCharField;
SetTable(TabSet1.TabIndex);
ShowTable(NewTab);
Seek(LIntPos, soFromBeginning);
InCharField := LBoolChars;
end;
end;
procedure TdlgEditCustomTranslation.btnLoadClick(Sender: TObject);
var
aIni: TIniFile;
i: integer;
s: string;
begin
with OpenDialog1 do
if Execute then
begin
aIni := TIniFile.Create(FileName);
with aIni do
try
for i := 0 to 255 do
begin
s := aIni.ReadString('From_Ansi', '0x' + IntToHex(i, 2),
'0x' + IntToHex(i, 2));
FCustTrans[cctFromAnsi][i] := Char(StrToIntDef(s, i));
s := aIni.ReadString('To_Ansi', '0x' + IntToHex(i, 2),
'0x' + IntToHex(i, 2));
FCustTrans[cctToAnsi][i] := Char(StrToIntDef(s, i));
end;
ShowTable(TabSet1.TabIndex);
finally
Free;
end;
end;
end;
procedure TdlgEditCustomTranslation.btnSaveClick(Sender: TObject);
var
aIni: TIniFile;
i: integer;
begin
with SaveDialog1 do
if Execute then
begin
SetTable(TabSet1.TabIndex);
if FileExistsUTF8(FileName) { *Converted from FileExists* } then
DeleteFileUTF8(PChar(FileName)); { *Converted from DeleteFile* }
aIni := TIniFile.Create(FileName);
with aIni do
try
EraseSection('From_Ansi');
EraseSection('To_Ansi');
for i := 0 to 255 do
begin
aIni.WriteString('From_Ansi', '0x' + IntToHex(i, 2),
'0x' + IntToHex(Byte(FCustTrans[cctFromAnsi][i]), 2));
aIni.WriteString('To_Ansi', '0x' + IntToHex(i, 2),
'0x' + IntToHex(Byte(FCustTrans[cctToAnsi][i]), 2));
end;
finally
Free;
end;
end;
end;
procedure TdlgEditCustomTranslation.btnAutoClick(Sender: TObject);
var
LBytCheck: array[Byte] of Byte;
LIntLoop,
LIntLoop1: Integer;
begin
SetTable(TabSet1.TabIndex);
// check if the current table is unambigous
FillChar(LBytCheck, sizeof(LBytCheck), #0);
for LIntLoop := 0 to 255 do
if TabSet1.TabIndex = 0 then
Inc(LBytCheck[Ord(FCustTrans[cctFromAnsi][LIntLoop])])
else
Inc(LBytCheck[Ord(FCustTrans[cctToAnsi][LIntLoop])]);
// whole check array must be set to 1 (else no 1:1 translation)
for LIntLoop := 0 to 255 do
case LBytCheck[LIntLoop] of
0: // not used, whine
raise Exception.CreateFmt(STR_ERR_TABLEVALNOTUSE, [LIntLoop]);
1: ; //ok
else
for LIntLoop1 := 0 to 255 do
MPHexEditor1.ByteChanged[LIntLoop1] := MPHexEditor1.Data[LIntLoop1] =
LIntLoop;
MPHexEditor1.Repaint;
raise Exception.CreateFmt(STR_ERR_TABLEVALMULTIPLE, [LIntLoop]);
end;
// all ok, create other table
for LIntLoop := 0 to 255 do
if TabSet1.TabIndex = 0 then
FCustTrans[cctToAnsi][Byte(FCustTrans[cctFromAnsi][LIntLoop])] := Char(LIntLoop)
else
FCustTrans[cctFromAnsi][Byte(FCustTrans[cctToAnsi][LIntLoop])] := Char(LIntLoop)
end;
procedure TdlgEditCustomTranslation.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
SetTable(TabSet1.TabIndex);
end;
procedure TdlgEditCustomTranslation.FormCreate(Sender: TObject);
begin
FOldIdle := Application.OnIdle;
Application.OnIdle := AppIdle;
end;
procedure TdlgEditCustomTranslation.FormDestroy(Sender: TObject);
begin
Application.OnIdle := FOldIdle;
end;
procedure TdlgEditCustomTranslation.AppIdle(Sender: TObject;
var Done: Boolean);
begin
with MPHexEditor1 do
pnPos.Caption := IntToHex(GetCursorPos, 2) + ':' +
IntToHex(Byte(Data[GetCursorPos]), 2)
end;
end.
|
unit UFormMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
StdCtrls, ExtCtrls, Dialogs, ExtDlgs, IniFiles,
ATPrintPreview,
ATxPrintProc, XPMan;
type
TFormMain = class(TForm)
OpenPictureDialog1: TOpenPictureDialog;
Panel1: TPanel;
btnOpen: TButton;
btnPreview: TButton;
btnClose: TButton;
Panel2: TPanel;
boxMain: TGroupBox;
Image1: TImage;
edMm: TComboBox;
labMm: TLabel;
XPManifest1: TXPManifest;
procedure FormShow(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
procedure btnPreviewClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure chkMmClick(Sender: TObject);
private
{ Private declarations }
FFileName: string;
FIni: TIniFile;
FOpt: TATPrintOptions;
FOldMm: TATPrintUnit;
procedure LoadImage(const fn: string);
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
uses
{$ifdef GIF}
GIFImage,
{$endif}
Jpeg;
{$R *.dfm}
procedure TFormMain.FormShow(Sender: TObject);
begin
LoadImage(ExtractFilePath(Application.ExeName) + 'Test_image_nature.jpg');
end;
procedure TFormMain.LoadImage(const fn: string);
begin
try
FFileName := fn;
Image1.Picture.LoadFromFile(FFileName);
btnPreview.Enabled := True;
except
Application.MessageBox(
PChar(Format('Could not load image from "%s"', [FFileName])),
PChar(Caption), MB_OK or MB_ICONERROR);
end;
end;
procedure TFormMain.btnOpenClick(Sender: TObject);
begin
with OpenPictureDialog1 do
if Execute then
LoadImage(FileName);
end;
procedure TFormMain.btnPreviewClick(Sender: TObject);
begin
with FOpt do
begin
OptUnit := TATPrintUnit(edMm.ItemIndex);
OptFooter.Caption := ExtractFileName(FFileName);
end;
ImagePrint(Image1, FOpt);
end;
procedure TFormMain.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TFormMain.FormCreate(Sender: TObject);
var
i: TATPrintUnit;
begin
FIni := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
with edMm do
begin
Items.Clear;
for i := Low(i) to High(i) do
Items.Add(MsgPreviewDlgUnit[i]);
ItemIndex := FIni.ReadInteger('Opt', 'Unit', 0);
FOldMm := TATPrintUnit(ItemIndex);
end;
FillChar(FOpt, SizeOf(FOpt), 0);
with FOpt do
begin
Copies := 1;
OptFit := pFitNormal;
OptPosition := pPosCenter;
OptUnit := pUnitMm;
OptMargins.Left := FIni.ReadFloat('Opt', 'MarginL', 20);
OptMargins.Top := FIni.ReadFloat('Opt', 'MarginT', 10);
OptMargins.Right := FIni.ReadFloat('Opt', 'MarginR', 10);
OptMargins.Bottom := FIni.ReadFloat('Opt', 'MarginB', 10);
OptFit := TATPrintFitMode(FIni.ReadInteger('Opt', 'Fit', 0));
OptFitSize.x := FIni.ReadFloat('Opt', 'SizeX', 100);
OptFitSize.y := FIni.ReadFloat('Opt', 'SizeY', 100);
OptGamma := FIni.ReadFloat('Opt', 'Gamma', 1.0);
with OptFooter do
begin
Enabled := True;
EnableLine := True;
FontName := FIni.ReadString('Opt', 'FontName', 'Arial');
FontSize := FIni.ReadInteger('Opt', 'FontSize', 9);
FontStyle := TFontStyles(byte(FIni.ReadInteger('Opt', 'FontStyle', 0)));
FontColor := FIni.ReadInteger('Opt', 'FontColor', clBlack);
FontCharset := FIni.ReadInteger('Opt', 'FontCharset', DEFAULT_CHARSET);
end;
PixelsPerInch := Screen.PixelsPerInch;
JobCaption := Self.Caption;
FailOnErrors := True;
end;
end;
procedure TFormMain.FormDestroy(Sender: TObject);
begin
FIni.WriteFloat('Opt', 'MarginL', FOpt.OptMargins.Left);
FIni.WriteFloat('Opt', 'MarginT', FOpt.OptMargins.Top);
FIni.WriteFloat('Opt', 'MarginR', FOpt.OptMargins.Right);
FIni.WriteFloat('Opt', 'MarginB', FOpt.OptMargins.Bottom);
FIni.WriteInteger('Opt', 'Fit', Integer(FOpt.OptFit));
FIni.WriteFloat('Opt', 'SizeX', FOpt.OptFitSize.x);
FIni.WriteFloat('Opt', 'SizeY', FOpt.OptFitSize.y);
FIni.WriteFloat('Opt', 'Gamma', FOpt.OptGamma);
FIni.WriteString('Opt', 'FontName', FOpt.OptFooter.FontName);
FIni.WriteInteger('Opt', 'FontSize', FOpt.OptFooter.FontSize);
FIni.WriteInteger('Opt', 'FontStyle', byte(FOpt.OptFooter.FontStyle));
FIni.WriteInteger('Opt', 'FontColor', FOpt.OptFooter.FontColor);
FIni.WriteInteger('Opt', 'FontCharset', FOpt.OptFooter.FontCharset);
FIni.WriteInteger('Opt', 'Unit', edMm.ItemIndex);
FreeAndNil(FIni);
end;
procedure EMul(var E: Double; const Mul: Double);
begin
E := E * Mul;
end;
procedure TFormMain.chkMmClick(Sender: TObject);
var
M: Extended;
FNewMm: TATPrintUnit;
begin
FNewMm := TATPrintUnit(edMm.ItemIndex);
if FNewMm <> FOldMm then
begin
M := cUnitIn[FNewMm] / cUnitIn[FOldMm];
FOldMm := FNewMm;
EMul(FOpt.OptMargins.Left, M);
EMul(FOpt.OptMargins.Top, M);
EMul(FOpt.OptMargins.Right, M);
EMul(FOpt.OptMargins.Bottom, M);
EMul(FOpt.OptFitSize.x, M);
EMul(FOpt.OptFitSize.y, M);
end;
end;
end.
|
unit ThostFtdcTraderApiDataDefine;
interface
const
/////////////////////////////////////////////////////////////////////////
///TFtdcDirectionType是一个买卖方向类型
/////////////////////////////////////////////////////////////////////////
///买
THOST_FTDC_D_Buy = '0';
///卖
THOST_FTDC_D_Sell = '1';
/////////////////////////////////////////////////////////////////////////
///TFtdcOffsetFlagType是一个开平标志类型
/////////////////////////////////////////////////////////////////////////
///开仓
THOST_FTDC_OF_Open = '0';
///平仓
THOST_FTDC_OF_Close = '1';
///强平
THOST_FTDC_OF_ForceClose = '2';
///平今
THOST_FTDC_OF_CloseToday = '3';
///平昨
THOST_FTDC_OF_CloseYesterday = '4';
///强减
THOST_FTDC_OF_ForceOff = '5';
///本地强平
THOST_FTDC_OF_LocalForceClose = '6';
//typedef char TThostFtdcOffsetFlagType;
/////////////////////////////////////////////////////////////////////////
///TFtdcHedgeFlagType是一个投机套保标志类型
/////////////////////////////////////////////////////////////////////////
///投机
THOST_FTDC_HF_Speculation = '1';
///套利
THOST_FTDC_HF_Arbitrage = '2';
///套保
THOST_FTDC_HF_Hedge = '3';
/////////////////////////////////////////////////////////////////////////
///TFtdcOrderStatusType是一个报单状态类型
/////////////////////////////////////////////////////////////////////////
/// 成交顺序 a --> 3 --> 3 --> 0
///全部成交
THOST_FTDC_OST_AllTraded = '0';
///部分成交还在队列中
THOST_FTDC_OST_PartTradedQueueing = '1';
///部分成交不在队列中
THOST_FTDC_OST_PartTradedNotQueueing = '2';
///未成交还在队列中
THOST_FTDC_OST_NoTradeQueueing = '3';
///未成交不在队列中
THOST_FTDC_OST_NoTradeNotQueueing = '4';
///撤单
THOST_FTDC_OST_Canceled = '5';
///未知
THOST_FTDC_OST_Unknown = 'a';
///尚未触发
THOST_FTDC_OST_NotTouched = 'b';
///已触发
THOST_FTDC_OST_Touched = 'c';
/////////////////////////////////////////////////////////////////////////
///TFtdcTimeConditionType是一个有效期类型类型
/////////////////////////////////////////////////////////////////////////
///立即完成,否则撤销
THOST_FTDC_TC_IOC = '1';
///本节有效
THOST_FTDC_TC_GFS = '2';
///当日有效
THOST_FTDC_TC_GFD = '3';
///指定日期前有效
THOST_FTDC_TC_GTD = '4';
///撤销前有效
THOST_FTDC_TC_GTC = '5';
///集合竞价有效
THOST_FTDC_TC_GFA = '6';
/////////////////////////////////////////////////////////////////////////
///TFtdcOrderPriceTypeType是一个报单价格条件类型
/////////////////////////////////////////////////////////////////////////
///任意价
THOST_FTDC_OPT_AnyPrice = '1';
///限价
THOST_FTDC_OPT_LimitPrice = '2';
///最优价
THOST_FTDC_OPT_BestPrice = '3';
///最新价
THOST_FTDC_OPT_LastPrice = '4';
///最新价浮动上浮1个ticks
THOST_FTDC_OPT_LastPricePlusOneTicks = '5';
///最新价浮动上浮2个ticks
THOST_FTDC_OPT_LastPricePlusTwoTicks = '6';
///最新价浮动上浮3个ticks
THOST_FTDC_OPT_LastPricePlusThreeTicks = '7';
///卖一价
THOST_FTDC_OPT_AskPrice1 = '8';
///卖一价浮动上浮1个ticks
THOST_FTDC_OPT_AskPrice1PlusOneTicks = '9';
///卖一价浮动上浮2个ticks
THOST_FTDC_OPT_AskPrice1PlusTwoTicks = 'A';
///卖一价浮动上浮3个ticks
THOST_FTDC_OPT_AskPrice1PlusThreeTicks = 'B';
///买一价
THOST_FTDC_OPT_BidPrice1 = 'C';
///买一价浮动上浮1个ticks
THOST_FTDC_OPT_BidPrice1PlusOneTicks = 'D';
///买一价浮动上浮2个ticks
THOST_FTDC_OPT_BidPrice1PlusTwoTicks = 'E';
///买一价浮动上浮3个ticks
THOST_FTDC_OPT_BidPrice1PlusThreeTicks = 'F';
///五档价
THOST_FTDC_OPT_FiveLevelPrice = 'G';
/////////////////////////////////////////////////////////////////////////
///TFtdcContingentConditionType是一个触发条件类型
/////////////////////////////////////////////////////////////////////////
///立即
THOST_FTDC_CC_Immediately = '1';
///止损
THOST_FTDC_CC_Touch = '2';
///止赢
THOST_FTDC_CC_TouchProfit = '3';
///预埋单
THOST_FTDC_CC_ParkedOrder = '4';
///最新价大于条件价
THOST_FTDC_CC_LastPriceGreaterThanStopPrice = '5';
///最新价大于等于条件价
THOST_FTDC_CC_LastPriceGreaterEqualStopPrice = '6';
///最新价小于条件价
THOST_FTDC_CC_LastPriceLesserThanStopPrice = '7';
///最新价小于等于条件价
THOST_FTDC_CC_LastPriceLesserEqualStopPrice = '8';
///卖一价大于条件价
THOST_FTDC_CC_AskPriceGreaterThanStopPrice = '9';
///卖一价大于等于条件价
THOST_FTDC_CC_AskPriceGreaterEqualStopPrice = 'A';
///卖一价小于条件价
THOST_FTDC_CC_AskPriceLesserThanStopPrice = 'B';
///卖一价小于等于条件价
THOST_FTDC_CC_AskPriceLesserEqualStopPrice = 'C';
///买一价大于条件价
THOST_FTDC_CC_BidPriceGreaterThanStopPrice = 'D';
///买一价大于等于条件价
THOST_FTDC_CC_BidPriceGreaterEqualStopPrice = 'E';
///买一价小于条件价
THOST_FTDC_CC_BidPriceLesserThanStopPrice = 'F';
///买一价小于等于条件价
THOST_FTDC_CC_BidPriceLesserEqualStopPrice = 'H';
/////////////////////////////////////////////////////////////////////////
///TFtdcVolumeConditionType是一个成交量类型类型
/////////////////////////////////////////////////////////////////////////
///任何数量
THOST_FTDC_VC_AV = '1';
///最小数量
THOST_FTDC_VC_MV = '2';
///全部数量
THOST_FTDC_VC_CV = '3';
/////////////////////////////////////////////////////////////////////////
///TFtdcForceCloseReasonType是一个强平原因类型
/////////////////////////////////////////////////////////////////////////
///非强平
THOST_FTDC_FCC_NotForceClose = '0';
///资金不足
THOST_FTDC_FCC_LackDeposit = '1';
///客户超仓
THOST_FTDC_FCC_ClientOverPositionLimit = '2';
///会员超仓
THOST_FTDC_FCC_MemberOverPositionLimit = '3';
///持仓非整数倍
THOST_FTDC_FCC_NotMultiple = '4';
///违规
THOST_FTDC_FCC_Violation = '5';
///其它
THOST_FTDC_FCC_Other = '6';
///自然人临近交割
THOST_FTDC_FCC_PersonDeliv = '7';
implementation
end.
|
unit UBigNum;
interface
uses
UOpenSSLdef, URawBytes;
type
TBigNum = Class
private
FBN : PBIGNUM;
procedure SetHexaValue(const Value: AnsiString);
function GetHexaValue: AnsiString;
procedure SetValue(const Value: Int64);
function GetValue: Int64;
function GetDecimalValue: AnsiString;
procedure SetDecimalValue(const Value: AnsiString);
function GetRawValue: TRawBytes;
procedure SetRawValue(const Value: TRawBytes);
public
Constructor Create; overload;
Constructor Create(initialValue : Int64); overload;
Constructor Create(hexaValue : AnsiString); overload;
Destructor Destroy; override;
Function Copy : TBigNum;
Function Add(BN : TBigNum) : TBigNum; overload;
Function Add(int : Int64) : TBigNum; overload;
Function Sub(BN : TBigNum) : TBigNum; overload;
Function Sub(int : Int64) : TBigNum; overload;
Function Multiply(BN : TBigNum) : TBigNum; overload;
Function Multiply(int : Int64) : TBigNum; overload;
Function LShift(nbits : Integer) : TBigNum;
Function RShift(nbits : Integer) : TBigNum;
Function CompareTo(BN : TBigNum) : Integer;
Function Divide(BN : TBigNum) : TBigNum; overload;
Function Divide(int : Int64) : TBigNum; overload;
Procedure Divide(dividend, remainder : TBigNum); overload;
Function ToInt64(var int : Int64) : TBigNum;
Function ToDecimal : AnsiString;
Property HexaValue : AnsiString read GetHexaValue write SetHexaValue;
Property RawValue : TRawBytes read GetRawValue write SetRawValue;
Property DecimalValue : AnsiString read GetDecimalValue write SetDecimalValue;
Property Value : Int64 read GetValue write SetValue;
Function IsZero : Boolean;
Class Function HexaToDecimal(hexa : AnsiString) : AnsiString;
Class Function TargetToHashRate(EncodedTarget : Cardinal) : TBigNum;
End;
implementation
uses
UOpenSSL, SysUtils, UCrypto, UCryptoException;
{ TBigNum }
function TBigNum.Add(BN: TBigNum): TBigNum;
begin
BN_add(FBN,BN.FBN,FBN);
Result := Self;
end;
function TBigNum.Add(int: Int64): TBigNum;
Var bn : TBigNum;
begin
bn := TBigNum.Create(int);
Result := Add(bn);
bn.Free;
end;
function TBigNum.CompareTo(BN: TBigNum): Integer;
begin
Result := BN_cmp(FBN,BN.FBN);
end;
function TBigNum.Copy: TBigNum;
begin
Result := TBigNum.Create(0);
BN_copy(Result.FBN,FBN);
end;
constructor TBigNum.Create;
begin
Create(0);
end;
constructor TBigNum.Create(hexaValue: AnsiString);
begin
Create(0);
SetHexaValue(hexaValue);
end;
constructor TBigNum.Create(initialValue : Int64);
begin
FBN := BN_new;
SetValue(initialValue);
end;
destructor TBigNum.Destroy;
begin
BN_free(FBN);
inherited;
end;
procedure TBigNum.Divide(dividend, remainder: TBigNum);
Var ctx : PBN_CTX;
begin
ctx := BN_CTX_new;
BN_div(FBN,remainder.FBN,FBN,dividend.FBN,ctx);
BN_CTX_free(ctx);
end;
function TBigNum.Divide(int: Int64): TBigNum;
Var bn : TBigNum;
begin
bn := TBigNum.Create(int);
Result := Divide(bn);
bn.Free;
end;
function TBigNum.Divide(BN: TBigNum): TBigNum;
Var _div,_rem : PBIGNUM;
ctx : PBN_CTX;
begin
_div := BN_new;
_rem := BN_new;
ctx := BN_CTX_new;
BN_div(FBN,_rem,FBN,BN.FBN,ctx);
BN_free(_div);
BN_free(_rem);
BN_CTX_free(ctx);
Result := Self;
end;
function TBigNum.GetDecimalValue: AnsiString;
var p : PAnsiChar;
begin
p := BN_bn2dec(FBN);
Result := strpas(p);
OpenSSL_free(p);
end;
function TBigNum.GetHexaValue: AnsiString;
Var p : PAnsiChar;
begin
p := BN_bn2hex(FBN);
Result := strpas( p );
OPENSSL_free(p);
end;
function TBigNum.GetRawValue: TRawBytes;
Var p : PAnsiChar;
i : Integer;
begin
i := BN_num_bytes(FBN);
SetLength(Result,i);
p := @Result[1];
i := BN_bn2bin(FBN,p);
end;
function TBigNum.GetValue: Int64;
Var p : PAnsiChar;
a : AnsiString;
err : Integer;
begin
p := BN_bn2dec(FBN);
a := strpas(p);
OPENSSL_free(p);
val(a,Result,err);
end;
class function TBigNum.HexaToDecimal(hexa: AnsiString): AnsiString;
Var bn : TBigNum;
begin
bn := TBigNum.Create(hexa);
result := bn.ToDecimal;
bn.Free;
end;
function TBigNum.IsZero: Boolean;
Var dv : AnsiString;
begin
dv := DecimalValue;
Result := dv='0';
end;
function TBigNum.LShift(nbits: Integer): TBigNum;
begin
if BN_lshift(FBN,FBN,nbits)<>1 then raise ECryptoException.Create('Error on LShift');
Result := Self;
end;
function TBigNum.Multiply(int: Int64): TBigNum;
Var n : TBigNum;
ctx : PBN_CTX;
begin
n := TBigNum.Create(int);
Try
ctx := BN_CTX_new;
if BN_mul(FBN,FBN,n.FBN,ctx)<>1 then raise ECryptoException.Create('Error on multiply');
Result := Self;
Finally
BN_CTX_free(ctx);
n.Free;
End;
end;
function TBigNum.RShift(nbits: Integer): TBigNum;
begin
if BN_rshift(FBN,FBN,nbits)<>1 then raise ECryptoException.Create('Error on LShift');
Result := Self;
end;
function TBigNum.Multiply(BN: TBigNum): TBigNum;
Var ctx : PBN_CTX;
begin
ctx := BN_CTX_new;
if BN_mul(FBN,FBN,BN.FBN,ctx)<>1 then raise ECryptoException.Create('Error on multiply');
Result := Self;
BN_CTX_free(ctx);
Result := Self;
end;
procedure TBigNum.SetDecimalValue(const Value: AnsiString);
Var i : Integer;
begin
if BN_dec2bn(@FBN,PAnsiChar(Value))=0 then raise ECryptoException.Create('Error on dec2bn');
end;
procedure TBigNum.SetHexaValue(const Value: AnsiString);
Var i : Integer;
begin
i := BN_hex2bn(@FBN,PAnsiChar(Value));
if i=0 then begin
Raise ECryptoException.Create('Invalid Hexadecimal value:'+Value);
end;
end;
procedure TBigNum.SetRawValue(const Value: TRawBytes);
var p : PBIGNUM;
begin
p := BN_bin2bn(PAnsiChar(Value),length(Value),FBN);
if (p<>FBN) Or (p=Nil) then Raise ECryptoException.Create('Error decoding Raw value to BigNum "'+TCrypto.ToHexaString(Value)+'" ('+inttostr(length(value))+')'+#10+
ERR_error_string(ERR_get_error(),nil));
end;
procedure TBigNum.SetValue(const Value: Int64);
var a : UInt64;
begin
if Value<0 then a := (Value * (-1))
else a := Value;
if BN_set_word(FBN,a)<>1 then raise ECryptoException.Create('Error on set Value');
if Value<0 then BN_set_negative(FBN,1)
else BN_set_negative(FBN,0);
end;
function TBigNum.Sub(BN: TBigNum): TBigNum;
begin
BN_sub(FBN,FBN,BN.FBN);
Result := Self;
end;
function TBigNum.Sub(int: Int64): TBigNum;
Var bn : TBigNum;
begin
bn := TBigNum.Create(int);
Result := Sub(bn);
bn.Free;
end;
class function TBigNum.TargetToHashRate(EncodedTarget: Cardinal): TBigNum;
Var bn1,bn2 : TBigNum;
part_A, part_B : Cardinal;
ctx : PBN_CTX;
begin
{ Target is 2 parts: First byte (A) is "0" bits on the left. Bytes 1,2,3 (B) are number after first "1" bit
Example: Target 23FEBFCE
Part_A: 23 -> 35 decimal
Part_B: FEBFCE
Target to Hash rate Formula:
Result = 2^Part_A + ( (2^(Part_A-24)) * Part_B )
}
Result := TBigNum.Create(2);
part_A := EncodedTarget shr 24;
bn1 := TBigNum.Create(part_A);
ctx := BN_CTX_new;
try
if BN_exp(Result.FBN,Result.FBN,bn1.FBN,ctx)<>1 then raise Exception.Create('Error 20161017-3');
finally
BN_CTX_free(ctx);
bn1.Free;
end;
//
if part_A<=24 then part_A:=24;
//
part_B := (EncodedTarget shl 8) shr 8;
bn2 := TBigNum.Create(2);
Try
bn1 := TBigNum.Create(part_A - 24);
ctx := BN_CTX_new;
try
If BN_exp(bn2.FBN,bn2.FBN,bn1.FBN,ctx)<>1 then raise Exception.Create('Error 20161017-4');
finally
BN_CTX_free(ctx);
bn1.Free;
end;
bn2.Multiply(part_B);
Result.Add(bn2);
Finally
bn2.Free;
End;
end;
function TBigNum.ToDecimal: AnsiString;
var p : PAnsiChar;
begin
p := BN_bn2dec(FBN);
Result := strpas(p);
OpenSSL_free(p);
end;
function TBigNum.ToInt64(var int: Int64): TBigNum;
Var s : AnsiString;
err : Integer;
p : PAnsiChar;
begin
p := BN_bn2dec(FBN);
s := strpas( p );
OPENSSL_free(p);
val(s,int,err);
if err<>0 then int := 0;
Result := Self;
end;
end.
|
PROGRAM Main (INPUT,OUTPUT);
BEGIN
WRITELN('MAIN');
END. |
unit m3SimpleDB;
{ Библиотека "M3" }
{ Автор: Люлин А.В. © }
{ Модуль: m3SimpleDB - }
{ Начат: 16.03.2009 16:11 }
{ $Id: m3SimpleDB.pas,v 1.3 2013/04/12 16:25:08 lulin Exp $ }
// $Log: m3SimpleDB.pas,v $
// Revision 1.3 2013/04/12 16:25:08 lulin
// - отлаживаем под XE3.
//
// Revision 1.2 2009/03/16 13:28:27 lulin
// - [$139434552].
//
{$Include m3Define.inc}
interface
uses
l3Interfaces,
m3StorageInterfaces,
m3DBInterfaces,
m3DB
;
type
Tm3SimpleDB = class(Tm3CustomDB)
private
// internal fields
f_Storage : Im3IndexedStorage;
f_StorageMode : Tm3StoreAccess;
protected
// interface methods
// Im3DB
function Purge: Integer;
override;
{* - удаляет файлы, помеченные как удаленные. }
function Update(aNotEmpty: Boolean = true): Boolean;
override;
{* - переливает файлы из переменной части в постоянную. }
procedure Start(aOpenMode : Tm3StoreAccess);
override;
{* - начинает процесс с базой. }
procedure Finish;
override;
{* - заканчивает процесс с базой. }
function GetDocument(anID: Integer): Im3DBDocument;
override;
{* - возвращает документ по номеру. }
//Im3DBInternal
//Вызываются из Tm3DBDocument, Tm3DBDocumentPart, Tm3BaseRange
function OpenStream(aDocID : Integer;
aPartSelector : Tm3DocPartSelector = m3_defDocPart;
aIndex: Integer = 0;
aMode : Tm3StoreAccess = m3_saRead;
aLevel: Integer = Cm3LastVersion): IStream;
override;
{* - . }
function OpenDocumentStream(aDocID : Integer;
out aPart : Im3DBDocumentPart;
aPartSelector : Tm3DocPartSelector = m3_defDocPart;
aIndex: Integer = 0;
aMode : Tm3StoreAccess = m3_saRead;
aLevel: Integer = Cm3LastVersion): IStream;
override;
{* - открывает поток документа. Возвращает версию документа из которой поток (aPart) и IStream}
function OpenList(const aName: AnsiString;
aStatStgMode: Integer = m3_saReadWrite;
aUseCompression : Boolean = True) : IStream;
override;
{-}
protected
// internal methods
{* - начинает процесс с базой. }
function Storage(aMode: Tm3StoreAccess = m3_saRead): Im3IndexedStorage;
{-}
procedure CloseBase;
override;
{* - закрывает открытые файлы. }
end;//Tm3SimpleDB
implementation
uses
SysUtils,
l3Types,
l3String,
l3Base,
l3Filer,
m3BackupTools,
m3StorageTools
;
// start class Tm3SimpleDB
procedure Tm3SimpleDB.CloseBase;
//virtual;
{* - закрывает открытые файлы. }
begin
f_StorageMode := 0;
f_Storage := nil;
l3Free(f_DeletedFiles);
end;
procedure Tm3SimpleDB.Finish;
{* - заканчивает процесс с базой. }
begin
if (f_Starts = 1) then
begin
CloseBase;
f_Elapsed := Now - f_Elapsed;
end;//f_Starts = 1
Dec(f_Starts);
end;
function Tm3SimpleDB.GetDocument(anID: Integer): Im3DBDocument;
{* - возвращает документ по номеру. }
begin
Result := Tm3DBDocument.Make(Self, anID);
end;
function Tm3SimpleDB.Storage(aMode: Tm3StoreAccess = m3_saRead): Im3IndexedStorage;
{-}
begin
if (f_Storage = nil) OR
((f_StorageMode <> m3_saReadWrite) AND (aMode = m3_saReadWrite)) then
begin
f_Storage := nil;
f_Storage := m3GetMainStorage(BaseName, aMode);
f_StorageMode := aMode;
end;//f_MainStorage = nil..
Result := f_Storage;
end;
function Tm3SimpleDB.OpenDocumentStream(aDocID : Integer; out aPart : Im3DBDocumentPart;
aPartSelector : Tm3DocPartSelector = m3_defDocPart;
aIndex: Integer = 0;
aMode : Tm3StoreAccess = m3_saRead;
aLevel: Integer = Cm3LastVersion): IStream;
{* - возвращает версию документа по номеру. }
var
l_Doc : Im3DBDocument;
//l_Part : Im3DBDocumentPart;
l_Stream : IStream;
begin
Result := nil;
if (aDocID <> 0) then
try
l_Doc := GetDocument(aDocID);
try
aPart := Tm3DBDocumentPart.Make(Self, l_Doc, aLevel);
l_Stream := aPart.Open(aMode, aPartSelector);
finally
l_Doc := nil;
end;//try..finally
Result := l_Stream;
finally
l_Stream := nil;
end;//try..finally
end;
function Tm3SimpleDB.OpenStream(aDocID : Integer;
aPartSelector : Tm3DocPartSelector = m3_defDocPart;
aIndex: Integer = 0;
aMode : Tm3StoreAccess = m3_saRead;
aLevel: Integer = Cm3LastVersion): IStream;
procedure l_TuneFiler(aFiler: Tl3CustomFiler);
begin//l_TuneFiler
TuneFiler(aFiler);
if (aMode <> m3_saRead) then
aFiler.Mode := l3_fmWrite;
end;//l_TuneFiler
var
l_Filer : Tl3CustomFiler;
l_DocStorage : Im3IndexedStorage;
l_Summ : Tm3BaseSummary;
l_Change : Boolean;
l_Version : Integer;
begin//OpenInNew
l_Filer := Tl3CustomFiler.Create;
try
l_Filer.Handle := aDocID;
l_TuneFiler(l_Filer);
Start(aMode);
try
// if (aLevel = Cm3ConstVersion) {f_IsConst} then ; // получить самую раннюю версию
l_DocStorage := Storage(aMode);
try
{$DEFINE MULTI_VERSION_STORAGE}
{$IFNDEF MULTI_VERSION_STORAGE}
l_Filer.COMStream := m3GetMain(l_DocStorage, aDocID, aPartSelector, aMode);
if (aMode <> m3_saRead) then
m3AddDocToBaseSummary(l_DocStorage, aDocID);
{$ELSE}
if (aMode = m3_saRead) then
{ TODO -oЖучков Антон : Доработать - объекты }
l_Filer.COMStream := m3GetVersionForRead(l_DocStorage, aDocID, False, aPartSelector, 0, aLevel)
else
begin
//ModifyDeleted(aDocID, false);
ModifyModified(aDocID, true);
{ TODO -oЖучков Антон : Доработать - объекты }
l_Filer.COMStream := m3GetVersionForWrite(l_DocStorage, aDocID, aPartSelector, 0, @l_Version);
if l_Version = 0 then
m3AddDocToBaseSummary(l_DocStorage, aDocID);
end;
{$ENDIF}
finally
l_DocStorage := nil;
end;//try..finally
Supports(l_Filer, IStream, Result);
finally
Finish;
end;//try..finally
finally
l3Free(l_Filer);
end;//try..finally
end;
function Tm3SimpleDB.Purge: Integer;
{* - удаляет файлы, помеченные как удаленные. }
var
l_Base : Im3IndexedStorage;
l_Index : Integer;
begin
Result := 0;
Start(m3_saReadWrite);
try
l_Base := Storage(m3_saReadWrite);
try
with DeletedFiles do
begin
if Assigned(f_FilesMeter) then
f_FilesMeter(piStart, Hi, 'Удаление файлов');
try
for l_Index := Lo to Hi do
begin
if Assigned(f_FilesMeter) then
f_FilesMeter(piCurrent, l_Index, '');
if l3IOk(l_Base.DeleteStore(Items[l_Index])) then
Inc(Result);
end;//for l_Index
finally
if Assigned(f_FilesMeter) then
f_FilesMeter(piEnd, 0, '');
end;//try..finally
end;//with DeletedFiles
finally
l_Base := nil;
end;//try..finally
finally
Finish;
end;//try..finally
end;
procedure Tm3SimpleDB.Start(aOpenMode : Tm3StoreAccess);
{* - начинает процесс с базой. }
begin
Inc(f_Starts);
if (f_Starts = 1) then
begin
if (aOpenMode <> m3_saRead) then
Storage(aOpenMode);
f_Stopped := false;
f_Elapsed := Now;
end;//f_Starts = 1
end;
function Tm3SimpleDB.Update(aNotEmpty: Boolean = true): Boolean;
{* - переливает файлы из переменной части в постоянную. }
begin
Result := false;
end;
function Tm3SimpleDB.OpenList(const aName: AnsiString;
aStatStgMode: Integer = m3_saReadWrite;
aUseCompression : Boolean = True) : IStream;
begin
Result := m3COMOpenStream(Storage(aStatStgMode),
l3PCharLen(aName),
aStatStgMode,
aUseCompression);
end;
end.
|
unit ddCustomIniStorage;
{* Базовый класс.
Ini-файлом НЕ владеет. Надо убивать его снаружи. }
// Модуль: "w:\common\components\rtl\Garant\dd\ddCustomIniStorage.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TddCustomIniStorage" MUID: (57A07B6903C1)
interface
uses
l3IntfUses
, l3ProtoObject
, ddConfigStorages
, IniFiles
, l3Interfaces
;
type
TddCustomIniStorage = class(Tl3ProtoObject, IddConfigStorage)
{* Базовый класс.
Ini-файлом НЕ владеет. Надо убивать его снаружи. }
private
f_Section: AnsiString;
f_Ini: TCustomIniFile;
protected
function ReadBool(const Alias: AnsiString;
Default: Boolean): Boolean;
function ReadDateTime(const Alias: AnsiString;
Default: TDateTime): TDateTime;
function ReadInteger(const Alias: AnsiString;
Default: Integer): Integer;
function ReadString(const Alias: AnsiString;
const Default: AnsiString): Il3CString;
procedure WriteBool(const Alias: AnsiString;
B: Boolean);
procedure WriteDateTime(const Alias: AnsiString;
DT: TDateTime);
procedure WriteInteger(const Alias: AnsiString;
I: Integer);
procedure WriteString(const Alias: AnsiString;
const S: AnsiString);
function Get_Section: AnsiString;
procedure Set_Section(const aValue: AnsiString);
public
constructor Create(aIniFile: TCustomIniFile); reintroduce;
protected
property Ini: TCustomIniFile
read f_Ini;
end;//TddCustomIniStorage
implementation
uses
l3ImplUses
, l3Base
//#UC START# *57A07B6903C1impl_uses*
//#UC END# *57A07B6903C1impl_uses*
;
constructor TddCustomIniStorage.Create(aIniFile: TCustomIniFile);
//#UC START# *57A07CAA01B1_57A07B6903C1_var*
//#UC END# *57A07CAA01B1_57A07B6903C1_var*
begin
//#UC START# *57A07CAA01B1_57A07B6903C1_impl*
inherited Create;
f_Ini := aIniFile;
//#UC END# *57A07CAA01B1_57A07B6903C1_impl*
end;//TddCustomIniStorage.Create
function TddCustomIniStorage.ReadBool(const Alias: AnsiString;
Default: Boolean): Boolean;
//#UC START# *51D51983016F_57A07B6903C1_var*
//#UC END# *51D51983016F_57A07B6903C1_var*
begin
//#UC START# *51D51983016F_57A07B6903C1_impl*
Result:= f_Ini.ReadBool(f_Section, Alias, Default);
//#UC END# *51D51983016F_57A07B6903C1_impl*
end;//TddCustomIniStorage.ReadBool
function TddCustomIniStorage.ReadDateTime(const Alias: AnsiString;
Default: TDateTime): TDateTime;
//#UC START# *51D519A40189_57A07B6903C1_var*
//#UC END# *51D519A40189_57A07B6903C1_var*
begin
//#UC START# *51D519A40189_57A07B6903C1_impl*
Result:= f_Ini.ReadDateTime(f_Section, Alias, Default);
//#UC END# *51D519A40189_57A07B6903C1_impl*
end;//TddCustomIniStorage.ReadDateTime
function TddCustomIniStorage.ReadInteger(const Alias: AnsiString;
Default: Integer): Integer;
//#UC START# *51D519B403D0_57A07B6903C1_var*
//#UC END# *51D519B403D0_57A07B6903C1_var*
begin
//#UC START# *51D519B403D0_57A07B6903C1_impl*
Result:= f_Ini.ReadInteger(f_Section, Alias, Default);
//#UC END# *51D519B403D0_57A07B6903C1_impl*
end;//TddCustomIniStorage.ReadInteger
function TddCustomIniStorage.ReadString(const Alias: AnsiString;
const Default: AnsiString): Il3CString;
//#UC START# *51D519D00291_57A07B6903C1_var*
//#UC END# *51D519D00291_57A07B6903C1_var*
begin
//#UC START# *51D519D00291_57A07B6903C1_impl*
Result:= l3CStr(f_Ini.ReadString(f_Section, Alias, Default));
//#UC END# *51D519D00291_57A07B6903C1_impl*
end;//TddCustomIniStorage.ReadString
procedure TddCustomIniStorage.WriteBool(const Alias: AnsiString;
B: Boolean);
//#UC START# *51D519FC00D5_57A07B6903C1_var*
//#UC END# *51D519FC00D5_57A07B6903C1_var*
begin
//#UC START# *51D519FC00D5_57A07B6903C1_impl*
f_Ini.WriteBool(f_Section, Alias, B);
//#UC END# *51D519FC00D5_57A07B6903C1_impl*
end;//TddCustomIniStorage.WriteBool
procedure TddCustomIniStorage.WriteDateTime(const Alias: AnsiString;
DT: TDateTime);
//#UC START# *51D51A0D0133_57A07B6903C1_var*
//#UC END# *51D51A0D0133_57A07B6903C1_var*
begin
//#UC START# *51D51A0D0133_57A07B6903C1_impl*
f_Ini.WriteDateTime(f_Section, Alias, DT);
//#UC END# *51D51A0D0133_57A07B6903C1_impl*
end;//TddCustomIniStorage.WriteDateTime
procedure TddCustomIniStorage.WriteInteger(const Alias: AnsiString;
I: Integer);
//#UC START# *51D51A1E025E_57A07B6903C1_var*
//#UC END# *51D51A1E025E_57A07B6903C1_var*
begin
//#UC START# *51D51A1E025E_57A07B6903C1_impl*
f_Ini.WriteInteger(f_Section, Alias, I);
//#UC END# *51D51A1E025E_57A07B6903C1_impl*
end;//TddCustomIniStorage.WriteInteger
procedure TddCustomIniStorage.WriteString(const Alias: AnsiString;
const S: AnsiString);
//#UC START# *51D51A3201BA_57A07B6903C1_var*
//#UC END# *51D51A3201BA_57A07B6903C1_var*
begin
//#UC START# *51D51A3201BA_57A07B6903C1_impl*
f_Ini.WriteString(f_Section, Alias, S);
//#UC END# *51D51A3201BA_57A07B6903C1_impl*
end;//TddCustomIniStorage.WriteString
function TddCustomIniStorage.Get_Section: AnsiString;
//#UC START# *51D51A48025D_57A07B6903C1get_var*
//#UC END# *51D51A48025D_57A07B6903C1get_var*
begin
//#UC START# *51D51A48025D_57A07B6903C1get_impl*
Result:= f_Section;
//#UC END# *51D51A48025D_57A07B6903C1get_impl*
end;//TddCustomIniStorage.Get_Section
procedure TddCustomIniStorage.Set_Section(const aValue: AnsiString);
//#UC START# *51D51A48025D_57A07B6903C1set_var*
//#UC END# *51D51A48025D_57A07B6903C1set_var*
begin
//#UC START# *51D51A48025D_57A07B6903C1set_impl*
if f_Section <> aValue then
f_Section:= aValue;
//#UC END# *51D51A48025D_57A07B6903C1set_impl*
end;//TddCustomIniStorage.Set_Section
end.
|
unit u_main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Gestures, Data.DB, MemDS, DBAccess,
FMX.Layouts, FMX.Memo, FMX.Objects, FMX.StdCtrls, FMX.Edit, LiteAccess,
Data.Bind.EngExt, Fmx.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs,
Fmx.Bind.Editors, Data.Bind.Components, Data.Bind.DBScope, LiteCall;
type
TMainForm = class(TForm)
Expander: TExpander;
lbDatabase: TLabel;
lbPassword: TLabel;
edDatabase: TEdit;
edPassword: TEdit;
btnConnect: TButton;
pMain: TPanel;
lbFishName: TLabel;
iPicture: TImage;
pInfo: TPanel;
Label1: TLabel;
lbSpeciesName: TLabel;
Label2: TLabel;
lbCategory: TLabel;
meDescription: TMemo;
GestureManager: TGestureManager;
LiteConnection: TLiteConnection;
LiteQuery: TLiteQuery;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
LinkPropertyToFieldText: TLinkPropertyToField;
LinkControlToField1: TLinkControlToField;
LinkPropertyToFieldBitmap: TLinkPropertyToField;
LinkPropertyToFieldText2: TLinkPropertyToField;
LinkPropertyToFieldText3: TLinkPropertyToField;
cbDirect: TCheckBox;
procedure btnConnectClick(Sender: TObject);
procedure pMainGesture(Sender: TObject; const EventInfo: TGestureEventInfo;
var Handled: Boolean);
private
public
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
procedure TMainForm.pMainGesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
if LiteQuery.Active then
if (EventInfo.GestureID = sgiLeft) and not LiteQuery.Eof then begin
LiteQuery.Next;
end
else
if (EventInfo.GestureID = sgiRight) and not LiteQuery.Bof then begin
LiteQuery.Prior;
end;
end;
procedure TMainForm.btnConnectClick(Sender: TObject);
begin
if LiteConnection.Connected then begin
LiteConnection.Disconnect;
btnConnect.Text := 'Connect';
end
else begin
LiteConnection.Database :={$IF Defined(IOS) or Defined(ANDROID)}GetHomePath + PathDelim{$IFNDEF ANDROID} + 'Documents'{$ENDIF} + PathDelim + {$ENDIF}edDatabase.Text;
LiteConnection.EncryptionKey := edPassword.Text;
LiteConnection.Options.Direct := cbDirect.IsChecked;
LiteConnection.Connect;
LiteQuery.Open;
Expander.IsExpanded := False;
btnConnect.Text := 'Disconnect';
end;
end;
end.
|
program TESTTRAP ( OUTPUT ) ;
type XRECORD = record
RC : INTEGER ;
MESSAGE : CHAR ( 80 ) ;
end ;
var X : XRECORD ;
begin (* HAUPTPROGRAMM *)
WRITELN ( 'test trap 5 with record parameter' ) ;
TRAP ( 5 , X ) ;
WRITELN ( 'after trap' ) ;
end (* HAUPTPROGRAMM *) .
|
var
m:int64;
a,b,g,t:longint;
function gcd(a,b:longint):longint;
begin
if a mod b=0 then
gcd:=b
else gcd:=gcd(b,a mod b);
end;
begin
readln(a,b);
inc(b,a);
if a=0 then g:=b
else g:=gcd(b,a);
a:=a div g;
b:=b div g;
t:=0;m:=1;
while b>m do
begin
inc(t);
m:=m shl 1;
end;
if m<>b then
writeln(-1)
else writeln(t);
end. |
{ Subroutine SST_DTYPE_CONVERTABLE (DTYPE_IN,DTYPE_RES)
*
* Check whether the data type DTYPE_IN can be unambigously converted to
* the data type DTYPE_RES. It is illegal to build opcodes that imply a
* conversion that can not be done unambigously. It is up to each back end
* how to handle any such conversions.
*
* Unambigous conversion here means that the VALUE is preserved, not the
* bit pattern.
}
module sst_DTYPE_CONVERTABLE;
define sst_dtype_convertable;
%include 'sst2.ins.pas';
function sst_dtype_convertable ( {check if data type convertable to another}
in dtype_in: sst_dtype_t; {data type to be converted}
in dtype_res: sst_dtype_t) {target data type to convert to}
:boolean; {TRUE unambigous conversion possible}
var
dt_in_p: sst_dtype_p_t; {pointer to base IN dtype descriptor}
dt_res_p: sst_dtype_p_t; {pointer to base RES dtype descriptor}
stat: sys_err_t;
label
retry, no_match;
{
********************************************************************************
*
* Local subroutine DTYPE_RESOLVE (DIN,DOUT_P)
*
* Resolve the base data type descriptor. All COPY and SUBRANGES will be
* resolved.
}
procedure dtype_resolve (
in din: sst_dtype_t; {data type to resolve base of}
out dout_p: sst_dtype_p_t); {will point to base data type descriptor}
label
loop;
begin
dout_p := addr(din); {init resolved data type to input data type}
loop: {back here to resolve next data type layer}
case dout_p^.dtype of
sst_dtype_range_k: begin {SUBRANGE}
dout_p := dout_p^.range_dtype_p;
goto loop;
end;
sst_dtype_copy_k: begin {COPY}
dout_p := dout_p^.copy_dtype_p;
goto loop;
end;
end;
end;
{
********************************************************************************
*
* Start execution
}
begin
sst_dtype_convertable := true; {init to conversion IS possible}
if addr(dtype_in) = addr(dtype_res) then return; {do trivial accept test}
dtype_resolve (dtype_in, dt_in_p); {resolve base IN data types}
dtype_resolve (dtype_res, dt_res_p); {resolve base RES data types}
retry: {back here to try again with new data types}
if dt_in_p = dt_res_p then return; {identical base data type descriptors ?}
{
* The base data type descriptors are not the same. This means the data types
* are different. However, some data types can be converted to others, and
* some require special handling to determine if they are the same. Only
* these data types will be checked below. Anything that is not explicitly
* decided is convertable will be assumed unconvertable.
}
case dt_res_p^.dtype of {what type is base RES descriptor ?}
{
********************************
*
* Base result data type is INTEGER or BOOLEAN.
}
sst_dtype_int_k,
sst_dtype_bool_k: begin
if dt_in_p^.dtype = dt_res_p^.dtype then return;
end;
{
********************************
*
* Base result data type is FLOATING POINT
}
sst_dtype_float_k: begin {FLOATING POINT}
case dt_in_p^.dtype of {what is base IN data type ?}
sst_dtype_int_k,
sst_dtype_float_k: return;
end;
end;
{
********************************
*
* Base result data type is CHARACTER
}
sst_dtype_char_k: begin {CHARACTER}
case dt_in_p^.dtype of
sst_dtype_char_k: return;
sst_dtype_array_k: begin
if not dt_in_p^.ar_string then goto no_match; {array is not a string}
if dt_in_p^.ar_ind_n = 1 then return; {string is exactly one character long ?}
end;
end;
end;
{
********************************
*
* Base result data type is ARRAY.
}
sst_dtype_array_k: begin {ARRAY}
if not dt_res_p^.ar_string then goto no_match; {not a STRING ?}
case dt_in_p^.dtype of
sst_dtype_char_k: return;
sst_dtype_array_k: begin
if dt_in_p^.ar_string then return;
end;
end;
end;
{
********************************
*
* Base result data type is SET
}
sst_dtype_set_k: begin {SET}
if dt_in_p^.dtype <> sst_dtype_set_k {IN data type not also a SET ?}
then goto no_match;
if dt_in_p^.set_n_ent = 0 {input set is NULL set ?}
then return;
if dt_in_p^.set_dtype_p = dt_res_p^.set_dtype_p {sets of exactly the same dtype ?}
then return;
if dt_in_p^.set_dtype_final and dt_res_p^.set_dtype_final {both ele dtypes firm ?}
then goto no_match;
dtype_resolve (dt_in_p^.set_dtype_p^, dt_in_p); {resolve base element data types}
dtype_resolve (dt_res_p^.set_dtype_p^, dt_res_p);
if dt_in_p = dt_res_p {elements have identical data types ?}
then return;
if dt_in_p^.dtype <> dt_res_p^.dtype {element data type IDs don't match ?}
then goto no_match;
if dt_in_p^.dtype = sst_dtype_enum_k {both ele ENUMERATED, but different types ?}
then goto no_match;
return; {element data types DO match}
end;
{
********************************
*
* Base result data type is PROCEDURE
}
sst_dtype_proc_k: begin {PROCEDURE}
if dt_in_p^.dtype <> sst_dtype_proc_k {IN data type not also a procedure ?}
then goto no_match;
sst_routines_match ( {compare the two routine templates}
dt_in_p^.proc_p^, dt_res_p^.proc_p^, stat);
if not sys_error(stat) then return;
end;
{
********************************
*
* Base result data type is POINTER
}
sst_dtype_pnt_k: begin {POINTER}
case dt_in_p^.dtype of
sst_dtype_pnt_k: begin {IN data type is also pointer}
if dt_res_p^.pnt_dtype_p = nil then return; {RES is universal pointer ?}
if dt_in_p^.pnt_dtype_p = nil then return; {IN is universal pointer ?}
dtype_resolve (dt_in_p^.pnt_dtype_p^, dt_in_p);
dtype_resolve (dt_res_p^.pnt_dtype_p^, dt_res_p);
goto retry; {back to try again with new data types}
end;
end;
end;
end; {end of result data type cases}
no_match: {jump here if can't convert data types}
sst_dtype_convertable := false; {conversion is not possible}
end;
|
unit uUnitTestHeader;
interface
{$Include RfMemoryProfilerOptions.inc}
uses
Classes;
const
AMOUNT_OF_ALLOCATIONS = 2000;
PERFOMANCE_AMOUNT_OF_ALLOCATIONS = AMOUNT_OF_ALLOCATIONS * 100;
BUFFER_TEST_SIZE = 777;
BUFFER_TEST_REALOC_SIZE = 787;
SIZE_OF_INT = SizeOf(Integer);
PARITY_BYTE = 7777777;
GAP_SIZE = SizeOf(PARITY_BYTE) + SIZE_OF_INT {$IFDEF INSTANCES_TRACKER} + SIZE_OF_INT {$ENDIF};
type
Address = integer;
PMappedRecord = ^TMappedRecord;
TMappedRecord = packed record
Parity: Integer;
SizeCounterAddr: Integer;
AllocationAddr: Integer;
end;
procedure RfInitilializeAllocDeallocArrays;
function IsSameValuesInAllocAndDeallocArray: Boolean;
procedure SetAllocationAddress(APointer: Pointer);
procedure SetDeallocationAddress(APointer: Pointer);
function ComparePointerListToAllocationAddress(AList: TList): Boolean;
implementation
type
ArrayOfAddress = array [0..AMOUNT_OF_ALLOCATIONS] of Address;
var
UAllocation_Addresses: ArrayOfAddress;
UDeallocation_Addresses: ArrayOfAddress;
UCurrentAllocationArrayPos: Integer;
UCurrentDeallocationArrayPos: Integer;
procedure RfInitilializeAllocDeallocArrays;
begin
UCurrentAllocationArrayPos := 0;
UCurrentDeallocationArrayPos := 0;
end;
function ComparePointerListToAllocationAddress(AList: TList): Boolean;
var
I: Integer;
LPointer: Pointer;
begin
for I := 0 to AList.Count -1 do
begin
LPointer := AList.Items[I];
Result := Integer((Integer(LPointer) - GAP_SIZE)) = UAllocation_Addresses[I];
if not Result then
Exit;
end;
end;
function IsSameValuesInArray(AArray1, AArray2: ArrayOfAddress): Boolean;
var
I: Integer;
begin
for I := 0 to AMOUNT_OF_ALLOCATIONS - 1 do
begin
Result := AArray1[I] = AArray2[I];
if not Result then
Exit;
end;
end;
function IsSameValuesInAllocAndDeallocArray: Boolean;
begin
Result := IsSameValuesInArray(UAllocation_Addresses, UDeallocation_Addresses);
end;
procedure SetAllocationAddress(APointer: Pointer);
begin
UAllocation_Addresses[UCurrentAllocationArrayPos] := Integer(APointer);
Inc(UCurrentAllocationArrayPos);
end;
procedure SetDeallocationAddress(APointer: Pointer);
begin
UDeallocation_Addresses[UCurrentDeallocationArrayPos] := Integer(APointer);
Inc(UCurrentDeallocationArrayPos);
end;
end.
|
unit frmInIOCPRegister;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, iocp_clients;
type
TFormInIOCPRegister = class(TForm)
btnRegister: TButton;
ledtUserCode: TLabeledEdit;
ledtAddUser: TLabeledEdit;
ledtPassword: TLabeledEdit;
ledtRole: TLabeledEdit;
btnClose: TButton;
Label1: TLabel;
Label2: TLabel;
procedure btnRegisterClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
FConnection: TInConnection;
end;
implementation
uses
iocp_base;
{$R *.dfm}
procedure TFormInIOCPRegister.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TFormInIOCPRegister.btnRegisterClick(Sender: TObject);
begin
{
服务端:
[USER_REGISTER]
// _UserName -> 字段 act_executor
// _ToUser -> 字段 user_name
INSERT INTO tbl_users
(user_code, user_name, user_password, user_level, act_executor, user_register_time) VALUES
(:user_code, :_ToUser, :user_password, :user_level, :_UserName, DATETIME('now'))
}
// TInCertifyClient.Register 的参数不够多,改用 TMessagePack
with TMessagePack.Create(FConnection) do // 内部会自动加入 UserName
begin
AsString['user_code'] := ledtUserCode.Text; // 参数值...
ToUser := ledtAddUser.Text; // = AsString['_ToUser']
AsString['user_password'] := ledtPassword.Text;
AsInteger['user_level'] := StrToInt(ledtRole.Text);
Post(atUserRegister);
end;
end;
end.
|
{*****************************************************}
{ }
{ EldoS Themes Support Library }
{ }
{ (C) 2002-2003 EldoS Corporation }
{ http://www.eldos.com/ }
{ }
{*****************************************************}
{$include elpack2.inc}
{$IFDEF ELPACK_SINGLECOMP}
{$I ElPack.inc}
{$ELSE}
{$IFDEF LINUX}
{$I ../ElPack.inc}
{$ELSE}
{$I ..\ElPack.inc}
{$ENDIF}
{$ENDIF}
unit ElThemes;
interface
{$ifdef MSWINDOWS}
uses
Windows, SysUtils;
{$ifdef ELPACK_THEME_ENGINE}
function ActivateTheme(ThemeManager: THandle; ColorScheme: PWideChar): HResult;
procedure DeactivateTheme;
function LoadTheme(const FileName: PWideChar): THandle;
function UnloadTheme(ThemeManager: THandle): HResult;
function GetThemeDisplayName(ThemeManager: THandle; DisplayName: PWideChar;
MaxNameChars: integer): HResult;
function EnumThemeColorSchemes(ThemeManager: THandle; Schemes: PWideChar;
MaxSchemesChars: integer): HResult;
function GetThemeColorSchemeDisplayName(ThemeManager: THandle;
SchemeName: PWideChar; DisplayName: PWideChar; MaxNameChars: integer): HResult;
function GetCurrentTheme: THandle;
{$endif}
{$endif} // MSWINDOWS
implementation
{$ifdef MSWINDOWS}
uses
Messages, Controls, Forms,
{$ifdef ELPACK_THEME_ENGINE}
ElThemesMain,
ElTmSchema,
ElThemeSysColorHook,
{$endif}
ElTools,
ElStrUtils,
ElUxTheme;
{$ifdef ELPACK_THEME_ENGINE}
var
CurrentSystemTheme: boolean;
DontLoadSystemTheme: boolean;
OldThemesAvailable: Boolean;
OldIsThemeActive: IsThemeActiveProc = nil;
OldEnableTheming: EnableThemingProc = nil;
OldOpenThemeData: OpenThemeDataProc = nil;
OldCloseThemeData: CloseThemeDataProc = nil;
OldDrawThemeParentBackground: DrawThemeParentBackgroundProc = nil;
OldDrawThemeBackground: DrawThemeBackgroundProc = nil;
OldDrawThemeText: DrawThemeTextProc = nil;
OldGetThemeBackgroundContentRect: GetThemeBackgroundContentRectProc = nil;
OldGetThemeBackgroundExtent: GetThemeBackgroundExtentProc = nil;
OldGetThemePartSize: GetThemePartSizeProc = nil;
OldGetThemeTextExtent: GetThemeTextExtentProc = nil;
OldGetThemeTextMetrics: GetThemeTextMetricsProc = nil;
OldGetThemeBackgroundRegion: GetThemeBackgroundRegionProc = nil;
OldHitTestThemeBackground: HitTestThemeBackgroundProc = nil;
OldDrawThemeEdge: DrawThemeEdgeProc = nil;
OldDrawThemeIcon: DrawThemeIconProc = nil;
OldIsThemePartDefined: IsThemePartDefinedProc = nil;
OldIsThemeBackgroundPartiallyTransparent: IsThemeBackgroundPartiallyTransparentProc = nil;
OldGetThemeColor: GetThemeColorProc = nil;
OldGetThemeMetric: GetThemeMetricProc = nil;
OldGetThemeString: GetThemeStringProc = nil;
OldGetThemeBool: GetThemeBoolProc = nil;
OldGetThemeInt: GetThemeIntProc = nil;
OldGetThemeEnumValue: GetThemeEnumValueProc = nil;
OldGetThemePosition: GetThemePositionProc = nil;
OldGetThemeFont: GetThemeFontProc = nil;
OldGetThemeRect: GetThemeRectProc = nil;
OldGetThemeMargins: GetThemeMarginsProc = nil;
OldGetThemeIntList: GetThemeIntListProc = nil;
OldGetThemePropertyOrigin: GetThemePropertyOriginProc = nil;
OldSetWindowTheme: SetWindowThemeProc = nil;
OldGetThemeFilename: GetThemeFilenameProc = nil;
OldGetThemeSysColor: GetThemeSysColorProc = nil;
OldGetThemeSysColorBrush: GetThemeSysColorBrushProc = nil;
OldGetThemeSysSize: GetThemeSysSizeProc = nil;
OldGetThemeSysBool: GetThemeSysBoolProc = nil;
OldGetThemeSysFont: GetThemeSysFontProc = nil;
OldGetThemeSysString: GetThemeSysStringProc = nil;
OldGetThemeSysInt: GetThemeSysIntProc = nil;
OldIsAppThemed: IsAppThemedProc = nil;
OldGetWindowTheme: GetWindowThemeProc = nil;
OldEnableThemeDialogTexture: EnableThemeDialogTextureProc = nil;
OldIsThemeDialogTextureEnabled: IsThemeDialogTextureEnabledProc = nil;
OldGetThemeAppProperties: GetThemeAppPropertiesProc = nil;
OldSetThemeAppProperties: SetThemeAppPropertiesProc = nil;
OldGetCurrentThemeName: GetCurrentThemeNameProc = nil;
OldGetThemeDocumentationProperty: GetThemeDocumentationPropertyProc = nil;
{$endif}
type
TElThemeWatcher = class
private
FHandle: THandle;
procedure WMThemeChanged(var Msg: TMessage); message WM_THEMECHANGED;
protected
procedure WndProc(var Msg: TMessage); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
end;
var
ThemeWatcher: TElThemeWatcher;
BroadcastMessageProps: TMessage;
function EnumChildWindowProc(Wnd: HWND; Param: LPARAM): BOOL; stdcall;
begin
SendMessage(Wnd, BroadcastMessageProps.Msg,
BroadcastMessageProps.WParam, BroadcastMessageProps.LParam);
EnumChildWindows(Wnd, @EnumChildWindowProc, Param);
Result := TRUE;
end;
function EnumWindowProc(Wnd: HWND; Param: LPARAM): BOOL; stdcall;
begin
SendMessage(Wnd, BroadcastMessageProps.Msg,
BroadcastMessageProps.WParam, BroadcastMessageProps.LParam);
EnumChildWindows(Wnd, @EnumChildWindowProc, Param);
Result := TRUE;
end;
procedure BroadcastMessage(Msg: cardinal; WParam: integer; LParam: integer);
var
ThreadID: DWORD;
begin
BroadcastMessageProps.Msg := Msg;
BroadcastMessageProps.WParam := WParam;
BroadcastMessageProps.LParam := LParam;
ThreadID := GetCurrentThreadId;
EnumThreadWindows(ThreadID, @EnumWindowProc, ThreadID);
end;
{function EnumTopWindowsProc(Wnd: HWND; Param: LPARAM): BOOL; stdcall;
begin
SendMessage(Wnd, BroadcastMessageProps.Msg,
BroadcastMessageProps.WParam, BroadcastMessageProps.LParam);
Result := TRUE;
end;
procedure BroadcastTopMessage(Msg: cardinal; WParam: integer; LParam: integer);
var
ThreadID: DWORD;
begin
BroadcastMessageProps.Msg := Msg;
BroadcastMessageProps.WParam := WParam;
BroadcastMessageProps.LParam := LParam;
ThreadID := GetCurrentThreadId;
EnumThreadWindows(ThreadID, @EnumTopWindowsProc, ThreadID);
end;}
{$ifdef ELPACK_THEME_ENGINE}
procedure RestoreThemeAPI_ButCloseThemeData; forward;
procedure RestoreThemeAPI_CloseThemeData; forward;
procedure HookThemeAPI;
begin
OldThemesAvailable := ThemesAvailable;
OldIsThemeActive := ElUxTheme.IsThemeActive;
ElUxTheme.IsThemeActive := ElThemesMain.IsThemeActive;
OldEnableTheming := ElUxTheme.EnableTheming;
ElUxTheme.EnableTheming := ElThemesMain.EnableTheming;
OldOpenThemeData := ElUxTheme.OpenThemeData;
ElUxTheme.OpenThemeData := ElThemesMain.OpenThemeData;
OldCloseThemeData := ElUxTheme.CloseThemeData;
ElUxTheme.CloseThemeData := ElThemesMain.CloseThemeData;
OldDrawThemeParentBackground := ElUxTheme.DrawThemeParentBackground;
ElUxTheme.DrawThemeParentBackground := ElThemesMain.DrawThemeParentBackground;
OldDrawThemeBackground := ElUxTheme.DrawThemeBackground;
ElUxTheme.DrawThemeBackground := ElThemesMain.DrawThemeBackground;
OldDrawThemeText := ElUxTheme.DrawThemeText;
ElUxTheme.DrawThemeText := ElThemesMain.DrawThemeText;
OldGetThemeBackgroundContentRect := ElUxTheme.GetThemeBackgroundContentRect;
ElUxTheme.GetThemeBackgroundContentRect := ElThemesMain.GetThemeBackgroundContentRect;
OldGetThemeBackgroundExtent := ElUxTheme.GetThemeBackgroundExtent;
ElUxTheme.GetThemeBackgroundExtent := ElThemesMain.GetThemeBackgroundExtent;
OldGetThemePartSize := ElUxTheme.GetThemePartSize;
ElUxTheme.GetThemePartSize := ElThemesMain.GetThemePartSize;
OldGetThemeTextExtent := ElUxTheme.GetThemeTextExtent;
ElUxTheme.GetThemeTextExtent := ElThemesMain.GetThemeTextExtent;
OldGetThemeTextMetrics := ElUxTheme.GetThemeTextMetrics;
ElUxTheme.GetThemeTextMetrics := ElThemesMain.GetThemeTextMetrics;
OldGetThemeBackgroundRegion := ElUxTheme.GetThemeBackgroundRegion;
ElUxTheme.GetThemeBackgroundRegion := ElThemesMain.GetThemeBackgroundRegion;
OldHitTestThemeBackground := ElUxTheme.HitTestThemeBackground;
ElUxTheme.HitTestThemeBackground := ElThemesMain.HitTestThemeBackground;
OldDrawThemeEdge := ElUxTheme.DrawThemeEdge;
ElUxTheme.DrawThemeEdge := ElThemesMain.DrawThemeEdge;
OldDrawThemeIcon := ElUxTheme.DrawThemeIcon;
ElUxTheme.DrawThemeIcon := ElThemesMain.DrawThemeIcon;
OldIsThemePartDefined := ElUxTheme.IsThemePartDefined;
ElUxTheme.IsThemePartDefined := ElThemesMain.IsThemePartDefined;
OldIsThemeBackgroundPartiallyTransparent := ElUxTheme.IsThemeBackgroundPartiallyTransparent;
ElUxTheme.IsThemeBackgroundPartiallyTransparent := IsThemeBackgroundPartiallyTransparent;
OldGetThemeColor := ElUxTheme.GetThemeColor;
ElUxTheme.GetThemeColor := ElThemesMain.GetThemeColor;
OldGetThemeMetric := ElUxTheme.GetThemeMetric;
ElUxTheme.GetThemeMetric := ElThemesMain.GetThemeMetric;
OldGetThemeString := ElUxTheme.GetThemeString;
ElUxTheme.GetThemeString := ElThemesMain.GetThemeString;
OldGetThemeBool := ElUxTheme.GetThemeBool;
ElUxTheme.GetThemeBool := ElThemesMain.GetThemeBool;
OldGetThemeInt := ElUxTheme.GetThemeInt;
ElUxTheme.GetThemeInt := ElThemesMain.GetThemeInt;
OldGetThemeEnumValue := ElUxTheme.GetThemeEnumValue;
ElUxTheme.GetThemeEnumValue := ElThemesMain.GetThemeEnumValue;
OldGetThemePosition := ElUxTheme.GetThemePosition;
ElUxTheme.GetThemePosition := ElThemesMain.GetThemePosition;
OldGetThemeFont := ElUxTheme.GetThemeFont;
ElUxTheme.GetThemeFont := ElThemesMain.GetThemeFont;
OldGetThemeRect := ElUxTheme.GetThemeRect;
ElUxTheme.GetThemeRect := ElThemesMain.GetThemeRect;
OldGetThemeMargins := ElUxTheme.GetThemeMargins;
ElUxTheme.GetThemeMargins := GetThemeMarginsProc(@ElThemesMain.GetThemeMargins);
OldGetThemeIntList := ElUxTheme.GetThemeIntList;
ElUxTheme.GetThemeIntList := GetThemeIntListProc(@ElThemesMain.GetThemeIntList);
OldGetThemePropertyOrigin := ElUxTheme.GetThemePropertyOrigin;
ElUxTheme.GetThemePropertyOrigin := GetThemePropertyOriginProc(@ElThemesMain.GetThemePropertyOrigin);
OldSetWindowTheme := ElUxTheme.SetWindowTheme;
ElUxTheme.SetWindowTheme := ElThemesMain.SetWindowTheme;
OldGetThemeFilename := ElUxTheme.GetThemeFilename;
ElUxTheme.GetThemeFilename := ElThemesMain.GetThemeFilename;
OldGetThemeSysColor := ElUxTheme.GetThemeSysColor;
ElUxTheme.GetThemeSysColor := ElThemesMain.GetThemeSysColor;
OldGetThemeSysColorBrush := ElUxTheme.GetThemeSysColorBrush;
ElUxTheme.GetThemeSysColorBrush := ElThemesMain.GetThemeSysColorBrush;
OldGetThemeSysSize := ElUxTheme.GetThemeSysSize;
ElUxTheme.GetThemeSysSize := ElThemesMain.GetThemeSysSize;
OldGetThemeSysBool := ElUxTheme.GetThemeSysBool;
ElUxTheme.GetThemeSysBool := ElThemesMain.GetThemeSysBool;
OldGetThemeSysFont := ElUxTheme.GetThemeSysFont;
ElUxTheme.GetThemeSysFont := GetThemeSysFontProc(@ElThemesMain.GetThemeSysFont);
OldGetThemeSysString := ElUxTheme.GetThemeSysString;
ElUxTheme.GetThemeSysString := ElThemesMain.GetThemeSysString;
OldGetThemeSysInt := ElUxTheme.GetThemeSysInt;
ElUxTheme.GetThemeSysInt := ElThemesMain.GetThemeSysInt;
OldIsAppThemed := ElUxTheme.IsAppThemed;
ElUxTheme.IsAppThemed := ElThemesMain.IsAppThemed;
OldGetWindowTheme := ElUxTheme.GetWindowTheme;
ElUxTheme.GetWindowTheme := ElThemesMain.GetWindowTheme;
OldEnableThemeDialogTexture := ElUxTheme.EnableThemeDialogTexture;
ElUxTheme.EnableThemeDialogTexture := ElThemesMain.EnableThemeDialogTexture;
OldIsThemeDialogTextureEnabled := ElUxTheme.IsThemeDialogTextureEnabled;
ElUxTheme.IsThemeDialogTextureEnabled := ElThemesMain.IsThemeDialogTextureEnabled;
OldGetThemeAppProperties := ElUxTheme.GetThemeAppProperties;
ElUxTheme.GetThemeAppProperties := ElThemesMain.GetThemeAppProperties;
OldSetThemeAppProperties := ElUxTheme.SetThemeAppProperties;
ElUxTheme.SetThemeAppProperties := ElThemesMain.SetThemeAppProperties;
OldGetCurrentThemeName := ElUxTheme.GetCurrentThemeName;
ElUxTheme.GetCurrentThemeName := ElThemesMain.GetCurrentThemeName;
OldGetThemeDocumentationProperty := ElUxTheme.GetThemeDocumentationProperty;
ElUxTheme.GetThemeDocumentationProperty := ElThemesMain.GetThemeDocumentationProperty;
ThemesAvailable := True;
end;
const
ColorIndexToThemeColorIndex: array [0..30] of integer = (
TMT_SCROLLBAR, TMT_BACKGROUND, TMT_ACTIVECAPTION, TMT_INACTIVECAPTION,
TMT_MENU, TMT_WINDOW, TMT_WINDOWFRAME, TMT_MENUTEXT, TMT_WINDOWTEXT,
TMT_CAPTIONTEXT, TMT_ACTIVEBORDER, TMT_INACTIVEBORDER, TMT_APPWORKSPACE,
TMT_HIGHLIGHT, TMT_HIGHLIGHTTEXT, TMT_BTNFACE, TMT_BTNSHADOW,
TMT_GRAYTEXT, TMT_BTNTEXT, TMT_INACTIVECAPTIONTEXT, TMT_BTNHIGHLIGHT,
TMT_DKSHADOW3D, TMT_LIGHT3D, TMT_INFOTEXT, TMT_INFOBK, 0,
TMT_HOTTRACKING, TMT_GRADIENTACTIVECAPTION, TMT_GRADIENTINACTIVECAPTION,
TMT_MENUHILIGHT, TMT_MENUBAR
);
function LoadThemeSysColors: Boolean;
var
Lock: THandle;
Data: PSpecialColorData;
I: integer;
begin
Data := BeginWriteSpecialColors(Lock);
try
Result := (Data<>nil);
if Result then
begin
for I := 0 to cSpecialColorArraySize do
begin
try
Data.Map[I] := ElThemesMain.GetThemeSysColor(0, ColorIndexToThemeColorIndex[I]);
except
Data.Map[I] := $FFFFFFFF;
end;
try
Data.BrushMap[I] := ElThemesMain.GetThemeSysColorBrush(0, ColorIndexToThemeColorIndex[I]);
except
Data.BrushMap[I] := 0;
end;
end;
end;
finally
EndWriteSpecialColors(Lock);
end;
end;
function UnloadThemeSysColors: Boolean;
var
Lock: THandle;
Data: PSpecialColorData;
begin
Data := BeginWriteSpecialColors(Lock);
try
Result := (Data <> nil);
if Result then
begin
FillChar(Data.Map, SizeOf(Data.Map), $FF);
FillChar(Data.BrushMap, SizeOf(Data.BrushMap), 0);
end;
finally
EndWriteSpecialColors(Lock);
end;
end;
procedure LoadCurrentSystemTheme; forward;
procedure RestoreThemeAPI_ButCloseThemeData;
begin
if @OldIsThemeActive <> nil then
begin
ElUxTheme.IsThemeActive := OldIsThemeActive;
OldIsThemeActive := nil;
end;
if @OldEnableTheming <> nil then
begin
ElUxTheme.EnableTheming := OldEnableTheming;
OldEnableTheming := nil;
end;
if @OldOpenThemeData <> nil then
begin
ElUxTheme.OpenThemeData := OldOpenThemeData;
OldOpenThemeData := nil;
end;
if @OldDrawThemeParentBackground <> nil then
begin
ElUxTheme.DrawThemeParentBackground := OldDrawThemeParentBackground;
OldDrawThemeParentBackground := nil;
end;
if @OldDrawThemeBackground <> nil then
begin
ElUxTheme.DrawThemeBackground := OldDrawThemeBackground;
OldDrawThemeBackground := nil;
end;
if @OldDrawThemeText <> nil then
begin
ElUxTheme.DrawThemeText := OldDrawThemeText;
OldDrawThemeText := nil;
end;
if @OldGetThemeBackgroundContentRect <> nil then
begin
ElUxTheme.GetThemeBackgroundContentRect := OldGetThemeBackgroundContentRect;
OldGetThemeBackgroundContentRect := nil;
end;
if @OldGetThemeBackgroundExtent <> nil then
begin
ElUxTheme.GetThemeBackgroundExtent := OldGetThemeBackgroundExtent;
OldGetThemeBackgroundExtent := nil;
end;
if @OldGetThemePartSize <> nil then
begin
ElUxTheme.GetThemePartSize := OldGetThemePartSize;
OldGetThemePartSize := nil;
end;
if @OldGetThemeTextExtent <> nil then
begin
ElUxTheme.GetThemeTextExtent := OldGetThemeTextExtent;
OldGetThemeTextExtent := nil;
end;
if @OldGetThemeTextMetrics <> nil then
begin
ElUxTheme.GetThemeTextMetrics := OldGetThemeTextMetrics;
OldGetThemeTextMetrics := nil;
end;
if @OldGetThemeBackgroundRegion <> nil then
begin
ElUxTheme.GetThemeBackgroundRegion := OldGetThemeBackgroundRegion;
OldGetThemeBackgroundRegion := nil;
end;
if @OldHitTestThemeBackground <> nil then
begin
ElUxTheme.HitTestThemeBackground := OldHitTestThemeBackground;
OldHitTestThemeBackground := nil;
end;
if @OldDrawThemeEdge <> nil then
begin
ElUxTheme.DrawThemeEdge := OldDrawThemeEdge;
OldDrawThemeEdge := nil;
end;
if @OldDrawThemeIcon <> nil then
begin
ElUxTheme.DrawThemeIcon := OldDrawThemeIcon;
OldDrawThemeIcon := nil;
end;
if @OldIsThemePartDefined <> nil then
begin
ElUxTheme.IsThemePartDefined := OldIsThemePartDefined;
OldIsThemePartDefined := nil;
end;
if @OldIsThemeBackgroundPartiallyTransparent <> nil then
begin
ElUxTheme.IsThemeBackgroundPartiallyTransparent := OldIsThemeBackgroundPartiallyTransparent;
OldIsThemeBackgroundPartiallyTransparent := nil;
end;
if @OldGetThemeColor <> nil then
begin
ElUxTheme.GetThemeColor := OldGetThemeColor;
OldGetThemeColor := nil;
end;
if @OldGetThemeMetric <> nil then
begin
ElUxTheme.GetThemeMetric := OldGetThemeMetric;
OldGetThemeMetric := nil;
end;
if @OldGetThemeString <> nil then
begin
ElUxTheme.GetThemeString := OldGetThemeString;
OldGetThemeString := nil;
end;
if @OldGetThemeBool <> nil then
begin
ElUxTheme.GetThemeBool := OldGetThemeBool;
OldGetThemeBool := nil;
end;
if @OldGetThemeInt <> nil then
begin
ElUxTheme.GetThemeInt := OldGetThemeInt;
OldGetThemeInt := nil;
end;
if @OldGetThemeEnumValue <> nil then
begin
ElUxTheme.GetThemeEnumValue := OldGetThemeEnumValue;
OldGetThemeEnumValue := nil;
end;
if @OldGetThemePosition <> nil then
begin
ElUxTheme.GetThemePosition := OldGetThemePosition;
OldGetThemePosition := nil;
end;
if @OldGetThemeFont <> nil then
begin
ElUxTheme.GetThemeFont := OldGetThemeFont;
OldGetThemeFont := nil;
end;
if @OldGetThemeRect <> nil then
begin
ElUxTheme.GetThemeRect := OldGetThemeRect;
OldGetThemeRect := nil;
end;
if @OldGetThemeMargins <> nil then
begin
ElUxTheme.GetThemeMargins := OldGetThemeMargins;
OldGetThemeMargins := nil;
end;
if @OldGetThemeIntList <> nil then
begin
ElUxTheme.GetThemeIntList := OldGetThemeIntList;
OldGetThemeIntList := nil;
end;
if @OldGetThemePropertyOrigin <> nil then
begin
ElUxTheme.GetThemePropertyOrigin := OldGetThemePropertyOrigin;
OldGetThemePropertyOrigin := nil;
end;
if @OldSetWindowTheme <> nil then
begin
ElUxTheme.SetWindowTheme := OldSetWindowTheme;
OldSetWindowTheme := nil;
end;
if @OldGetThemeFilename <> nil then
begin
ElUxTheme.GetThemeFilename := OldGetThemeFilename;
OldGetThemeFilename := nil;
end;
if @OldGetThemeSysColor <> nil then
begin
ElUxTheme.GetThemeSysColor := OldGetThemeSysColor;
OldGetThemeSysColor := nil;
end;
if @OldGetThemeSysColorBrush <> nil then
begin
ElUxTheme.GetThemeSysColorBrush := OldGetThemeSysColorBrush;
OldGetThemeSysColorBrush := nil;
end;
if @OldGetThemeSysSize <> nil then
begin
ElUxTheme.GetThemeSysSize := OldGetThemeSysSize;
OldGetThemeSysSize := nil;
end;
if @OldGetThemeSysBool <> nil then
begin
ElUxTheme.GetThemeSysBool := OldGetThemeSysBool;
OldGetThemeSysBool := nil;
end;
if @OldGetThemeSysFont <> nil then
begin
ElUxTheme.GetThemeSysFont := OldGetThemeSysFont;
OldGetThemeSysFont := nil;
end;
if @OldGetThemeSysString <> nil then
begin
ElUxTheme.GetThemeSysString := OldGetThemeSysString;
OldGetThemeSysString := nil;
end;
if @OldGetThemeSysInt <> nil then
begin
ElUxTheme.GetThemeSysInt := OldGetThemeSysInt;
OldGetThemeSysInt := nil;
end;
if @OldIsAppThemed <> nil then
begin
ElUxTheme.IsAppThemed := OldIsAppThemed;
OldIsAppThemed := nil;
end;
if @OldGetWindowTheme <> nil then
begin
ElUxTheme.GetWindowTheme := OldGetWindowTheme;
OldGetWindowTheme := nil;
end;
if @OldEnableThemeDialogTexture <> nil then
begin
ElUxTheme.EnableThemeDialogTexture := OldEnableThemeDialogTexture;
OldEnableThemeDialogTexture := nil;
end;
if @OldIsThemeDialogTextureEnabled <> nil then
begin
ElUxTheme.IsThemeDialogTextureEnabled := OldIsThemeDialogTextureEnabled;
OldIsThemeDialogTextureEnabled := nil;
end;
if @OldGetThemeAppProperties <> nil then
begin
ElUxTheme.GetThemeAppProperties := OldGetThemeAppProperties;
OldGetThemeAppProperties := nil;
end;
if @OldSetThemeAppProperties <> nil then
begin
ElUxTheme.SetThemeAppProperties := OldSetThemeAppProperties;
OldSetThemeAppProperties := nil;
end;
if @OldGetCurrentThemeName <> nil then
begin
ElUxTheme.GetCurrentThemeName := OldGetCurrentThemeName;
OldGetCurrentThemeName := nil;
end;
if @OldGetThemeDocumentationProperty <> nil then
begin
ElUxTheme.GetThemeDocumentationProperty := OldGetThemeDocumentationProperty;
OldGetThemeDocumentationProperty := nil;
end;
end;
procedure RestoreThemeAPI_CloseThemeData;
begin
if @OldCloseThemeData <> nil then
begin
ElUxTheme.CloseThemeData := OldCloseThemeData;
OldCloseThemeData := nil;
end;
ThemesAvailable := OldThemesAvailable;
end;
function ActivateTheme(ThemeManager: THandle; ColorScheme: PWideChar): HResult;
var
Current: THandle;
begin
if ThemeManager = 0 then
begin
Result := E_FAIL;
exit;
end;
Current := GetCurrentTheme;
if (Current <> 0) then
begin
UnloadThemeSysColors;
end;
Result := ElThemesMain.ActivateTheme(ThemeManager, ColorScheme);
if Succeeded(Result) then
begin
LoadThemeSysColors;
if Current = 0 then
HookThemeAPI;
BroadcastMessage(EL_THEMECHANGED, 0, 0);
BroadcastMessage(WM_SYSCOLORCHANGE, 0, 0);
BroadcastMessage(WM_NCPAINT, NULLREGION, 0);
BroadcastMessage(CM_COLORCHANGED, 0, 0);
CurrentSystemTheme := False;
end;
end;
procedure DeactivateTheme;
begin
UnloadThemeSysColors;
RestoreThemeAPI_ButCloseThemeData;
ElThemesMain.DeactivateTheme;
BroadcastMessage(EL_THEMECHANGED, 0, 0);
BroadcastMessage(WM_SYSCOLORCHANGE, 0, 0);
BroadcastMessage(WM_NCPAINT, NULLREGION, 0);
BroadcastMessage(CM_COLORCHANGED, 0, 0);
RestoreThemeAPI_CloseThemeData;
if IsWinXPUp and not DontLoadSystemTheme then
LoadCurrentSystemTheme;
end;
function LoadTheme(const FileName: PWideChar): THandle;
begin
Result := ElThemesMain.LoadTheme(FileName);
end;
function UnloadTheme(ThemeManager: THandle): HResult;
begin
try
if ThemeManager <> 0 then
begin
if ThemeManager = GetCurrentTheme then
DeactivateTheme;
Result := ElThemesMain.UnloadTheme(ThemeManager);
end
else
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeDisplayName(ThemeManager: THandle; DisplayName: PWideChar;
MaxNameChars: integer): HResult;
begin
Result := ElThemesMain.GetThemeDisplayName(ThemeManager, DisplayName,
MaxNameChars);
end;
function EnumThemeColorSchemes(ThemeManager: THandle; Schemes: PWideChar;
MaxSchemesChars: integer): HResult;
begin
Result := ElThemesMain.EnumThemeColorSchemes(ThemeManager, Schemes, MaxSchemesChars);
end;
function GetThemeColorSchemeDisplayName(ThemeManager: THandle;
SchemeName: PWideChar; DisplayName: PWideChar; MaxNameChars: integer): HResult;
begin
Result := ElThemesMain.GetThemeColorSchemeDisplayName(ThemeManager,
SchemeName, DisplayName, MaxNameChars);
end;
function GetCurrentTheme: THandle;
begin
Result := GetGlobalCurrentTheme; //ElThemesMain.GetCurrentTheme;
end;
procedure LoadCurrentSystemTheme;
var
FileName, ColorScheme: WideString;
Manager: THandle;
begin
if not CurrentSystemTheme and ElUxTheme.IsThemeActive then
begin
SetLength(FileName, 1024);
SetLength(ColorScheme, 100);
if Succeeded(ElUxTheme.GetCurrentThemeName(PWideChar(FileName), 1024,
PWideChar(ColorScheme), 100, nil, 0)) then
begin
SetLength(FileName, WideStrLen(PWideChar(FileName)));
SetLength(ColorScheme, WideStrLen(PWideChar(ColorScheme)));
Manager := LoadTheme(PWideChar(FileName));
if Manager <> 0 then
begin
ActivateTheme(Manager, PWideChar(ColorScheme));
CurrentSystemTheme := True;
end;
end;
end;
end;
procedure UnloadCurrentSystemTheme;
var
Manager: THandle;
begin
if CurrentSystemTheme and (GetCurrentTheme <> 0) then
begin
Manager := GetCurrentTheme;
DontLoadSystemTheme := True;
DeactivateTheme;
UnloadTheme(Manager);
end;
end;
{$endif}
{ TElThemeWatcher }
constructor TElThemeWatcher.Create;
begin
inherited;
{$warnings off}
FHandle := AllocateHWnd(WndProc);
{$warnings on}
end;
destructor TElThemeWatcher.Destroy;
begin
{$warnings off}
DeallocateHWnd(FHandle);
{$warnings on}
inherited;
end;
procedure TElThemeWatcher.WMThemeChanged(var Msg: TMessage);
begin
{$ifdef ELPACK_THEME_ENGINE}
if CurrentSystemTheme then
begin
UnloadCurrentSystemTheme;
LoadCurrentSystemTheme;
end;
{$endif}
BroadcastMessage(EL_THEMECHANGED, 0, 0);
{$ifdef ELPACK_THEME_ENGINE}
BroadcastMessage(WM_SYSCOLORCHANGE, 0, 0);
BroadcastMessage(WM_NCPAINT, NULLREGION, 0);
BroadcastMessage(CM_COLORCHANGED, 0, 0);
{$endif}
end;
procedure TElThemeWatcher.WndProc(var Msg: TMessage);
begin
if Msg.Msg = WM_ThemeChanged then
WMThemeChanged(Msg)
else
if Msg.Msg = WM_QUERYENDSESSION then
Msg.Result := 1
else
DefWindowProc(Self.FHandle, Msg.Msg, Msg.wParam, Msg.lParam);
end;
{$endif} // MSWINDOWS
initialization
{$ifdef MSWINDOWS}
try
InitializeUxTheme;
ThemeWatcher := TElThemeWatcher.Create;
{$ifdef ELPACK_THEME_ENGINE}
CurrentSystemTheme := False;
DontLoadSystemTheme := False;
if IsWinXPUp then
LoadCurrentSystemTheme;
{$endif}
except
on e:exception do
begin
OutputDebugString( PChar('ERROR (ElThemes.pas): '+e.Message) );
raise;
end;
end;
{$endif}
finalization
{$ifdef MSWINDOWS}
{$ifdef ELPACK_THEME_ENGINE}
if IsWinXPUp then
UnloadCurrentSystemTheme;
{$endif}
ThemeWatcher.Free;
FinalizeUxTheme;
{$endif}
end.
|
// ---------------------------------
// Truncated and converted GRADD.H
// ---------------------------------
unit GRADD;
interface
uses os2def;
{&cdecl+}
{
Prototype declarations for low level driver function call table.
}
type
CID = ULONG;
{ Chain ID }
GID = ULONG;
{ Gradd ID }
const
GID_DONTCARE = $ffffffff;
type FNHWCMD=function(_p1:pointer; _p2:pointer):ulong;
type FNHWENTRY=function(_p1:GID; _p2:ULONG; _p3:pointer; _p4:pointer):ulong;
type FNSDBITBLT=function(_p1:pointer; _p2:pointer):ulong;
type FNSDLINE=function(_p1:pointer; _p2:pointer):ulong;
type PFNHWENTRY = ^FNHWENTRY;
PFNHWCMD = ^FNHWCMD;
PFNSDBITBLT = ^FNSDBITBLT;
PFNSDLINE = ^FNSDLINE;
{ gddmodeinfo }
{ used to make SETMODE request }
{ no of colors (bpp) }
{ horizontal pels }
{ vertical scan lines }
{ in Hz (0 if not available) }
{ physical address of VRAM }
{ Current bank size }
{ size (in bytes) of one scan line }
{ Pel format (defines above }
{ Total size of VRAM in bytes }
{ Total number of colors }
type
GDDMODEINFO = record
ulLength : ULONG;
ulModeId : ULONG;
ulBpp : ULONG;
ulHorizResolution : ULONG;
ulVertResolution : ULONG;
ulRefreshRate : ULONG;
pbVRAMPhys : ^BYTE;
ulApertureSize : ULONG;
ulScanLineSize : ULONG;
fccColorEncoding : ULONG;
ulTotalVRAMSize : ULONG;
cColors : ULONG;
end;
_GDDMODEINFO = GDDMODEINFO;
PGDDMODEINFO = ^GDDMODEINFO;
{
Structure for HWEntry router, see gdddata.c for array.
}
{ hwcmd }
{ return code if pfnHWCmd is NULL }
{ ring change otherwise }
HWCMD = record
pfnHWCmd : PFNHWCMD;
ulRc : ULONG;
end;
_HWCMD = HWCMD;
PHWCMD = ^HWCMD;
{
Ring change codes
}
const
DONTCARE = 0;
RING2 = 2;
{
Graphics Hardware Interface (GHI) commands for
the Base Function class.
}
const
BASE_FUNCTION_CLASS = 'Base Function';
GHI_CMD_INIT = 0;
GHI_CMD_INITPROC = 1;
GHI_CMD_TERM = 2;
GHI_CMD_TERMPROC = 3;
GHI_CMD_QUERYCAPS = 4;
GHI_CMD_QUERYMODES = 5;
GHI_CMD_SETMODE = 6;
GHI_CMD_PALETTE = 7;
GHI_CMD_BITBLT = 8;
GHI_CMD_LINE = 9;
GHI_CMD_MOVEPTR = 10;
GHI_CMD_SETPTR = 11;
GHI_CMD_SHOWPTR = 12;
GHI_CMD_VRAM = 13;
GHI_CMD_REQUESTHW = 14;
GHI_CMD_EVENT = 15;
GHI_CMD_EXTENSION = 16;
GHI_CMD_BANK = 17;
GHI_CMD_TEXT = 18;
GHI_CMD_USERCAPS = 19;
GHI_CMD_POLYGON = 20;
GHI_CMD_MAX = 21;
{
Defines and structures for the GHI_CMD_INIT DDI
}
{ gddinitin }
type
GDDINITIN = record
ulLength : ULONG;
pfnChainedHWEntry : PFNHWENTRY;
end;
_GDDINITIN = GDDINITIN;
PGDDINITIN = ^GDDINITIN;
{ gddinitout }
GDDINITOUT = record
ulLength : ULONG;
cFunctionClasses : ULONG;
end;
_GDDINITOUT = GDDINITOUT;
PGDDINITOUT = ^GDDINITOUT;
{
Defines and structures for the GHI_CMD_INITPROC DDI
}
{ initprocout }
INITPROCOUT = record
ulLength : ULONG;
ulVRAMVirt : ULONG;
end;
_INITPROCOUT = INITPROCOUT;
PINITPROCOUT = ^INITPROCOUT;
{
Defines and structures for the GHI_CMD_QUERYCAPS DDI
}
{ capsinfo }
{ sizeof CAPSINFO structure }
{ Name describing function set }
{ Function class specific flags }
CAPSINFO = record
ulLength : ULONG;
pszFunctionClassID : pchar;
ulFCFlags : ULONG;
end;
_CAPSINFO = CAPSINFO;
PCAPSINFO = ^CAPSINFO;
{
Defines for ulFCFlags field of the CAPSINFO data structure
NOTE: The flags below are GRADD Caps for the base function class.
}
{ GRADD wants to see M2M blits }
const
GC_SEND_MEM_TO_MEM = $00000001;
{ GRADD wants to simulate 3way rops as sequence of 2way rops. }
GC_SIM_SRC_PAT_ROPS = $00000002;
{RESERVED - NOT USED NOW }
{ GRADD supports alpha blending rules and }
GC_ALPHA_SUPPORT = $00000004;
{ ALPHABITBLTINFO. }
{ If this flag is not returned, }
{ VMAN will never call the Gradd for }
{ Alpha Blending. }
{ SHOULD match DS2_* in pmddi.h }
{ GRADD handles stretchblts }
GC_SRC_STRETCH = $00000008;
{ GRADD can handle polygon(concave or convex) }
GC_POLYGON_SIZE_ANY = $00000010;
{ of any size. }
{ GC_POLYGON_FILL must be set }
{ GRADD can handle single clip rect of }
GC_CLIP = $00000020;
{ polygons for pfnPolygon and }
{ source bitmap for pfnBitblt with }
{ GC_SRC_STRETCH set. }
{ see GC_CLP_COMPLEX }
{ GRADD can handle clipping }
GC_CLIP_COMPLEX = $00000040;
{ with more than one clip rect }
{ GC_CLIP must be set. }
{ following defines GC_ SHOULD match DS_ in pmddi.h }
{ Downloadable Fonts }
GC_TEXTBLT_DOWNLOADABLE = $00002000;
{ CLIPPABLE Fonts }
GC_TEXTBLT_CLIPABLE = $00004000;
{ Device has Hardware Fonts }
GC_TEXTBLT_DS_DEVICE_FONTS = $00008000;
{ Device handles LINEINFO2. }
GC_SIMPLE_LINES = $00800000;
{ For compatibility with old source code retain old definitions }
TEXTBLT_DOWNLOADABLE = GC_TEXTBLT_DOWNLOADABLE;
TEXTBLT_CLIPABLE = GC_TEXTBLT_CLIPABLE;
TEXTBLT_DS_DEVICE_FONTS = GC_TEXTBLT_DS_DEVICE_FONTS;
{$ifndef DS_SIMPLE_LINES}
const
DS_SIMPLE_LINES = GC_SIMPLE_LINES;
{$endif}
{RESERVED - NOT USED NOW }
{ send Device independent bitmaps }
const
GC_SRC_CONVERT = $02000000;
{ without converting to device internal format. }
{ Gradd will convert during blts or }
{ call softdraw to simulate. }
{ If not set, GRE will convert DIB in a temporary buffer. }
{ Gradd should set this based on performance. }
{ GRADD can handle polygon(triangle and quad) }
GC_POLYGON_FILL = $08000000;
{ fills and POLYGONINFO. see GC_POLYGON_SIZE_ANY }
{ if set, Graphics Engine call pfnPolygon }
{ for fills instead of pfnBitBlt. }
{
Defines and structures for the GHI_CMD_QUERYMODES and GHI_CMD_SETMODE
}
QUERYMODE_NUM_MODES = $0001;
QUERYMODE_MODE_DATA = $0002;
QUERYMODE_VALID = QUERYMODE_NUM_MODES or QUERYMODE_MODE_DATA;
{
Defines and structures for the GHI_CMD_VRAM
}
{ vramin }
type
VRAMIN = record
ulLength : ULONG;
ulFunction : ULONG;
pIn : Pointer;
end;
_VRAMIN = VRAMIN;
PVRAMIN = ^VRAMIN;
{
Defines for the ulFunction field of the VRAMIN data structure.
}
const
VRAM_ALLOCATE = 1;
VRAM_DEALLOCATE = 2;
VRAM_QUERY = 3;
VRAM_REGISTER = 4;
VRAM_DEREGISTER = 5;
{ vramregisterin }
{ sizeof(VRAMREGISTERIN) }
{ de-registering handle }
{ Input flags }
type
VRAMREGISTERIN = record
ulLength : ULONG;
ulHandle : ULONG;
ulFlags : ULONG;
end;
_VRAMREGISTERIN = VRAMREGISTERIN;
PVRAMREGISTERIN = ^VRAMREGISTERIN;
{
Defines for the ulFlags field of the VRAMREGISTERIN data structure.
}
{ If this bit is set we have }
const
VRAM_REGISTER_HANDLE = $0001;
{ a registration if it is off }
{ we have a deregistration }
{ If this flag is set the app }
VRAM_REGISTER_VRAMONLY = $1000;
{ is registering and telling }
{ us that it does not intend }
{ to use the accelerator }
{ vramregisterout }
{ Returned flags (currently none def) }
{ Returned handle }
type
VRAMREGISTEROUT = record
ulLength : ULONG;
ulFlags : ULONG;
ulHandle : ULONG;
end;
_VRAMREGISTEROUT = VRAMREGISTEROUT;
PVRAMREGISTEROUT = ^VRAMREGISTEROUT;
{ vramallocin }
{ Used for de-allocation }
VRAMALLOCIN = record
ulLength : ULONG;
ulFlags : ULONG;
ulID : ULONG;
ulFunction : ULONG;
ulHandle : ULONG;
ulSize : ULONG;
ulWidth : ULONG;
ulHeight : ULONG;
end;
_VRAMALLOCIN = VRAMALLOCIN;
PVRAMALLOCIN = ^VRAMALLOCIN;
{
Defines for the ulFlags field of the VRAMALLOCIN data structure.
}
const
VRAM_ALLOC_SHARED = $0001;
VRAM_ALLOC_RECTANGLE = $0002;
VRAM_ALLOC_WORKBUFFER = $0004;
VRAM_ALLOC_STATIC = $1000;
{
Defines for the ulFunction field of the VRAMALLOCIN data structure.
}
// VRAM_ALLOCATE = 1;
// VRAM_DEALLOCATE = 2;
// VRAM_QUERY = 3;
{ vramallocout }
type
VRAMALLOCOUT = record
ulLength : ULONG;
ulFlags : ULONG;
ulID : ULONG;
ptlStart : POINTL;
ulSize : ULONG;
ulScanLineBytes : ULONG;
end;
_VRAMALLOCOUT = VRAMALLOCOUT;
PVRAMALLOCOUT = ^VRAMALLOCOUT;
{
Defines and structures for the GHI_CMD_EVENT command
}
{ hweventin }
{ Event type }
{ Pointer to event specific data }
HWEVENTIN = record
ulLength : ULONG;
ulEvent : ULONG;
pEventData : Pointer;
end;
_HWEVENTIN = HWEVENTIN;
PHWEVENTIN = ^HWEVENTIN;
{
Defines for the ulEvent field of the HWEVENTIN data structure.
}
const
EVENT_FOREGROUND = 1;
EVENT_BACKGROUND = 2;
EVENT_NEWCHAININFO = 3;
{
Defines and structures for the GHI_CMD_EXTENSION command
}
{ hwextension }
type
HWEXTENSION = record
ulLength : ULONG;
ulXSubFunction : ULONG;
cScrChangeRects : ULONG;
arectlScreen : PRECTL;
ulXFlags : ULONG;
pXP1 : Pointer;
end;
_HWEXTENSION = HWEXTENSION;
PHWEXTENSION = ^HWEXTENSION;
{
Defines for the ulXFlags field of the HWEXTENSION data structure.
}
const
X_REQUESTHW = 1;
{
GRADD.SYS defines
}
GRADDPDD_IOCTL = $10;
GRADDPDD_LOCK = 0;
GRADDPDD_UNLOCK = 1;
GRADDPDD_SETMTRR = 2;
{ Starting Physical address }
{ Range to be enabled for WC }
{ Flags as defined above. Bit 27 is }
{ interrpreted as a Enable MTRR if set }
{ and as a Disable MTRR if not set }
type
MTRRIN = record
ulPhysAddr : ULONG;
ulLength : ULONG;
ulFlags : ULONG;
end;
PMTRRIN = ^MTRRIN;
_MTRRIN = MTRRIN;
{
The following are the possible values for the flags which are returned when
calling GRADDPDD_SETMTRR these are also defined in GRADDSYS.H for use by
GRADD.SYS please make sure any updates are kept in synch.
The first(low order byte) is reserved for Processor Identification and is
interpreted as a number. The 2nd byte is reserved for future use. The
3rd byte is interpreted as a set of flags indicating what support is
available and the high order byte is interpreted as a number corresponding
to the command passed in to the SetMTRR function.
}
const
INTEL_PROCESSOR = $00000001;
AMD_PROCESSOR = $00000002;
CYRIX_PROCESSOR = $00000003;
CPUID_SUPPORT = $00010000;
MTRR_SUPPORT = $00020000;
MTRR_ENABLED = $00040000;
MTRR_AVAILABLE = $00080000;
WC_ENABLED = $00100000;
VENDOR_MASK = $000000FF;
COMMAND_MASK = $FF000000;
{
Or one of the following into the ulFlags field of MTRRIN to
enabled/disable WC
}
MTRR_DISABLE = $00000000;
MTRR_ENABLE = $01000000;
MTRR_QUERY = $02000000;
MTRR_CMD_MAX = MTRR_QUERY;
{
End of GRADD.SYS defines
}
{
Prototype declarations for Video Manager Interface (VMI)
}
type FNVMIENTRY=function(GraddID:GID; _p2:ULONG; _p3:Pointer; _p4:Pointer):ULONG;
PFNVMIENTRY=^FNVMIENTRY;
Const
{
VMI commands which map directly to GRADD commands
}
VMI_CMD_INIT = GHI_CMD_INIT;
VMI_CMD_INITPROC = GHI_CMD_INITPROC;
VMI_CMD_TERM = GHI_CMD_TERM;
VMI_CMD_TERMPROC = GHI_CMD_TERMPROC;
VMI_CMD_QUERYCAPS = GHI_CMD_QUERYCAPS;
VMI_CMD_QUERYMODES = GHI_CMD_QUERYMODES;
VMI_CMD_SETMODE = GHI_CMD_SETMODE;
VMI_CMD_PALETTE = GHI_CMD_PALETTE;
VMI_CMD_BITBLT = GHI_CMD_BITBLT;
VMI_CMD_LINE = GHI_CMD_LINE;
VMI_CMD_MOVEPTR = GHI_CMD_MOVEPTR;
VMI_CMD_SETPTR = GHI_CMD_SETPTR;
VMI_CMD_SHOWPTR = GHI_CMD_SHOWPTR;
VMI_CMD_VRAM = GHI_CMD_VRAM;
VMI_CMD_REQUESTHW = GHI_CMD_REQUESTHW;
VMI_CMD_EVENT = GHI_CMD_EVENT;
VMI_CMD_EXTENSION = GHI_CMD_EXTENSION;
VMI_CMD_BANK = GHI_CMD_BANK;
VMI_CMD_TEXT = GHI_CMD_TEXT;
VMI_CMD_USERCAPS = GHI_CMD_USERCAPS;
VMI_CMD_POLYGON = GHI_CMD_POLYGON;
{
VMI commands unique to the video manager
}
VMI_CMD_BASE = $1000;
VMI_CMD_QUERYCHAININFO = VMI_CMD_BASE + 0;
VMI_CMD_QUERYCURRENTMODE = VMI_CMD_BASE + 1;
VMI_CMD_EXCLUDEPTR = VMI_CMD_BASE + 2;
VMI_CMD_UPDATECHAININFO = VMI_CMD_BASE + 3;
VMI_CMD_MAX = VMI_CMD_BASE + 4;
{
Defines and structures for VMI_CMD_QUERYCHAININFO
}
{ graddinfo }
type
PGRADDINFO = ^GRADDINFO;
GRADDINFO = record
gid : GID;
pszGraddName : Pchar;
pGraddEntry : PFNHWENTRY;
pChainEntry : PFNHWENTRY;
cModes : ULONG;
pModeInfo : PGDDMODEINFO;
pCapsInfo : PCAPSINFO;
pNextGraddInfo : PGRADDINFO;
end;
_GRADDINFO = GRADDINFO;
{ chaininfo }
PCHAININFO = ^CHAININFO;
CHAININFO = record
cid : CID;
pszChainName : Pchar;
pChainHWEntry : PFNHWENTRY;
pGraddList : PGRADDINFO;
pNextChainInfo : PCHAININFO;
end;
_CHAININFO = CHAININFO;
{ vmiqci }
{ Head of the GRADD chain }
VMIQCI = record
ulLength : ULONG;
pciHead : PCHAININFO;
end;
_VMIQCI = VMIQCI;
PVMIQCI = ^VMIQCI;
{
Defines and structures for VMI_CMD_EXCLUDEPTR
}
{ excludeptrin }
{ sizeof(EXCLUDEPTRIN) }
{ TRUE - add, FASE - remove rects }
{ count of exclude rectangles }
{ array of exclude rectangles }
EXCLUDEPTRIN = record
ulLength : ULONG;
fAdd : BOOL;
cExcludeRects : ULONG;
apRectls : PRECTL;
end;
_EXCLUDEPTRIN = EXCLUDEPTRIN;
PEXCLUDEPTRIN = ^EXCLUDEPTRIN;
{
Video Helper services exported by VMAN
}
{ meminfo }
MEMINFO = record
ulPhysAddr : ULONG;
ulMemLen : ULONG;
ulVirtAddr : ULONG;
pNextMI : Pointer;
end;
_MEMINFO = MEMINFO;
PMEMINFO = ^MEMINFO;
{ Defines for xxxxxx }
const
TRAPEZOID_COLLINEAR = $0000;
TRAPEZOID_TRIANGLE = $0001;
TRAPEZOID_TWO_TRIANGLES = $0002;
TRAPEZOID_DIAMOND = $0004;
TRAPEZOID_MINY_HORIZONTAL = $0010;
TRAPEZOID_MAXY_HORIZONTAL = $0020;
TRAPEZOID_LEFT_SPLIT = $0040;
TRAPEZOID_RIGHT_SPLIT = $0080;
TRAPEZOID_MIDY_HORIZONTAL = $0100;
TRAPEZOID_SECOND_SPLIT_LEFT = $0200;
TRAPEZOID_SECOND_SPLIT_RIGHT = $0400;
{
Defines for the ulFlags field of the HEADER data structure.
}
SERIALIZE_REQUIRED = $1;
QUERYCAPS = 1;
QUERYCAPSLIST = 2;
SETCAP = 3;
type
USERCAPSIN = record
ulLength : ULONG;
ulFunction : ULONG;
ulSize : ULONG;
end;
_USERCAPSIN = USERCAPSIN;
PUSERCAPSIN = ^USERCAPSIN;
{ Structure for VMI_CMD_SHOWPTR }
type
HWSHOWPTRIN = record
ulLength : ULONG;
fShow : BOOL;
end;
_HWSHOWPTRIN = HWSHOWPTRIN;
PHWSHOWPTRIN = ^HWSHOWPTRIN;
implementation
end.
|
unit FFSRPTSTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TFFSRPTSRecord = record
PCNumber: String[20];
PInstallDate: String[10];
PNumberOfRuns: Integer;
PRunNumberNow: Integer;
End;
TFFSRPTSBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TFFSRPTSRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIFFSRPTS = (FFSRPTSPrimaryKey);
TFFSRPTSTable = class( TDBISAMTableAU )
private
FDFCNumber: TStringField;
FDFInstallDate: TStringField;
FDFNumberOfRuns: TIntegerField;
FDFRunNumberNow: TIntegerField;
procedure SetPCNumber(const Value: String);
function GetPCNumber:String;
procedure SetPInstallDate(const Value: String);
function GetPInstallDate:String;
procedure SetPNumberOfRuns(const Value: Integer);
function GetPNumberOfRuns:Integer;
procedure SetPRunNumberNow(const Value: Integer);
function GetPRunNumberNow:Integer;
procedure SetEnumIndex(Value: TEIFFSRPTS);
function GetEnumIndex: TEIFFSRPTS;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TFFSRPTSRecord;
procedure StoreDataBuffer(ABuffer:TFFSRPTSRecord);
property DFCNumber: TStringField read FDFCNumber;
property DFInstallDate: TStringField read FDFInstallDate;
property DFNumberOfRuns: TIntegerField read FDFNumberOfRuns;
property DFRunNumberNow: TIntegerField read FDFRunNumberNow;
property PCNumber: String read GetPCNumber write SetPCNumber;
property PInstallDate: String read GetPInstallDate write SetPInstallDate;
property PNumberOfRuns: Integer read GetPNumberOfRuns write SetPNumberOfRuns;
property PRunNumberNow: Integer read GetPRunNumberNow write SetPRunNumberNow;
published
property Active write SetActive;
property EnumIndex: TEIFFSRPTS read GetEnumIndex write SetEnumIndex;
end; { TFFSRPTSTable }
procedure Register;
implementation
procedure TFFSRPTSTable.CreateFields;
begin
FDFCNumber := CreateField( 'CNumber' ) as TStringField;
FDFInstallDate := CreateField( 'InstallDate' ) as TStringField;
FDFNumberOfRuns := CreateField( 'NumberOfRuns' ) as TIntegerField;
FDFRunNumberNow := CreateField( 'RunNumberNow' ) as TIntegerField;
end; { TFFSRPTSTable.CreateFields }
procedure TFFSRPTSTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TFFSRPTSTable.SetActive }
procedure TFFSRPTSTable.SetPCNumber(const Value: String);
begin
DFCNumber.Value := Value;
end;
function TFFSRPTSTable.GetPCNumber:String;
begin
result := DFCNumber.Value;
end;
procedure TFFSRPTSTable.SetPInstallDate(const Value: String);
begin
DFInstallDate.Value := Value;
end;
function TFFSRPTSTable.GetPInstallDate:String;
begin
result := DFInstallDate.Value;
end;
procedure TFFSRPTSTable.SetPNumberOfRuns(const Value: Integer);
begin
DFNumberOfRuns.Value := Value;
end;
function TFFSRPTSTable.GetPNumberOfRuns:Integer;
begin
result := DFNumberOfRuns.Value;
end;
procedure TFFSRPTSTable.SetPRunNumberNow(const Value: Integer);
begin
DFRunNumberNow.Value := Value;
end;
function TFFSRPTSTable.GetPRunNumberNow:Integer;
begin
result := DFRunNumberNow.Value;
end;
procedure TFFSRPTSTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('CNumber, String, 20, N');
Add('InstallDate, String, 10, N');
Add('NumberOfRuns, Integer, 0, N');
Add('RunNumberNow, Integer, 0, N');
end;
end;
procedure TFFSRPTSTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, CNumber, Y, Y, N, N');
end;
end;
procedure TFFSRPTSTable.SetEnumIndex(Value: TEIFFSRPTS);
begin
case Value of
FFSRPTSPrimaryKey : IndexName := '';
end;
end;
function TFFSRPTSTable.GetDataBuffer:TFFSRPTSRecord;
var buf: TFFSRPTSRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCNumber := DFCNumber.Value;
buf.PInstallDate := DFInstallDate.Value;
buf.PNumberOfRuns := DFNumberOfRuns.Value;
buf.PRunNumberNow := DFRunNumberNow.Value;
result := buf;
end;
procedure TFFSRPTSTable.StoreDataBuffer(ABuffer:TFFSRPTSRecord);
begin
DFCNumber.Value := ABuffer.PCNumber;
DFInstallDate.Value := ABuffer.PInstallDate;
DFNumberOfRuns.Value := ABuffer.PNumberOfRuns;
DFRunNumberNow.Value := ABuffer.PRunNumberNow;
end;
function TFFSRPTSTable.GetEnumIndex: TEIFFSRPTS;
var iname : string;
begin
result := FFSRPTSPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := FFSRPTSPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'FFS Tables', [ TFFSRPTSTable, TFFSRPTSBuffer ] );
end; { Register }
function TFFSRPTSBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..4] of string = ('CNUMBER','INSTALLDATE','NUMBEROFRUNS','RUNNUMBERNOW' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 4) and (flist[x] <> s) do inc(x);
if x <= 4 then result := x else result := 0;
end;
function TFFSRPTSBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftInteger;
4 : result := ftInteger;
end;
end;
function TFFSRPTSBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCNumber;
2 : result := @Data.PInstallDate;
3 : result := @Data.PNumberOfRuns;
4 : result := @Data.PRunNumberNow;
end;
end;
end.
|
program P6f (Input, Output);
{Program to perform a variety of computations for
geometric figures; this version illustrates overall
program control using repeat.}
{uses Crt;}
var
FigureOption,
CalculationOption : Char; {Input Variables}
{**********************************************************************}
procedure GetValidFigureOption (var FigureOption : Char);
{Procedure to display the menu and get user's choice}
const
FigureOptionPrompt = 'Enter desired option ';
VerificationPrompt = 'Are you sure you wish to quit ? (Y/N)';
var
ValidOption : Boolean; {Control Variable}
Verify : Char;
{------------------------------------------------------------------}
procedure DisplayMenu;
{Procedure to display the menu}
const
MenuLine1 = 'Main Menu';
MenuLine2 = 'Geometric Figure Code';
MenuLine3 = 'Square S';
MenuLine4 = 'Rectangle R';
MenuLine5 = 'Triangle T';
MenuLine6 = 'Quit Q';
begin {DisplayMenu}
{Clrscr;}
Writeln (MenuLine1);
Writeln;
Writeln (MenuLine2);
Writeln (MenuLine3);
Writeln (MenuLine4);
Writeln (MenuLine5);
Writeln (Menuline6);
Writeln;
end; {DisplayMenu}
{------------------------------------------------------------------}
procedure ValidateFigureOption (Option : Char;
var ValidOption : Boolean);
{Procedure to test validity of figure option entered
by user}
begin {ValidateFigureOption}
if (Option = 'R') or (Option = 'S') or
(Option = 'T') or (Option = 'Q') then
ValidOption := True
else
begin
ValidOption := False;
Writeln ('Invalid figure option : ',Option)
end {if}
end; {ValidateFigureOption}
{------------------------------------------------------------------}
begin {GetValidFigureOption}
DisplayMenu;
repeat
Write (FigureOptionPrompt);
Readln (FigureOption);
FigureOption := UpCase (FigureOption);
ValidateFigureOption(FigureOption,ValidOption);
if FigureOption = 'Q' then
begin
Write (VerificationPrompt);
Readln (Verify);
if UpCase (Verify) <> 'Y' then
ValidOption := False
end {if}
until ValidOption
end; {GetValidFigureOption}
{----------------------------------------------------------------------}
procedure GetValidComputationOption
(var ComputationOption : Char);
{Procedure to get valid computation option}
begin {GetValidComputationOption}
Writeln ('Computation options not implemented')
end; {GetValidCompuationOption}
{----------------------------------------------------------------------}
procedure SquareComputations (ComputationOption : Char);
{Procedure to perform computations for a square}
begin {SquareComputations}
Writeln ('Square computations not implemented')
end; {SquareComputations}
{----------------------------------------------------------------------}
procedure RectangleComputations (ComputationOption : Char);
{Procedure to perform computations for rectangle}
begin {RectangleComputations}
Writeln ('Rectangle computations not implemented')
end; {RectangleComputations}
{----------------------------------------------------------------------}
procedure TriangleComputations (ComputationOption : Char);
{Procedure to perform computations for Triangle}
begin {TriangleComputations}
Writeln ('Triangle computations not implemented')
end; {TriangleComputations}
{----------------------------------------------------------------------}
procedure Wait;
begin {Wait}
Writeln ('Press <Enter> to continue ');
Readln
end; {Wait}
{**********************************************************************}
begin {Main Program}
{1.0 Process user requests until FigureOption = 'Q'}
repeat
GetValidFigureOption (FigureOption);
if FigureOption <> 'Q' then
begin
GetValidComputationOption (CalculationOption);
case FigureOption of
'S' : SquareComputations (CalculationOption);
'R' : RectangleComputations (CalculationOption);
'T' : TriangleComputations (CalculationOption)
end; {case}
Wait;
end {if}
until FigureOption = 'Q'
end. {Main Program}
|
unit ItfwCompilerWordsPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\ItfwCompilerWordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "ItfwCompilerWordsPack" MUID: (559BDDE30092)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwScriptingInterfaces
;
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, tfwClassLike
, TypInfo
, tfwTypeInfo
, tfwPropertyLike
, kwValue
, BasicsPack
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *559BDDE30092impl_uses*
//#UC END# *559BDDE30092impl_uses*
;
type
TkwPopCompilerCompileInParameterPopCode = {final} class(TtfwClassLike)
{* Слово скрипта pop:Compiler:CompileInParameterPopCode }
private
procedure CompileInParameterPopCode(const aCtx: TtfwContext;
aCompiler: TtfwCompiler;
aParameterToPop: TtfwWord);
{* Реализация слова скрипта pop:Compiler:CompileInParameterPopCode }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopCompilerCompileInParameterPopCode
TkwPopCompilerGetWordCompilingNow = {final} class(TtfwClassLike)
{* Слово скрипта pop:Compiler:GetWordCompilingNow }
private
function GetWordCompilingNow(const aCtx: TtfwContext;
aCompiler: TtfwCompiler): TtfwWord;
{* Реализация слова скрипта pop:Compiler:GetWordCompilingNow }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopCompilerGetWordCompilingNow
TkwPopCompilerAddCodePart = {final} class(TtfwClassLike)
{* Слово скрипта pop:Compiler:AddCodePart }
private
procedure AddCodePart(const aCtx: TtfwContext;
aCompiler: TtfwCompiler;
aWord: TtfwWord);
{* Реализация слова скрипта pop:Compiler:AddCodePart }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopCompilerAddCodePart
TkwPopCompilerAddCodePartValue = {final} class(TtfwClassLike)
{* Слово скрипта pop:Compiler:AddCodePartValue }
private
procedure AddCodePartValue(const aCtx: TtfwContext;
aCompiler: TtfwCompiler;
const aValue: TtfwStackValue);
{* Реализация слова скрипта pop:Compiler:AddCodePartValue }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopCompilerAddCodePartValue
TkwPopCompilerAddCodePartRef = {final} class(TtfwClassLike)
{* Слово скрипта pop:Compiler:AddCodePartRef }
private
procedure AddCodePartRef(const aCtx: TtfwContext;
aCompiler: TtfwCompiler;
aWord: TtfwWord);
{* Реализация слова скрипта pop:Compiler:AddCodePartRef }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
end;//TkwPopCompilerAddCodePartRef
TkwPopCompilerKeywordFinder = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Compiler:KeywordFinder }
private
function KeywordFinder(const aCtx: TtfwContext;
aCompiler: TtfwCompiler): TtfwKeywordFinder;
{* Реализация слова скрипта pop:Compiler:KeywordFinder }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopCompilerKeywordFinder
TkwPopCompilerNewWordDefinitor = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:Compiler:NewWordDefinitor }
private
function NewWordDefinitor(const aCtx: TtfwContext;
aCompiler: TtfwCompiler): TtfwNewWordDefinitor;
{* Реализация слова скрипта pop:Compiler:NewWordDefinitor }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwPopCompilerNewWordDefinitor
procedure TkwPopCompilerCompileInParameterPopCode.CompileInParameterPopCode(const aCtx: TtfwContext;
aCompiler: TtfwCompiler;
aParameterToPop: TtfwWord);
{* Реализация слова скрипта pop:Compiler:CompileInParameterPopCode }
//#UC START# *559BDE1700B0_559BDE1700B0_4DB6E2EE0259_Word_var*
//#UC END# *559BDE1700B0_559BDE1700B0_4DB6E2EE0259_Word_var*
begin
//#UC START# *559BDE1700B0_559BDE1700B0_4DB6E2EE0259_Word_impl*
aCompiler.CompileInParameterPopCode(aCtx, aParameterToPop);
//#UC END# *559BDE1700B0_559BDE1700B0_4DB6E2EE0259_Word_impl*
end;//TkwPopCompilerCompileInParameterPopCode.CompileInParameterPopCode
class function TkwPopCompilerCompileInParameterPopCode.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Compiler:CompileInParameterPopCode';
end;//TkwPopCompilerCompileInParameterPopCode.GetWordNameForRegister
function TkwPopCompilerCompileInParameterPopCode.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopCompilerCompileInParameterPopCode.GetResultTypeInfo
function TkwPopCompilerCompileInParameterPopCode.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopCompilerCompileInParameterPopCode.GetAllParamsCount
function TkwPopCompilerCompileInParameterPopCode.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwCompiler), TypeInfo(TtfwWord)]);
end;//TkwPopCompilerCompileInParameterPopCode.ParamsTypes
procedure TkwPopCompilerCompileInParameterPopCode.DoDoIt(const aCtx: TtfwContext);
var l_aCompiler: TtfwCompiler;
var l_aParameterToPop: TtfwWord;
begin
try
l_aCompiler := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCompiler: TtfwCompiler : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aParameterToPop := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aParameterToPop: TtfwWord : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
CompileInParameterPopCode(aCtx, l_aCompiler, l_aParameterToPop);
end;//TkwPopCompilerCompileInParameterPopCode.DoDoIt
function TkwPopCompilerGetWordCompilingNow.GetWordCompilingNow(const aCtx: TtfwContext;
aCompiler: TtfwCompiler): TtfwWord;
{* Реализация слова скрипта pop:Compiler:GetWordCompilingNow }
//#UC START# *559BDF1000D6_559BDF1000D6_4DB6E2EE0259_Word_var*
//#UC END# *559BDF1000D6_559BDF1000D6_4DB6E2EE0259_Word_var*
begin
//#UC START# *559BDF1000D6_559BDF1000D6_4DB6E2EE0259_Word_impl*
Result := aCompiler;
//#UC END# *559BDF1000D6_559BDF1000D6_4DB6E2EE0259_Word_impl*
end;//TkwPopCompilerGetWordCompilingNow.GetWordCompilingNow
class function TkwPopCompilerGetWordCompilingNow.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Compiler:GetWordCompilingNow';
end;//TkwPopCompilerGetWordCompilingNow.GetWordNameForRegister
function TkwPopCompilerGetWordCompilingNow.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TtfwWord);
end;//TkwPopCompilerGetWordCompilingNow.GetResultTypeInfo
function TkwPopCompilerGetWordCompilingNow.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopCompilerGetWordCompilingNow.GetAllParamsCount
function TkwPopCompilerGetWordCompilingNow.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwCompiler)]);
end;//TkwPopCompilerGetWordCompilingNow.ParamsTypes
procedure TkwPopCompilerGetWordCompilingNow.DoDoIt(const aCtx: TtfwContext);
var l_aCompiler: TtfwCompiler;
begin
try
l_aCompiler := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCompiler: TtfwCompiler : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(GetWordCompilingNow(aCtx, l_aCompiler));
end;//TkwPopCompilerGetWordCompilingNow.DoDoIt
procedure TkwPopCompilerAddCodePart.AddCodePart(const aCtx: TtfwContext;
aCompiler: TtfwCompiler;
aWord: TtfwWord);
{* Реализация слова скрипта pop:Compiler:AddCodePart }
//#UC START# *559BDF500382_559BDF500382_4DB6E2EE0259_Word_var*
//#UC END# *559BDF500382_559BDF500382_4DB6E2EE0259_Word_var*
begin
//#UC START# *559BDF500382_559BDF500382_4DB6E2EE0259_Word_impl*
aCompiler.AddCodePart(aWord, aCtx, tfw_sniNo);
//#UC END# *559BDF500382_559BDF500382_4DB6E2EE0259_Word_impl*
end;//TkwPopCompilerAddCodePart.AddCodePart
class function TkwPopCompilerAddCodePart.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Compiler:AddCodePart';
end;//TkwPopCompilerAddCodePart.GetWordNameForRegister
function TkwPopCompilerAddCodePart.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopCompilerAddCodePart.GetResultTypeInfo
function TkwPopCompilerAddCodePart.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopCompilerAddCodePart.GetAllParamsCount
function TkwPopCompilerAddCodePart.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwCompiler), TypeInfo(TtfwWord)]);
end;//TkwPopCompilerAddCodePart.ParamsTypes
procedure TkwPopCompilerAddCodePart.DoDoIt(const aCtx: TtfwContext);
var l_aCompiler: TtfwCompiler;
var l_aWord: TtfwWord;
begin
try
l_aCompiler := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCompiler: TtfwCompiler : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
AddCodePart(aCtx, l_aCompiler, l_aWord);
end;//TkwPopCompilerAddCodePart.DoDoIt
procedure TkwPopCompilerAddCodePartValue.AddCodePartValue(const aCtx: TtfwContext;
aCompiler: TtfwCompiler;
const aValue: TtfwStackValue);
{* Реализация слова скрипта pop:Compiler:AddCodePartValue }
//#UC START# *56E13F740281_56E13F740281_4DB6E2EE0259_Word_var*
var
l_W : TtfwWord;
//#UC END# *56E13F740281_56E13F740281_4DB6E2EE0259_Word_var*
begin
//#UC START# *56E13F740281_56E13F740281_4DB6E2EE0259_Word_impl*
l_W := TkwValue.Create(aValue);
try
aCompiler.AddCodePart(l_W, aCtx, tfw_sniNo);
finally
FreeAndNil(l_W);
end;//try..finally
//#UC END# *56E13F740281_56E13F740281_4DB6E2EE0259_Word_impl*
end;//TkwPopCompilerAddCodePartValue.AddCodePartValue
class function TkwPopCompilerAddCodePartValue.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Compiler:AddCodePartValue';
end;//TkwPopCompilerAddCodePartValue.GetWordNameForRegister
function TkwPopCompilerAddCodePartValue.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopCompilerAddCodePartValue.GetResultTypeInfo
function TkwPopCompilerAddCodePartValue.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopCompilerAddCodePartValue.GetAllParamsCount
function TkwPopCompilerAddCodePartValue.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwCompiler), @tfw_tiStruct]);
end;//TkwPopCompilerAddCodePartValue.ParamsTypes
procedure TkwPopCompilerAddCodePartValue.DoDoIt(const aCtx: TtfwContext);
var l_aCompiler: TtfwCompiler;
var l_aValue: TtfwStackValue;
begin
try
l_aCompiler := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCompiler: TtfwCompiler : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aValue := aCtx.rEngine.Pop;
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aValue: TtfwStackValue : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
AddCodePartValue(aCtx, l_aCompiler, l_aValue);
end;//TkwPopCompilerAddCodePartValue.DoDoIt
procedure TkwPopCompilerAddCodePartRef.AddCodePartRef(const aCtx: TtfwContext;
aCompiler: TtfwCompiler;
aWord: TtfwWord);
{* Реализация слова скрипта pop:Compiler:AddCodePartRef }
//#UC START# *579B57270341_579B57270341_4DB6E2EE0259_Word_var*
var
l_W : TtfwWord;
//#UC END# *579B57270341_579B57270341_4DB6E2EE0259_Word_var*
begin
//#UC START# *579B57270341_579B57270341_4DB6E2EE0259_Word_impl*
l_W := TkwCompiledPushWord.Create(aWord, nil, aCtx);
try
aCompiler.AddCodePart(l_W, aCtx, tfw_sniNo);
finally
FreeAndNil(l_W);
end;//try..finally
//#UC END# *579B57270341_579B57270341_4DB6E2EE0259_Word_impl*
end;//TkwPopCompilerAddCodePartRef.AddCodePartRef
class function TkwPopCompilerAddCodePartRef.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Compiler:AddCodePartRef';
end;//TkwPopCompilerAddCodePartRef.GetWordNameForRegister
function TkwPopCompilerAddCodePartRef.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := @tfw_tiVoid;
end;//TkwPopCompilerAddCodePartRef.GetResultTypeInfo
function TkwPopCompilerAddCodePartRef.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopCompilerAddCodePartRef.GetAllParamsCount
function TkwPopCompilerAddCodePartRef.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwCompiler), TypeInfo(TtfwWord)]);
end;//TkwPopCompilerAddCodePartRef.ParamsTypes
procedure TkwPopCompilerAddCodePartRef.DoDoIt(const aCtx: TtfwContext);
var l_aCompiler: TtfwCompiler;
var l_aWord: TtfwWord;
begin
try
l_aCompiler := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCompiler: TtfwCompiler : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aWord := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aWord: TtfwWord : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
AddCodePartRef(aCtx, l_aCompiler, l_aWord);
end;//TkwPopCompilerAddCodePartRef.DoDoIt
function TkwPopCompilerKeywordFinder.KeywordFinder(const aCtx: TtfwContext;
aCompiler: TtfwCompiler): TtfwKeywordFinder;
{* Реализация слова скрипта pop:Compiler:KeywordFinder }
//#UC START# *559BDEF4039F_559BDEF4039F_4DB6E2EE0259_Word_var*
//#UC END# *559BDEF4039F_559BDEF4039F_4DB6E2EE0259_Word_var*
begin
//#UC START# *559BDEF4039F_559BDEF4039F_4DB6E2EE0259_Word_impl*
Result := aCompiler.KeywordFinder(aCtx);
//#UC END# *559BDEF4039F_559BDEF4039F_4DB6E2EE0259_Word_impl*
end;//TkwPopCompilerKeywordFinder.KeywordFinder
class function TkwPopCompilerKeywordFinder.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Compiler:KeywordFinder';
end;//TkwPopCompilerKeywordFinder.GetWordNameForRegister
function TkwPopCompilerKeywordFinder.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TtfwKeywordFinder);
end;//TkwPopCompilerKeywordFinder.GetResultTypeInfo
function TkwPopCompilerKeywordFinder.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopCompilerKeywordFinder.GetAllParamsCount
function TkwPopCompilerKeywordFinder.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwCompiler)]);
end;//TkwPopCompilerKeywordFinder.ParamsTypes
procedure TkwPopCompilerKeywordFinder.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству KeywordFinder', aCtx);
end;//TkwPopCompilerKeywordFinder.SetValuePrim
procedure TkwPopCompilerKeywordFinder.DoDoIt(const aCtx: TtfwContext);
var l_aCompiler: TtfwCompiler;
begin
try
l_aCompiler := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCompiler: TtfwCompiler : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(KeywordFinder(aCtx, l_aCompiler));
end;//TkwPopCompilerKeywordFinder.DoDoIt
function TkwPopCompilerNewWordDefinitor.NewWordDefinitor(const aCtx: TtfwContext;
aCompiler: TtfwCompiler): TtfwNewWordDefinitor;
{* Реализация слова скрипта pop:Compiler:NewWordDefinitor }
//#UC START# *55A9055200C5_55A9055200C5_4DB6E2EE0259_Word_var*
//#UC END# *55A9055200C5_55A9055200C5_4DB6E2EE0259_Word_var*
begin
//#UC START# *55A9055200C5_55A9055200C5_4DB6E2EE0259_Word_impl*
Result := aCompiler.NewWordDefinitor;
//#UC END# *55A9055200C5_55A9055200C5_4DB6E2EE0259_Word_impl*
end;//TkwPopCompilerNewWordDefinitor.NewWordDefinitor
class function TkwPopCompilerNewWordDefinitor.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:Compiler:NewWordDefinitor';
end;//TkwPopCompilerNewWordDefinitor.GetWordNameForRegister
function TkwPopCompilerNewWordDefinitor.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TtfwNewWordDefinitor);
end;//TkwPopCompilerNewWordDefinitor.GetResultTypeInfo
function TkwPopCompilerNewWordDefinitor.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopCompilerNewWordDefinitor.GetAllParamsCount
function TkwPopCompilerNewWordDefinitor.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwCompiler)]);
end;//TkwPopCompilerNewWordDefinitor.ParamsTypes
procedure TkwPopCompilerNewWordDefinitor.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству NewWordDefinitor', aCtx);
end;//TkwPopCompilerNewWordDefinitor.SetValuePrim
procedure TkwPopCompilerNewWordDefinitor.DoDoIt(const aCtx: TtfwContext);
var l_aCompiler: TtfwCompiler;
begin
try
l_aCompiler := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aCompiler: TtfwCompiler : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(NewWordDefinitor(aCtx, l_aCompiler));
end;//TkwPopCompilerNewWordDefinitor.DoDoIt
initialization
TkwPopCompilerCompileInParameterPopCode.RegisterInEngine;
{* Регистрация pop_Compiler_CompileInParameterPopCode }
TkwPopCompilerGetWordCompilingNow.RegisterInEngine;
{* Регистрация pop_Compiler_GetWordCompilingNow }
TkwPopCompilerAddCodePart.RegisterInEngine;
{* Регистрация pop_Compiler_AddCodePart }
TkwPopCompilerAddCodePartValue.RegisterInEngine;
{* Регистрация pop_Compiler_AddCodePartValue }
TkwPopCompilerAddCodePartRef.RegisterInEngine;
{* Регистрация pop_Compiler_AddCodePartRef }
TkwPopCompilerKeywordFinder.RegisterInEngine;
{* Регистрация pop_Compiler_KeywordFinder }
TkwPopCompilerNewWordDefinitor.RegisterInEngine;
{* Регистрация pop_Compiler_NewWordDefinitor }
TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwCompiler));
{* Регистрация типа TtfwCompiler }
TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwWord));
{* Регистрация типа TtfwWord }
TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwKeywordFinder));
{* Регистрация типа TtfwKeywordFinder }
TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwNewWordDefinitor));
{* Регистрация типа TtfwNewWordDefinitor }
TtfwTypeRegistrator.RegisterType(@tfw_tiStruct);
{* Регистрация типа TtfwStackValue }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
program AskName(input, output);
var
response: string;
begin
writeLn('What is your name? ');
readLn(input, response);
writeLn('hello ', response, '!')
end. |
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
// Yawara static site generator
// console unit
// create console application
// @author : Zendrael <zendrael@gmail.com>
// @date : 2013/10/20
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
unit untConsoleYawara;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, CustApp,
//the Content Management System
untSSG;
type
TYawaraConsole = class( TCustomApplication )
protected
{Config: TSetupYawara;
strCatalogFiles, strCatalogTags: TStringList; }
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
{procedure Draft( strFileName: string );
procedure Publish;
procedure Update( strFileName: string );
}
procedure Help; virtual;
{
function ProcessaTema(): WideString;
function ProcessaPost( strDetail: string; strPost: TPost; criaLink: boolean): WideString;
procedure ProcessaArquivo( strNomeArquivo: string; strCaminho: string; bolFinal: Boolean );
procedure CriaIndexes;
procedure CriaTags;
}
{
procedure setCatalog( strTipo: string ); //tags ou posts
procedure getCatalog( strTipo: string ); //tags ou posts
}
end;
implementation
procedure TYawaraConsole.DoRun;
var
ErrorMsg: String;
SSG : TSSG;
begin
(*
╔ = 201
╚ = 200
╗ = 187
╝ = 188
═ = 205
║ = 186
*)
WriteLn('╔══════════════════════════════════════════════════════════════════════════════╗');
WriteLn('║ YAWARA ║');
WriteLn('╚══════════════════════════════════════════════════════════════════════════════╝');
WriteLn(' Static Site and Blog Generator v0.7b ');
WriteLn('--------------------------------------------------------------------------------');
WriteLn('');
//WriteLn('YAWARA - Static Site Generator - v0.6b');
WriteLn('');
{
-d <filename> (draft/rascunho)
-p (publica todos os posts e gera/atualiza o index, tags, sitemap e feed)
-u (gera/atualiza o index, tags, sitemap e feed)
-h (ajuda)
}
// quick check parameters
ErrorMsg:= CheckOptions('dpu:h','draft publish update: help');
if ErrorMsg<>'' then
begin
ShowException( Exception.Create( ErrorMsg ) );
Terminate;
Exit;
end;
// lendo parâmetros
if HasOption('d','draft') then
begin
try
SSG := TSSG.Create;
SSG.Draft;//( GetOptionValue('d', 'draft') )
finally
FreeAndNil( SSG );
end;
Terminate;
Exit;
end;
if HasOption('p','publish') then
begin
try
SSG := TSSG.Create;
SSG.Publish;//( GetOptionValue('p', 'publish') )
finally
FreeAndNil( SSG );
end;
Terminate;
Exit;
end;
if HasOption('u','update') then
begin
{try
Config:= TSetupYawara.Create;
Config.getConfig;
Atualizar( GetOptionValue('u', 'update') );
finally
Config.Destroy;
end;
}
Terminate;
Exit;
end;
if HasOption('h','help') then
begin
Help;
Terminate;
Exit;
end;
//nothing called, show help
Help;
//terminate app
Terminate;
Exit;
end;
procedure TYawaraConsole.Help;
begin
WriteLn('Use as: ',ExeName,' [options]');
WriteLn('');
WriteLn('Commands:');
WriteLn(' -d [file]' + #9 + ' Create drafs for all posts or single files');
WriteLn(' -p' + #9#9 + ' Publish all posts');
WriteLn(' -u [file]' + #9 + ' Update some file or post');
WriteLn(' -h, --help' + #9 + ' Show this help message');
WriteLn('');
WriteLn('');
end;
constructor TYawaraConsole.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TYawaraConsole.Destroy;
begin
inherited Destroy;
end;
end.
|
program newton(input, output);
const
EPSILON = 1E-6;
var
number, root : real;
begin
repeat
read(number);
if number < 0 then
writeln(number:5:6, ' does not have a real square root.')
else if number = 0
then writeln(0)
else
begin
root := 1;
repeat
root := (number / root + root) / 2;
until abs(number / sqr(root) - 1) < EPSILON;
writeln(root:5:6)
end;
until number = 0;
end. |
unit Crack_TLB;
{ This file contains pascal declarations imported from a type library.
This file will be written during each import or refresh of the type
library editor. Changes to this file will be discarded during the
refresh process. }
{ Crack Library }
{ Version 1.0 }
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
const
LIBID_Crack: TGUID = '{3150CC22-6E56-11D1-AB1C-008029EC1811}';
const
{ Component class GUIDs }
Class_TestCrack: TGUID = '{3150CC24-6E56-11D1-AB1C-008029EC1811}';
type
{ Forward declarations: Interfaces }
ITestCrack = interface;
ITestCrackDisp = dispinterface;
{ Forward declarations: CoClasses }
TestCrack = ITestCrack;
{ Dispatch interface for TestCrack Object }
ITestCrack = interface(IDispatch)
['{3150CC23-6E56-11D1-AB1C-008029EC1811}']
function GetCrack: WideString; safecall;
end;
{ DispInterface declaration for Dual Interface ITestCrack }
ITestCrackDisp = dispinterface
['{3150CC23-6E56-11D1-AB1C-008029EC1811}']
function GetCrack: WideString; dispid 1;
end;
{ TestCrackObject }
CoTestCrack = class
class function Create: ITestCrack;
class function CreateRemote(const MachineName: string): ITestCrack;
end;
implementation
uses ComObj;
class function CoTestCrack.Create: ITestCrack;
begin
Result := CreateComObject(Class_TestCrack) as ITestCrack;
end;
class function CoTestCrack.CreateRemote(const MachineName: string): ITestCrack;
begin
Result := CreateRemoteComObject(MachineName, Class_TestCrack) as ITestCrack;
end;
end.
|
unit sdlwindow;
{
$Id: sdlwindow.pas,v 1.9 2006/10/22 18:55:25 savage Exp $
}
{******************************************************************************}
{ }
{ JEDI-SDL : Pascal units for SDL - Simple DirectMedia Layer }
{ SDL Window Wrapper }
{ }
{ }
{ The initial developer of this Pascal code was : }
{ Dominique Louis <Dominique@SavageSoftware.com.au> }
{ }
{ Portions created by Dominique Louis are }
{ Copyright (C) 2004 - 2100 Dominique Louis. }
{ }
{ }
{ Contributor(s) }
{ -------------- }
{ Dominique Louis <Dominique@SavageSoftware.com.au> }
{ }
{ Obtained through: }
{ Joint Endeavour of Delphi Innovators ( Project JEDI ) }
{ }
{ You may retrieve the latest version of this file at the Project }
{ JEDI home page, located at http://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.1.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. }
{ }
{ Description }
{ ----------- }
{ SDL Window Wrapper }
{ }
{ }
{ Requires }
{ -------- }
{ SDL.dll on Windows platforms }
{ libSDL-1.1.so.0 on Linux platform }
{ }
{ Programming Notes }
{ ----------------- }
{ }
{ }
{ }
{ }
{ Revision History }
{ ---------------- }
{ January 31 2003 - DL : Initial creation }
{ }
{
$Log: sdlwindow.pas,v $
Revision 1.9 2006/10/22 18:55:25 savage
Slight Change to handle OpenGL context
Revision 1.8 2005/08/03 18:57:32 savage
Various updates and additions. Mainly to handle OpenGL 3D Window support and better cursor support for the mouse class
Revision 1.7 2004/09/30 22:35:47 savage
Changes, enhancements and additions as required to get SoAoS working.
Revision 1.6 2004/09/12 21:52:58 savage
Slight changes to fix some issues with the sdl classes.
Revision 1.5 2004/05/10 21:11:49 savage
changes required to help get SoAoS off the ground.
Revision 1.4 2004/05/01 14:59:27 savage
Updated code
Revision 1.3 2004/04/23 10:45:28 savage
Changes made by Dean Ellis to work more modularly.
Revision 1.2 2004/03/31 10:06:41 savage
Changed so that it now compiles, but is untested.
Revision 1.1 2004/02/05 00:08:20 savage
Module 1.0 release
}
{******************************************************************************}
interface
{$i jedi-sdl.inc}
uses
Classes,
sdl,
sdlinput,
sdlticks;
type
TSDLNotifyEvent = procedure {$IFNDEF NOT_OO}of object{$ENDIF};
TSDLUpdateEvent = procedure( aElapsedTime : single ) {$IFNDEF NOT_OO}of object{$ENDIF};
TSDLResizeEvent = procedure( aWidth : integer; aHeight : integer; aBitDepth : integer; aVideoFlags : Uint32 ) {$IFNDEF NOT_OO}of object{$ENDIF};
TSDLUserEvent = procedure( aType : UInt8; aCode : integer; aData1 : Pointer; aData2 : Pointer ) {$IFNDEF NOT_OO}of object{$ENDIF};
TSDLActiveEvent = procedure( aGain: UInt8; aState: UInt8 ) {$IFNDEF NOT_OO}of object{$ENDIF};
TSDLBaseWindow = class( TObject )
private
FDisplaySurface : PSDL_Surface;
FVideoFlags : Uint32;
FOnDestroy: TSDLNotifyEvent;
FOnCreate: TSDLNotifyEvent;
FOnShow: TSDLNotifyEvent;
FOnResize: TSDLResizeEvent;
FOnUpdate: TSDLUpdateEvent;
FOnRender: TSDLNotifyEvent;
FOnClose: TSDLNotifyEvent;
FLoaded: Boolean;
FRendering: Boolean;
FHeight: integer;
FBitDepth: integer;
FWidth: integer;
FInputManager: TSDLInputManager;
FCaptionText : PChar;
FIconName : PChar;
FOnActive: TSDLActiveEvent;
FOnQuit: TSDLNotifyEvent;
FOnExpose: TSDLNotifyEvent;
FOnUser: TSDLUserEvent;
FTimer : TSDLTicks;
protected
procedure DoActive( aGain: UInt8; aState: UInt8 );
procedure DoCreate;
procedure DoClose;
procedure DoDestroy;
procedure DoUpdate( aElapsedTime : single );
procedure DoQuit;
procedure DoRender;
procedure DoResize( aWidth : integer; aHeight : integer; aBitDepth : integer; aVideoFlags : Uint32 );
procedure DoShow;
procedure DoUser( aType : UInt8; aCode : integer; aData1 : Pointer; aData2 : Pointer );
procedure DoExpose;
procedure Render; virtual;
procedure Update( aElapsedTime : single ); virtual;
procedure InitialiseObjects; virtual;
procedure RestoreObjects; virtual;
procedure DeleteObjects; virtual;
function Flip : integer; virtual;
property OnActive : TSDLActiveEvent read FOnActive write FOnActive;
property OnClose: TSDLNotifyEvent read FOnClose write FOnClose;
property OnDestroy : TSDLNotifyEvent read FOnDestroy write FOnDestroy;
property OnCreate : TSDLNotifyEvent read FOnCreate write FOnCreate;
property OnUpdate: TSDLUpdateEvent read FOnUpdate write FOnUpdate;
property OnQuit : TSDLNotifyEvent read FOnQuit write FOnQuit;
property OnResize : TSDLResizeEvent read FOnResize write FOnResize;
property OnRender: TSDLNotifyEvent read FOnRender write FOnRender;
property OnShow : TSDLNotifyEvent read FOnShow write FOnShow;
property OnUser : TSDLUserEvent read FOnUser write FOnUser;
property OnExpose : TSDLNotifyEvent read FOnExpose write FOnExpose;
property DisplaySurface: PSDL_Surface read FDisplaySurface;
public
property InputManager : TSDLInputManager read FInputManager;
property Loaded : Boolean read FLoaded;
property Width : integer read FWidth;
property Height : integer read FHeight;
property BitDepth : integer read FBitDepth;
property Rendering : Boolean read FRendering write FRendering;
procedure SetCaption( const aCaptionText : string; const aIconName : string );
procedure GetCaption( var aCaptionText : string; var aIconName : string );
procedure SetIcon( aIcon : PSDL_Surface; aMask: UInt8 );
procedure ActivateVideoMode;
constructor Create( aWidth : integer; aHeight : integer; aBitDepth : integer; aVideoFlags : Uint32 ); virtual;
destructor Destroy; override;
procedure InitialiseEnvironment;
function Show : Boolean; virtual;
end;
TSDLCustomWindow = class( TSDLBaseWindow )
public
property OnCreate;
property OnDestroy;
property OnClose;
property OnShow;
property OnResize;
property OnRender;
property OnUpdate;
property DisplaySurface;
end;
TSDL2DWindow = class( TSDLCustomWindow )
public
constructor Create( aWidth : integer; aHeight : integer; aBitDepth : integer; aVideoFlags : Uint32 = SDL_DOUBLEBUF or SDL_SWSURFACE); override;
procedure Render; override;
procedure Update( aElapsedTime : single ); override;
procedure InitialiseObjects; override;
procedure RestoreObjects; override;
procedure DeleteObjects; override;
function Flip : integer; override;
end;
TSDL3DWindow = class( TSDLCustomWindow )
public
constructor Create( aWidth : integer; aHeight : integer; aBitDepth : integer; aVideoFlags : Uint32 = SDL_OPENGL or SDL_DOUBLEBUF); override;
function Flip : integer; override;
procedure Render; override;
procedure Update( aElapsedTime : single ); override;
procedure InitialiseObjects; override;
procedure RestoreObjects; override;
procedure DeleteObjects; override;
end;
implementation
uses
logger,
SysUtils;
{ TSDLBaseWindow }
procedure TSDLBaseWindow.ActivateVideoMode;
begin
FDisplaySurface := SDL_SetVideoMode( FWidth, FHeight, FBitDepth, FVideoFlags);
if (FDisplaySurface = nil) then
begin
Log.LogError( Format('Could not set video mode: %s', [SDL_GetError]), 'Main');
exit;
end;
SetCaption( 'Made with JEDI-SDL', 'JEDI-SDL Icon' );
end;
constructor TSDLBaseWindow.Create( aWidth : integer; aHeight : integer; aBitDepth : integer; aVideoFlags : Uint32 );
begin
inherited Create;
SDL_Init(SDL_INIT_EVERYTHING);
FInputManager := TSDLInputManager.Create( [ itJoystick, itKeyBoard, itMouse ]);
FTimer := TSDLTicks.Create;
FWidth := aWidth;
FHeight := aHeight;
FBitDepth := aBitDepth;
FVideoFlags := aVideoFlags;
DoCreate;
end;
procedure TSDLBaseWindow.DeleteObjects;
begin
FLoaded := False;
end;
destructor TSDLBaseWindow.Destroy;
begin
DoDestroy;
if FLoaded then
DeleteObjects;
if FInputManager <> nil then
FreeAndNil( FInputManager );
if FTimer <> nil then
FreeAndNil( FTimer );
if FDisplaySurface <> nil then
SDL_FreeSurface( FDisplaySurface );
inherited Destroy;
SDL_Quit;
end;
procedure TSDLBaseWindow.DoActive(aGain, aState: UInt8);
begin
if Assigned( FOnActive ) then
begin
FOnActive( aGain, aState );
end;
end;
procedure TSDLBaseWindow.DoClose;
begin
if Assigned( FOnClose ) then
begin
FOnClose;
end;
end;
procedure TSDLBaseWindow.DoCreate;
begin
if Assigned( FOnCreate ) then
begin
FOnCreate;
end;
end;
procedure TSDLBaseWindow.DoDestroy;
begin
if Assigned( FOnDestroy ) then
begin
FOnDestroy;
end;
end;
procedure TSDLBaseWindow.DoExpose;
begin
if Assigned( FOnExpose ) then
begin
FOnExpose;
end;
end;
procedure TSDLBaseWindow.DoUpdate( aElapsedTime : single );
begin
if Assigned( FOnUpdate ) then
begin
FOnUpdate( aElapsedTime );
end;
end;
procedure TSDLBaseWindow.DoQuit;
begin
FRendering := false;
if Assigned( FOnQuit ) then
begin
FOnQuit;
end;
end;
procedure TSDLBaseWindow.DoRender;
begin
if Assigned( FOnRender ) then
begin
FOnRender;
end;
end;
procedure TSDLBaseWindow.DoResize( aWidth : integer; aHeight : integer; aBitDepth : integer; aVideoFlags : Uint32 );
begin
// resize to the new size
SDL_FreeSurface(FDisplaySurface);
FWidth := aWidth;
FHeight := aHeight;
FBitDepth := aBitDepth;
FVideoFlags := aVideoFlags;
FDisplaySurface := SDL_SetVideoMode(aWidth, aHeight, aBitDepth, aVideoFlags);
if Assigned( FOnResize ) then
begin
FOnResize( aWidth, aHeight, aBitDepth, aVideoFlags );
end;
end;
procedure TSDLBaseWindow.DoShow;
begin
if Assigned( FOnShow ) then
begin
FOnShow;
end;
end;
procedure TSDLBaseWindow.DoUser(aType: UInt8; aCode: integer; aData1, aData2: Pointer);
begin
if Assigned( FOnUser ) then
begin
FOnUser( aType, aCode, aData1, aData2 );
end;
end;
function TSDLBaseWindow.Flip : integer;
begin
result := 0;
end;
procedure TSDLBaseWindow.GetCaption( var aCaptionText : string; var aIconName : string );
begin
aCaptionText := string( FCaptionText );
aIconName := string( FIconName );
end;
procedure TSDLBaseWindow.InitialiseEnvironment;
begin
InitialiseObjects;
RestoreObjects;
end;
procedure TSDLBaseWindow.InitialiseObjects;
begin
FLoaded := True;
end;
procedure TSDLBaseWindow.Update( aElapsedTime : single );
begin
DoUpdate( aElapsedTime );
end;
procedure TSDLBaseWindow.Render;
begin
DoRender;
end;
procedure TSDLBaseWindow.RestoreObjects;
begin
FLoaded := false;
end;
procedure TSDLBaseWindow.SetCaption( const aCaptionText : string; const aIconName : string );
begin
if FCaptionText <> aCaptionText then
begin
FCaptionText := PChar( aCaptionText );
FIconName := PChar( aIconName );
SDL_WM_SetCaption( FCaptionText, FIconName );
end;
end;
procedure TSDLBaseWindow.SetIcon(aIcon: PSDL_Surface; aMask: UInt8);
begin
SDL_WM_SetIcon( aIcon, aMask );
end;
function TSDLBaseWindow.Show : Boolean;
var
eBaseWindowEvent : TSDL_Event;
begin
DoShow;
FTimer.Init;
FRendering := true;
// repeat until we are told not to render
while FRendering do
begin
// wait for an event
while SDL_PollEvent( @eBaseWindowEvent ) > 0 do
begin
// check for a quit event
case eBaseWindowEvent.type_ of
SDL_ACTIVEEVENT :
begin
DoActive( eBaseWindowEvent.active.gain, eBaseWindowEvent.active.state );
end;
SDL_QUITEV :
begin
DoQuit;
DoClose;
end;
SDL_USEREVENT :
begin
DoUser( eBaseWindowEvent.user.type_, eBaseWindowEvent.user.code, eBaseWindowEvent.user.data1, eBaseWindowEvent.user.data2 );
end;
SDL_VIDEOEXPOSE :
begin
DoExpose;
end;
SDL_VIDEORESIZE :
begin
DoResize( eBaseWindowEvent.resize.w, eBaseWindowEvent.resize.h, FDisplaySurface.format.BitsPerPixel, FVideoflags );
end;
end;
InputManager.UpdateInputs( eBaseWindowEvent );
end;
// Prepare the Next Frame
Update( FTimer.GetElapsedSeconds );
// Display the Next Frame
Render;
// Flip the surfaces
Flip;
end;
Result := FRendering;
end;
{ TSDL2DWindow }
constructor TSDL2DWindow.Create(aWidth, aHeight, aBitDepth: integer; aVideoFlags: Uint32);
begin
// make sure double buffer is always included in the video flags
inherited Create(aWidth,aHeight, aBitDepth, aVideoFlags or SDL_DOUBLEBUF);
end;
procedure TSDL2DWindow.DeleteObjects;
begin
inherited;
end;
function TSDL2DWindow.Flip: integer;
begin
// let's show the back buffer
result := SDL_Flip( FDisplaySurface );
end;
procedure TSDL2DWindow.InitialiseObjects;
begin
inherited;
end;
procedure TSDL2DWindow.Update( aElapsedTime : single );
begin
inherited;
end;
procedure TSDL2DWindow.Render;
begin
inherited;
end;
procedure TSDL2DWindow.RestoreObjects;
begin
inherited;
end;
{ TSDL3DWindow }
constructor TSDL3DWindow.Create(aWidth,
aHeight, aBitDepth: integer; aVideoFlags: Uint32);
begin
// make sure opengl is always included in the video flags
inherited Create(aWidth,aHeight, aBitDepth, aVideoFlags or SDL_OPENGL or SDL_DOUBLEBUF);
end;
procedure TSDL3DWindow.DeleteObjects;
begin
inherited;
end;
function TSDL3DWindow.Flip : integer;
begin
SDL_GL_SwapBuffers;
result := 0;
end;
procedure TSDL3DWindow.InitialiseObjects;
begin
inherited;
end;
procedure TSDL3DWindow.Update( aElapsedTime : single );
begin
inherited;
end;
procedure TSDL3DWindow.Render;
begin
inherited;
end;
procedure TSDL3DWindow.RestoreObjects;
begin
inherited;
end;
end.
|
{+--------------------------------------------------------------------------+
| Component: TmPasParser
| Created: 11.97
| Author: Martin Waldenburg
| Copyright 1997, all rights reserved.
| Description: A Pascal parser.
| Version: 1.91
| Status: FreeWare
| DISCLAIMER: This is provided as is, expressly without a warranty of any kind.
| You use it at your own risk.
+--------------------------------------------------------------------------+}
unit mwPasParser;
interface
type
TTokenKind = (tkAbsolute, tkAbstract, tkAnd, tkAnsiComment, tkArray, tkAs,
tkAsciiChar, tkAsm, tkAssembler, tkAssign, tkAutomated, tkBegin, tkBadString,
tkBorComment, tkCase, tkCdecl, tkClass, tkColon, tkComma, tkCompDirect,
tkConst, tkConstructor, tkCRLF, tkCRLFCo, tkDefault, tkDestructor, tkDispid,
tkDispinterface, tkDiv, tkDo, tkDotDot, tkDownto, tkDynamic, tkElse, tkEnd,
tkEqual, tkError, tkExcept, tkExport, tkExports, tkExternal, tkFar, tkFile,
tkFinalization, tkFinally, tkFloat, tkFor, tkForward, tkFunction, tkGoto,
tkGreater, tkGreaterEqual, tkIdentifier, tkIf, tkImplementation, tkIn,
tkIndex, tkInherited, tkInitialization, tkInline, tkInteger, tkInterface,
tkIs, tkKeyString, tkLabel, tkLibrary, tkLower, tkLowerEqual, tkMessage,
tkMinus, tkMod, tkName, tkNear, tkNil, tkNodefault, tkNone, tkNot,
tkNotEqual, tkNull, tkNumber, tkObject, tkOf, tkOr, tkOut, tkOverride,
tkPacked, tkPascal, tkPlus, tkPoint, tkPrivate, tkProcedure, tkProgram,
tkProperty, tkProtected, tkPublic, tkPublished, tkRaise, tkRead, tkReadonly,
tkRecord, tkRegister, tkRepeat, tkResident, tkResourcestring, tkRoundClose,
tkRoundOpen, tkSafecall, tkSemiColon, tkSet, tkShl, tkShr, tkSlash,
tkSlashesComment, tkSquareClose, tkSquareOpen, tkSpace, tkStar, tkStdcall,
tkStored, tkString, tkStringresource, tkSymbol, tkThen, tkThreadvar, tkTo,
tkTry, tkType, tkUnit, tkUnknown, tkUntil, tkUses, tkVar, tkVirtual, tkWhile,
tkWith, tkWrite, tkWriteonly, tkXor, tkReintroduce, tkOverload, tkImplements,
tkInt64, tkLongWord, tkOperator, tkStatic, tkStrict); // D4-8 items added by Erik Berry
TIdentDirect = Set of TTokenKind;
TCommentState = (csAnsi, csBor, csNo, csSlashes);
TmPasParser = class;
TmPasToken = class(TObject)
private
function GetData: string;
public
ID: TTokenKind;
LineNumber: Integer;
LinePos: Integer;
Position: Integer;
Length: Integer;
Origin: PChar;
constructor Create;
property Data: string read GetData;
end;
TmPasParser = class(TObject)
private
FToken: TmPasToken;
FComment: TCommentState;
FEndCount: Integer;
FImplementationsPos: Integer;
FLastComment: Integer;
FLastIdentPos: Integer;
FLastSemiColon: Integer;
fOrigin: PChar;
Run: Integer;
FRoundCount: ShortInt;
FSquareCount: ShortInt;
FVisibility: TTokenKind;
function GetIsJunk: Boolean;
function IdentKind: TTokenKind;
procedure SetOrigin(Value: PChar);
procedure SetRunPos(NewPos: Integer);
procedure HandleComments;
public
constructor Create;
destructor Destroy; override;
function GetSubString(StartPos, EndPos: Integer): string;
procedure NextClassLine;
procedure NextObjectLine;
procedure NextID(ID: TTokenKind);
procedure NextNonComment;
procedure NextNonJunk;
procedure NextNonSpace;
procedure NextToken;
procedure ToLineStart;
function GetMethodImpLine(const ClassName, MethodName: string): Integer;
property Comments: TCommentState read FComment write FComment;
property EndCount: Integer read FEndCount write FEndCount;
property ImplementationsPos: Integer read FImplementationsPos;
property IsJunk: Boolean read GetIsJunk;
property LastComment: Integer read FLastComment;
property LastIdentPos: Integer read FLastIdentPos;
property LastSemiColon: Integer read FLastSemiColon;
property Origin: PChar read fOrigin write SetOrigin;
property RunPos: Integer read Run write SetRunPos;
property RoundCount: ShortInt read FRoundCount write FRoundCount;
property SquareCount: ShortInt read FSquareCount write FSquareCount;
property Token: TmPasToken read FToken;
property Visibility: TTokenKind read FVisibility write FVisibility;
end;
Const
IdentDirect: TIdentDirect = [tkAbsolute, tkAbstract, tkAssembler, tkCdecl,
tkDefault, tkDispid, tkDynamic, tkExport, tkExternal, tkFar, tkForward,
tkIdentifier, tkIndex, tkMessage, tkName, tkNear, tkNodefault, tkOverride,
tkPascal, tkRead, tkReadonly, tkRegister, tkResident, tksafecall, tkstdcall,
tkStored, tkVirtual, tkWrite, tkWriteonly, tkReintroduce, tkOverload, tkImplements];
BigIdentDirect: TIdentDirect = [tkAbsolute, tkAbstract, tkAssembler,
tkAutomated, tkCdecl, tkDefault, tkDispid, tkDynamic, tkExport, tkExternal,
tkFar, tkForward, tkIdentifier, tkIndex, tkMessage, tkName, tkNear,
tkNodefault, tkOverride, tkPascal, tkPrivate, tkProtected, tkPublic,
tkPublished, tkRead, tkReadonly, tkRegister, tkResident, tksafecall,
tkstdcall, tkStored, tkVirtual, tkWrite, tkWriteOnly, tkReintroduce, tkOverload, tkImplements];
MethodMarkers = [tkFunction, tkProcedure, tkConstructor, tkDestructor, tkOperator];
implementation
uses
SysUtils, GX_GenericUtils;
constructor TmPasToken.Create;
begin
inherited Create;
ID := tkNone;
LineNumber := 0;
LinePos := 0;
Position := 0;
Length := 0;
end; { Create }
function TmPasToken.GetData: string; // This incorrectly returns data as UTF-8 for D8+
begin
SetString(Result, (Origin + Position), Length);
end;
{ GetData }
destructor TmPasParser.Destroy;
begin
Token.Free;
inherited Destroy;
end; { Destroy }
constructor TmPasParser.Create;
begin
inherited Create;
FComment := csNo;
FEndCount := 0;
FImplementationsPos := 0;
FToken := TmPasToken.Create;
Visibility := tkUnknown;
end; { Create }
function TmPasParser.GetSubString(StartPos, EndPos: Integer): string;
var
SubLen: Integer;
begin
if FOrigin[EndPos] = #10 then Inc(EndPos);
SubLen := EndPos - StartPos;
SetString(Result, (FOrigin + StartPos), SubLen);
end; { GetSubString }
procedure TmPasParser.SetOrigin(Value: PChar);
begin
FOrigin := Value;
Run := 0;
FToken.Origin := Value;
end; { SetOrigin }
procedure TmPasParser.SetRunPos(NewPos: Integer);
begin
Run := NewPos;
NextToken;
end; { SetRunPos }
procedure TmPasParser.HandleComments;
begin
Case FComment of
csAnsi:
begin
FLastComment := Run;
FToken.Position := Run;
FToken.ID := tkAnsiComment;
while FOrigin[Run] <> #0 do
begin
Case FOrigin[Run] of
#13:
begin
Case FToken.Position = Run of
True:
begin
FToken.Id := tkCRLFCo;
FToken.Length := 2;
FToken.Position := Run;
Inc(Run);
end;
False:
begin
FToken.Length := Run - FToken.Position;
end;
end;
Break;
end;
#10:
begin
Inc(Run);
Inc(FToken.LineNumber);
FToken.LinePos := Run;
HandleComments;
Break;
end;
'*': if FOrigin[Run + 1] = ')' then
begin
Inc(Run, 2);
FToken.Length := Run - FToken.Position;
FComment := csNo;
Break;
end;
end;
Inc(Run);
end;
end;
csBor:
begin
FLastComment := Run;
FToken.Position := Run;
FToken.ID := tkBorComment;
while FOrigin[Run] <> #0 do
begin
Case FOrigin[Run] of
#13:
begin
Case FToken.Position = Run of
True:
begin
FToken.Id := tkCRLFCo;
FToken.Length := 2;
FToken.Position := Run;
Inc(Run);
end;
False:
begin
FToken.Length := Run - FToken.Position;
end;
end;
Break;
end;
#10:
begin
Inc(Run);
Inc(FToken.LineNumber);
FToken.LinePos := Run;
HandleComments;
Break;
end;
'}':
begin
Inc(Run);
FToken.Length := Run - FToken.Position;
FComment := csNo;
Break;
end;
end;
Inc(Run);
end;
end;
csSlashes:
begin
FLastComment := Run;
FToken.Position := Run;
FToken.ID := tkSlashesComment;
while FOrigin[Run] <> #0 do
begin
Case FOrigin[Run] of
#13:
begin
FToken.Length := Run - FToken.Position;
FComment := csNo;
Break;
end;
end;
Inc(Run);
end;
end;
end;
end; { HandleComments }
function TmPasParser.IdentKind: TTokenKind;
var
HashKey: Integer;
aToken: string;
function KeyHash: Integer;
var
I: Integer;
begin
Result := 0;
for i := 1 to Length(aToken) do Result := Result + Ord(aToken[i]);
end; { KeyHash }
begin
Result := tkIdentifier;
aToken := UpperCase(FToken.GetData);
HashKey := KeyHash;
Case HashKey of
143: if aToken = 'IF' then Result := tkIf;
147: if aToken = 'DO' then Result := tkDo;
148: if aToken = 'AS' then Result := tkAs;
149: if aToken = 'OF' then Result := tkOf;
151: if aToken = 'IN' then Result := tkIn;
156: if aToken = 'IS' then Result := tkIs;
161: if aToken = 'OR' then Result := tkOr;
163: if aToken = 'TO' then Result := tkTo;
211: if aToken = 'AND' then Result := tkAnd;
215: if aToken = 'END' then Result := tkEnd;
217: if aToken = 'FAR' then Result := tkFar;
224: if aToken = 'MOD' then Result := tkMod;
225: if aToken = 'ASM' then Result := tkAsm;
227:
begin
if aToken = 'DIV' then Result := tkDiv;
if aToken = 'NIL' then Result := tkNil;
end;
231:
begin
if aToken = 'FOR' then Result := tkFor;
if aToken = 'SHL' then Result := tkShl;
end;
233: if aToken = 'VAR' then Result := tkVar;
236: if aToken = 'SET' then Result := tkSet;
237: if aToken = 'SHR' then Result := tkShr;
241: if aToken = 'NOT' then Result := tkNot;
248: if aToken = 'OUT' then Result := tkOut;
249: if aToken = 'XOR' then Result := tkXor;
255: if aToken = 'TRY' then Result := tkTry;
284:
begin
if aToken = 'CASE' then Result := tkCase;
if aToken = 'READ' then Result := tkRead;
end;
288: if aToken = 'FILE' then Result := tkFile;
289: if aToken = 'NAME' then Result := tkName;
294: if aToken = 'NEAR' then Result := tkNear;
297: if aToken = 'ELSE' then Result := tkElse;
303: if aToken = 'THEN' then Result := tkThen;
313: if aToken = 'GOTO' then Result := tkGoto;
316: if aToken = 'WITH' then Result := tkWith;
320:
begin
if aToken = 'UNIT' then Result := tkUnit;
if aToken = 'USES' then Result := tkUses;
end;
322: if aToken = 'TYPE' then Result := tkType;
341: if aToken = 'INT64' then Result := tkInt64;
347: if aToken = 'CDECL' then Result := tkCdecl;
352: if aToken = 'LABEL' then Result := tkLabel;
357: if aToken = 'BEGIN' then Result := tkBegin;
372: if aToken = 'RAISE' then Result := tkRaise;
374: if aToken = 'CLASS' then Result := tkClass;
376: if aToken = 'INDEX' then Result := tkIndex;
377: if aToken = 'WHILE' then Result := tkWhile;
383: if aToken = 'ARRAY' then Result := tkArray;
391: if aToken = 'CONST' then Result := tkConst;
395: if aToken = 'WRITE' then Result := tkWrite;
396: if aToken = 'UNTIL' then Result := tkUntil;
424: if aToken = 'PACKED' then Result := tkPacked;
436: if aToken = 'PASCAL' then Result := tkPascal;
439: if aToken = 'OBJECT' then Result := tkObject;
445: if aToken = 'DISPID' then Result := tkDispid;
447:
begin
if aToken = 'INLINE' then Result := tkInline;
if aToken = 'PUBLIC' then Result := tkPublic;
if aToken = 'RECORD' then Result := tkRecord;
end;
449: if aToken = 'REPEAT' then Result := tkRepeat;
456: if aToken = 'STATIC' then Result := tkStatic;
457: if aToken = 'EXCEPT' then Result := tkExcept;
465: if aToken = 'STORED' then Result := tkStored;
471: if aToken = 'STRING' then Result := tkKeyString;
473: if aToken = 'STRICT' then Result := tkStrict;
475: if aToken = 'DOWNTO' then Result := tkDownto;
482: if aToken = 'EXPORT' then Result := tkExport;
517:
begin
if aToken = 'DEFAULT' then Result := tkDefault;
if aToken = 'DYNAMIC' then Result := tkDynamic;
if aToken = 'MESSAGE' then Result := tkMessage;
end;
519: if aToken = 'STDCALL' then Result := tkStdcall;
527: if aToken = 'FINALLY' then Result := tkFinally;
533:
begin
if aToken = 'FORWARD' then Result := tkForward;
if aToken = 'LIBRARY' then Result := tkLibrary;
end;
536: if aToken = 'PROGRAM' then Result := tkProgram;
539: if aToken = 'PRIVATE' then Result := tkPrivate;
551: if aToken = 'VIRTUAL' then Result := tkVirtual;
565: if aToken = 'EXPORTS' then Result := tkExports;
571: if aToken = 'SAFECALL' then Result := tkSafecall;
596: if aToken = 'ABSTRACT' then Result := tkAbstract;
604: if aToken = 'OVERLOAD' then Result := tkOverload;
606:
begin
if aToken = 'READONLY' then Result := tkReadonly;
if aToken = 'RESIDENT' then Result := tkResident;
end;
607: if aToken = 'ABSOLUTE' then Result := tkAbsolute;
608: if aToken = 'OVERRIDE' then Result := tkOverride;
611: if aToken = 'EXTERNAL' then Result := tkExternal;
613: if aToken = 'REGISTER' then Result := tkRegister;
614: if aToken = 'FUNCTION' then Result := tkFunction;
620:
begin
if aToken = 'LONGWORD' then Result := tkLongWord;
if aToken = 'OPERATOR' then Result := tkOperator;
end;
645: if aToken = 'PROPERTY' then Result := tkProperty;
657: if aToken = 'INTERFACE' then Result := tkInterface;
668: if aToken = 'INHERITED' then Result := tkInherited;
670: if aToken = 'ASSEMBLER' then Result := tkAssembler;
672: if aToken = 'PUBLISHED' then Result := tkPublished;
673: if aToken = 'THREADVAR' then Result := tkThreadvar;
674: if aToken = 'NODEFAULT' then Result := tkNodefault;
676: if aToken = 'AUTOMATED' then Result := tkAutomated;
681: if aToken = 'PROCEDURE' then Result := tkProcedure;
682: if aToken = 'PROTECTED' then Result := tkProtected;
717: if aToken = 'WRITEONLY' then Result := tkWriteonly;
766: if aToken = 'IMPLEMENTS' then Result := tkImplements;
783: if aToken = 'DESTRUCTOR' then Result := tkDestructor;
836: if aToken = 'REINTRODUCE' then Result := tkReintroduce;
870: if aToken = 'CONSTRUCTOR' then Result := tkConstructor;
904: if aToken = 'FINALIZATION' then Result := tkFinalization;
961: if aToken = 'DISPINTERFACE' then Result := tkDispinterface;
1062: if aToken = 'IMPLEMENTATION' then Result := tkImplementation;
1064: if aToken = 'INITIALIZATION' then Result := tkInitialization;
1087:
begin
if aToken = 'RESOURCESTRING' then Result := tkResourcestring;
if aToken = 'STRINGRESOURCE' then Result := tkStringresource;
end;
end;
Case Result of
tkIdentifier: FLastIdentPos := FToken.Position;
tkImplementation: FImplementationsPos := FToken.Position;
tkCase: Inc(FEndCount);
tkClass: FEndCount := 1;
tkBegin: Inc(FEndCount);
tkEnd: Dec(FEndCount);
tkRecord: Inc(FEndCount);
tkObject: Inc(FEndCount);
end;
end; { IdentKind }
procedure TmPasParser.NextToken;
begin
Case FOrigin[Run] of
#0:
begin
FToken.Id := tkNull;
FToken.Length := 0;
FToken.Position := Run;
Exit;
end;
end;
FToken.Position := Run;
if FComment <> csNo then HandleComments
else
begin
Case FOrigin[Run] of
#10:
begin
Inc(Run);
Inc(FToken.LineNumber);
FToken.LinePos := Run;
NextToken;
end;
#13:
begin
FToken.Id := tkCRLF;
FToken.Length := 2;
FToken.Position := Run;
if not (fOrigin[Run + 1] = #10) then
Inc(FToken.LineNumber);
Inc(Run);
end;
#1..#9, #11, #12, #14..#32:
begin
FToken.Position := Run;
while CharInSet(FOrigin[Run], [#1..#9, #11, #12, #14..#32]) do Inc(Run);
FToken.ID := tkSpace;
FToken.Length := Run - FToken.Position;
end;
'/':
Case FOrigin[Run + 1] of
'/':
begin
FComment := csSlashes;
HandleComments;
end;
else
begin
FToken.Position := Run;
Inc(Run);
FToken.ID := tkSymbol;
FToken.Length := 1;
end;
end;
'(':
Case FOrigin[Run + 1] of
'*':
begin
FComment := csAnsi;
HandleComments;
end;
'.':
begin
FToken.Position := Run;
Inc(Run, 2);
FToken.ID := tkSquareOpen;
FToken.Length := 2;
end;
else
begin
FToken.Position := Run;
Inc(Run);
FToken.Length := 1;
FToken.ID := tkRoundOpen;
Inc(FRoundCount);
end;
end;
'A'..'Z', 'a'..'z', '_':
begin
FToken.Position := Run;
Inc(Run);
while CharInSet(FOrigin[Run], ['A'..'Z', 'a'..'z', '0'..'9', '_']) do Inc(Run);
FToken.Length := Run - FToken.Position;
FToken.ID := IdentKind;
end;
'0'..'9':
begin
FToken.Position := Run;
Inc(Run);
FToken.ID := tkNumber;
while CharInSet(FOrigin[Run], ['0'..'9', '.', 'e', 'E']) do
begin
Case FOrigin[Run] of
'.': if FOrigin[Run + 1] <> '.' then FToken.ID := tkFloat else Break;
end;
Inc(Run);
end;
FToken.Length := Run - FToken.Position;
end;
'{':
begin
FComment := csBor;
HandleComments;
end;
'!', '"', '%', '&', ')'..'.', ':'..'@', '['..'^', '`', '~':
begin
FToken.Position := Run;
Case FOrigin[Run] of
')':
begin
FToken.ID := tkRoundClose;
Dec(FRoundCount);
end;
'*': FToken.ID := tkStar;
'+': FToken.ID := tkPlus;
',': FToken.ID := tkComma;
'-': FToken.ID := tkMinus;
'.':
Case FOrigin[Run + 1] of
')':
begin
Inc(Run);
FToken.ID := tkSquareClose;
end;
else FToken.ID := tkPoint;
end;
':':
Case FOrigin[Run + 1] of
'=':
begin
Inc(Run);
FToken.ID := tkAssign;
end;
else FToken.ID := tkColon;
end;
';':
begin
FToken.ID := tkSemiColon;
FLastSemiColon := Run;
end;
'<':
Case FOrigin[Run + 1] of
'=':
begin
Inc(Run);
FToken.ID := tkLowerEqual;
end;
'>':
begin
Inc(Run);
FToken.ID := tkNotEqual;
end;
else FToken.ID := tkLower;
end;
'=': FToken.ID := tkEqual;
'>':
Case FOrigin[Run + 1] of
'=':
begin
Inc(Run);
FToken.ID := tkGreaterEqual;
end;
else FToken.ID := tkGreater;
end;
'[':
begin
FToken.ID := tkSquareOpen;
Inc(FSquareCount);
end;
']':
begin
FToken.ID := tkSquareClose;
Dec(FSquareCount);
end;
else FToken.ID := tkSymbol;
end;
Inc(Run);
FToken.Length := Run - FToken.Position;
end;
#39:
begin
FToken.ID := tkString;
Inc(Run);
while True do begin
if (fOrigin[Run] = #39) then begin
if (fOrigin[Run + 1] = #39) then
Inc(Run)
else begin
Inc(Run);
Break;
end;
end
else if IsCharLineEndingOrNull(fOrigin[Run]) then
begin
FToken.ID := tkBadString;
Break;
end;
Inc(Run);
end;
FToken.Length := Run - FToken.Position;
end;
'#':
begin
FToken.Position := Run;
FToken.ID := tkAsciiChar;
Inc(Run);
while CharInSet(FOrigin[Run], ['0'..'9']) do Inc(Run);
FToken.Length := Run - FToken.Position;
end;
'$':
begin
FToken.Position := Run;
FToken.ID := tkInteger;
Inc(Run);
while CharInSet(FOrigin[Run], ['0'..'9', 'A'..'F', 'a'..'f']) do Inc(Run);
FToken.Length := Run - FToken.Position;
end;
else
begin
FToken.Position := Run;
Inc(Run);
FToken.ID := tkUnknown;
FToken.Length := Run - FToken.Position;
end;
end;
end;
end; {NextToken}
procedure TmPasParser.NextID(ID: TTokenKind);
begin
NextToken;
while FToken.ID <> ID do
begin
Case FToken.ID of
tkNull: Break;
else NextToken;
end;
end;
end; { NextID }
function TmPasParser.GetIsJunk: Boolean;
begin
Case FToken.ID of
tkAnsiComment, tkBorComment, tkCRLF, tkCRLFCo, tkSlashesComment, tkSpace:
Result := True;
else Result := False;
end;
end;
procedure TmPasParser.NextNonComment;
begin
repeat
NextToken;
until not (Token.ID in [tkAnsiComment, tkBorComment, tkCRLFCo,
tkSlashesComment]);
end; { NextNonComCRLF }
procedure TmPasParser.NextNonJunk;
begin
repeat
NextToken;
until not (Token.ID in [tkAnsiComment, tkBorComment, tkCRLF, tkCRLFCo,
tkSlashesComment, tkSpace]);
end; { NextNonJunk }
procedure TmPasParser.NextNonSpace;
begin
NextToken;
while FToken.ID = tkSpace do NextToken;
end; { NextNonSpace }
procedure TmPasParser.ToLineStart;
begin
Run := FToken.LinePos;
NextToken;
end; { ToLineStart }
procedure TmPasParser.NextClassLine;
begin
while FToken.ID <> tkNull do
begin
if FToken.ID in BigIdentDirect then
begin
FLastIdentPos := FToken.Position;
NextNonJunk;
if FToken.ID = tkEqual then
begin
NextNonJunk;
if FToken.ID = tkClass then Break;
end;
end;
NextNonJunk;
end;
end; { NextClassLine }
procedure TmPasParser.NextObjectLine;
begin
while FToken.ID <> tkNull do
begin
if FToken.ID in BigIdentDirect then
begin
FLastIdentPos := FToken.Position;
NextNonJunk;
if FToken.ID = tkEqual then
begin
NextNonJunk;
if FToken.ID in [tkClass, tkDispInterface, tkInterface] then Break;
end;
end;
NextNonJunk;
end;
end; { NextObjectLine }
function TmPasParser.GetMethodImpLine(const ClassName, MethodName: string): Integer;
begin
Result := -1;
while FToken.ID <> tkNull do
begin
NextToken;
if FToken.ID in [tkClass] + MethodMarkers then
begin
// For class methods, skip past the "class" keyword: function/procedure is next
if FToken.ID = tkClass then
NextNonJunk;
NextNonJunk;
if UpperCase(FToken.Data) = UpperCase(ClassName) then
begin
NextNonJunk;
if FToken.ID = tkPoint then
begin
NextNonJunk;
if UpperCase(FToken.Data) = UpperCase(MethodName) then
begin
Result := FToken.LineNumber;
Break;
end;
end;
end;
end;
end;
end; { GetMethodImpLine }
end.
|
unit Solid.Samples.OCP.Streaming.Ok;
interface
uses
System.SysUtils;
type
{ IMeasurable }
IMeasurable = interface
['{D47A7A76-F058-4E36-89F5-F49F10926DAE}']
function GetLength: Integer;
function GetSent: Integer;
end;
{ TStreamingMusic }
TStreamingMusic = class(TInterfacedObject, IMeasurable)
private
FAlbum: string;
FArtist: string;
FBytesLength: Integer;
FBytesSent: Integer;
FReleaseDate: TDateTime;
FTitle: string;
procedure SetAlbum(const AValue: string);
procedure SetArtist(const AValue: string);
procedure SetBytesSent(const AValue: Integer);
procedure SetReleaseDate(const AValue: TDateTime);
procedure SetTitle(const AValue: string);
public
constructor Create(const ABytesLength: Integer);
function GetLength: Integer;
function GetSent: Integer;
property Album: string read FAlbum write SetAlbum;
property Artist: string read FArtist write SetArtist;
property BytesLength: Integer read FBytesLength;
property BytesSent: Integer read FBytesSent write SetBytesSent;
property ReleaseDate: TDateTime read FReleaseDate write SetReleaseDate;
property Title: string read FTitle write SetTitle;
end;
{ TStreamingFile }
TStreamingFile = class(TInterfacedObject, IMeasurable)
private
FAttachmentName: string;
FContentType: string;
FLength: Integer;
FSent: Integer;
public
constructor Create(const ALength: Integer);
function GetLength: Integer;
function GetSent: Integer;
property AttachmentName: string read FAttachmentName write FAttachmentName;
property ContentType: string read FContentType write FContentType;
property Length: Integer read FLength;
property Sent: Integer read FSent write FSent;
end;
{ TProgressViewer }
TProgressViewer = class
private
FMedia: IMeasurable;
public
constructor Create(AMedia: IMeasurable);
function GetAsPercent: Double;
end;
implementation
{ TStreamingMusic }
constructor TStreamingMusic.Create(const ABytesLength: Integer);
begin
inherited Create;
FBytesLength := ABytesLength;
end;
function TStreamingMusic.GetLength: Integer;
begin
Result := FBytesLength;
end;
function TStreamingMusic.GetSent: Integer;
begin
Result := FBytesSent;
end;
procedure TStreamingMusic.SetAlbum(const AValue: string);
begin
FAlbum := Trim(AValue);
end;
procedure TStreamingMusic.SetArtist(const AValue: string);
begin
FArtist := Trim(AValue);
end;
procedure TStreamingMusic.SetBytesSent(const AValue: Integer);
begin
FBytesSent := AValue;
end;
procedure TStreamingMusic.SetReleaseDate(const AValue: TDateTime);
begin
FReleaseDate := AValue;
end;
procedure TStreamingMusic.SetTitle(const AValue: string);
begin
FTitle := Trim(AValue);
end;
{ TStreamingFile }
constructor TStreamingFile.Create(const ALength: Integer);
begin
inherited Create;
FLength := ALength;
end;
function TStreamingFile.GetLength: Integer;
begin
Result := FLength;
end;
function TStreamingFile.GetSent: Integer;
begin
Result := FSent;
end;
{ TProgressViewer }
constructor TProgressViewer.Create(AMedia: IMeasurable);
begin
inherited Create;
FMedia := AMedia;
end;
function TProgressViewer.GetAsPercent: Double;
begin
Result := FMedia.GetSent / FMedia.GetLength * 100;
end;
end.
|
{
TForge Library
Copyright (c) Sergey Kasandrov 1997, 2018
-------------------------------------------------------
# GHash for GCM mode of operation
}
unit tfGHash;
{$I TFL.inc}
interface
uses
tfTypes;
type
PGHash = ^TGHash;
TGHash = record
private type
TValue = array[0..3] of UInt32;
private
FH: TValue;
FY: TValue;
FPos: Cardinal; // 0..15
public
procedure Init(HashKey: Pointer);
procedure Update(Data: Pointer; DataSize: Cardinal);
procedure Pad;
procedure Done(Tag: Pointer; TagSize: Cardinal);
end;
implementation
{ TGHash }
function Swap32(Value: UInt32): UInt32;
begin
Result:= (Value and $000000FF) shl 24
or (Value and $0000FF00) shl 8
or (Value and $00FF0000) shr 8
or (Value and $FF000000) shr 24;
end;
procedure GF128Mul(Y: PByte; const H: TGHash.TValue);
var
Z, V: TGHash.TValue;
I, Bit: Integer;
Value: Byte;
Mask: UInt32;
begin
Z[0]:= 0; // Z = 0
Z[1]:= 0;
Z[2]:= 0;
Z[3]:= 0;
// V:= H;
V[0]:= H[0]; // V = H
V[1]:= H[1];
V[2]:= H[2];
V[3]:= H[3];
// Multiply Z by V for the set bits in Y, starting at the top.
// This is a very simple bit by bit version that may not be very
// fast but it should be resistant to cache timing attacks.
for I:= 0 to 15 do begin
Value:= Y[I];
for Bit:= 0 to 7 do begin
// Extract the high bit of "value" and turn it into a mask.
Mask:= not UInt32(Value shr 7) + 1;
// XOR V with Z if the bit is 1.
Z[0]:= Z[0] xor (V[0] and Mask);
Z[1]:= Z[1] xor (V[1] and Mask);
Z[2]:= Z[2] xor (V[2] and Mask);
Z[3]:= Z[3] xor (V[3] and Mask);
// Rotate V right by 1 bit.
Mask:= (not (V[3] and 1) + 1) and $E1000000;
V[3]:= (V[3] shr 1) or (V[2] shl 31);
V[2]:= (V[2] shr 1) or (V[1] shl 31);
V[1]:= (V[1] shr 1) or (V[0] shl 31);
V[0]:= (V[0] shr 1) xor Mask;
Value:= Value shl 1;
end;
end;
// We have finished the block so copy Z into Y and byte-swap.
PUInt32(Y)[0]:= Swap32(Z[0]);
PUInt32(Y)[1]:= Swap32(Z[1]);
PUInt32(Y)[2]:= Swap32(Z[2]);
PUInt32(Y)[3]:= Swap32(Z[3]);
end;
procedure TGHash.Init(HashKey: Pointer);
begin
// Move(HashKey^, FH, SizeOf(FH));
FH[0]:= Swap32(PUInt32(HashKey)[0]);
FH[1]:= Swap32(PUInt32(HashKey)[1]);
FH[2]:= Swap32(PUInt32(HashKey)[2]);
FH[3]:= Swap32(PUInt32(HashKey)[3]);
FillChar(FY, SizeOf(FY), 0);
FPos:= 0;
end;
procedure TGHash.Done(Tag: Pointer; TagSize: Cardinal);
begin
Pad;
if TagSize > 16 then TagSize:= 16;
Move(FY, Tag^, TagSize);
end;
procedure TGHash.Pad;
begin
if FPos <> 0 then begin
// Padding involves XOR'ing the rest of FY with zeroes, which does nothing.
GF128mul(@FY, FH);
FPos:= 0;
end;
end;
procedure TGHash.Update(Data: Pointer; DataSize: Cardinal);
var
Size: Cardinal;
P: PByte;
I: Integer;
begin
while DataSize > 0 do begin
Size:= 16 - FPos;
if Size > DataSize
then Size:= DataSize;
P:= PByte(@FY) + FPos;
for I:= 0 to Size - 1 do
P[I]:= P[I] xor PByte(Data)[I];
Inc(FPos, Size);
Dec(DataSize, Size);
Inc(PByte(Data), Size);
if FPos = 16 then begin
GF128mul(@FY, FH);
FPos:= 0;
end;
end;
end;
end.
|
unit untHFiltreImage;
interface
uses
Windows, Forms, ExtCtrls, Controls, StdCtrls, Classes,
untCalcImage;
type
TfrmHFiltreImage = class(TForm)
bvbImages: TBevel;
imgPrevisualisation: TImage;
lblPrevisualisation: TLabel;
lblImage: TLabel;
btnOK: TButton;
btnAnnuler: TButton;
lstImage: TListBox;
procedure FormShow(Sender: TObject);
procedure lstImageDrawItem(Control: TWinControl; Index: Integer;
Rectangle: TRect; State: TOwnerDrawState);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lstImageClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
CalcImagePrevisualisation : TCalcImage;
CalcImagePrev : TCalcImage;
Image : Pointer;
procedure RafraichirListeImages;
procedure AffichePrevisualisation;
function EnabledOK : Boolean;
procedure PrevisualiseResultat; virtual; abstract;
end;
var
frmHFiltreImage: TfrmHFiltreImage;
implementation
uses
SysUtils, Graphics,
untMDIImage, untPrincipale;
{$R *.DFM}
{ TfrmHFiltreImage }
procedure TfrmHFiltreImage.AffichePrevisualisation;
var
X, Y : Integer;
begin
for X := 0 to CalcImagePrevisualisation.TailleX - 1 do // Parcourt tous les
for Y := 0 to CalcImagePrevisualisation.TailleY - 1 do // pixels de l'images
imgPrevisualisation.Canvas.Pixels[X, Y] := CouleurToColor(CalcImagePrevisualisation.Image[X, Y]);
end;
function TfrmHFiltreImage.EnabledOK: Boolean;
begin
if (lstImage.ItemIndex > -1) then // Si une image est sélectionnée
Result := True
else
Result := False;
end;
procedure TfrmHFiltreImage.RafraichirListeImages;
var
NumImage : Integer;
begin
lstImage.Clear; // Efface toute la liste
for NumImage := 0 to ListeImages.Count - 1 do // Parcourt toute la liste d'images
lstImage.Items.Add(TfrmMDIImage(ListeImages.Items[NumImage]).Caption); // Ajoute le titre des images à la liste
end;
procedure TfrmHFiltreImage.FormShow(Sender: TObject);
begin
btnOK.Enabled := False; // Au début, aucune image n'est sélectionnée donc on ne peut pas cliquer sur OK
imgPrevisualisation.Canvas.Rectangle(0, 0, imgPrevisualisation.Width, imgPrevisualisation.Height); // Efface l'image de la prévisualisation
RafraichirListeImages;
end;
procedure TfrmHFiltreImage.lstImageDrawItem(Control: TWinControl;
Index: Integer; Rectangle: TRect; State: TOwnerDrawState);
procedure CopieImage(CanvasDest : TCanvas; Rect : TRect; BitmapSource : TBitmap);
var
X, Y : Integer;
begin
for X := Rect.Left to Rect.Right do // Parcourt tous les
for Y := Rect.Top to Rect.Bottom do // pixels du rectangle
CanvasDest.Pixels[X, Y] := BitmapSource.Canvas.Pixels[(X - Rect.Left) * (BitmapSource.Width - 1) div (Rect.Right - Rect.Left), (Y - Rect.Top) * (BitmapSource.Height - 1) div (Rect.Bottom - Rect.Top)]; //Copie l'image pixel par pixel dans le rectangle
end;
var
Bitmap : TBitmap;
begin
Bitmap := TBitmap.Create; // Création du Bitmap temporaire
Bitmap.Width := Rectangle.Right - Rectangle.Left; // Changement des dimensions
Bitmap.Height := Rectangle.Bottom - Rectangle.Top; // du bitmap temporaire
Bitmap.Canvas.Font := lstImage.Canvas.Font; // Affectation des
Bitmap.Canvas.Brush := lstImage.Canvas.Brush; // mêmes propriétés
Bitmap.Canvas.Pen := lstImage.Canvas.Pen; // au bitmap temporaire
Bitmap.Canvas.FillRect(Rect(0, 0, Rectangle.Right - Rectangle.Left, Rectangle.Bottom - Rectangle.Top)); // Effacement du bitmap
if Index < lstImage.Items.Count then
begin
Bitmap.Canvas.TextOut(70, (Rectangle.Bottom - Rectangle.Top - Bitmap.Canvas.TextHeight(lstImage.Items[Index])) div 2, lstImage.Items[Index]); // Ecrit le titre de l'image dans le bitmap temporaire
CopieImage(Bitmap.Canvas, Rect(4, 2, 64, Rectangle.Bottom - Rectangle.Top - 4), TfrmMDIImage(ListeImages.Items[Index]).imgImage.Picture.Bitmap); // Affiche la petite image à coté du titre
end;
lstImage.Canvas.CopyRect(Rectangle, Bitmap.Canvas, Rect(0, 0, Rectangle.Right - Rectangle.Left, Rectangle.Bottom - Rectangle.Top)); // Copie du bitmap temporaire dans le canvas de la liste
Bitmap.Free;
end;
procedure TfrmHFiltreImage.FormCreate(Sender: TObject);
begin
imgPrevisualisation.Canvas.Pen.Color := clBlack;
imgPrevisualisation.Canvas.Brush.Color := Color;
CalcImagePrevisualisation := TCalcImage.Create; // Crée le tableau de données de l'image d prévisualisation
CalcImagePrevisualisation.ChangeDimensions(imgPrevisualisation.Width, imgPrevisualisation.Height); // Dimensionne le tableau de données
CalcImagePrev := TCalcImage.Create;
CalcImagePrev.ChangeDimensions(imgPrevisualisation.Width, imgPrevisualisation.Height);
end;
procedure TfrmHFiltreImage.FormDestroy(Sender: TObject);
begin
CalcImagePrevisualisation.Destroy;
CalcImagePrev.Destroy;
end;
procedure TfrmHFiltreImage.lstImageClick(Sender: TObject);
begin
Image := ListeImages.Items[lstImage.ItemIndex]; // Pointe sur l'image sélectionnée
imgPrevisualisation.Canvas.Rectangle(0, 0, imgPrevisualisation.Width, imgPrevisualisation.Height); // Efface l'image de la prévisualisation
btnOK.Enabled := EnabledOK; // Vérifie si l'image est "compatible"
PrevisualiseResultat;
end;
procedure TfrmHFiltreImage.btnOKClick(Sender: TObject);
begin
ListeImages.Add(TfrmMDIImage.Create(nil)); // Crée une nouvelle Form image
TfrmMDIImage(ListeImages.Last).ChangerDimensionsImage(TfrmMDIImage(Image).CalcImage.TailleX, TfrmMDIImage(Image).CalcImage.TailleY); // Redimensionne l'image
TfrmMDIImage(ListeImages.Last).Caption := 'Image : ' + IntToStr(ListeImages.Count); // Affiche le titre de l'image
end;
end.
|
unit Solid.Samples.SRP.BookRight;
interface
uses
System.SysUtils;
type
{ TBookEntity }
TBookEntity = class
private
FAuthor: string;
FPageCount: Integer;
FTitle: string;
function GetLocation: string;
procedure SetAuthor(const AValue: string);
procedure SetLocation(const AValue: string);
procedure SetPageCount(const AValue: Integer);
procedure SetTitle(const AValue: string);
public
property Author: string read FAuthor write SetAuthor;
property Location: string read GetLocation write SetLocation; // WARNING!
property PageCount: Integer read FPageCount write SetPageCount;
property Title: string read FTitle write SetTitle;
end;
{ TBookPaperPrinter }
TBookPaperPrinter = class
public
procedure Print(ABook: TBookEntity; APage: Integer = 0);
end;
{ TBookDbPersistor }
TBookDbPersistor = class
private
FConnectionString: string;
public
constructor Create(const AConnectionString: string);
procedure Save(ABook: TBookEntity; APage: Integer = 0);
end;
{ TBookStand }
TBookStand = class
private
FCurrentBook: TBookEntity;
FCurrentPage: Integer;
FPersistor: TBookDbPersistor;
FPrinter: TBookPaperPrinter;
procedure SetCurrentBook(AValue: TBookEntity);
procedure SetCurrentPage(AValue: Integer);
function HasBook: Boolean;
public
constructor Create(APersistor: TBookDbPersistor;
APrinter: TBookPaperPrinter);
property CurrentBook: TBookEntity read FCurrentBook write SetCurrentBook;
property CurrentPage: Integer read FCurrentPage write SetCurrentPage;
procedure OpenNewBook(ABook: TBookEntity);
procedure CloseBook;
procedure NextPage();
procedure PriorPage();
procedure Print(APage: Integer = 0);
procedure Save(APage: Integer = 0);
end;
implementation
{ TBookEntity }
function TBookEntity.GetLocation: string;
begin
Result := EmptyStr; // TODO
end;
procedure TBookEntity.SetAuthor(const AValue: string);
begin
FAuthor := Trim(AValue);
end;
procedure TBookEntity.SetLocation(const AValue: string);
begin
// TODO
end;
procedure TBookEntity.SetPageCount(const AValue: Integer);
begin
if FPageCount < 0 then
Exit;
FPageCount := AValue;
end;
procedure TBookEntity.SetTitle(const AValue: string);
begin
FTitle := Trim(AValue);
end;
{ TBookStand }
procedure TBookStand.CloseBook;
begin
SetCurrentBook(nil);
end;
constructor TBookStand.Create(APersistor: TBookDbPersistor;
APrinter: TBookPaperPrinter);
begin
inherited Create;
FPersistor := APersistor;
FPrinter := APrinter;
end;
function TBookStand.HasBook: Boolean;
begin
Result := FCurrentBook <> nil;
end;
procedure TBookStand.OpenNewBook(ABook: TBookEntity);
begin
SetCurrentBook(ABook);
end;
procedure TBookStand.Print(APage: Integer = 0);
begin
if not HasBook then
raise Exception.Create('Book not opened');
FPrinter.Print(FCurrentBook, APage);
end;
procedure TBookStand.PriorPage;
begin
if not HasBook then
Exit;
if FCurrentPage <= 1 then
Exit;
Dec(FCurrentPage);
end;
procedure TBookStand.Save(APage: Integer = 0);
begin
if not HasBook then
raise Exception.Create('Book not opened');
FPersistor.Save(FCurrentBook, APage);
end;
procedure TBookStand.SetCurrentBook(AValue: TBookEntity);
begin
FCurrentBook := AValue;
if HasBook then
FCurrentPage := 1
else
FCurrentPage := 0;
end;
procedure TBookStand.SetCurrentPage(AValue: Integer);
begin
if AValue < 0 then
Exit;
if FCurrentBook = nil then
Exit;
if AValue > FCurrentBook.PageCount then
Exit;
FCurrentPage := AValue;
end;
procedure TBookStand.NextPage;
begin
if not HasBook then
Exit;
if FCurrentPage >= FCurrentBook.PageCount then
Exit;
Inc(FCurrentPage);
end;
{ TBookPaperPrinter }
procedure TBookPaperPrinter.Print(ABook: TBookEntity; APage: Integer);
begin
// TODO
end;
{ TBookDbPersistor }
constructor TBookDbPersistor.Create(const AConnectionString: string);
begin
inherited Create;
FConnectionString := AConnectionString;
end;
procedure TBookDbPersistor.Save(ABook: TBookEntity; APage: Integer);
begin
// TODO
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2013 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clRequestEdit;
interface
{$I ..\common\clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Messages, Forms, Menus, Classes, Controls, StdCtrls, ExtCtrls, ComCtrls,
Grids, Buttons, SysUtils, TypInfo, Graphics, Dialogs, Windows, Types,
{$ELSE}
Winapi.Messages, Vcl.Forms, Vcl.Menus, System.Classes, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
Vcl.Grids, Vcl.Buttons, System.SysUtils, System.TypInfo, Vcl.Graphics, Vcl.Dialogs, Winapi.Windows, System.Types,
{$ENDIF}
clHttpRequest, clMenuButton;
type
TclItemEditor = class
private
FItem: TclHttpRequestItem;
FParent: TWinControl;
protected
procedure FillControls; virtual; abstract;
procedure FillData; virtual; abstract;
procedure CreateControls; virtual; abstract;
procedure DestroyControls; virtual; abstract;
public
constructor Create(AItem: TclHttpRequestItem; AParent: TWinControl); virtual;
destructor Destroy; override;
procedure AlignControls; virtual; abstract;
property Item: TclHttpRequestItem read FItem;
property Parent: TWinControl read FParent;
end;
TclItemEditorClass = class of TclItemEditor;
TclTextItemEditor = class(TclItemEditor)
private
FRichEdit: TRichEdit;
protected
procedure FillControls; override;
procedure FillData; override;
procedure CreateControls; override;
procedure DestroyControls; override;
public
constructor Create(AItem: TclHttpRequestItem; AParent: TWinControl); override;
procedure AlignControls; override;
end;
TclFileItemEditor = class(TclItemEditor)
private
FFieldNameLabel: TLabel;
FFileNameLabel: TLabel;
FContentTypeLabel: TLabel;
FFieldName: TEdit;
FFileName: TEdit;
FBrowseButton: TButton;
FContentType: TEdit;
FCanonicalized: TCheckBox;
procedure DoOnBrowseClick(Sender: TObject);
function GetItem: TclSubmitFileRequestItem;
protected
procedure FillControls; override;
procedure FillData; override;
procedure CreateControls; override;
procedure DestroyControls; override;
public
constructor Create(AItem: TclHttpRequestItem; AParent: TWinControl); override;
procedure AlignControls; override;
end;
TclFormItemEditor = class(TclItemEditor)
private
FLoading: Boolean;
FCanonicalized: TCheckBox;
FFieldName: TEdit;
FFieldValue: TEdit;
FFieldNameLabel: TLabel;
FFieldValueLabel: TLabel;
function GetItem: TclFormFieldRequestItem;
protected
procedure FillControls; override;
procedure FillData; override;
procedure CreateControls; override;
procedure DestroyControls; override;
public
constructor Create(AItem: TclHttpRequestItem; AParent: TWinControl); override;
procedure AlignControls; override;
end;
TclHttpRequestEditorDlg = class(TForm)
Panel4: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Panel1: TPanel;
PageControl: TPageControl;
tsItems: TTabSheet;
Panel5: TPanel;
Panel6: TPanel;
Panel8: TPanel;
pnButtons: TPanel;
btnAdd: TButton;
btnDelete: TButton;
btnUp: TButton;
btnDown: TButton;
ItemList: TListBox;
pmItems: TPopupMenu;
miAdd: TMenuItem;
miDelete: TMenuItem;
miUp: TMenuItem;
miDown: TMenuItem;
tsContent: TTabSheet;
Panel7: TPanel;
btnOK: TButton;
btnCancel: TButton;
pDetails: TPanel;
N1: TMenuItem;
miBuildUrl: TMenuItem;
miBuildFile: TMenuItem;
miBuildText: TMenuItem;
procedure FormResize(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnUpClick(Sender: TObject);
procedure btnDownClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ItemListDblClick(Sender: TObject);
procedure PageControlChange(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure miBuildUrlClick(Sender: TObject);
procedure miBuildFileClick(Sender: TObject);
procedure miBuildTextClick(Sender: TObject);
private
FItemEditor: TclItemEditor;
FHttpRequest: TclHttpRequest;
btnBuild: TclMenuButton;
procedure SetHttpRequest(const Value: TclHttpRequest);
procedure LoadItemList(ASelectedIndex: Integer);
procedure AddItemToList(AItem: TclHttpRequestItem);
function CurrentItem: TclHttpRequestItem;
procedure StoreItems;
procedure CreateBuildButton;
protected
function CreateItemEditor(AItem: TclHttpRequestItem;
AParent: TWinControl): TclItemEditor; virtual;
public
property HttpRequest: TclHttpRequest read FHttpRequest write SetHttpRequest;
end;
function ModifyHttpRequest(AHttpRequest: TclHttpRequest): Boolean;
implementation
uses
clRequestChooser;
{$R *.DFM}
function ModifyHttpRequest(AHttpRequest: TclHttpRequest): Boolean;
var
Dlg: TclHttpRequestEditorDlg;
begin
Dlg := TclHttpRequestEditorDlg.Create(nil);
try
Dlg.HttpRequest := AHttpRequest;
Result := Dlg.ShowModal() = mrOK;
if (Result) then
begin
AHttpRequest.Assign(Dlg.HttpRequest);
end;
finally
Dlg.Free();
end;
end;
procedure SetFocusControl(AControl: TWinControl);
begin
if AControl.CanFocus() then
begin
AControl.SetFocus();
end;
end;
{ TclHttpRequestEditorDlg }
function TclHttpRequestEditorDlg.CreateItemEditor(AItem: TclHttpRequestItem;
AParent: TWinControl): TclItemEditor;
const
ItemCount = 3;
Items: array[0..ItemCount - 1] of TclHttpRequestItemClass = (
TclTextRequestItem, TclSubmitFileRequestItem, TclFormFieldRequestItem);
Editors: array[0..ItemCount - 1] of TclItemEditorClass = (
TclTextItemEditor, TclFileItemEditor, TclFormItemEditor);
var
i: Integer;
begin
Result := nil;
if (AItem = nil) then Exit;
for i := Low(Items) to High(Items) do
begin
if (Items[i] = AItem.ClassType) then
begin
Result := Editors[i].Create(AItem, AParent);
Break;
end;
end;
end;
procedure TclHttpRequestEditorDlg.FormResize(Sender: TObject);
begin
if (FItemEditor <> nil) then
begin
FItemEditor.AlignControls();
end;
end;
procedure TclHttpRequestEditorDlg.btnDeleteClick(Sender: TObject);
var
Ind: Integer;
begin
Ind := ItemList.ItemIndex;
if (Ind > - 1) then
begin
FHttpRequest.Items.Delete(Ind);
if (Ind = FHttpRequest.Items.Count) then
begin
Dec(Ind);
end;
LoadItemList(Ind);
end;
end;
procedure TclHttpRequestEditorDlg.btnUpClick(Sender: TObject);
var
Ind: Integer;
begin
Ind := ItemList.ItemIndex;
if (Ind > 0) and (Ind < FHttpRequest.Items.Count) then
begin
FHttpRequest.Items.Move(Ind, Ind - 1);
LoadItemList(Ind - 1);
end;
end;
procedure TclHttpRequestEditorDlg.btnDownClick(Sender: TObject);
var
Ind: Integer;
begin
Ind := ItemList.ItemIndex;
if (Ind > -1) and (Ind < FHttpRequest.Items.Count - 1) then
begin
FHttpRequest.Items.Move(Ind, Ind + 1);
LoadItemList(Ind + 1);
end;
end;
procedure TclHttpRequestEditorDlg.SetHttpRequest(const Value: TclHttpRequest);
begin
FHttpRequest.Assign(Value);
LoadItemList(0);
end;
procedure TclHttpRequestEditorDlg.CreateBuildButton;
begin
btnBuild := TclMenuButton.Create(nil);
btnBuild.Parent := pnButtons;
btnBuild.Left := 8;
btnBuild.Top := 146;
btnBuild.Height := btnAdd.Height;
btnBuild.Width := btnAdd.Width;
btnBuild.Caption := 'Build...';
btnBuild.AddMenuItem(miBuildUrl.Caption, miBuildUrl.OnClick);
btnBuild.AddMenuItem(miBuildFile.Caption, miBuildFile.OnClick);
btnBuild.AddMenuItem(miBuildText.Caption, miBuildText.OnClick);
btnBuild.OnClick := miBuildTextClick;
end;
procedure TclHttpRequestEditorDlg.FormCreate(Sender: TObject);
begin
CreateBuildButton();
FHttpRequest := TclHttpRequest.Create(nil);
PageControl.ActivePage := tsItems;
end;
procedure TclHttpRequestEditorDlg.FormDestroy(Sender: TObject);
begin
StoreItems();
FHttpRequest.Free();
btnBuild.Free();
end;
procedure TclHttpRequestEditorDlg.AddItemToList(AItem: TclHttpRequestItem);
begin
ItemList.Items.AddObject(AItem.ClassName, AItem);
end;
procedure TclHttpRequestEditorDlg.LoadItemList(ASelectedIndex: Integer);
var
i: Integer;
begin
ItemList.Clear();
for i := 0 to FHttpRequest.Items.Count - 1 do
begin
AddItemToList(FHttpRequest.Items[i]);
end;
if (ItemList.Items.Count > ASelectedIndex) then
begin
ItemList.ItemIndex := ASelectedIndex;
end;
end;
procedure TclHttpRequestEditorDlg.ItemListDblClick(Sender: TObject);
begin
PageControl.ActivePage := tsContent;
PageControlChange(PageControl);
end;
function TclHttpRequestEditorDlg.CurrentItem: TclHttpRequestItem;
begin
if (ItemList.ItemIndex > -1) then
begin
Result := TclHttpRequestItem(ItemList.Items.Objects[ItemList.ItemIndex]);
end else
begin
Result := nil;
end;
end;
procedure TclHttpRequestEditorDlg.PageControlChange(Sender: TObject);
begin
FItemEditor.Free();
FItemEditor := nil;
if (PageControl.ActivePage = tsItems) then
begin
SetFocusControl(ItemList);
end else
if (PageControl.ActivePage = tsContent) then
begin
FItemEditor := CreateItemEditor(CurrentItem(), pDetails);
end;
end;
{ TclItemEditor }
constructor TclItemEditor.Create(AItem: TclHttpRequestItem; AParent: TWinControl);
begin
inherited Create();
FItem := AItem;
FParent := AParent;
CreateControls();
AlignControls();
FillControls();
end;
destructor TclItemEditor.Destroy;
begin
FillData();
DestroyControls();
inherited Destroy();
end;
{ TclTextItemEditor }
constructor TclTextItemEditor.Create(AItem: TclHttpRequestItem; AParent: TWinControl);
begin
inherited Create(AItem, AParent);
SetFocusControl(FRichEdit);
end;
procedure TclTextItemEditor.AlignControls();
begin
FRichEdit.Align := alClient;
end;
procedure TclTextItemEditor.CreateControls;
begin
FRichEdit := TRichEdit.Create(nil);
FRichEdit.Parent := Parent;
FRichEdit.WordWrap := False;
end;
procedure TclTextItemEditor.DestroyControls;
begin
FRichEdit.Free();
end;
procedure TclTextItemEditor.FillControls;
begin
FRichEdit.Lines.Text := (Item as TclTextRequestItem).TextData;
end;
procedure TclTextItemEditor.FillData;
begin
(Item as TclTextRequestItem).TextData := FRichEdit.Lines.Text;
end;
{ TclFileItemEditor }
procedure TclFileItemEditor.AlignControls;
function GetMaxLabelWidth: Integer;
begin
Result := FFieldNameLabel.Width;
if (Result < FFileNameLabel.Width) then
begin
Result := FFileNameLabel.Width;
end;
if (Result < FContentTypeLabel.Width) then
begin
Result := FContentTypeLabel.Width;
end;
Result := Result + 4;
end;
var
w: Integer;
begin
FFieldNameLabel.Top := 3;
FFileNameLabel.Top := FFieldNameLabel.Top + FFieldName.Height + 3;
FContentTypeLabel.Top := FFileNameLabel.Top + FFileName.Height + 5;
FFieldName.Top := 0;
FFileName.Top := FFieldName.Top + FFieldName.Height + 3;
FBrowseButton.Top := FFileName.Top;
FContentType.Top := FFileName.Top + FFileName.Height + 5;
FCanonicalized.Top := FContentType.Top + FContentType.Height + 5;
w := GetMaxLabelWidth();
FFieldName.Left := w;
FFileName.Left := w;
FContentType.Left := w;
FBrowseButton.Height := FFileName.Height;
FBrowseButton.Width := FBrowseButton.Height;
FBrowseButton.Left := Parent.ClientWidth - FBrowseButton.Width;
FFieldName.Width := Parent.ClientWidth - FFieldName.Left;
FContentType.Width := Parent.ClientWidth - FContentType.Left;
FFileName.Width := Parent.ClientWidth - FFileName.Left - FBrowseButton.Width;
FCanonicalized.Width := Parent.ClientWidth;
end;
procedure TclFileItemEditor.CreateControls;
begin
FFieldNameLabel := TLabel.Create(nil);
FFileNameLabel := TLabel.Create(nil);
FContentTypeLabel := TLabel.Create(nil);
FFieldName := TEdit.Create(nil);
FFileName := TEdit.Create(nil);
FBrowseButton := TButton.Create(nil);
FContentType := TEdit.Create(nil);
FCanonicalized := TCheckBox.Create(nil);
FFieldNameLabel.Parent := Parent;
FFileNameLabel.Parent := Parent;
FContentTypeLabel.Parent := Parent;
FFieldName.Parent := Parent;
FFileName.Parent := Parent;
FBrowseButton.Parent := Parent;
FContentType.Parent := Parent;
FCanonicalized.Parent := Parent;
FFieldNameLabel.Caption := 'Field Name';
FFileNameLabel.Caption := 'File Name';
FContentTypeLabel.Caption := 'Content Type';
FBrowseButton.Caption := '...';
FBrowseButton.OnClick := DoOnBrowseClick;
FCanonicalized.Caption := 'Canonicalize Fields';
end;
constructor TclFileItemEditor.Create(AItem: TclHttpRequestItem; AParent: TWinControl);
begin
inherited Create(AItem, AParent);
SetFocusControl(FFieldName);
end;
procedure TclFileItemEditor.DoOnBrowseClick(Sender: TObject);
var
dlg: TOpenDialog;
begin
dlg := TOpenDialog.Create(nil);
try
dlg.Filename := FFileName.Text;
dlg.InitialDir := ExtractFilePath(dlg.Filename);
dlg.Filter := '*.*';
dlg.Options := dlg.Options + [ofEnableSizing];
if dlg.Execute then FFileName.Text := dlg.Filename;
finally
dlg.Free();
end;
end;
procedure TclFileItemEditor.FillControls;
begin
FFieldName.Text := GetItem().FieldName;
FFileName.Text := GetItem().FileName;
FContentType.Text := GetItem().ContentType;
FCanonicalized.Checked := GetItem().Canonicalized;
end;
procedure TclFileItemEditor.FillData;
begin
GetItem().FieldName := FFieldName.Text;
GetItem().FileName := FFileName.Text;
GetItem().ContentType := FContentType.Text;
GetItem().Canonicalized := FCanonicalized.Checked;
end;
function TclFileItemEditor.GetItem: TclSubmitFileRequestItem;
begin
Result := (Item as TclSubmitFileRequestItem);
end;
procedure TclFileItemEditor.DestroyControls;
begin
FCanonicalized.Free();
FContentType.Free();
FBrowseButton.Free();
FFileName.Free();
FFieldName.Free();
FContentTypeLabel.Free();
FFileNameLabel.Free();
FFieldNameLabel.Free();
end;
{ TclFormItemEditor }
procedure TclFormItemEditor.AlignControls;
var
w: Integer;
begin
FFieldNameLabel.Top := 3;
FFieldValueLabel.Top := FFieldNameLabel.Top + FFieldName.Height + 3;
FFieldName.Top := 0;
FFieldValue.Top := FFieldName.Top + FFieldName.Height + 3;
FCanonicalized.Top := FFieldValue.Top + FFieldValue.Height + 5;
w := FFieldNameLabel.Width;
if (w < FFieldValueLabel.Width) then
begin
w := FFieldValueLabel.Width;
end;
w := w + 4;
FFieldName.Left := w;
FFieldValue.Left := w;
FFieldName.Width := Parent.ClientWidth - FFieldName.Left;
FFieldValue.Width := Parent.ClientWidth - FFieldValue.Left;
FCanonicalized.Width := Parent.ClientWidth;
end;
procedure TclFormItemEditor.CreateControls();
begin
FFieldNameLabel := TLabel.Create(nil);
FFieldValueLabel := TLabel.Create(nil);
FFieldName := TEdit.Create(nil);
FFieldValue := TEdit.Create(nil);
FCanonicalized := TCheckBox.Create(nil);
FFieldNameLabel.Parent := Parent;
FFieldValueLabel.Parent := Parent;
FFieldName.Parent := Parent;
FFieldValue.Parent := Parent;
FCanonicalized.Parent := Parent;
FFieldNameLabel.Caption := 'Field Name';
FFieldValueLabel.Caption := 'Field Value';
FCanonicalized.Caption := 'Canonicalize Fields';
end;
procedure TclFormItemEditor.FillControls();
begin
FLoading := True;
try
FFieldName.Text := GetItem().FieldName;
FFieldValue.Text := GetItem().FieldValue;
FCanonicalized.Checked := GetItem().Canonicalized;
finally
FLoading := False;
end;
end;
procedure TclFormItemEditor.FillData();
begin
GetItem().FieldName := FFieldName.Text;
GetItem().FieldValue := FFieldValue.Text;
GetItem().Canonicalized := FCanonicalized.Checked;
end;
constructor TclFormItemEditor.Create(AItem: TclHttpRequestItem; AParent: TWinControl);
begin
inherited Create(AItem, AParent);
SetFocusControl(FFieldName);
end;
function TclFormItemEditor.GetItem: TclFormFieldRequestItem;
begin
Result := (Item as TclFormFieldRequestItem);
end;
procedure TclHttpRequestEditorDlg.FormHide(Sender: TObject);
begin
StoreItems();
end;
procedure TclHttpRequestEditorDlg.StoreItems();
begin
FItemEditor.Free();
FItemEditor := nil;
end;
procedure TclHttpRequestEditorDlg.btnAddClick(Sender: TObject);
begin
if THttpRequestChooser.AddSingleHttpItem(FHttpRequest) then
begin
LoadItemList(FHttpRequest.Items.Count - 1);
end;
end;
procedure TclFormItemEditor.DestroyControls;
begin
FCanonicalized.Free();
FFieldValue.Free();
FFieldName.Free();
FFieldValueLabel.Free();
FFieldNameLabel.Free();
end;
procedure TclHttpRequestEditorDlg.miBuildUrlClick(Sender: TObject);
begin
if THttpRequestChooser.BuildRequestItemsByUrl(FHttpRequest) then
begin
LoadItemList(FHttpRequest.Items.Count - 1);
end;
end;
procedure TclHttpRequestEditorDlg.miBuildFileClick(Sender: TObject);
begin
if THttpRequestChooser.BuildRequestItemsByFile(FHttpRequest) then
begin
LoadItemList(FHttpRequest.Items.Count - 1);
end;
end;
procedure TclHttpRequestEditorDlg.miBuildTextClick(Sender: TObject);
begin
if THttpRequestChooser.BuildRequestItemsByText(FHttpRequest) then
begin
LoadItemList(FHttpRequest.Items.Count - 1);
end;
end;
end.
|
unit UnitFDDatabase;
interface
uses SysUtils, UnitDataInterfaces, Data.DbxSqlite, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
FireDAC.Comp.Client, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef,
FireDAC.Phys.SQLite, FireDAC.Phys.MSSQL, FireDAC.Phys.MSSQLDef,
FireDAC.Phys.ODBCBase, FireDAC.Comp.ScriptCommands, FireDAC.Stan.Util,
FireDAC.Comp.Script, Data.DB,
FireDAC.DatS, FireDAC.Stan.Param,
FireDAC.DApt.Intf,
FireDAC.Comp.DataSet;
type
TFDDatabase = class(TInterfacedObject, IDataConnection)
private
function GetFDConn : TFDConnection;
procedure PopulateData;
protected
FDB_NAME : String;
FFDConn: TFDConnection;
function DatabaseNotExists:Boolean;virtual;abstract;
procedure CreateDatabase;virtual;abstract;
function ResetConnToInventoryDB : Boolean;virtual;abstract;
procedure CreateSchema;virtual;
public
constructor Create; virtual;
function ConnectToDB : Boolean;
property FDConn : TFDConnection read GetFDConn;
end;
implementation
uses Com_Exception;
constructor TFDDatabase.Create;
begin
inherited create;
FFDConn := TFDConnection.Create(nil);
end;
function TFDDatabase.GetFDConn : TFDConnection;
begin
result := FFDConn;
end;
function TFDDatabase.ConnectToDB: boolean;
begin
if DatabaseNotExists then
begin
CreateDatabase;
CreateSchema;
PopulateData;
end;
result := ResetConnToInventoryDB;
end;
procedure TFDDatabase.CreateSchema;
var
Table: TFDTable;
begin
ResetConnToInventoryDB;
Table := TFDTable.Create(nil);
try
Table.Connection := FDConn;
Table.TableName := 'CUSTOMER';
Table.FieldDefs.Add('CUSTOMERID', ftInteger, 0, True);
Table.FieldDefs.Add('FIRSTNAME', ftString, 50);
Table.FieldDefs.Add('LASTNAME', ftString, 50);
Table.FieldDefs.Add('GENDER', ftString, 50);
Table.FieldDefs.Add('EMAILADDRESS', ftString, 50);
Table.FieldDefs.Add('ADDRESS1', ftString, 50);
Table.FieldDefs.Add('ADDRESS2', ftString, 50);
Table.FieldDefs.Add('CITY', ftString, 50);
Table.FieldDefs.Add('ADDEDON', ftDateTime);
Table.CreateTable(False);
finally
FreeAndNil(Table);
end;
Table := TFDTable.Create(nil);
try
Table.Connection := FDConn;
Table.TableName := 'SUPPLIER';
Table.FieldDefs.Add('SUPPLIERID', ftInteger, 0, True);
Table.FieldDefs.Add('FIRSTNAME', ftString, 50);
Table.FieldDefs.Add('LASTNAME', ftString, 50);
Table.FieldDefs.Add('GENDER', ftString, 50);
Table.FieldDefs.Add('EMAILADDRESS', ftString, 50);
Table.FieldDefs.Add('ADDRESS1', ftString, 50);
Table.FieldDefs.Add('ADDRESS2', ftString, 50);
Table.FieldDefs.Add('CITY', ftString, 50);
Table.FieldDefs.Add('ADDEDON', ftDateTime);
Table.CreateTable(False);
finally
FreeAndNil(Table);
end;
Table := TFDTable.Create(nil);
try
Table.Connection := FDConn;
Table.TableName := 'STOCKITEM';
Table.FieldDefs.Add('STOCKITEMID', ftInteger, 0, True);
Table.FieldDefs.Add('PRODUCTCODE', ftString, 25, True);
Table.FieldDefs.Add('QUANTITYONHAND', ftInteger);
Table.FieldDefs.Add('LASTSTOCKQUQNTITY', ftInteger);
Table.FieldDefs.Add('ADDEDON', ftDateTime);
Table.CreateTable(False);
finally
FreeAndNil(Table);
end;
Table := TFDTable.Create(nil);
try
Table.Connection := FDConn;
Table.TableName := 'PRODUCT';
Table.FieldDefs.Add('PRODUCTID', ftInteger, 0, True);
Table.FieldDefs.Add('PRODUCTCODE', ftString, 25, True);
Table.FieldDefs.Add('PRODUCTNAME', ftString, 50, True);
Table.FieldDefs.Add('STANDARDCOST', ftFloat);
Table.FieldDefs.Add('SAFETYSTOCKLEVEL', ftSmallint);
Table.FieldDefs.Add('REORDERPOINT', ftSmallint);
Table.FieldDefs.Add('LISTPRICE', ftFloat);
Table.FieldDefs.Add('PRODUCTLINE', ftString, 2);
Table.FieldDefs.Add('DEALERPRICE', ftFloat);
Table.FieldDefs.Add('MODELNAME', ftString, 50);
Table.FieldDefs.Add('DESCRIPTION', ftString, 400);
Table.FieldDefs.Add('STATUS', ftSmallint);
Table.FieldDefs.Add('TAXTYPE', ftSmallint);
Table.FieldDefs.Add('ADDEDON', ftDateTime);
Table.CreateTable(False);
finally
FreeAndNil(Table);
end;
Table := TFDTable.Create(nil);
try
Table.Connection := FDConn;
Table.TableName := 'ORDERS';
Table.FieldDefs.Add('ORDERSID', ftInteger, 0, True);
Table.FieldDefs.Add('CUSTOMERID', ftInteger, 0, True);
Table.FieldDefs.Add('ORDERSDATE', ftDatetime, 0, True);
Table.FieldDefs.Add('STATUS', ftSmallInt, 0, True);
Table.FieldDefs.Add('PAYMENTTYPE', ftSmallint, 0, True);
Table.FieldDefs.Add('TRACKINGNUMBER', ftString, 50);
Table.FieldDefs.Add('ADDEDON', ftDateTime);
Table.CreateTable(False);
finally
FreeAndNil(Table);
end;
Table := TFDTable.Create(nil);
try
Table.Connection := FDConn;
Table.TableName := 'ORDERITEM';
Table.FieldDefs.Add('ORDERITEMID', ftInteger);
Table.FieldDefs.Add('ORDERID', ftInteger, 0, True);
Table.FieldDefs.Add('ORDERLINE', ftSmallInt);
Table.FieldDefs.Add('PRODUCTID', ftInteger, 0, True);
Table.FieldDefs.Add('QUANTITY', ftInteger, 0, True);
Table.FieldDefs.Add('UNITPRICE', ftFloat, 0, True);
Table.FieldDefs.Add('TAXTYPE', ftSmallint, 0, True);
Table.FieldDefs.Add('ADDEDON', ftDateTime);
Table.CreateTable(False);
finally
FreeAndNil(Table);
end;
end;
procedure TFDDatabase.PopulateData;
const
SqlInsertStockItem : String ='Insert Into STOCKITEM(STOCKITEMID, PRODUCTCODE, QUANTITYONHAND'+
', LASTSTOCKQUQNTITY, ADDEDON )' +
' Values ( %s, ''%s'', %s, %s, %s)';
SqlInsertProduct : String ='Insert Into PRODUCT (PRODUCTID, PRODUCTCODE, PRODUCTNAME'+
', STANDARDCOST, SAFETYSTOCKLEVEL, REORDERPOINT'+
', LISTPRICE, PRODUCTLINE, DEALERPRICE, MODELNAME'+
', DESCRIPTION, STATUS, TAXTYPE, ADDEDON )' +
' Values ( %s, ''%s'', ''%s'', %s, %s, %s' +
', %s, ''%s'', %s, ''%s'', ''%s'', %s, %s, %s)';
var
aSqlStr : String;
begin
aSqlStr := Format(SqlInsertStockItem,['551','FR-M21S-40','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['552','FD-2342','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['553','HB-T721','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['554','HB-T928','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['555','FB-9873','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['556','CS-4759','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['557','CS-6583','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['558','CS-9183','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['559','CH-0234','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['560','BK-T44U-60','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['561','BK-T79Y-46','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['562','BK-T79Y-50','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['563','BK-T79Y-54','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['564','BK-T79Y-60','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['565','BK-T18U-54','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['566','BK-T18U-58','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['567','BK-T18U-62','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['568','BK-T18Y-44','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['569','BK-T18Y-50','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['570','BK-T18Y-54','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['571','BK-T18Y-58','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['572','BK-T18Y-62','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['573','BK-T79U-46','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['574','BK-T79U-50','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['575','BK-T79U-54','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['576','BK-T79U-60','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['577','BK-T44U-46','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['578','BK-T44U-50','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['579','BK-T44U-54','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['580','BK-R79Y-40','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['581','BK-R79Y-42','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['582','BK-R79Y-44','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['583','BK-R79Y-48','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['584','BK-R19B-58','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['585','BK-T18U-44','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['586','BK-T18U-50','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['587','BK-M38S-38','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['588','BK-M38S-40','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['589','BK-M38S-42','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['590','BK-M38S-46','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['591','BK-M18S-40','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['592','BK-M18S-42','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['593','BK-M18S-44','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['594','BK-M18S-48','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['595','BK-M18S-52','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['596','BK-M18B-40','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['597','BK-M18B-42','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['598','BK-M18B-44','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['599','BK-M18B-48','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['600','BK-M18B-52','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['601','BB-7421','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['602','BB-8107','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['603','BB-9108','500','375',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['604','BK-R19B-44','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['605','BK-R19B-48','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertStockItem,['606','BK-R19B-52','100','75',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['551','FR-M21S-40','LL Mountain Frame - Silver 40','144.5938','500','375','264.05','M','158.43','LL Mountain Frame','Our best value utilizing the same ground-breaking frame technology as the ML aluminum frame','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['552','FD-2342', 'Front Derailleur', '40.6216','500','375','91.49', 'M','54.894','Front Derailleur', 'Wide-link design.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['553','HB-T721', 'LL Touring Handlebars', '20.464', '500','375','46.09', 'T','27.654','LL Touring Handlebars','Unique shape reduces fatigue for entry level riders','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['554','HB-T928', 'HL Touring Handlebars', '40.6571','500','375','91.57', 'T','54.942','HL Touring Handlebars','A light yet stiff aluminum bar for long distance riding','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['555','FB-9873', 'Front Brakes', '47.286', '500','375','106.50','T','63.90','Front Brakes','All-weather brake pads; provides superior stopping by applying more surface to the rim','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['556','CS-4759', 'LL Crankset', '77.9176','500','375','175.49','T','105.294','LL','Crankset Super rigid spindle','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['557','CS-6583', 'ML Crankset', '113.8816','500','375','256.49','T','153.894','ML','Crankset High-strength crank arm','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['558','CS-9183','HL Crankset','179.8156','500','375','404.99','T','242.994','HL','Crankset Triple crankset; alumunim crank arm; flawless shifting.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['559','CH-0234','Chain','8.9866','500','375','20.24','T','12.144','C','Superior shifting performance.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['560','BK-T44U-60','Touring-2000 Blue 60','755.1508','100','75','1214.85','T','28.91','Touring-2000','The plush custom saddle keeps you riding all day and there plenty of space to add panniers and bike bags to the newly-redesigned carrier. This bike has stability when fully-loaded.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['561','BK-T79Y-46','Touring-1000 Yellow 46','1481.9379','100','75','2384.07','T','1430.442','Touring-1000','Travel in style and comfort. Designed for maximum comfort and safety. Wide gear range takes on all hills. High-tech aluminum alloy construction provides durability without added weight.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['562','BK-T79Y-50','Touring-1000 Yellow 50','1481.9379','100','75','2384.07','T','1430.442','Touring-1000','Travel in style and comfort. Designed for maximum comfort and safety. Wide gear range takes on all hills. High-tech aluminum alloy construction provides durability without added weight.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['563','BK-T79Y-54','Touring-1000 Yellow 54','1481.9379','100','75','2384.07','T','1430.442','Touring-1000','Travel in style and comfort. Designed for maximum comfort and safety. Wide gear range takes on all hills. High-tech aluminum alloy construction provides durability without added weight.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['564','BK-T79Y-60','Touring-1000 Yellow 60','1481.9379','100','75','2384.07','T','1430.442','Touring-1000','Travel in style and comfort. Designed for maximum comfort and safety. Wide gear range takes on all hills. High-tech aluminum alloy construction provides durability without added weight.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['565','BK-T18U-54','Touring-3000 Blue 54','461.4448','100','75','742.35','T','445.41','Touring-3000','All-occasion value bike with our basic comfort and safety features. Offers wider more stable tires for a ride around town or weekend trip.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['566','BK-T18U-58','Touring-3000 Blue 58','461.4448','100','75','742.35','T','445.41','Touring-3000','All-occasion value bike with our basic comfort and safety features. Offers wider more stable tires for a ride around town or weekend trip.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['567','BK-T18U-62','Touring-3000 Blue 62','461.4448','100','75','742.35','T','445.41','Touring-3000','All-occasion value bike with our basic comfort and safety features. Offers wider more stable tires for a ride around town or weekend trip.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['568','BK-T18Y-44','Touring-3000 Yellow 44','461.4448','100','75','742.35','T','445.41','Touring-3000','All-occasion value bike with our basic comfort and safety features. Offers wider more stable tires for a ride around town or weekend trip.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['569','BK-T18Y-50','Touring-3000 Yellow 50','461.4448','100','75','742.35','T','445.41','Touring-3000','All-occasion value bike with our basic comfort and safety features. Offers wider more stable tires for a ride around town or weekend trip.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['570','BK-T18Y-54','Touring-3000 Yellow 54','461.4448','100','75','742.35','T','445.41','Touring-3000','All-occasion value bike with our basic comfort and safety features. Offers wider more stable tires for a ride around town or weekend trip.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['571','BK-T18Y-58','Touring-3000 Yellow 58','461.4448','100','75','742.35','T','445.41','Touring-3000','All-occasion value bike with our basic comfort and safety features. Offers wider more stable tires for a ride around town or weekend trip.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['572','BK-T18Y-62','Touring-3000 Yellow 62','461.4448','100','75','742.35','T','445.41','Touring-3000','All-occasion value bike with our basic comfort and safety features. Offers wider more stable tires for a ride around town or weekend trip.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['573','BK-T79U-46','Touring-1000 Blue 46','1481.9379','100','75','2384.07','T','1430.442','Touring-1000','Travel in style and comfort. Designed for maximum comfort and safety. Wide gear range takes on all hills. High-tech aluminum alloy construction provides durability without added weight.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['574','BK-T79U-50','Touring-1000 Blue 50','1481.9379','100','75','2384.07','T','1430.442','Touring-1000','Travel in style and comfort. Designed for maximum comfort and safety. Wide gear range takes on all hills. High-tech aluminum alloy construction provides durability without added weight.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['575','BK-T79U-54','Touring-1000 Blue 54','1481.9379','100','75','2384.07','T','1430.442','Touring-1000','Travel in style and comfort. Designed for maximum comfort and safety. Wide gear range takes on all hills. High-tech aluminum alloy construction provides durability without added weight.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['576','BK-T79U-60','Touring-1000 Blue 60','1481.9379','100','75','2384.07','T','1430.442','Touring-1000','Travel in style and comfort. Designed for maximum comfort and safety. Wide gear range takes on all hills. High-tech aluminum alloy construction provides durability without added weight.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['577','BK-T44U-46','Touring-2000 Blue 46','755.1508','100','75','1214.85','T','728.91','Touring-2000','The plush custom saddle keeps you riding all day and theres plenty of space to add panniers and bike bags to the newly-redesigned carrier. This bike has stability when fully-loaded.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['578','BK-T44U-50','Touring-2000 Blue 50','755.1508','100','75','1214.85','T','728.91','Touring-2000','The plush custom saddle keeps you riding all day and theres plenty of space to add panniers and bike bags to the newly-redesigned carrier. This bike has stability when fully-loaded.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['579','BK-T44U-54','Touring-2000 Blue 54','755.1508','100','75','1214.85','T','728.91','Touring-2000','The plush custom saddle keeps you riding all day and theres plenty of space to add panniers and bike bags to the newly-redesigned carrier. This bike has stability when fully-loaded.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['580','BK-R79Y-40','Road-350-W Yellow 40','1082.51','100','75','1700.99','R','1020.594','Road-350-W','Cross-train race or just socialize on a sleek aerodynamic bike designed for a woman. Advanced seat technology provides comfort all day.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['581','BK-R79Y-42','Road-350-W Yellow 42','1082.51','100','75','1700.99','R','1020.594','Road-350-W','Cross-train race or just socialize on a sleek aerodynamic bike designed for a woman. Advanced seat technology provides comfort all day.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['582','BK-R79Y-44','Road-350-W Yellow 44','1082.51','100','75','1700.99','R','1020.594','Road-350-W','Cross-train race or just socialize on a sleek aerodynamic bike designed for a woman. Advanced seat technology provides comfort all day.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['583','BK-R79Y-48','Road-350-W Yellow 48','1082.51','100','75','1700.99','R','1020.594','Road-350-W','Cross-train race or just socialize on a sleek aerodynamic bike designed for a woman. Advanced seat technology provides comfort all day.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['584','BK-R19B-58','Road-750 Black 58','343.6496','100','75','539.99','R','323.994','Road-750','Entry level adult bike; offers a comfortable ride cross-country or down the block. Quick-release hubs and rims.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['585','BK-T18U-44','Touring-3000 Blue 44','461.4448','100','75','742.35','T','445.41','Touring-3000','All-occasion value bike with our basic comfort and safety features. Offers wider more stable tires for a ride around town or weekend trip.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['586','BK-T18U-50','Touring-3000 Blue 50','461.4448','100','75','742.35','T','445.41','Touring-3000','All-occasion value bike with our basic comfort and safety features. Offers wider more stable tires for a ride around town or weekend trip.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['587','BK-M38S-38','Mountain-400-W Silver 38','419.7784','100','75','769.49','M','461.694','Mountain-400-W','This bike delivers a high-level of performance on a budget. It is responsive and maneuverable and offers peace-of-mind when you decide to go off-road.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['588','BK-M38S-40','Mountain-400-W Silver 40','419.7784','100','75','769.49','M','461.694','Mountain-400-W','This bike delivers a high-level of performance on a budget. It is responsive and maneuverable and offers peace-of-mind when you decide to go off-road.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['589','BK-M38S-42','Mountain-400-W Silver 42','419.7784','100','75','769.49','M','461.694','Mountain-400-W','This bike delivers a high-level of performance on a budget. It is responsive and maneuverable and offers peace-of-mind when you decide to go off-road.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['590','BK-M38S-46','Mountain-400-W Silver 46','419.7784','100','75','769.49','M','461.694','Mountain-400-W','This bike delivers a high-level of performance on a budget. It is responsive and maneuverable and offers peace-of-mind when you decide to go off-road.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['591','BK-M18S-40','Mountain-500 Silver 40','308.2179','100','75','564.99','M','338.994','Mountain-500','Suitable for any type of riding on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['592','BK-M18S-42','Mountain-500 Silver 42','308.2179','100','75','564.99','M','338.994','Mountain-500','Suitable for any type of riding on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['593','BK-M18S-44','Mountain-500 Silver 44','308.2179','100','75','564.99','M','338.994','Mountain-500','Suitable for any type of riding on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['594','BK-M18S-48','Mountain-500 Silver 48','308.2179','100','75','564.99','M','338.994','Mountain-500','Suitable for any type of riding on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['595','BK-M18S-52','Mountain-500 Silver 52','308.2179','100','75','564.99','M','338.994','Mountain-500','Suitable for any type of riding on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['596','BK-M18B-40','Mountain-500 Black 40','294.5797','100','75','539.99','M','323.994','Mountain-500','Suitable for any type of riding on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['597','BK-M18B-42','Mountain-500 Black 42','294.5797','100','75','539.99','M','323.994','Mountain-500','Suitable for any type of riding on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['598','BK-M18B-44','Mountain-500 Black 44','294.5797','100','75','539.99','M','323.994','Mountain-500','Suitable for any type of riding on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['599','BK-M18B-48','Mountain-500 Black 48','294.5797','100','75','539.99','M','323.994','Mountain-500','Suitable for any type of riding on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['600','BK-M18B-52','Mountain-500 Black 52','294.5797','100','75','539.99','M','323.994','Mountain-500','Suitable for any type of riding on or off-road. Fits any budget. Smooth-shifting with a comfortable ride.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['601','BB-7421', 'LL Bottom Bracket', '23.9716', '500','375','53.99','T','32.394', 'LL', 'Bottom Bracket Chromoly steel.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['602','BB-8107', 'ML Bottom Bracket', '44.9506', '500','375','101.24','T','60.744','ML', 'Bottom Bracket Aluminum alloy cups; large diameter spindle.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['603','BB-9108', 'HL Bottom Bracket', '53.9416', '500','375','121.49','T','72.894','HL', 'Bottom Bracket Aluminum alloy cups and a hollow axle.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['604','BK-R19B-44','Road-750 Black 44','343.6496','100','75','539.99', 'R','323.994','Road-750', 'Entry level adult bike; offers a comfortable ride cross-country or down the block. Quick-release hubs and rims.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['605','BK-R19B-48','Road-750 Black 48','343.6496','100','75','539.99', 'R','323.994','Road-750', 'Entry level adult bike; offers a comfortable ride cross-country or down the block. Quick-release hubs and rims.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
aSqlStr := Format(SqlInsertProduct,['606','BK-R19B-52','Road-750 Black 52','343.6496','100','75','539.99', 'R','323.994','Road-750', 'Entry level adult bike; offers a comfortable ride cross-country or down the block. Quick-release hubs and rims.','1','0',QuotedStr(FormatDateTime('dd.mm.yyyy hh:nn',NOW))]);
FDConn.ExecSQL(aSqlStr);
end;
end.
|
Unit VersionSupport;
{* Проверка на правильность номера версии }
{ Автор: Дудко Д.В. }
{ Модуль: VersionSupport}
{ Начат: 01.10.2002 }
{ $Id: VersionSupport.pas,v 1.7 2004/12/23 11:47:02 lulin Exp $ }
// $Log: VersionSupport.pas,v $
// Revision 1.7 2004/12/23 11:47:02 lulin
// - rename unit: User_Cfg -> l3IniFile.
//
// Revision 1.6 2003/12/05 17:05:11 voba
// - add procedure CompareLongVersions
//
// Revision 1.5 2002/10/16 10:58:05 narry
// - new behavior: больше не обновляет файл с версией, добавлен параметр максимальной версии
//
// Revision 1.4 2002/10/15 06:27:22 narry
// - new behavior: обновление номера версии
//
// Revision 1.3 2002/10/02 06:48:55 narry
// - bug fix: ошибки синтаксиса
//
// Revision 1.2 2002/10/01 14:53:13 narry
// - update
//
// Revision 1.1 2002/10/01 14:30:26 voba
// Проверка номера версии Архивариуса
//
interface
function IsValidVersion: Boolean;
implementation
Uses
vtVerInf, l3IniFile, l3FileUtils, SysUtils;
function VersionFileName: String;
var
S: ShortString;
begin
ServerConfig.Section:= 'FamilyConst';
S:= ServerConfig.ReadParamStrDef('FamilyPath', '');
Result:= ConcatDirName(S, 'archi.version');
end;
function IsValidVersion: Boolean;
var
l_MyVersion : TLongVersion;
l_ArchiVersionLo,
l_ArchiVersionHi: String;
begin
with TVersionInfo.Create, FileLongVersion do
try
l_MyVersion := FileLongVersion;
finally
Free;
end; // with
l_ArchiVersionLo:= '0.0.0.0';
l_ArchiVersionHi:= '9.9.9.9';
if FileExists(VersionFileName) then
begin
with TCfgList.Create(VersionFileName)do
try
Section:= 'Version';
l_ArchiVersionLo:= ReadParamStrDef('Ver', l_ArchiVersionLo);
l_ArchiVersionHi:= ReadParamStrDef('VerMax', l_ArchiVersionHi);
finally
Free;
end; // try..finally
end;
Result := (CompareLongVersions(l_MyVersion, StringToLongVersion(l_ArchiVersionLo)) >= 0) and
(CompareLongVersions(l_MyVersion, StringToLongVersion(l_ArchiVersionHi)) <= 0);
end;
end. |
namespace Sugar.Threading;
interface
type
{$IF COOPER}
Semaphore = public class mapped to java.util.concurrent.Semaphore
public
method Leave; mapped to release;
method Leave(aReleaseCount: Integer); mapped to release(aReleaseCount);
method WaitOne; mapped to acquire;
method WaitOne(aTimeout: Integer); mapped to tryAcquire(aTimeout, java.util.concurrent.TimeUnit.MILLISECONDS);
end;
{$ELSEIF ECHOES}
Semaphore = public class mapped to System.Threading.Semaphore
public
method Leave; mapped to Release;
method Leave(aReleaseCount: Integer); mapped to Release(aReleaseCount);
method WaitOne; mapped to WaitOne;
method WaitOne(aTimeout: Integer); mapped to WaitOne(aTimeout);
end;
{$ELSEIF TOFFEE}
Semaphore = public class mapped to Foundation.NSRecursiveLock
method Leave; mapped to unlock;
method Leave(aReleaseCount: Integer);
method WaitOne; mapped to lock;
method WaitOne(aTimeout: Integer);
end;
{$ENDIF}
implementation
{$IF TOFFEE}
method Semaphore.Leave(aReleaseCount: Integer);
begin
for i: Int32 := 0 to aReleaseCount-1 do mapped.unlock;
end;
method Semaphore.WaitOne(aTimeout: Integer);
begin
mapped.lockBeforeDate(Foundation.NSDate.dateWithTimeIntervalSinceNow(aTimeout*1000)); // ms to s
end;
{$ENDIF}
end. |
unit FFSColorLabel;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, FFSTypes;
type
TFFSColorLabel = class(tlabel)
private
FFieldsColorScheme: TFieldsColorScheme;
procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange;
procedure SetFieldsColorScheme(const Value: TFieldsColorScheme);
protected
{ Protected declarations }
public
constructor create(AOwner:TComponent);override;
published
property FieldsColorScheme:TFieldsColorScheme read FFieldsColorScheme write SetFieldsColorScheme;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Controls', [TFFSColorLabel]);
end;
{ TFFSColorLabel }
constructor TFFSColorLabel.create(AOwner: TComponent);
begin
inherited;
font.Color := FFSColor[fcsDataUnderline];
end;
procedure TFFSColorLabel.MsgFFSColorChange(var Msg: TMessage);
begin
font.color := FFSColor[FFieldsColorScheme];
end;
procedure TFFSColorLabel.SetFieldsColorScheme(
const Value: TFieldsColorScheme);
begin
FFieldsColorScheme := Value;
font.color := FFSColor[FFieldsColorScheme];
end;
end.
|
unit TokyoScript.Keywords;
{
TokyoScript (c)2018 Execute SARL
http://www.execute.Fr
}
interface
uses
System.SysUtils;
type
TKeyword = (
kw_None,
kwAnd,
kwArray,
kwAs,
kwBegin,
kwCase,
kwChr,
kwClass,
kwConst,
kwConstructor,
kwDestructor,
kwDiv,
kwDo,
kwDownto,
kwElse,
kwEnd,
kwExcept,
kwExit,
kwExport,
kwExternal,
kwFinalization,
kwFinally,
kwFor,
kwForward,
kwFunction,
kwGoto,
kwIf,
kwImplementation,
kwIn,
kwInherited,
kwInitialization,
kwInterface,
kwIs,
kwLabel,
kwMod,
kwNil,
kwNot,
kwOf,
kwOr,
kwOrd,
kwOut,
kwOverride,
kwPrivate,
kwProcedure,
kwProgram,
kwProperty,
kwProtected,
kwPublic,
kwPublished,
kwRecord,
kwRepeat,
kwSet,
kwShl,
kwShr,
kwThen,
kwTo,
kwTry,
kwType,
kwUnit,
kwUntil,
kwUses,
kwVar,
kwVirtual,
kwWhile,
kwWith,
kwXor
);
TKeywords = set of TKeyword;
const
KEYWORDS: array[TKeyword] of string = (
'',
'AND',
'ARRAY',
'AS',
'BEGIN',
'CASE',
'CHR',
'CLASS',
'CONST',
'CONSTRUCTOR',
'DESTRUCTOR',
'DIV',
'DO',
'DOWNTO',
'ELSE',
'END',
'EXCEPT',
'EXIT',
'EXPORT',
'EXTERNAL',
'FINALIZATION',
'FINALLY',
'FOR',
'FORWARD',
'FUNCTION',
'GOTO',
'IF',
'IMPLEMENTATION',
'IN',
'INHERITED',
'INITIALIZATION',
'INTERFACE',
'IS',
'LABEL',
'MOD',
'NIL',
'NOT',
'OF',
'OR',
'ORD',
'OUT',
'OVERRIDE',
'PRIVATE',
'PROCEDURE',
'PROGRAM',
'PROPERTY',
'PROTECTED',
'PUBLIC',
'PUBLISHED',
'RECORD',
'REPEAT',
'SET',
'SHL',
'SHR',
'THEN',
'TO',
'TRY',
'TYPE',
'UNIT',
'UNTIL',
'USES',
'VAR',
'VIRTUAL',
'WHILE',
'WITH',
'XOR'
);
function GetKeyword(Str: string): TKeyword;
implementation
const
KW2: array[0..7] of TKeyword = (
kwAs,
kwDo,
kwIf,
kwIn,
kwIs,
kwOf,
kwOr,
kwTo
);
KW3: array[0..17] of TKeyword = (
kwAnd,
kwChr,
kwDiv,
kwEnd,
kwFor,
kwMod,
kwSet,
kwVar,
kwNil,
kwNot,
kwOrd,
kwOut,
kwSet,
kwShl,
kwShr,
kwTry,
kwVar,
kwXor
);
KW4: array[0..8] of TKeyword = (
kwCase,
kwElse,
kwExit,
kwGoto,
kwThen,
kwType,
kwUnit,
kwUses,
kwWith
);
KW5: array[0..6] of TKeyword = (
kwArray,
kwBegin,
kwClass,
kwConst,
kwLabel,
kwUntil,
kwWhile
);
KW6: array[0..5] of TKeyword = (
kwDownto,
kwExcept,
kwExport,
kwPublic,
kwRecord,
kwRepeat
);
KW7: array[0..4] of TKeyword = (
kwFinally,
kwForward,
kwPrivate,
kwProgram,
kwVirtual
);
KW8: array[0..3] of TKeyword = (
kwExternal,
kwFunction,
kwOverride,
kwProperty
);
KW9: array[0..4] of TKeyword = (
kwInherited,
kwInterface,
kwProcedure,
kwProtected,
kwPublished
);
KW10: array[0..0] of TKeyword = (
kwDestructor
);
KW11: array[0..0] of TKeyword = (
kwConstructor
);
KW12: array[0..0] of TKeyword = (
kwFinalization
);
KW14: array[0..1] of TKeyword = (
kwImplementation,
kwInitialization
);
function IsKeyword(const AKeywords: array of TKeyword; const AStr: string): TKeyword;
var
Index: Integer;
begin
for Index := 0 to Length(AKeywords) - 1 do
begin
Result := AKeywords[Index];
if KEYWORDS[Result] = AStr then
Exit;
end;
Result := kw_None;
end;
function GetKeyword(Str: string): TKeyword;
var
Index: Integer;
begin
Str := UpperCase(Str);
case Length(Str) of
2 : Result := IsKeyword(KW2, Str);
3 : Result := IsKeyword(KW3, Str);
4 : Result := IsKeyword(KW4, Str);
5 : Result := IsKeyword(KW5, Str);
6 : Result := IsKeyword(KW6, Str);
7 : Result := IsKeyword(KW7, Str);
8 : Result := IsKeyword(KW8, Str);
9 : Result := IsKeyword(KW9, Str);
10 : Result := IsKeyword(KW10, Str);
11 : Result := IsKeyword(KW11, Str);
12 : Result := IsKeyword(KW12, Str);
14 : Result := IsKeyword(KW14, Str);
else
Result := kw_None;
end;
end;
end.
|
unit MLInt;
interface
uses MLObj;
type
MLInteger = ^MLIntegerObj;
MLIntegerObj = object(MLObjectObj)
constructor init(val : integer);
(* destructor done; virtual; *)
function asString : string; virtual;
function isEqualTo(o : MLObject) : boolean; virtual;
function isLessThan(o : MLObject) : boolean; virtual;
private
val : integer;
end;
function newInteger(val : integer) : MLInteger;
implementation
function newInteger(val : integer) : MLInteger;
var i : MLInteger;
begin
new(i, init(val));
newInteger := i;
end;
constructor MLIntegerObj.init(val : integer);
begin
inherited init;
register('MLInteger', 'MLObject');
self.val := val;
end;
function MLIntegerObj.asString : string;
var s : string;
begin
str(val, s);
asString := s;
end;
function MLIntegerObj.isEqualTo(o : MLObject) : boolean;
var other : MLInteger;
begin
if o^.Class = 'MLInteger' then begin
other := MLInteger(o);
isEqualTo := SELF.val = other^.val;
end else
isEqualTo := FALSE;
end;
function MLIntegerObj.isLessThan(o : MLObject) : boolean;
var other : MLInteger;
begin
if o^.class = 'MLInteger' then begin
other := MLInteger(o);
isLessThan := self.val < other^.val;
end else
isLessThan := FALSE;
end;
begin
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpECCurve;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
SyncObjs,
SysUtils,
Generics.Collections,
ClpIPreCompCallback,
ClpECPoint,
ClpCryptoLibTypes,
ClpBigInteger,
ClpBits,
ClpIGlvEndomorphism,
ClpECAlgorithms,
ClpIECFieldElement,
ClpECFieldElement,
ClpLongArray,
ClpGlvMultiplier,
ClpWNafL2RMultiplier,
ClpWTauNafMultiplier,
ClpFiniteFields,
ClpTnaf,
ClpIECInterface,
ClpIFiniteField,
ClpIPreCompInfo;
resourcestring
SUnSupportedCoordinateSystem = 'UnSupported Coordinate System';
SCurrentCurve = 'Implementation returned Current Curve';
SInvalidPointCoordinates = 'Invalid Point Coordinates';
SInvalidAffineCoordinates = 'not valid for affine coordinates, "iso"';
SInvalidPointOnCurve = 'must be non-null and on this curve, "point"';
SInvalidPointOnCurve2 = 'Entries must be null or on this curve, "points"';
SPointsNil = 'points';
SInvalidRangeSpecified = 'Invalid Range Specified", "points"';
SInvalidPointCompression = 'Invalid Point Compression';
SInvalidK1 = 'k1 must be > 0';
SInvalidK3 = 'k3 must be 0 if k2 == 0';
SK2K1MisMatch = 'k2 must be > k1';
SK3K2Mismatch = 'k3 must be > k2';
SInvalidInfinityEncoding = 'Invalid Infinity Encoding, "encoded"';
SInvalidPointEncoding = 'Invalid Point Encoding %u';
SIncorrectLengthInfinityEncoding =
'Incorrect Length for infinity encoding", "encoded"';
SIncorrectLengthCompressedEncoding =
'Incorrect Length for Compressed Encoding", "encoded"';
SInvalidPoint = 'Invalid Point';
SIncorrectLengthUnCompressedEncoding =
'Incorrect Length for UnCompressed Encoding", "encoded"';
SIncorrectLengthHybridEncoding =
'Incorrect Length for Hybrid Encoding", "encoded"';
SInConsistentYCoord =
'Inconsistent Y Coordinate in Hybrid Encoding", "encoded"';
type
/// <summary>
/// Base class for an elliptic curve.
/// </summary>
TECCurve = class abstract(TInterfacedObject, IECCurve)
strict private
procedure SetCoord(const Value: Int32); inline;
procedure SetEndomorphism(const Value: IECEndomorphism); inline;
procedure SetMultiplier(const Value: IECMultiplier); inline;
function GetField: IFiniteField; virtual;
function GetA: IECFieldElement; virtual;
function GetB: IECFieldElement; virtual;
function GetOrder: TBigInteger; virtual;
function GetCofactor: TBigInteger; virtual;
function GetCoordinateSystem: Int32; virtual;
class constructor CreateECCurve();
class destructor DestroyECCurve();
strict protected
class var
FLock: TCriticalSection;
var
Fm_field: IFiniteField;
Fm_order, Fm_cofactor: TBigInteger;
Fm_coord: Int32;
Fm_endomorphism: IECEndomorphism;
Fm_multiplier: IECMultiplier;
Fm_a, Fm_b: IECFieldElement;
constructor Create(const field: IFiniteField);
function GetFieldSize: Int32; virtual; abstract;
function GetInfinity: IECPoint; virtual; abstract;
function CloneCurve(): IECCurve; virtual; abstract;
function CreateRawPoint(const x, y: IECFieldElement;
withCompression: Boolean): IECPoint; overload; virtual; abstract;
function CreateRawPoint(const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>;
withCompression: Boolean): IECPoint; overload; virtual; abstract;
function CreateDefaultMultiplier(): IECMultiplier; virtual;
procedure CheckPoint(const point: IECPoint); virtual;
procedure CheckPoints(const points: TCryptoLibGenericArray<IECPoint>);
overload; virtual;
procedure CheckPoints(const points: TCryptoLibGenericArray<IECPoint>;
off, len: Int32); overload; virtual;
function DecompressPoint(yTilde: Int32; const X1: TBigInteger): IECPoint;
virtual; abstract;
public
const
COORD_AFFINE = Int32(0);
COORD_HOMOGENEOUS = Int32(1);
COORD_JACOBIAN = Int32(2);
COORD_JACOBIAN_CHUDNOVSKY = Int32(3);
COORD_JACOBIAN_MODIFIED = Int32(4);
COORD_LAMBDA_AFFINE = Int32(5);
COORD_LAMBDA_PROJECTIVE = Int32(6);
COORD_SKEWED = Int32(7);
type
TConfig = class(TInterfacedObject, IConfig)
strict protected
var
Fouter: IECCurve;
Fcoord: Int32;
Fendomorphism: IECEndomorphism;
Fmultiplier: IECMultiplier;
public
constructor Create(const outer: IECCurve; coord: Int32;
const endomorphism: IECEndomorphism;
const multiplier: IECMultiplier); overload;
destructor Destroy(); override;
function SetCoordinateSystem(coord: Int32): IConfig; inline;
function SetEndomorphism(const endomorphism: IECEndomorphism)
: IConfig; inline;
function SetMultiplier(const multiplier: IECMultiplier): IConfig; inline;
function CreateCurve(): IECCurve;
end;
function FromBigInteger(const x: TBigInteger): IECFieldElement;
virtual; abstract;
function IsValidFieldElement(const x: TBigInteger): Boolean; virtual;
abstract;
function Configure(): IConfig; virtual;
function ValidatePoint(const x, y: TBigInteger): IECPoint; overload; virtual;
function ValidatePoint(const x, y: TBigInteger; withCompression: Boolean)
: IECPoint; overload; virtual;
deprecated 'Per-point compression property will be removed';
/// <summary>
/// Create a cache-safe lookup table for the specified sequence of points.
/// All the points MUST <br />belong to this <c>ECCurve</c> instance, and
/// MUST already be normalized.
/// </summary>
function CreateCacheSafeLookupTable(const points
: TCryptoLibGenericArray<IECPoint>; off, len: Int32)
: IECLookupTable; virtual;
function CreatePoint(const x, y: TBigInteger): IECPoint; overload; virtual;
function CreatePoint(const x, y: TBigInteger; withCompression: Boolean)
: IECPoint; overload; virtual;
deprecated 'Per-point compression property will be removed';
function SupportsCoordinateSystem(coord: Int32): Boolean; virtual;
function GetPreCompInfo(const point: IECPoint; const name: String)
: IPreCompInfo; virtual;
/// <summary>
/// Compute a <c>PreCompInfo</c> for a point on this curve, under a given
/// name. Used by <c>ECMultiplier</c> to save the precomputation for this <c>
/// ECPoint</c> for use by subsequent multiplication.
/// </summary>
/// <param name="point">
/// The <c>ECPoint</c> to store precomputations for.
/// </param>
/// <param name="name">
/// A <c>String</c> used to index precomputations of different types.
/// </param>
/// <param name="callback">
/// Called to calculate the <c>PreCompInfo</c>
/// </param>
function Precompute(const point: IECPoint; const name: String;
const callback: IPreCompCallback): IPreCompInfo; virtual;
function ImportPoint(const p: IECPoint): IECPoint; virtual;
/// <summary>
/// Normalization ensures that any projective coordinate is 1, and
/// therefore that the x, y coordinates reflect those of the equivalent
/// point in an affine coordinate system. Where more than one point is to
/// be normalized, this method will generally be more efficient than
/// normalizing each point separately.
/// </summary>
/// <param name="points">
/// An array of points that will be updated in place with their normalized
/// versions, where necessary
/// </param>
procedure NormalizeAll(const points: TCryptoLibGenericArray<IECPoint>);
overload; virtual;
/// <summary>
/// Normalization ensures that any projective coordinate is 1, and
/// therefore that the x, y coordinates reflect those of the equivalent
/// point in an affine coordinate system. Where more than one point is to
/// be normalized, this method will generally be more efficient than
/// normalizing each point separately. An (optional) z-scaling factor can
/// be applied; effectively each z coordinate is scaled by this value prior
/// to normalization (but only one actual multiplication is needed).
/// </summary>
/// <param name="points">
/// An array of points that will be updated in place with their normalized
/// versions, where necessary
/// </param>
/// <param name="off">
/// The start of the range of points to normalize
/// </param>
/// <param name="len">
/// The length of the range of points to normalize
/// </param>
/// <param name="iso">
/// The (optional) z-scaling factor - can be null
/// </param>
procedure NormalizeAll(const points: TCryptoLibGenericArray<IECPoint>;
off, len: Int32; const iso: IECFieldElement); overload; virtual;
function GetEndomorphism(): IECEndomorphism; virtual;
/// <summary>
/// Sets the default <c>ECMultiplier</c>, unless already set.
/// </summary>
function GetMultiplier(): IECMultiplier; virtual;
/// <summary>
/// Decode a point on this curve from its ASN.1 encoding. The different
/// encodings are taken account of, including point compression for <br /><c>
/// F</c><b>p</b> (X9.62 s 4.2.1 pg 17).
/// </summary>
/// <returns>
/// The decoded point.
/// </returns>
function DecodePoint(const encoded: TCryptoLibByteArray): IECPoint; virtual;
property coord: Int32 write SetCoord;
property endomorphism: IECEndomorphism write SetEndomorphism;
property multiplier: IECMultiplier write SetMultiplier;
property FieldSize: Int32 read GetFieldSize;
property Infinity: IECPoint read GetInfinity;
property field: IFiniteField read GetField;
property A: IECFieldElement read GetA;
property B: IECFieldElement read GetB;
property Order: TBigInteger read GetOrder;
property Cofactor: TBigInteger read GetCofactor;
property CoordinateSystem: Int32 read GetCoordinateSystem;
function Equals(const other: IECCurve): Boolean; reintroduce;
function GetHashCode(): {$IFDEF DELPHI}Int32; {$ELSE}PtrInt;
{$ENDIF DELPHI}override;
destructor Destroy; override;
class function GetAllCoordinateSystems(): TCryptoLibInt32Array;
static; inline;
end;
type
TDefaultLookupTable = class(TInterfacedObject, IDefaultLookupTable,
IECLookupTable)
strict private
var
Fm_outer: IECCurve;
Fm_table: TCryptoLibByteArray;
Fm_size: Int32;
public
constructor Create(const outer: IECCurve; const table: TCryptoLibByteArray;
size: Int32);
function GetSize: Int32; virtual;
function Lookup(index: Int32): IECPoint; virtual;
property size: Int32 read GetSize;
end;
type
TAbstractFpCurve = class(TECCurve, IAbstractFpCurve)
strict protected
constructor Create(const q: TBigInteger);
function DecompressPoint(yTilde: Int32; const X1: TBigInteger)
: IECPoint; override;
public
destructor Destroy; override;
function IsValidFieldElement(const x: TBigInteger): Boolean; override;
end;
type
TDefaultF2mLookupTable = class(TInterfacedObject, IDefaultF2mLookupTable,
IECLookupTable)
strict private
var
Fm_outer: IF2mCurve;
Fm_table: TCryptoLibInt64Array;
Fm_size: Int32;
public
constructor Create(const outer: IF2mCurve;
const table: TCryptoLibInt64Array; size: Int32);
function GetSize: Int32; virtual;
function Lookup(index: Int32): IECPoint; virtual;
property size: Int32 read GetSize;
end;
type
TFpCurve = class(TAbstractFpCurve, IFpCurve)
strict private
const
FP_DEFAULT_COORDS = Int32(TECCurve.COORD_JACOBIAN_MODIFIED);
strict protected
var
Fm_q, Fm_r: TBigInteger;
Fm_infinity: IFpPoint;
constructor Create(const q, r: TBigInteger; const A, B: IECFieldElement);
overload; deprecated 'Use constructor taking order/cofactor';
constructor Create(const q, r: TBigInteger; const A, B: IECFieldElement;
const Order, Cofactor: TBigInteger); overload;
function GetQ: TBigInteger; virtual;
function GetInfinity: IECPoint; override;
function GetFieldSize: Int32; override;
function CloneCurve(): IECCurve; override;
function CreateRawPoint(const x, y: IECFieldElement;
withCompression: Boolean): IECPoint; overload; override;
function CreateRawPoint(const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>;
withCompression: Boolean): IECPoint; overload; override;
public
constructor Create(const q, A, B: TBigInteger); overload;
deprecated 'Use constructor taking order/cofactor';
constructor Create(const q, A, B, Order, Cofactor: TBigInteger); overload;
destructor Destroy; override;
function FromBigInteger(const x: TBigInteger): IECFieldElement; override;
function ImportPoint(const p: IECPoint): IECPoint; override;
function SupportsCoordinateSystem(coord: Int32): Boolean; override;
property q: TBigInteger read GetQ;
property Infinity: IECPoint read GetInfinity;
property FieldSize: Int32 read GetFieldSize;
end;
type
TAbstractF2mCurve = class abstract(TECCurve, IAbstractF2mCurve)
strict private
/// <summary>
/// The auxiliary values <c>s</c><b>0</b> and <c>s</c><b>1</b> used for
/// partial modular reduction for Koblitz curves.
/// </summary>
Fsi: TCryptoLibGenericArray<TBigInteger>;
class function BuildField(m, k1, k2, k3: Int32): IFiniteField; static;
strict protected
constructor Create(m, k1, k2, k3: Int32);
/// <summary>
/// Returns true if this is a Koblitz curve (ABC curve).
/// </summary>
/// <returns>
/// true if this is a Koblitz curve (ABC curve), false otherwise
/// </returns>
function GetIsKoblitz: Boolean; virtual;
function DecompressPoint(yTilde: Int32; const X1: TBigInteger)
: IECPoint; override;
// /**
// * Solves a quadratic equation <code>z<sup>2</sup> + z = beta</code>(X9.62
// * D.1.6) The other solution is <code>z + 1</code>.
// *
// * @param beta
// * The value to solve the qradratic equation for.
// * @return the solution for <code>z<sup>2</sup> + z = beta</code> or
// * <code>null</code> if no solution exists.
// */
function SolveQuadraticEquation(const beta: IECFieldElement)
: IECFieldElement;
public
destructor Destroy; override;
function IsValidFieldElement(const x: TBigInteger): Boolean; override;
function CreatePoint(const x, y: TBigInteger; withCompression: Boolean)
: IECPoint; override;
deprecated 'Per-point compression property will be removed';
// /**
// * @return the auxiliary values <code>s<sub>0</sub></code> and
// * <code>s<sub>1</sub></code> used for partial modular reduction for
// * Koblitz curves.
// */
function GetSi(): TCryptoLibGenericArray<TBigInteger>; virtual;
property IsKoblitz: Boolean read GetIsKoblitz;
class function Inverse(m: Int32; const ks: TCryptoLibInt32Array;
const x: TBigInteger): TBigInteger; static; inline;
end;
type
// /**
// * Elliptic curves over F2m. The Weierstrass equation is given by
// * <code>y<sup>2</sup> + xy = x<sup>3</sup> + ax<sup>2</sup> + b</code>.
// */
TF2mCurve = class sealed(TAbstractF2mCurve, IF2mCurve)
strict private
const
F2M_DEFAULT_COORDS = Int32(TECCurve.COORD_LAMBDA_PROJECTIVE);
var
// /**
// * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>.
// */
Fm: Int32;
// /**
// * TPB: The integer <code>k</code> where <code>x<sup>m</sup> +
// * x<sup>k</sup> + 1</code> represents the reduction polynomial
// * <code>f(z)</code>.<br/>
// * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.<br/>
// */
Fk1: Int32;
// /**
// * TPB: Always set to <code>0</code><br/>
// * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.<br/>
// */
Fk2: Int32;
//
// /**
// * TPB: Always set to <code>0</code><br/>
// * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.<br/>
// */
Fk3: Int32;
/// <summary>
/// The point at infinity on this curve.
/// </summary>
Fm_infinity: IF2mPoint;
constructor Create(m, k1, k2, k3: Int32; const A, B: IECFieldElement;
const Order, Cofactor: TBigInteger); overload;
function GetM: Int32; inline;
function GetK1: Int32; inline;
function GetK2: Int32; inline;
function GetK3: Int32; inline;
strict protected
function GetFieldSize: Int32; override;
function GetInfinity: IECPoint; override;
function CloneCurve(): IECCurve; override;
function CreateDefaultMultiplier(): IECMultiplier; override;
function CreateRawPoint(const x, y: IECFieldElement;
withCompression: Boolean): IECPoint; overload; override;
function CreateRawPoint(const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>;
withCompression: Boolean): IECPoint; overload; override;
public
// /**
// * Constructor for Trinomial Polynomial Basis (TPB).
// * @param m The exponent <code>m</code> of
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param k The integer <code>k</code> where <code>x<sup>m</sup> +
// * x<sup>k</sup> + 1</code> represents the reduction
// * polynomial <code>f(z)</code>.
// * @param a The coefficient <code>a</code> in the Weierstrass equation
// * for non-supersingular elliptic curves over
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param b The coefficient <code>b</code> in the Weierstrass equation
// * for non-supersingular elliptic curves over
// * <code>F<sub>2<sup>m</sup></sub></code>.
// */
constructor Create(m, k: Int32; const A, B: TBigInteger); overload;
deprecated 'Use constructor taking order/cofactor';
// /**
// * Constructor for Trinomial Polynomial Basis (TPB).
// * @param m The exponent <code>m</code> of
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param k The integer <code>k</code> where <code>x<sup>m</sup> +
// * x<sup>k</sup> + 1</code> represents the reduction
// * polynomial <code>f(z)</code>.
// * @param a The coefficient <code>a</code> in the Weierstrass equation
// * for non-supersingular elliptic curves over
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param b The coefficient <code>b</code> in the Weierstrass equation
// * for non-supersingular elliptic curves over
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param order The order of the main subgroup of the elliptic curve.
// * @param cofactor The cofactor of the elliptic curve, i.e.
// * <code>#E<sub>a</sub>(F<sub>2<sup>m</sup></sub>) = h * n</code>.
// */
constructor Create(m, k: Int32;
const A, B, Order, Cofactor: TBigInteger); overload;
// /**
// * Constructor for Pentanomial Polynomial Basis (PPB).
// * @param m The exponent <code>m</code> of
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.
// * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.
// * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.
// * @param a The coefficient <code>a</code> in the Weierstrass equation
// * for non-supersingular elliptic curves over
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param b The coefficient <code>b</code> in the Weierstrass equation
// * for non-supersingular elliptic curves over
// * <code>F<sub>2<sup>m</sup></sub></code>.
// */
constructor Create(m, k1, k2, k3: Int32; const A, B: TBigInteger); overload;
deprecated 'Use constructor taking order/cofactor';
// /**
// * Constructor for Pentanomial Polynomial Basis (PPB).
// * @param m The exponent <code>m</code> of
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.
// * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.
// * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.
// * @param a The coefficient <code>a</code> in the Weierstrass equation
// * for non-supersingular elliptic curves over
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param b The coefficient <code>b</code> in the Weierstrass equation
// * for non-supersingular elliptic curves over
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param order The order of the main subgroup of the elliptic curve.
// * @param cofactor The cofactor of the elliptic curve, i.e.
// * <code>#E<sub>a</sub>(F<sub>2<sup>m</sup></sub>) = h * n</code>.
// */
constructor Create(m, k1, k2, k3: Int32;
const A, B, Order, Cofactor: TBigInteger); overload;
destructor Destroy; override;
function SupportsCoordinateSystem(coord: Int32): Boolean; override;
function FromBigInteger(const x: TBigInteger): IECFieldElement; override;
/// <summary>
/// Return true if curve uses a Trinomial basis.
/// </summary>
/// <returns>
/// return true if curve Trinomial, false otherwise.
/// </returns>
function IsTrinomial(): Boolean; inline;
function CreateCacheSafeLookupTable(const points
: TCryptoLibGenericArray<IECPoint>; off, len: Int32)
: IECLookupTable; override;
property FieldSize: Int32 read GetFieldSize;
property Infinity: IECPoint read GetInfinity;
property m: Int32 read GetM;
property k1: Int32 read GetK1;
property k2: Int32 read GetK2;
property k3: Int32 read GetK3;
end;
implementation
{ TECCurve }
procedure TECCurve.CheckPoint(const point: IECPoint);
begin
if ((point = Nil) or ((Self as IECCurve) <> point.Curve)) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidPointOnCurve);
end;
end;
procedure TECCurve.CheckPoints(const points: TCryptoLibGenericArray<IECPoint>);
begin
CheckPoints(points, 0, System.Length(points));
end;
procedure TECCurve.CheckPoints(const points: TCryptoLibGenericArray<IECPoint>;
off, len: Int32);
var
i: Int32;
point: IECPoint;
begin
if (points = Nil) then
begin
raise EArgumentNilCryptoLibException.CreateRes(@SPointsNil);
end;
if ((off < 0) or (len < 0) or (off > (System.Length(points) - len))) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidRangeSpecified);
end;
for i := 0 to System.Pred(len) do
begin
point := points[off + i];
if ((point <> Nil) and ((Self as IECCurve) <> point.Curve)) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidPointOnCurve2);
end;
end;
end;
function TECCurve.Configure: IConfig;
begin
Result := TConfig.Create(Self as IECCurve, Self.Fm_coord,
Self.Fm_endomorphism, Self.Fm_multiplier);
end;
constructor TECCurve.Create(const field: IFiniteField);
begin
inherited Create();
Fm_field := field;
end;
function TECCurve.CreateCacheSafeLookupTable(const points
: TCryptoLibGenericArray<IECPoint>; off, len: Int32): IECLookupTable;
var
FE_BYTES, position, i, pxStart, pyStart, pxLen, pyLen: Int32;
table, px, py: TCryptoLibByteArray;
p: IECPoint;
begin
FE_BYTES := (FieldSize + 7) div 8;
System.SetLength(table, len * FE_BYTES * 2);
position := 0;
for i := 0 to System.Pred(len) do
begin
p := points[off + i];
px := p.RawXCoord.ToBigInteger().ToByteArray();
py := p.RawYCoord.ToBigInteger().ToByteArray();
if System.Length(px) > FE_BYTES then
begin
pxStart := 1
end
else
begin
pxStart := 0
end;
pxLen := System.Length(px) - pxStart;
if System.Length(py) > FE_BYTES then
begin
pyStart := 1
end
else
begin
pyStart := 0
end;
pyLen := System.Length(py) - pyStart;
System.Move(px[pxStart], table[position + FE_BYTES - pxLen],
pxLen * System.SizeOf(Byte));
position := position + FE_BYTES;
System.Move(py[pyStart], table[position + FE_BYTES - pyLen],
pyLen * System.SizeOf(Byte));
position := position + FE_BYTES;
end;
Result := TDefaultLookupTable.Create(Self as IECCurve, table, len);
end;
function TECCurve.CreateDefaultMultiplier: IECMultiplier;
var
glvEndomorphism: IGlvEndomorphism;
begin
if (Supports(Fm_endomorphism, IGlvEndomorphism, glvEndomorphism)) then
begin
Result := TGlvMultiplier.Create(Self as IECCurve, glvEndomorphism);
Exit;
end;
Result := TWNafL2RMultiplier.Create();
end;
class constructor TECCurve.CreateECCurve;
begin
FLock := TCriticalSection.Create;
end;
function TECCurve.CreatePoint(const x, y: TBigInteger): IECPoint;
begin
Result := CreatePoint(x, y, false);
end;
function TECCurve.CreatePoint(const x, y: TBigInteger; withCompression: Boolean)
: IECPoint;
begin
Result := CreateRawPoint(FromBigInteger(x), FromBigInteger(y),
withCompression);
end;
function TECCurve.DecodePoint(const encoded: TCryptoLibByteArray): IECPoint;
var
x, y: TBigInteger;
p: IECPoint;
expectedLength, yTilde: Int32;
ltype: Byte;
begin
p := Nil;
expectedLength := (FieldSize + 7) div 8;
ltype := encoded[0];
case ltype of
$00: // infinity
begin
if (System.Length(encoded) <> 1) then
begin
raise EArgumentCryptoLibException.CreateRes
(@SIncorrectLengthInfinityEncoding);
end;
p := Infinity;
end;
$02, // compressed
$03: // compressed
begin
if (System.Length(encoded) <> (expectedLength + 1)) then
begin
raise EArgumentCryptoLibException.CreateRes
(@SIncorrectLengthCompressedEncoding);
end;
yTilde := ltype and 1;
x := TBigInteger.Create(1, encoded, 1, expectedLength);
p := DecompressPoint(yTilde, x);
// TODO Skip curve equation check?
if ((not p.ImplIsValid(true, true))) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidPoint);
end;
end;
$04: // uncompressed
begin
if (System.Length(encoded) <> ((2 * expectedLength) + 1)) then
begin
raise EArgumentCryptoLibException.CreateRes
(@SIncorrectLengthUnCompressedEncoding);
end;
x := TBigInteger.Create(1, encoded, 1, expectedLength);
y := TBigInteger.Create(1, encoded, 1 + expectedLength, expectedLength);
p := ValidatePoint(x, y);
end;
$06, // hybrid
$07: // hybrid
begin
if (System.Length(encoded) <> ((2 * expectedLength) + 1)) then
begin
raise EArgumentCryptoLibException.CreateRes
(@SIncorrectLengthHybridEncoding);
end;
x := TBigInteger.Create(1, encoded, 1, expectedLength);
y := TBigInteger.Create(1, encoded, 1 + expectedLength, expectedLength);
if ((y.TestBit(0)) <> (ltype = $07)) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInConsistentYCoord);
end;
p := ValidatePoint(x, y);
end
else
begin
raise EFormatCryptoLibException.CreateResFmt
(@SInvalidPointEncoding, [ltype]);
end;
end;
if ((ltype <> $00) and (p.IsInfinity)) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidInfinityEncoding);
end;
Result := p;
end;
destructor TECCurve.Destroy;
begin
inherited Destroy;
end;
class destructor TECCurve.DestroyECCurve;
begin
FLock.Free;
end;
function TECCurve.Equals(const other: IECCurve): Boolean;
begin
if ((Self as IECCurve) = other) then
begin
Result := true;
Exit;
end;
if (other = Nil) then
begin
Result := false;
Exit;
end;
Result := (field as TObject).Equals(other.field as TObject) and
(A.ToBigInteger().Equals(other.A.ToBigInteger())) and
(B.ToBigInteger().Equals(other.B.ToBigInteger()));
end;
function TECCurve.GetA: IECFieldElement;
begin
Result := Fm_a;
end;
class function TECCurve.GetAllCoordinateSystems: TCryptoLibInt32Array;
begin
Result := TCryptoLibInt32Array.Create(COORD_AFFINE, COORD_HOMOGENEOUS,
COORD_JACOBIAN, COORD_JACOBIAN_CHUDNOVSKY, COORD_JACOBIAN_MODIFIED,
COORD_LAMBDA_AFFINE, COORD_LAMBDA_PROJECTIVE, COORD_SKEWED);
end;
function TECCurve.GetB: IECFieldElement;
begin
Result := Fm_b;
end;
function TECCurve.GetCofactor: TBigInteger;
begin
Result := Fm_cofactor;
end;
function TECCurve.GetCoordinateSystem: Int32;
begin
Result := Fm_coord;
end;
function TECCurve.GetEndomorphism: IECEndomorphism;
begin
Result := Fm_endomorphism;
end;
function TECCurve.GetField: IFiniteField;
begin
Result := Fm_field;
end;
function TECCurve.GetHashCode: {$IFDEF DELPHI}Int32; {$ELSE}PtrInt;
{$ENDIF DELPHI}
begin
Result := (field as TObject).GetHashCode()
xor Int32(TBits.RotateLeft32(A.ToBigInteger().GetHashCode(), 8))
xor Int32(TBits.RotateLeft32(B.ToBigInteger().GetHashCode(), 16));
end;
function TECCurve.GetMultiplier: IECMultiplier;
begin
FLock.Acquire;
try
if (Fm_multiplier = Nil) then
begin
Fm_multiplier := CreateDefaultMultiplier();
end;
Result := Fm_multiplier;
finally
FLock.Release;
end;
end;
function TECCurve.GetOrder: TBigInteger;
begin
Result := Fm_order;
end;
function TECCurve.GetPreCompInfo(const point: IECPoint; const name: String)
: IPreCompInfo;
var
table: TDictionary<String, IPreCompInfo>;
begin
CheckPoint(point);
FLock.Acquire;
try
table := point.preCompTable;
if table = Nil then
begin
Result := Nil;
end
else
begin
table.TryGetValue(name, Result);
end;
finally
FLock.Release;
end;
end;
function TECCurve.ImportPoint(const p: IECPoint): IECPoint;
var
Lp: IECPoint;
begin
if ((Self as IECCurve) = p.Curve) then
begin
Result := p;
Exit;
end;
if (p.IsInfinity) then
begin
Result := Infinity;
Exit;
end;
// TODO Default behaviour could be improved if the two curves have the same coordinate system by copying any Z coordinates.
Lp := p.Normalize();
Result := CreatePoint(Lp.XCoord.ToBigInteger(), Lp.YCoord.ToBigInteger(),
Lp.IsCompressed);
end;
procedure TECCurve.NormalizeAll(const points: TCryptoLibGenericArray<IECPoint>;
off, len: Int32; const iso: IECFieldElement);
var
zs: TCryptoLibGenericArray<IECFieldElement>;
indices: TCryptoLibInt32Array;
count, i, j, index: Int32;
p: IECPoint;
begin
CheckPoints(points, off, len);
case CoordinateSystem of
COORD_AFFINE, COORD_LAMBDA_AFFINE:
begin
if (iso <> Nil) then
begin
raise EArgumentCryptoLibException.CreateRes
(@SInvalidAffineCoordinates);
end;
Exit;
end;
end;
// /*
// * Figure out which of the points actually need to be normalized
// */
System.SetLength(zs, len);
System.SetLength(indices, len);
count := 0;
for i := 0 to System.Pred(len) do
begin
p := points[off + i];
if ((p <> Nil) and ((iso <> Nil) or (not(p.IsNormalized())))) then
begin
zs[count] := p.GetZCoord(0);
indices[count] := off + i;
System.Inc(count);
end;
end;
if (count = 0) then
begin
Exit;
end;
TECAlgorithms.MontgomeryTrick(zs, 0, count, iso);
for j := 0 to System.Pred(count) do
begin
index := indices[j];
points[index] := points[index].Normalize(zs[j]);
end;
end;
procedure TECCurve.NormalizeAll(const points: TCryptoLibGenericArray<IECPoint>);
begin
NormalizeAll(points, 0, System.Length(points), Nil);
end;
procedure TECCurve.SetCoord(const Value: Int32);
begin
Fm_coord := Value;
end;
procedure TECCurve.SetEndomorphism(const Value: IECEndomorphism);
begin
Fm_endomorphism := Value;
end;
procedure TECCurve.SetMultiplier(const Value: IECMultiplier);
begin
Fm_multiplier := Value;
end;
function TECCurve.Precompute(const point: IECPoint; const name: String;
const callback: IPreCompCallback): IPreCompInfo;
var
table: TDictionary<String, IPreCompInfo>;
existing: IPreCompInfo;
begin
CheckPoint(point);
FLock.Acquire;
try
table := point.preCompTable;
if table = Nil then
begin
table := TDictionary<String, IPreCompInfo>.Create(4);
point.preCompTable := table;
end;
table.TryGetValue(name, existing);
Result := callback.Precompute(existing);
if (Result <> existing) then
begin
table.AddOrSetValue(name, Result);
end;
finally
FLock.Release;
end;
end;
function TECCurve.SupportsCoordinateSystem(coord: Int32): Boolean;
begin
Result := coord = COORD_AFFINE;
end;
function TECCurve.ValidatePoint(const x, y: TBigInteger;
withCompression: Boolean): IECPoint;
var
p: IECPoint;
begin
p := CreatePoint(x, y, withCompression);
if (not p.IsValid()) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidPointCoordinates);
end;
Result := p;
end;
function TECCurve.ValidatePoint(const x, y: TBigInteger): IECPoint;
var
p: IECPoint;
begin
p := CreatePoint(x, y);
if (not p.IsValid()) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidPointCoordinates);
end;
Result := p;
end;
{ TECCurve.TConfig }
constructor TECCurve.TConfig.Create(const outer: IECCurve; coord: Int32;
const endomorphism: IECEndomorphism; const multiplier: IECMultiplier);
begin
Inherited Create();
Fouter := outer;
Fcoord := coord;
Fendomorphism := endomorphism;
Fmultiplier := multiplier;
end;
function TECCurve.TConfig.CreateCurve: IECCurve;
var
c: IECCurve;
begin
if (not Fouter.SupportsCoordinateSystem(Fcoord)) then
begin
raise EInvalidOperationCryptoLibException.CreateRes
(@SUnSupportedCoordinateSystem);
end;
c := Fouter.CloneCurve();
if (c = Fouter) then
begin
raise EInvalidOperationCryptoLibException.CreateRes(@SCurrentCurve);
end;
c.coord := Fcoord;
c.endomorphism := Fendomorphism;
c.multiplier := Fmultiplier;
Result := c;
end;
destructor TECCurve.TConfig.Destroy;
begin
inherited Destroy;
end;
function TECCurve.TConfig.SetCoordinateSystem(coord: Int32): IConfig;
begin
Fcoord := coord;
Result := Self as IConfig;
end;
function TECCurve.TConfig.SetEndomorphism(const endomorphism
: IECEndomorphism): IConfig;
begin
Fendomorphism := endomorphism;
Result := Self as IConfig;
end;
function TECCurve.TConfig.SetMultiplier(const multiplier
: IECMultiplier): IConfig;
begin
Fmultiplier := multiplier;
Result := Self as IConfig;
end;
{ TAbstractFpCurve }
constructor TAbstractFpCurve.Create(const q: TBigInteger);
begin
Inherited Create(TFiniteFields.GetPrimeField(q));
end;
function TAbstractFpCurve.DecompressPoint(yTilde: Int32; const X1: TBigInteger)
: IECPoint;
var
x, rhs, y: IECFieldElement;
begin
x := FromBigInteger(X1);
rhs := x.Square().Add(A).Multiply(x).Add(B);
y := rhs.Sqrt();
// /*
// * If y is not a square, then we haven't got a point on the curve
// */
if (y = Nil) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidPointCompression);
end;
if (y.TestBitZero() <> (yTilde = 1)) then
begin
// Use the other root
y := y.Negate();
end;
Result := CreateRawPoint(x, y, true);
end;
destructor TAbstractFpCurve.Destroy;
begin
inherited Destroy;
end;
function TAbstractFpCurve.IsValidFieldElement(const x: TBigInteger): Boolean;
begin
Result := (x.IsInitialized) and (x.SignValue >= 0) and
(x.CompareTo(field.Characteristic) < 0);
end;
{ TFpCurve }
function TFpCurve.CloneCurve: IECCurve;
begin
Result := TFpCurve.Create(Fm_q, Fm_r, Fm_a, Fm_b, Fm_order, Fm_cofactor);
end;
constructor TFpCurve.Create(const q, r: TBigInteger;
const A, B: IECFieldElement; const Order, Cofactor: TBigInteger);
begin
Inherited Create(q);
Fm_q := q;
Fm_r := r;
Fm_infinity := TFpPoint.Create(Self as IECCurve, Nil, Nil, false);
Fm_a := A;
Fm_b := B;
Fm_order := Order;
Fm_cofactor := Cofactor;
Fm_coord := FP_DEFAULT_COORDS;
end;
constructor TFpCurve.Create(const q, r: TBigInteger;
const A, B: IECFieldElement);
begin
Create(q, r, A, B, Default (TBigInteger), Default (TBigInteger));
end;
constructor TFpCurve.Create(const q, A, B, Order, Cofactor: TBigInteger);
begin
Inherited Create(q);
Fm_q := q;
Fm_r := TFpFieldElement.CalculateResidue(q);
Fm_infinity := TFpPoint.Create(Self as IECCurve, Nil, Nil, false);
Fm_a := FromBigInteger(A);
Fm_b := FromBigInteger(B);
Fm_order := Order;
Fm_cofactor := Cofactor;
Fm_coord := FP_DEFAULT_COORDS;
end;
constructor TFpCurve.Create(const q, A, B: TBigInteger);
begin
Create(q, A, B, Default (TBigInteger), Default (TBigInteger));
end;
function TFpCurve.CreateRawPoint(const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean)
: IECPoint;
begin
Result := TFpPoint.Create(Self as IECCurve, x, y, zs, withCompression);
end;
destructor TFpCurve.Destroy;
begin
inherited Destroy;
end;
function TFpCurve.CreateRawPoint(const x, y: IECFieldElement;
withCompression: Boolean): IECPoint;
begin
Result := TFpPoint.Create(Self as IECCurve, x, y, withCompression);
end;
function TFpCurve.FromBigInteger(const x: TBigInteger): IECFieldElement;
begin
Result := TFpFieldElement.Create(Fm_q, Fm_r, x);
end;
function TFpCurve.GetFieldSize: Int32;
begin
Result := Fm_q.BitLength;
end;
function TFpCurve.GetInfinity: IECPoint;
begin
Result := Fm_infinity;
end;
function TFpCurve.GetQ: TBigInteger;
begin
Result := Fm_q;
end;
function TFpCurve.ImportPoint(const p: IECPoint): IECPoint;
begin
if ((Self as IECCurve <> p.Curve) and (CoordinateSystem = COORD_JACOBIAN) and
(not p.IsInfinity)) then
begin
case p.Curve.CoordinateSystem of
COORD_JACOBIAN, COORD_JACOBIAN_CHUDNOVSKY, COORD_JACOBIAN_MODIFIED:
begin
Result := TFpPoint.Create(Self as IECCurve,
FromBigInteger(p.RawXCoord.ToBigInteger()),
FromBigInteger(p.RawYCoord.ToBigInteger()),
TCryptoLibGenericArray<IECFieldElement>.Create
(FromBigInteger(p.GetZCoord(0).ToBigInteger())), p.IsCompressed);
Exit;
end;
end;
end;
Result := (Inherited ImportPoint(p));
end;
function TFpCurve.SupportsCoordinateSystem(coord: Int32): Boolean;
begin
case coord of
COORD_AFFINE, COORD_HOMOGENEOUS, COORD_JACOBIAN, COORD_JACOBIAN_MODIFIED:
begin
Result := true;
end
else
begin
Result := false;
end;
end;
end;
{ TAbstractF2mCurve }
class function TAbstractF2mCurve.BuildField(m, k1, k2, k3: Int32): IFiniteField;
begin
if (k1 = 0) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidK1);
end;
if (k2 = 0) then
begin
if (k3 <> 0) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidK3);
end;
Result := TFiniteFields.GetBinaryExtensionField
(TCryptoLibInt32Array.Create(0, k1, m));
Exit;
end;
if (k2 <= k1) then
begin
raise EArgumentCryptoLibException.CreateRes(@SK2K1MisMatch);
end;
if (k3 <= k2) then
begin
raise EArgumentCryptoLibException.CreateRes(@SK3K2Mismatch);
end;
Result := TFiniteFields.GetBinaryExtensionField(TCryptoLibInt32Array.Create(0,
k1, k2, k3, m));
end;
constructor TAbstractF2mCurve.Create(m, k1, k2, k3: Int32);
begin
Inherited Create(BuildField(m, k1, k2, k3));
end;
function TAbstractF2mCurve.CreatePoint(const x, y: TBigInteger;
withCompression: Boolean): IECPoint;
var
LX, LY: IECFieldElement;
begin
LX := FromBigInteger(x);
LY := FromBigInteger(y);
case CoordinateSystem of
COORD_LAMBDA_AFFINE, COORD_LAMBDA_PROJECTIVE:
begin
if (LX.IsZero) then
begin
if (not LY.Square().Equals(B)) then
begin
raise EArgumentCryptoLibException.Create('');
end;
end
else
begin
// Y becomes Lambda (X + Y/X) here
LY := LY.Divide(LX).Add(LX);
end;
end;
end;
Result := CreateRawPoint(LX, LY, withCompression);
end;
function TAbstractF2mCurve.DecompressPoint(yTilde: Int32; const X1: TBigInteger)
: IECPoint;
var
xp, yp, beta, z: IECFieldElement;
begin
xp := FromBigInteger(X1);
yp := Nil;
if (xp.IsZero) then
begin
yp := B.Sqrt();
end
else
begin
beta := xp.Square().Invert().Multiply(B).Add(A).Add(xp);
z := SolveQuadraticEquation(beta);
if (z <> Nil) then
begin
if (z.TestBitZero() <> (yTilde = 1)) then
begin
z := z.AddOne();
end;
case CoordinateSystem of
COORD_LAMBDA_AFFINE, COORD_LAMBDA_PROJECTIVE:
begin
yp := z.Add(xp);
end
else
begin
yp := z.Multiply(xp);
end;
end;
end;
end;
if (yp = Nil) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidPointCompression);
end;
Result := CreateRawPoint(xp, yp, true);
end;
destructor TAbstractF2mCurve.Destroy;
begin
inherited Destroy;
end;
function TAbstractF2mCurve.GetIsKoblitz: Boolean;
begin
Result := (Fm_order.IsInitialized) and (Fm_cofactor.IsInitialized) and
(Fm_b.IsOne) and (Fm_a.IsZero or Fm_a.IsOne);
end;
function TAbstractF2mCurve.GetSi: TCryptoLibGenericArray<TBigInteger>;
begin
if (Fsi = Nil) then
begin
FLock.Acquire;
try
if (Fsi = Nil) then
begin
Fsi := TTnaf.GetSi(Self as IAbstractF2mCurve);
end;
finally
FLock.Release;
end;
end;
Result := Fsi;
end;
class function TAbstractF2mCurve.Inverse(m: Int32;
const ks: TCryptoLibInt32Array; const x: TBigInteger): TBigInteger;
begin
Result := TLongArray.Create(x).ModInverse(m, ks).ToBigInteger();
end;
function TAbstractF2mCurve.IsValidFieldElement(const x: TBigInteger): Boolean;
begin
Result := (x.IsInitialized) and (x.SignValue >= 0) and
(x.BitLength <= FieldSize);
end;
function TAbstractF2mCurve.SolveQuadraticEquation(const beta: IECFieldElement)
: IECFieldElement;
var
gamma, z, zeroElement, t, w, w2: IECFieldElement;
m, i: Int32;
begin
if (beta.IsZero) then
begin
Result := beta;
Exit;
end;
zeroElement := FromBigInteger(TBigInteger.Zero);
m := FieldSize;
repeat
t := FromBigInteger(TBigInteger.Arbitrary(m));
z := zeroElement;
w := beta;
i := 1;
while i < m do
begin
w2 := w.Square();
z := z.Square().Add(w2.Multiply(t));
w := w2.Add(beta);
System.Inc(i);
end;
if (not w.IsZero) then
begin
Result := Nil;
Exit;
end;
gamma := z.Square().Add(z);
until (not(gamma.IsZero));
Result := z;
end;
{ TF2mCurve }
function TF2mCurve.GetFieldSize: Int32;
begin
Result := Fm;
end;
function TF2mCurve.GetInfinity: IECPoint;
begin
Result := Fm_infinity;
end;
function TF2mCurve.GetK1: Int32;
begin
Result := Fk1;
end;
function TF2mCurve.GetK2: Int32;
begin
Result := Fk2;
end;
function TF2mCurve.GetK3: Int32;
begin
Result := Fk3;
end;
function TF2mCurve.GetM: Int32;
begin
Result := Fm;
end;
function TF2mCurve.IsTrinomial: Boolean;
begin
Result := (k2 = 0) and (k3 = 0);
end;
function TF2mCurve.CloneCurve: IECCurve;
begin
Result := TF2mCurve.Create(m, k1, k2, k3, Fm_a, Fm_b, Fm_order, Fm_cofactor);
end;
constructor TF2mCurve.Create(m, k: Int32; const A, B: TBigInteger);
begin
Create(m, k, 0, 0, A, B, Default (TBigInteger), Default (TBigInteger));
end;
constructor TF2mCurve.Create(m, k1, k2, k3: Int32; const A, B: IECFieldElement;
const Order, Cofactor: TBigInteger);
begin
Inherited Create(m, k1, k2, k3);
Fm := m;
Fk1 := k1;
Fk2 := k2;
Fk3 := k3;
Fm_order := Order;
Fm_cofactor := Cofactor;
Fm_infinity := TF2mPoint.Create(Self as IECCurve, Nil, Nil, false);
Fm_a := A;
Fm_b := B;
Fm_coord := F2M_DEFAULT_COORDS;
end;
constructor TF2mCurve.Create(m, k: Int32;
const A, B, Order, Cofactor: TBigInteger);
begin
Create(m, k, 0, 0, A, B, Order, Cofactor);
end;
constructor TF2mCurve.Create(m, k1, k2, k3: Int32;
const A, B, Order, Cofactor: TBigInteger);
begin
Inherited Create(m, k1, k2, k3);
Fm := m;
Fk1 := k1;
Fk2 := k2;
Fk3 := k3;
Fm_order := Order;
Fm_cofactor := Cofactor;
Fm_infinity := TF2mPoint.Create(Self as IECCurve, Nil, Nil, false);
if (k1 = 0) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidK1);
end;
if (k2 = 0) then
begin
if (k3 <> 0) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInvalidK3);
end;
end
else
begin
if (k2 <= k1) then
begin
raise EArgumentCryptoLibException.CreateRes(@SK2K1MisMatch);
end;
if (k3 <= k2) then
begin
raise EArgumentCryptoLibException.CreateRes(@SK3K2Mismatch);
end;
end;
Fm_a := FromBigInteger(A);
Fm_b := FromBigInteger(B);
Fm_coord := F2M_DEFAULT_COORDS;
end;
function TF2mCurve.CreateCacheSafeLookupTable(const points
: TCryptoLibGenericArray<IECPoint>; off, len: Int32): IECLookupTable;
var
FE_LONGS, position, i: Int32;
table: TCryptoLibInt64Array;
p: IECPoint;
begin
FE_LONGS := (m + 63) div 64;
System.SetLength(table, len * FE_LONGS * 2);
position := 0;
for i := 0 to System.Pred(len) do
begin
p := points[off + i];
(p.RawXCoord as IF2mFieldElement).x.CopyTo(table, position);
position := position + FE_LONGS;
(p.RawYCoord as IF2mFieldElement).x.CopyTo(table, position);
position := position + FE_LONGS;
end;
Result := TDefaultF2mLookupTable.Create(Self as IF2mCurve, table, len);
end;
constructor TF2mCurve.Create(m, k1, k2, k3: Int32; const A, B: TBigInteger);
begin
Create(m, k1, k2, k3, A, B, Default (TBigInteger), Default (TBigInteger));
end;
function TF2mCurve.CreateDefaultMultiplier: IECMultiplier;
begin
if (IsKoblitz) then
begin
Result := TWTauNafMultiplier.Create();
Exit;
end;
Result := (Inherited CreateDefaultMultiplier());
end;
function TF2mCurve.CreateRawPoint(const x, y: IECFieldElement;
withCompression: Boolean): IECPoint;
begin
Result := TF2mPoint.Create(Self as IECCurve, x, y, withCompression);
end;
function TF2mCurve.CreateRawPoint(const x, y: IECFieldElement;
const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean)
: IECPoint;
begin
Result := TF2mPoint.Create(Self as IECCurve, x, y, zs, withCompression);
end;
destructor TF2mCurve.Destroy;
begin
inherited Destroy;
end;
function TF2mCurve.FromBigInteger(const x: TBigInteger): IECFieldElement;
begin
Result := TF2mFieldElement.Create(Fm, Fk1, Fk2, Fk3, x);
end;
function TF2mCurve.SupportsCoordinateSystem(coord: Int32): Boolean;
begin
case coord of
COORD_AFFINE, COORD_HOMOGENEOUS, COORD_LAMBDA_PROJECTIVE:
begin
Result := true;
end
else
begin
Result := false;
end;
end;
end;
{ TDefaultLookupTable }
constructor TDefaultLookupTable.Create(const outer: IECCurve;
const table: TCryptoLibByteArray; size: Int32);
begin
Inherited Create();
Fm_outer := outer;
Fm_table := table;
Fm_size := size;
end;
function TDefaultLookupTable.GetSize: Int32;
begin
Result := Fm_size;
end;
function TDefaultLookupTable.Lookup(index: Int32): IECPoint;
var
FE_BYTES, position, i, j: Int32;
x, y: TCryptoLibByteArray;
MASK: Byte;
XFieldElement, YFieldElement: IECFieldElement;
begin
FE_BYTES := (Fm_outer.FieldSize + 7) div 8;
System.SetLength(x, FE_BYTES);
System.SetLength(y, FE_BYTES);
position := 0;
for i := 0 to System.Pred(Fm_size) do
begin
MASK := Byte(TBits.Asr32((i xor index) - 1, 31));
for j := 0 to System.Pred(FE_BYTES) do
begin
x[j] := x[j] xor Byte(Fm_table[position + j] and MASK);
y[j] := y[j] xor Byte(Fm_table[position + FE_BYTES + j] and MASK);
end;
position := position + (FE_BYTES * 2);
end;
XFieldElement := Fm_outer.FromBigInteger(TBigInteger.Create(1, x));
YFieldElement := Fm_outer.FromBigInteger(TBigInteger.Create(1, y));
Result := Fm_outer.CreateRawPoint(XFieldElement, YFieldElement, false);
end;
{ TDefaultF2mLookupTable }
constructor TDefaultF2mLookupTable.Create(const outer: IF2mCurve;
const table: TCryptoLibInt64Array; size: Int32);
begin
Inherited Create();
Fm_outer := outer;
Fm_table := table;
Fm_size := size;
end;
function TDefaultF2mLookupTable.GetSize: Int32;
begin
Result := Fm_size;
end;
function TDefaultF2mLookupTable.Lookup(index: Int32): IECPoint;
var
FE_LONGS, position, m, i, j: Int32;
ks: TCryptoLibInt32Array;
x, y: TCryptoLibInt64Array;
MASK: Int64;
XFieldElement, YFieldElement: IECFieldElement;
begin
m := Fm_outer.m;
if Fm_outer.IsTrinomial() then
begin
ks := TCryptoLibInt32Array.Create(Fm_outer.k1);
end
else
begin
ks := TCryptoLibInt32Array.Create(Fm_outer.k1, Fm_outer.k2, Fm_outer.k3);
end;
FE_LONGS := (Fm_outer.m + 63) div 64;
System.SetLength(x, FE_LONGS);
System.SetLength(y, FE_LONGS);
position := 0;
for i := 0 to System.Pred(Fm_size) do
begin
MASK := TBits.Asr32((i xor index) - 1, 31);
for j := 0 to System.Pred(FE_LONGS) do
begin
x[j] := x[j] xor (Fm_table[position + j] and MASK);
y[j] := y[j] xor (Fm_table[position + FE_LONGS + j] and MASK);
end;
position := position + (FE_LONGS * 2);
end;
XFieldElement := TF2mFieldElement.Create(m, ks, TLongArray.Create(x));
YFieldElement := TF2mFieldElement.Create(m, ks, TLongArray.Create(y));
Result := Fm_outer.CreateRawPoint(XFieldElement, YFieldElement, false);
end;
end.
|
UNIT ReadingWords;
INTERFACE
FUNCTION ReadWord(VAR Word: STRING): STRING; { Читает из INPUT слово в Word, возвращает его }
IMPLEMENTATION
CONST
ValidSymbols = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш',
'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я',
'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш',
'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я', '-'];
SpecialSymbols = ['-'];
PROCEDURE DoCharSmall(VAR Symbol: CHAR);
{ Делает символ-Symbol строчным(маленьким), пример "А" -> "а" }
BEGIN { DoCharSmall }
{ English alphabet } { Русский алфавит }
IF Symbol = 'A' THEN Symbol := 'a' ELSE IF Symbol = 'А' THEN Symbol := 'а' ELSE
IF Symbol = 'B' THEN Symbol := 'b' ELSE IF Symbol = 'Б' THEN Symbol := 'б' ELSE
IF Symbol = 'C' THEN Symbol := 'c' ELSE IF Symbol = 'В' THEN Symbol := 'в' ELSE
IF Symbol = 'D' THEN Symbol := 'd' ELSE IF Symbol = 'Г' THEN Symbol := 'г' ELSE
IF Symbol = 'E' THEN Symbol := 'e' ELSE IF Symbol = 'Д' THEN Symbol := 'д' ELSE
IF Symbol = 'F' THEN Symbol := 'f' ELSE IF Symbol = 'Е' THEN Symbol := 'е' ELSE
IF Symbol = 'G' THEN Symbol := 'g' ELSE IF Symbol = 'Ё' THEN Symbol := 'ё' ELSE
IF Symbol = 'H' THEN Symbol := 'h' ELSE IF Symbol = 'Ж' THEN Symbol := 'ж' ELSE
IF Symbol = 'I' THEN Symbol := 'i' ELSE IF Symbol = 'З' THEN Symbol := 'з' ELSE
IF Symbol = 'J' THEN Symbol := 'j' ELSE IF Symbol = 'И' THEN Symbol := 'и' ELSE
IF Symbol = 'K' THEN Symbol := 'k' ELSE IF Symbol = 'Й' THEN Symbol := 'й' ELSE
IF Symbol = 'L' THEN Symbol := 'l' ELSE IF Symbol = 'К' THEN Symbol := 'к' ELSE
IF Symbol = 'M' THEN Symbol := 'm' ELSE IF Symbol = 'Л' THEN Symbol := 'л' ELSE
IF Symbol = 'N' THEN Symbol := 'n' ELSE IF Symbol = 'М' THEN Symbol := 'м' ELSE
IF Symbol = 'O' THEN Symbol := 'o' ELSE IF Symbol = 'Н' THEN Symbol := 'н' ELSE
IF Symbol = 'P' THEN Symbol := 'p' ELSE IF Symbol = 'О' THEN Symbol := 'о' ELSE
IF Symbol = 'Q' THEN Symbol := 'q' ELSE IF Symbol = 'П' THEN Symbol := 'п' ELSE
IF Symbol = 'R' THEN Symbol := 'r' ELSE IF Symbol = 'Р' THEN Symbol := 'р' ELSE
IF Symbol = 'S' THEN Symbol := 's' ELSE IF Symbol = 'С' THEN Symbol := 'с' ELSE
IF Symbol = 'T' THEN Symbol := 't' ELSE IF Symbol = 'Т' THEN Symbol := 'т' ELSE
IF Symbol = 'U' THEN Symbol := 'u' ELSE IF Symbol = 'У' THEN Symbol := 'у' ELSE
IF Symbol = 'V' THEN Symbol := 'v' ELSE IF Symbol = 'Ф' THEN Symbol := 'ф' ELSE
IF Symbol = 'W' THEN Symbol := 'w' ELSE IF Symbol = 'Х' THEN Symbol := 'х' ELSE
IF Symbol = 'X' THEN Symbol := 'x' ELSE IF Symbol = 'Ц' THEN Symbol := 'ц' ELSE
IF Symbol = 'Y' THEN Symbol := 'y' ELSE IF Symbol = 'Ч' THEN Symbol := 'ч' ELSE
IF Symbol = 'Z' THEN Symbol := 'z' ELSE IF Symbol = 'Ш' THEN Symbol := 'ш' ELSE
IF Symbol = 'Щ' THEN Symbol := 'щ' ELSE
IF Symbol = 'Ъ' THEN Symbol := 'ъ' ELSE
IF Symbol = 'Ы' THEN Symbol := 'ы' ELSE
IF Symbol = 'Ь' THEN Symbol := 'ь' ELSE
IF Symbol = 'Э' THEN Symbol := 'э' ELSE
IF Symbol = 'Ю' THEN Symbol := 'ю' ELSE
IF Symbol = 'Я' THEN Symbol := 'я'
END; { DoCharSmall }
PROCEDURE DoCharBigger(VAR Symbol: CHAR);
{ Делает символ-Symbol прописным(заглавным), пример "а" -> "А" }
BEGIN { DoCharBigger }
{ English alphabet } { Русский алфавит }
IF Symbol = 'a' THEN Symbol := 'A' ELSE IF Symbol = 'а' THEN Symbol := 'А' ELSE
IF Symbol = 'b' THEN Symbol := 'B' ELSE IF Symbol = 'б' THEN Symbol := 'Б' ELSE
IF Symbol = 'c' THEN Symbol := 'C' ELSE IF Symbol = 'в' THEN Symbol := 'В' ELSE
IF Symbol = 'd' THEN Symbol := 'D' ELSE IF Symbol = 'г' THEN Symbol := 'Г' ELSE
IF Symbol = 'e' THEN Symbol := 'E' ELSE IF Symbol = 'д' THEN Symbol := 'Д' ELSE
IF Symbol = 'f' THEN Symbol := 'F' ELSE IF Symbol = 'е' THEN Symbol := 'Е' ELSE
IF Symbol = 'g' THEN Symbol := 'G' ELSE IF Symbol = 'ё' THEN Symbol := 'Ё' ELSE
IF Symbol = 'h' THEN Symbol := 'H' ELSE IF Symbol = 'ж' THEN Symbol := 'Ж' ELSE
IF Symbol = 'i' THEN Symbol := 'I' ELSE IF Symbol = 'з' THEN Symbol := 'З' ELSE
IF Symbol = 'j' THEN Symbol := 'J' ELSE IF Symbol = 'и' THEN Symbol := 'И' ELSE
IF Symbol = 'k' THEN Symbol := 'K' ELSE IF Symbol = 'й' THEN Symbol := 'Й' ELSE
IF Symbol = 'l' THEN Symbol := 'L' ELSE IF Symbol = 'к' THEN Symbol := 'К' ELSE
IF Symbol = 'm' THEN Symbol := 'M' ELSE IF Symbol = 'л' THEN Symbol := 'Л' ELSE
IF Symbol = 'n' THEN Symbol := 'N' ELSE IF Symbol = 'м' THEN Symbol := 'М' ELSE
IF Symbol = 'o' THEN Symbol := 'O' ELSE IF Symbol = 'н' THEN Symbol := 'Н' ELSE
IF Symbol = 'p' THEN Symbol := 'P' ELSE IF Symbol = 'о' THEN Symbol := 'О' ELSE
IF Symbol = 'q' THEN Symbol := 'Q' ELSE IF Symbol = 'п' THEN Symbol := 'П' ELSE
IF Symbol = 'r' THEN Symbol := 'R' ELSE IF Symbol = 'р' THEN Symbol := 'Р' ELSE
IF Symbol = 's' THEN Symbol := 'S' ELSE IF Symbol = 'с' THEN Symbol := 'С' ELSE
IF Symbol = 't' THEN Symbol := 'T' ELSE IF Symbol = 'т' THEN Symbol := 'Т' ELSE
IF Symbol = 'u' THEN Symbol := 'U' ELSE IF Symbol = 'у' THEN Symbol := 'У' ELSE
IF Symbol = 'v' THEN Symbol := 'V' ELSE IF Symbol = 'ф' THEN Symbol := 'Ф' ELSE
IF Symbol = 'w' THEN Symbol := 'W' ELSE IF Symbol = 'х' THEN Symbol := 'Х' ELSE
IF Symbol = 'x' THEN Symbol := 'X' ELSE IF Symbol = 'ц' THEN Symbol := 'Ц' ELSE
IF Symbol = 'y' THEN Symbol := 'Y' ELSE IF Symbol = 'ч' THEN Symbol := 'Ч' ELSE
IF Symbol = 'z' THEN Symbol := 'Z' ELSE IF Symbol = 'ш' THEN Symbol := 'Ш' ELSE
IF Symbol = 'щ' THEN Symbol := 'Щ' ELSE
IF Symbol = 'ъ' THEN Symbol := 'Ъ' ELSE
IF Symbol = 'ы' THEN Symbol := 'Ы' ELSE
IF Symbol = 'ь' THEN Symbol := 'Ь' ELSE
IF Symbol = 'э' THEN Symbol := 'Э' ELSE
IF Symbol = 'ю' THEN Symbol := 'Ю' ELSE
IF Symbol = 'я' THEN Symbol := 'Я'
END; { DoCharBigger }
CONST
MaxWordLength = 50;
FUNCTION FormatWord(VAR Word: STRING): STRING;
{ Форматирует слово }
VAR
I: INTEGER;
BEGIN { FormatWord }
FOR I := 1 TO Length(Word)
DO
DoCharSmall(Word[I]); //сделать все буквы строчными(маленькими)
DoCharBigger(Word[1]); //сделать первый символ строки прописным(большим)
FormatWord := Word
END; { FormatWord }
FUNCTION ReadWord(VAR Word: STRING): STRING;
{ Читает слово из INPUT и кладёт его отформатированным во внешнюю переменную Word }
VAR
Symbol: CHAR;
BEGIN { ReadWord }
Word := '';
WHILE NOT EOF AND (Symbol <> ' ')
DO
BEGIN
READ(Symbol);
IF Symbol IN ValidSymbols
THEN
Word := Word + Symbol
ELSE
//Обрубаем считывание слова
Symbol := ' '
END;
//Игнорируем слова 1-длины, состоящие из специальных символов
IF (Length(Word) = 1) AND (Word[1] IN SpecialSymbols)
THEN
Word := '';
IF Word <> '' THEN Word := FormatWord(Word);
ReadWord := Word
END; { ReadWord }
BEGIN { ReadWord }
END. { ReadWord }
|
unit SharedTimer;
interface
uses
Windows, Classes, TimerUtils, NumUtils, ListUtils;
type
ITickeable =
interface
procedure Tick;
function Enabled : boolean;
function Interval : integer;
end;
type
PClientList = ^TClientList;
TClientList =
class
protected
fClients : TInterfaceList;
fInterval : integer;
fTickCount : integer;
fTickCounter : integer;
function Interval : integer;
function GetCount : integer;
public
property TickCount : integer read fTickCount;
property TickCounter : integer read fTickCounter write fTickCounter;
property Count : integer read GetCount;
constructor Create;
destructor Destroy;
override;
procedure Tick;
procedure Add( const Client : ITickeable );
procedure Delete( const Client : ITickeable );
procedure Replace( const OldClient, NewClient : ITickeable );
end;
type
TSharedTimer =
class
public
constructor Create( aTimerResolution : integer );
destructor Destroy; override;
protected
fTimerResolution : integer;
fTimer : TTicker;
fItems : TObjectList;
function ClientList( const Client : ITickeable ) : TClientList;
function Add( const Client : ITickeable ) : boolean; // Returns true if a new list with a different interval was created
function Delete( const Client : ITickeable ) : boolean; // Returns true if a list was deleted
procedure Release;
procedure TimerTick;
procedure SetTimerResolution( aTimerResolution : integer );
public
property Items : TObjectList read fItems;
property Timer : TTicker read fTimer;
property TimerResolution : integer read fTimerResolution write SetTimerResolution;
procedure Changed( IntervalChanged : boolean );
procedure InsertClient( const Client : ITickeable );
procedure DeleteClient( const Client : ITickeable );
procedure RefreshClient( const Client : ITickeable );
procedure ReplaceClient( const OldClient, NewClient : ITickeable );
end;
implementation
// TClientList
function TClientList.GetCount : integer;
begin
Result := fClients.Count;
end;
function TClientList.Interval : integer;
begin
Result := fInterval;
end;
constructor TClientList.Create;
begin
inherited;
fClients := TInterfaceList.Create;
end;
destructor TClientList.Destroy;
begin
fClients.Free;
inherited;
end;
procedure TClientList.Tick;
var
i : integer;
begin
if TickCount > 0
then
if TickCounter = 0
then
begin
// NotifyClients
for i := 0 to Count - 1 do
if Assigned( fClients[i] )
then ITickeable( fClients[i] ).Tick;
TickCounter := TickCount;
end
else TickCounter := TickCounter - 1
else
// NotifyClients
for i := 0 to Count - 1 do
if Assigned( fClients[i] )
then ITickeable( fClients[i] ).Tick;
end;
procedure TClientList.Add( const Client : ITickeable );
begin
assert( ( fInterval = Client.Interval ) or ( fInterval = 0 ), 'Client with wrong interval in SharedTimer.TClientList.Add!!' );
fClients.Add( Client );
end;
procedure TClientList.Delete( const Client : ITickeable );
begin
fClients.Remove( Client );
end;
procedure TClientList.Replace( const OldClient, NewClient : ITickeable );
begin
assert( fClients.IndexOf( OldClient ) > 0, 'Unregistered client in SharedTimer.TClientList.Replace!!' );
fClients[ fClients.IndexOf( OldClient ) ] := NewClient;
end;
// TSharedTimer
procedure TSharedTimer.TimerTick;
var
i : integer;
begin
with fItems do
for i := 0 to Count - 1 do
with TClientList( Items[i] ) do
if Count > 0
then Tick;
end;
procedure TSharedTimer.SetTimerResolution( aTimerResolution : integer );
begin
fTimerResolution := aTimerResolution;
Changed( true );
end;
procedure TSharedTimer.Changed( IntervalChanged : boolean );
var
i, OrgInterval, NewInterval : integer;
fTimerNeeded : boolean;
ClientsLeft : boolean;
begin
if IntervalChanged
then
begin
fTimerNeeded := false;
with Items do
begin
if Count > 0
then
begin
i := 0;
while ( i < Count ) and ( TClientList( Items[i] ).Count = 0 ) do
inc( i );
ClientsLeft := ( i < Count );
if ClientsLeft and IntervalChanged
then // Some timer has changed its interval..
begin
OrgInterval := Timer.Interval;
// Get NewInterval
i := 0;
repeat
NewInterval := NearestMult( TClientList( Items[i] ).Interval, TimerResolution );
inc( i );
until (NewInterval > 0) or (i >= Count);
if NewInterval > 0
then
begin
for i := 1 to Count - 1 do
with TClientList( fItems[i] ) do
if Interval > 0
then NewInterval := mcd( NewInterval, NearestMult( Interval, TimerResolution ) );
// Adjust each timer interval based on NewInterval
for i := 0 to Count - 1 do
with TClientList( Items[i] ) do
begin
fTickCounter := ( TickCounter * OrgInterval ) div NewInterval;
fTickCount := pred( Interval div NewInterval );
if Count > 0
then fTimerNeeded := true;
end;
Timer.Interval := NewInterval;
end
else fTimerNeeded := false;
end;
end;
end;
Timer.Enabled := fTimerNeeded;
end;
end;
procedure TSharedTimer.RefreshClient( const Client : ITickeable );
begin
DeleteClient( Client );
InsertClient( Client );
end;
procedure TSharedTimer.InsertClient( const Client : ITickeable );
begin
Changed( Add( Client ) );
end;
procedure TSharedTimer.DeleteClient( const Client : ITickeable );
begin
Changed( Delete( Client ) );
end;
constructor TSharedTimer.Create( aTimerResolution : integer );
begin
fTimer := TSimpleTimer.Create;//TEnhancedTimer.Create; //TEnhancedTimer
fItems := TObjectList.Create;
TimerResolution := aTimerResolution;
with fTimer do
begin
PostTicks := true;
Enabled := false;
OnTimer := TimerTick;
Resolution := TimerResolution div 2;
end;
end;
destructor TSharedTimer.Destroy;
begin
fTimer.Free;
fItems.Free;
inherited;
end;
procedure TSharedTimer.Release;
begin
if fItems.Count = 0
then Destroy;
end;
function TSharedTimer.ClientList( const Client : ITickeable ) : TClientList;
var
i : integer;
WantedInterval : integer;
begin
i := 0;
WantedInterval := Client.Interval; // !! FuncToVar
while (i < fItems.Count) and ( WantedInterval <> TClientList( fItems[i] ).Interval ) do
inc( i );
if i < fItems.Count
then Result := TClientList( fItems[i] )
else
begin
Result := TClientList.Create;
Result.fInterval := Client.Interval;
fItems.Add( Result );
end;
end;
const
AllocGranularity = 6;
function TSharedTimer.Add( const Client : ITickeable ) : boolean;
var
List : TClientList;
begin
List := ClientList( Client );
Result := ( List.Count = 0 ); // A new list means the new interval is different from the previous ones
List.Add( Client );
end;
function TSharedTimer.Delete( const Client : ITickeable ) : boolean;
var
List : TClientList;
begin
List := ClientList( Client );
assert( List.Count > 0, 'Unregistered client in SharedTimer.TSharedTimer.Delete!!' );
List.Delete( Client );
Result := ( List.Count = 0 ); // No clients with this interval remain
end;
procedure TSharedTimer.ReplaceClient( const OldClient, NewClient : ITickeable );
begin
assert( OldClient.Interval = NewClient.Interval, 'Client mismatch in SharedTimer.TSharedTimer.Delete!!' );
assert( ClientList( OldClient ).Count > 0, 'Unregistered client in SharedTimer.TSharedTimer.Delete!!' );
ClientList( OldClient ).Replace( OldClient, NewClient );
end;
end.
|
unit Control.LogradourosCEP;
interface
uses FireDAC.Comp.Client, Common.ENum, Model.LogradourosCEP;
type
TLogradourosCEPControl = class
private
FLogradourosCEP: TLogradouroCEP;
public
constructor Create;
destructor Destroy; override;
function Gravar: Boolean;
function Localizar(aParam: array of variant): TFDQuery;
function GetId(): Integer;
property LogradourosCEP: TLogradouroCEP read FLogradourosCEP write FLogradourosCEP;
end;
implementation
{ TLogradourosCEPControl }
constructor TLogradourosCEPControl.Create;
begin
FLogradourosCEP := TLogradouroCEP.Create;
end;
destructor TLogradourosCEPControl.Destroy;
begin
FLogradourosCEP.Free;
inherited;
end;
function TLogradourosCEPControl.GetId: Integer;
begin
Result := FLogradourosCEP.GetID;
end;
function TLogradourosCEPControl.Gravar: Boolean;
begin
Result := FLogradourosCEP.Gravar;
end;
function TLogradourosCEPControl.Localizar(aParam: array of variant): TFDQuery;
begin
Result := FLogradourosCEP.Localizar(aParam);
end;
end.
|
unit UnitUserSel;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit,
cxDBLookupComboBox, ExtCtrls, RzButton, Menus, JvComponentBase,
JvFormPlacement, cxGraphics, cxListBox, cxDBEdit, Grids, DBGrids,
cxLookAndFeels,
cxLookAndFeelPainters, RzPanel, RzDlgBtn, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxNavigator, DB, cxDBData, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView,
cxGrid, StrUtils;
type
TFormUserSel = class(TForm)
cbUserName: TcxDBLookupComboBox;
Label1: TLabel;
Label2: TLabel;
Image1: TImage;
Timer1: TTimer;
EditPsw: TcxMaskEdit;
Image2: TImage;
Label3: TLabel;
RzMenuButton1: TRzMenuButton;
PopupMenu1: TPopupMenu;
N_Save: TMenuItem;
N2: TMenuItem;
EN_Menu: TMenuItem;
RU_Menu: TMenuItem;
JvFormStorage1: TJvFormStorage;
RzDialogButtons1: TRzDialogButtons;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
cxGrid1DBTableView1basename: TcxGridDBColumn;
cxGrid1DBTableView1basepath: TcxGridDBColumn;
procedure FormShow(Sender: TObject);
procedure cxDBLookupComboBox1PropertiesEditValueChanged(
Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure EN_MenuClick(Sender: TObject);
procedure RU_MenuClick(Sender: TObject);
procedure JvFormStorage1RestorePlacement(Sender: TObject);
private
FPassword: string;
FTypeUser: string;
FUser: string;
procedure GetUserData;
protected
public
class function UserChecked(TryCount: Integer): Boolean;
{ Public declarations }
end;
var
// FormUserSel: TFormUserSel;
Layout: array[0.. KL_NAMELENGTH] of char;
implementation
Uses UnitDM, UnitMain, UnitSplash;
{$R *.dfm}
function WhichLanguage:string;
begin
if GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow, nil)) = 67699721 then
Result := 'EN'
else
Result := 'RU';
end;
procedure TFormUserSel.FormShow(Sender: TObject);
begin
GetUserData;
Editpsw.SelectAll;
EditPsw.SetFocus;
// AnimateWindow(handle, 500, AW_BLEND or AW_ACTIVATE);
end;
procedure TFormUserSel.cxDBLookupComboBox1PropertiesEditValueChanged(
Sender: TObject);
begin
GetUserData;
end;
procedure TFormUserSel.Timer1Timer(Sender: TObject);
begin
RzMenuButton1.Caption:= WhichLanguage;
EN_Menu.Checked:=(RzMenuButton1.Caption='EN');
RU_Menu.Checked:=(RzMenuButton1.Caption='RU');
Timer1.Enabled:=False;
end;
procedure TFormUserSel.EN_MenuClick(Sender: TObject);
begin
LoadKeyboardLayout(StrCopy(Layout,'00000409'),KLF_ACTIVATE);
end;
procedure TFormUserSel.GetUserData;
begin
if dm.tUsers.Locate('NameUser',cbUserName.Text,[]) then
begin
FUser:= dm.tUsersNameUser.AsString;
FPassword:=dm.tUsersPassword.AsString;
FTypeUser:=dm.tUsersTip.AsString;
DM.IsAdmin:= (FTypeUser = 'Администратор');
end;
end;
procedure TFormUserSel.RU_MenuClick(Sender: TObject);
begin
LoadKeyboardLayout( StrCopy(Layout,'00000419'),KLF_ACTIVATE);
end;
procedure TFormUserSel.JvFormStorage1RestorePlacement(Sender: TObject);
begin
if N_Save.Checked then
if EN_Menu.Checked then
EN_MenuClick(Self)
else
RU_MenuClick(Self);
EditPsw.Text:='';
end;
class function TFormUserSel.UserChecked(TryCount: Integer): Boolean;
var
Trys:Integer;
FormUserSel:TFormUserSel;
mr:TModalResult;
begin
Trys:=TryCount;
Result:=False;
//Form:= TFormUserSel.Create(Application);
Application.CreateForm(TFormUserSel, FormUserSel);
try
repeat
mr:=FormUserSel.ShowModal;
if mr = mrOk then
begin
Dec(Trys);
Result:=(FormUserSel.cbUserName.Text <> EmptyStr) and (FormUserSel.EditPsw.Text = FormUserSel.FPassword);
If not Result then ShowMessage('Не верно! Попытка -'+IntToStr(Trys)) else
Dm.CurrentDataBasePath:=StrUtils.ReplaceStr(DM.tBasesbasepath.asString,'.\',ExtractFilePath(ParamStr(0)));
end;
// else Break;
until (Trys = 0) or Result or (mr <> mrOk);
finally
if Assigned(FormUserSel) then
FreeAndNil(FormUserSel);
end;
end;
end.
|
{ @author: Lara Carrión }
program Sudoku;
USES crt;
TYPE
TIndice = 1..9;
TValorJuego = 0..9;
TValorSolucion = 1..9;
TDim = 1..3;
tIndiceRegion = 1..3;
{-----------------------}
TTableroJuego = array [TIndice,TIndice] of TValorJuego;
TTableroSolucion= array [TIndice,Tindice] of TValorSolucion;
TTableroInicial = array [Tindice,TIndice] of boolean;
{-----------------------}
TConjunto = SET of tValorJuego;
TEscaneo = array [TIndice] of TConjunto;
TEscaneoReg = array [TDim, TDim] of TConjunto;
{------------------------}
VAR
opcion: integer;
tabJuego: ttablerojuego;
tabIni:TTableroInicial;
tabSol:ttablerosolucion;
f,c: tindice;
a,b: tIndiceRegion;
cFilas, cCols: tEscaneo;
cRegs:tEscaneoReg;
{//////////////////// DECLARACIÓN DE SUBPROGRAMAS /////////////////////}
procedure pintarSudoku;
begin
gotoxy(22,7);
textcolor(lightred);
writeln('************************************');
writeln;
gotoxy(22,8);
textcolor(lightblue);
writeln(' **** * * *** **** * * * *');
gotoxy(22,9);
writeln(' * * * * * * * * * * *');
gotoxy(22,10);
writeln(' **** * * * * * * * * * *');
gotoxy(22,11);
writeln(' * * * * * * * * * * *');
gotoxy(22,12);
writeln(' **** **** *** **** * * ****');
writeln;
gotoxy(22,13);
textcolor(lightred);
writeln('************************************');
end;
{=======================================================================}
{ Esta función comprueba si una casilla está ocupada o no }
function verSiOcupada(f,c:TValorJuego; t: ttablerojuego): boolean;
begin
if t[f,c] <> 0
then verSiOcupada:=true
else versiocupada:=false
end;
{=======================================================================}
{ Este procedimiento pide las coordenadas de una casilla al usuario }
procedure pedirCoordenadas (var x, y: TIndice);
begin
repeat
textcolor(lightgray);
writeln('Introduce las coordenadas de la casilla:');
readln(x,y);
until (((x>0) and (x<10)) and ((y>0) and (y<10)))
end;
{=======================================================================}
{ Esta función devuelve true si el usuario pulsa 0, false en caso contrario }
function salir(opcion:integer):boolean;
begin
if opcion=0 then salir:=true
else salir:=false
end;
{=======================================================================}
{ Esta función devuelve true si todas las casillas est n rellenas, false en cc }
function tableroLLeno(t:ttablerojuego):boolean;
var
f, c: tindice;
cont:integer;
begin
cont:=0;
for f:=1 to 9 do
for c:=1 to 9 do
if t[f,c]<>0 then cont:=cont+1;
if cont=81 then tablerolleno:= true
else tablerolleno:=false
end;
{========================================================================}
{ Este procedimiento calcula los índices del array cRegs a partir de f y c }
procedure calcularIndices (f, c: tIndice; var a, b: tIndiceRegion);
var
m, n: tIndice;
begin
m:=f-1;
n:= c-1;
case (m div 3) of
0: case (n div 3) of
0: begin
a:=1; b:=1;
end;
1: begin
a:=1; b:=2;
end;
2: begin
a:=1; b:=3;
end;
end;
1: case (n div 3) of
0: begin
a:=2; b:=1;
end;
1: begin
a:=2; b:=2;
end;
2: begin
a:=2; b:=3;
end;
end;
2: case (n div 3) of
0: begin
a:=3; b:=1;
end;
1: begin
a:=3; b:=2;
end;
2: begin
a:=3; b:=3;
end;
end;
end;
end;
{========================================================================}
{ Este procedimiento elimina valores de los conjuntos }
procedure quitarValorConjunto(f, c: tindice;t: ttableroJuego;
var cfilas, ccols:tescaneo;
var cregs: tescaneoreg);
var
a, b: tindiceregion;
begin
cFilas[f]:=cFilas[f]- [t[f,c]];
cCols[c]:= cCols[c] - [t[f,c]];
calcularIndices(f, c, a,b);
cRegs[a, b]:= cRegs[a,b] - [t[f,c]];
end;
{========================================================================}
{ Este procedimiento a¤ade valores a los conjuntos }
procedure ponerValorConjunto (f, c: tIndice; t: ttableroJuego;
var cfilas, ccols:tescaneo;
var cregs: tescaneoreg);
var
a, b: tIndiceRegion;
begin
cFilas[f]:=cFilas[f] + [t[f, c]];
cCols[c]:= cCols[c] + [t[f, c]];
calcularIndices(f,c,a,b);
cRegs[a, b]:= cRegs[a,b] + [t[f,c]];
end;
{==========================================================================}
{ Este procedimiento calcula los candidatos de una casilla }
procedure calcularCandidatos (f,c: tIndice; a, b: tindiceregion;var candidatos: tConjunto);
begin
candidatos:= (cFilas[f] * cCols[c] * cRegs [a,b]);
end;
{=======================================================================}
{ Este procedimiento detecta los fallos cometidos por el usuario }
procedure detectarValoresIncorrectos(var t: tTableroJuego; s: tTableroSolucion; i:tTableroInicial);
var
f, c: tIndice;
valor:tvalorjuego;
begin
clrscr;
for f:=1 to 9 do begin
for c:= 1 to 9 do begin
if verSiOcupada(f,c,t)= true then begin
if i[f,c] = true then begin
textcolor(lightcyan);
write(t[f,c]);
write(' ');
end
else
if ((t[f,c]<>s[f,c]) and (t[f,c]<>0)) then begin
textcolor(red);
valor:=(t[f,c]);
write(valor);
write(' ');
normvideo;
end
else begin
textcolor(lightgreen);
write(t[f,c]);
write(' ');
end
end
else begin
textcolor(yellow);
write('_');
write(' ');
end;
end;
writeln; writeln;
end;
textcolor(lightgray);
readln
end;
{=========================================================================}
{ Esta funci¢n verifica si los valores introducidos por el usuario coinciden
con la solución del tablero}
function comprobarSolucion(t: ttablerojuego; s: ttablerosolucion; i:ttableroinicial): boolean;
var
f, c: tindice;
solucion: boolean;
cuentaFallos: integer;
begin
cuentaFallos:=0;
for f:=1 to 9 do begin
for c:=1 to 9 do begin
if (t[f,c] <> s[f,c]) and (i[f,c]<>false) then
cuentaFallos:=cuentaFallos+1;
end;
end;
detectarValoresIncorrectos(t, s, i);
if cuentaFallos<>0 then begin
solucion:=false;
textcolor(lightgray);
writeln('Has cometido ', cuentafallos, ' fallos.');
readln
end
else begin
solucion:=true;
textcolor(lightgreen);
writeln('No has cometido ning£n fallo. Enhorabuena.');
readln;
end;
comprobarSolucion:=solucion
end;
{=======================================================================}
{ Este procedimiento muestra el tablero de juego }
procedure mostrarTablero(var t:ttableroJuego; i: ttableroInicial);
var
f, c: tIndice;
begin
clrscr;
for f:=1 to 9 do begin
for c:= 1 to 9 do begin
{ Si la casilla está ocupada }
if verSiOcupada(f,c,t)=true then
{ Si es un valor inicial }
if i[f,c]=true then begin
textcolor(lightcyan);
write(t[f,c]);
write(' ');
end
{ Si no es un valor inicial }
else begin
textcolor(lightgreen);
write(t[f,c]);
write(' ');
end
else begin
textcolor(yellow);
write('_', ' ');
end;
end;
writeln; writeln;
end;
end;
{========================================================================}
{ Este procedimiento elimina todos los valores introducidos y deja el tablero
como estaba al principio }
procedure reiniciarTablero (var t: ttableroJuego;var i: ttableroinicial);
var
candidatos: tConjunto;
begin
for f:=1 to 9 do begin
for c:=1 to 9 do begin
if i[f,c]=false then begin
ponerValorConjunto(f,c,t, cfilas, ccols, cregs);
t[f,c]:=0;
end
end
end
end;
{=======================================================================}
{ Este procedimiento borra el valor correspondiente a la casilla indicada
por el usuario. Si la casilla pertenece al tablero inicial o en la casilla
no hay ningún valor, el programa lanza un mensaje de error }
procedure borrarValor(var t: ttablerojuego;var i: TTableroInicial);
var
f, c: tIndice;
v: tvalorjuego;
begin
pedirCoordenadas(f,c);
if i[f,c] then begin
textcolor(red);
writeln('¡Ese valor no se puede borrar!!');
readln;
end
else begin
if t[f,c] = 0 then begin
textcolor(red);
writeln('En esa casilla no hay ningún valor para borrar.')
end
else begin
ponerValorConjunto (f, c, t, cfilas, ccols, cregs);
t[f,c] := 0;
clrscr;
end
end
end;
{========================================================================}
{ Este procedimiento se encarga de mostrar los posibles valores de una
casilla introducida por el usuario }
procedure mostrarCandidatos (t:ttablerojuego);
var
f, c: tIndice;
a,b: tIndiceRegion;
v: tValorJuego;
candidatos: tConjunto;
cont:integer;
begin
pedirCoordenadas(f,c);
if verSiOcupada(f,c,t)=true then begin
textcolor(lightblue);
writeln ('¡La casilla ya está ocupada!');
end
else begin
calcularIndices(f,c,a,b);
calcularCandidatos(f, c, a, b, candidatos);
cont:=0;
writeln('Los candidatos son: ');
for v:= 1 to 9 do begin
textcolor(lightgreen);
if (v in candidatos) then begin
cont:=cont+1;
write(v, ' ')
end
end;
end;
textcolor(lightred);
if cont=0 then writeln('No hay candidatos. Revisa tus errores.');
readln;
end;
{========================================================================}
{ Este procedimiento pide unas coordenadas al usuario y si no está ocupada,
le pide que introduzca un valor. Después se lo asigna a la casilla
correspondiente y elimina el valor de los conjuntos }
procedure colocarValor (var t:ttablerojuego);
var
f,c: tIndice;
a, b: tindiceregion;
valor :tvalorjuego;
candidatos: tConjunto;
begin
pedirCoordenadas(f,c);
verSiOcupada(f,c,t);
textcolor(white);
if verSiOcupada(f,c,t)=true then begin
write('La casilla ya est ocupada ');
writeln('por el valor ', t[f,c]);
readln;
end
else begin
calcularIndices(f,c,a,b);
calcularCandidatos(f, c, a, b, candidatos);
writeln('La casilla elegida es correcta.');
writeln('Introduce el valor que deseas colocar en ella: ');
repeat
readln(valor);
if (valor in candidatos) then
t[f,c]:=valor
else begin
write('El valor no corresponde a los candidatos.');
writeln('Por favor, elige otro:');
end;
until (valor in candidatos) ;
clrscr;
quitarValorConjunto(f, c, t,cfilas,ccols,cregs);
end;
end;
{==========================================================================}
{ Este procedimiento coloca los valores obvios del tablero, es decir, los valores
de aquellas casillas que sólo tienen 1 candidato }
procedure autocompletar(var t:ttablerojuego; i:ttableroinicial; s:ttablerosolucion;
var cfilas, ccols: tEscaneo; var cregs:tEscaneoReg);
var
f,c: tindice;
v, aux: tvalorjuego;
cont: integer;
candidatos: tconjunto;
a,b: tindiceregion;
begin
for f:=1 to 9 do begin
for c:=1 to 9 do begin
if ((i[f,c] =false) and (versiocupada(f,c,t)=false)) then begin
calcularIndices(f,c,a,b);
calcularCandidatos(f,c,a,b,candidatos);
cont:=0;
for v:= 1 to 9 do begin
if (v in candidatos) then begin
cont:=cont+1;
aux:=v;
end
end;
if (cont = 1) then begin
t[f,c]:=aux;
quitarvalorconjunto(f,c,t,cfilas,ccols,cregs);
end
end;
end;
end;
end;
{==============================================================================}
{ Este procedimiento pide una opción del menú al usuario }
procedure mostrarMenu(var opcion: integer);
{=============================================================}
{ Este procedimiento lee la opción del usuario }
procedure pedirOpcion;
var
f,c: tvalorjuego;
begin
readln(opcion);
if ((opcion<0) OR (opcion>6)) then begin
textcolor(yellow);
writeln('Esa opci¢n no es v lida'); writeln;
end;
end;
{============================================================}
begin
textcolor(lightgray);
writeln('Elige una opción: '); writeln;
writeln('1. Ver los posibles valores de una casilla.');
writeln('2. Colocar valor en una casilla.');
writeln('3. Borrar valor de una casilla.');
writeln('4. Detectar valores incorrectos.');
writeln('5. Reiniciar tablero.');
writeln('6. Autocompletar tablero.');
writeln('0. Salir.');
pediropcion;
textcolor(red)
end;
{========================================================================}
{ Este procedimiento inicializa los arrays del tablero inicial y tablero de juego
y después carga desde fichero los tableros de juego }
procedure cargarTableros(var t:tTableroJuego; var i:tTableroInicial; var s: tTableroSolucion);
{===================================================}
{ Este procedimiento inicializa el tablero de juego y el inicial }
(*/*) procedure inicializarTableros(var t:tTableroJuego; var i:tTableroInicial);
var
f, c: tIndice;
begin
for f:= 1 to 9 do begin
for c:=1 to 9 do begin
t[f,c]:=0;
i[f,c]:=false
end
end;
end;(* inicializarTableros *)
{===================================================}
{ Este procedimiento carga el archivo del tablero inicial desde fichero }
(*/*) procedure cargarTableroInicial (var t:tTableroJuego; var i:tTableroInicial);
var
f,c: tindice;
v: tvalorjuego;
fichero1: text;
rutaInicial: string;
begin
repeat
gotoxy(22,15);
pintarsudoku;
textcolor(lightcyan);
gotoxy(22,16);
writeln('Introduce la ruta del tablero inicial:');
gotoxy(22,17);
textcolor(lightred);
readln(rutaInicial);
clrscr;
assign (fichero1, rutaInicial);
{$I-}
reset (fichero1);
{$I+}
until ioresult =0;
while not eof (fichero1) do begin
read(fichero1, f, c, v);
i[f,c]:=true;
t[f, c]:= v;
end;
close (fichero1);
end;
{===================================================}
{ Este procedimiento carga desde fichero el tablero con la solución }
(*/*) procedure cargarTableroSolucion (var s:tTableroSolucion);
var
f,c: tindice;
v: tvalorSolucion;
fichero: text;
rutaSol: string;
begin
repeat
gotoxy(22,15);
pintarsudoku;
textcolor(lightcyan);
gotoxy(22,16);
writeln('Introduce la ruta del tablero solución:');
gotoxy(22,17);
textcolor(lightred);
readln(rutaSol);
clrscr;
assign (fichero, rutaSol);
{$I-}
reset (fichero);
{$I+}
until ioresult =0;
while not eof (fichero) do begin
read(fichero, f, c, v);
s[f, c]:= v;
end;
close (fichero);
end;
begin
inicializarTableros(t,i);
cargarTableroInicial(t,i);
cargarTableroSolucion(s);
end;
{========================================================================}
{ Este procedimiento prepara los candidatos inicializando los conjuntos con
todos los valores posibles. Despu‚s elimina los valores iniciales de los
conjuntos de candidatos }
procedure prepararCandidatos(t:tTableroJuego; i:tTableroInicial; var cFilas, cCols: tEscaneo; var cRegs:tEscaneoReg);
var
f,c: tIndice;
a,b: tIndiceRegion;
c1, c2, c3: tconjunto;
{=======================================================================}
{ Este procedimiento inicializa los conjuntos de filas, columnas, y regiones }
(*/*) procedure inicializarConjuntos(var cFilas,cCols: tEscaneo;
var cRegs:tEscaneoReg;
var c1, c2, c3: tConjunto);
var
f, c: tIndice;
a,b: tIndiceRegion;
begin
c1:=[1..9];
c2:=[1..9];
c3:=[1..9];
for f:=1 to 9 do
cFilas[f]:=c1;
for c:=1 to 9 do
cCols[c]:=c2;
for f:=1 to 3 do begin
for c:=1 to 3 do
cRegs[f, c] := c3;
end;
end;
{=======================================================================}
begin
inicializarConjuntos (cFilas, cCols, cRegs, c1, c2, c3);
for f:=1 to 9 do begin
for c:=1 to 9 do begin
if i[f,c] then
quitarValorConjunto (f, c, t, cfilas, ccols, cregs);
end;
end;
end;
{================= PROGRAMA PRINCIPAL ===============}
BEGIN
clrscr;
cargarTableros(tabJuego, tabIni, tabSol);
prepararCandidatos(tabJuego,tabIni,cFilas, cCols, cRegs);
REPEAT
window(25,10,80,50);
mostrarTablero(tabJuego, tabIni);
mostrarMenu(opcion);
case (opcion) of
1: mostrarCandidatos(tabJuego);
2: colocarValor(tabJuego);
3: borrarValor(tabJuego, tabIni);
4: detectarValoresIncorrectos(tabJuego, tabSol, tabIni);
5: reiniciarTablero(tabJuego, tabIni);
6: autocompletar(tabJuego, tabIni, tabSol, cfilas, ccols, cregs);
end;
UNTIL salir(opcion) or tableroLleno (tabJuego);
IF not salir(opcion) then begin
comprobarSolucion(tabJuego,tabSol,tabIni);
textcolor(yellow);
writeln(' * FIN DEL PROGRAMA * ');
readln;
end
END.
|
unit kwProcedure;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwProcedure.pas"
// Начат: 04.05.2011 12:24
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::TkwProcedure
//
// Поддержка определения процедуры в стиле Паскаля:
// {code}
// PROCEDURE Choice
//
// BEGIN
// CASE
// 1 ( 1 . )
// 2 ( 2 . )
// DEFAULT ( 'else' . )
// ENDCASE
// END
// ;
// {code}
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
l3Interfaces,
tfwScriptingInterfaces,
kwCompiledWord,
l3ParserInterfaces
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\tfwStandardProcedure.imp.pas}
TkwProcedure = class(_tfwStandardProcedure_)
{* Поддержка определения процедуры в стиле Паскаля:
[code]
PROCEDURE Choice
BEGIN
CASE
1 ( 1 . )
2 ( 2 . )
DEFAULT ( 'else' . )
ENDCASE
END
;
[code] }
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwProcedure
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
kwCompiledProcedure,
SysUtils,
l3String,
l3Parser,
kwInteger,
kwString,
TypInfo,
l3Base,
kwIntegerFactory,
kwStringFactory,
l3Chars,
tfwAutoregisteredDiction,
tfwScriptEngine
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwProcedure;
{$Include ..\ScriptEngine\tfwStandardProcedure.imp.pas}
// start class TkwProcedure
class function TkwProcedure.GetWordNameForRegister: AnsiString;
//#UC START# *4DB0614603C8_4DBFBB930070_var*
//#UC END# *4DB0614603C8_4DBFBB930070_var*
begin
//#UC START# *4DB0614603C8_4DBFBB930070_impl*
Result := 'PROCEDURE';
//#UC END# *4DB0614603C8_4DBFBB930070_impl*
end;//TkwProcedure.GetWordNameForRegister
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\tfwStandardProcedure.imp.pas}
{$IfEnd} //not NoScripts
end. |
unit UtilsUnit;
interface
uses
Windows, Classes, SysUtils, System.Generics.Collections, Generics.Defaults, CommonTypesUnit;
type
TUtils = class
public
/// <summary>
/// Convert DateTime to Unix epoch time
/// </summary>
class function ConvertToUnixTimestamp(Date: TDateTime): int64;
class function FloatToStrDot(Value: Extended): String;
class function StrToFloat(Value: String): double;
class function SortStringArray(Strings: TStringArray): TStringArray;
class function SortIntegerArray(Integers: TIntegerArray): TIntegerArray;
class function EncodeURL(URL: String): String;
end;
var
DottedFormat: TFormatSettings;
implementation
uses
DateUtils, System.NetEncoding, IdURI, Math;
{ TUtils }
class function TUtils.ConvertToUnixTimestamp(Date: TDateTime): int64;
begin
Result := DateTimeToUnix(Date, False);
end;
class function TUtils.EncodeURL(URL: String): String;
begin
Result := TIdURI.ParamsEncode(URL);
// Result := TNetEncoding.URL.Encode(URL);
end;
class function TUtils.FloatToStrDot(Value: Extended): String;
begin
Result := FloatToStr(Value, DottedFormat);
end;
class function TUtils.SortIntegerArray(Integers: TIntegerArray): TIntegerArray;
begin
SetLength(Result, Length(Integers));
if Length(Integers) = 0 then
Exit;
TArray.Copy<integer>(Integers, Result, Length(Integers));
TArray.Sort<integer>(Result, TComparer<integer>.Construct(
function (const Value1, Value2: integer): Integer
begin
Result := Math.CompareValue(Value1, Value2);
end));
end;
class function TUtils.SortStringArray(Strings: TStringArray): TStringArray;
begin
SetLength(Result, Length(Strings));
if Length(Strings) = 0 then
Exit;
TArray.Copy<String>(Strings, Result, Length(Strings));
TArray.Sort<String>(Result, TComparer<String>.Construct(
function (const String1, String2: String): Integer
begin
Result := String.Compare(String1, String2);
end));
end;
class function TUtils.StrToFloat(Value: String): double;
begin
Result := SysUtils.StrToFloat(Value, DottedFormat);
end;
initialization
// GetLocaleFormatSettings(LOCALE_SYSTEM_DEFAULT, DottedFormat);
{$WARN SYMBOL_PLATFORM OFF}
DottedFormat := TFormatSettings.Create(LOCALE_SYSTEM_DEFAULT);
DottedFormat.DecimalSeparator := '.';
{$WARN SYMBOL_PLATFORM ON}
end.
|
{**************************************************************************************************************************
* Classe/Objeto : TAbrangenciaExpressasControl
* Finalidade : Módulo controller da classe TAbrangenciaExpressas
* Nível : Controller
* Autor : Celso Mutti
* Data : 12/05/2021
* Versão : 1
* Histórico : 12/05/2021 - Criação - Celso Mutti (1)
**************************************************************************************************************************}
unit Control.AbrangenciaExpressas;
interface
uses System.SysUtils, FireDAC.Comp.Client, Common.ENum, Model.AbrangenciaExpressas;
type
TAbrangenciaExpressasControl = class
private
FAbrangencia : TAbrangenciaExpressas;
public
constructor Create;
destructor Destroy; override;
function Search(aParam : array of variant) : boolean; // realiza pesquisa em banco de dados
function Save() : Boolean; // salva, exclue dados no banco de dados
function GetField(sField : String; sKey : String; sKeyValue : String) : String; // localiza e retorna o valor de um campo de uma tabela
procedure SetupSelf(fdQuery : TFDQuery); // atribui os valores dos campos de uma query às propriedades da classe
procedure ClearSelf(); // limpa as propriedades da dos campos da tabela da classe
property Abrangencia: TAbrangenciaExpressas read FAbrangencia write FAbrangencia;
end;
implementation
{ TAbrangenciaExpressasControl }
procedure TAbrangenciaExpressasControl.ClearSelf;
begin
FAbrangencia.ClearSelf;
end;
constructor TAbrangenciaExpressasControl.Create;
begin
FAbrangencia := TAbrangenciaExpressas.Create;
end;
destructor TAbrangenciaExpressasControl.Destroy;
begin
FAbrangencia.Free;
inherited;
end;
function TAbrangenciaExpressasControl.GetField(sField, sKey, sKeyValue: String): String;
begin
Result := FAbrangencia.GetField(sField, sKey, sKeyValue);
end;
function TAbrangenciaExpressasControl.Save: Boolean;
begin
Result := FAbrangencia.Save();
end;
function TAbrangenciaExpressasControl.Search(aParam: array of variant): boolean;
begin
Result := FAbrangencia.Search(aParam)
end;
procedure TAbrangenciaExpressasControl.SetupSelf(fdQuery: TFDQuery);
begin
FAbrangencia.SetupSelf(fdQuery);
end;
end.
|
program prime(input, output);
var
number : integer;
function isPrime(n : integer) : boolean;
var
soFarPrime : boolean;
candidate : integer;
begin
soFarPrime := TRUE;
for candidate := 2 to (n - 1) do
if (n mod candidate = 0) then
soFarPrime := FALSE;
isPrime := soFarPrime
end;
procedure printPrimesUpTo(bound : integer);
var
i : integer;
begin
for i := 1 to bound do
if isPrime(i) then write(i : 8)
end;
begin
write('BOUND: '); read(number);
writeln('PRIMES UP TO ', number);
writeln();
printPrimesUpTo(number);
writeln();
end. |
{*******************************************************************************
作者: dmzn@163.com 2011-11-30
描述: 商品订单收货明细
*******************************************************************************}
unit UFormProductBillDeal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, USkinFormBase, UGridPainter, ExtCtrls, UImageButton, Grids,
UGridExPainter, StdCtrls, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, Menus, cxButtons;
type
TfFormProductBillDeal = class(TSkinFormBase)
GridList: TDrawGridEx;
Panel1: TPanel;
BtnOK: TImageButton;
BtnExit: TImageButton;
Panel2: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
EditID: TcxTextEdit;
EditMan: TcxTextEdit;
EditTime: TcxTextEdit;
procedure FormCreate(Sender: TObject);
procedure BtnExitClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Panel1Resize(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
private
{ Private declarations }
FPainter: TGridPainter;
//绘制对象
procedure LoadDealDetail(const nOrderID: string);
//商品信息
public
{ Public declarations }
class function FormSkinID: string; override;
end;
function ShowProductBillDealView(const nOrderID: string): Boolean;
//查看收货明细
implementation
{$R *.dfm}
uses
ULibFun, DB, UFormCtrl, USysDB, USysConst, USysFun, UDataModule;
function ShowProductBillDealView(const nOrderID: string): Boolean;
begin
with TfFormProductBillDeal.Create(Application) do
begin
LoadDealDetail(nOrderID);
Result := ShowModal = mrOk;
Free;
end;
end;
class function TfFormProductBillDeal.FormSkinID: string;
begin
Result := 'FormDialog';
end;
procedure TfFormProductBillDeal.FormCreate(Sender: TObject);
var nIdx: Integer;
begin
for nIdx:=ComponentCount-1 downto 0 do
if Components[nIdx] is TImageButton then
LoadFixImageButton(TImageButton(Components[nIdx]));
//xxxxx
FPainter := TGridPainter.Create(GridList);
with FPainter do
begin
HeaderFont.Style := HeaderFont.Style + [fsBold];
//粗体
AddHeader('序号', 50);
AddHeader('品牌', 50);
AddHeader('商品名称', 50);
AddHeader('收货单价', 50);
AddHeader('收货件数', 50);
AddHeader('收货人', 50);
AddHeader('收货时间', 50);
end;
LoadFormConfig(Self);
LoadDrawGridConfig(Name, GridList);
end;
procedure TfFormProductBillDeal.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
SaveFormConfig(Self);
SaveDrawGridConfig(Name, GridList);
FPainter.Free;
end;
procedure TfFormProductBillDeal.BtnExitClick(Sender: TObject);
begin
Close;
end;
//Desc: 调整按钮位置
procedure TfFormProductBillDeal.Panel1Resize(Sender: TObject);
var nW,nL: Integer;
begin
nW := BtnOK.Width + 65 + BtnExit.Width;
nL := Trunc((Panel1.Width - nW) / 2);
BtnOk.Left := nL;
BtnExit.Left := nL + BtnOK.Width + 65;
end;
//------------------------------------------------------------------------------
//Desc: 载入订单明细
procedure TfFormProductBillDeal.LoadDealDetail(const nOrderID: string);
var nStr,nHint: string;
nIdx,nInt,nNum: Integer;
nDS: TDataSet;
nData: TGridDataArray;
begin
nStr := 'Select dt.*,BrandName,StyleName,ColorName,SizeName,' +
'O_Man,O_Date From $DT dt ' +
' Left Join $PT pt On pt.ProductID=dt.D_Product ' +
' Left Join $ST st On st.StyleID=pt.StyleID ' +
' Left Join $SZ sz On sz.SizeID=pt.SizeID ' +
' Left Join $CR cr On cr.ColorID=pt.ColorID ' +
' Left Join $OD od On od.O_ID=dt.D_Order ' +
' Left Join $BR br On br.BrandID=pt.BrandID ' +
'Where D_Order=''$ID'' Order By dt.R_ID';
//xxxxx
nStr := MacroValue(nStr, [MI('$DT', sTable_OrderDeal), MI('$ID', nOrderID),
MI('$ST', sTable_DL_Style), MI('$SZ', sTable_DL_Size),
MI('$CR', sTable_DL_Color), MI('$OD', sTable_Order),
MI('$BR', sTable_DL_Brand), MI('$PT', sTable_DL_Product)]);
//xxxxx
nDS := FDM.LockDataSet(nStr, nHint);
try
if not Assigned(nDS) then
begin
ShowDlg(nHint, sWarn); Exit;
end;
FPainter.ClearData;
if nDS.RecordCount < 1 then Exit;
with nDS do
begin
First;
nInt := 1;
nNum := 0;
EditID.Text := nOrderID;
EditMan.Text := FieldByName('O_Man').AsString;
EditTime.Text := DateTime2Str(FieldByName('O_Date').AsDateTime);
while not Eof do
begin
SetLength(nData, 7);
for nIdx:=Low(nData) to High(nData) do
begin
nData[nIdx].FCtrls := nil;
nData[nIdx].FAlign := taCenter;
end;
nData[0].FText := IntToStr(nInt);
Inc(nInt);
nData[1].FText := FieldByName('BrandName').AsString;
nStr := Format('%s_%s_%s', [FieldByName('StyleName').AsString,
FieldByName('ColorName').AsString, FieldByName('SizeName').AsString]);
nData[2].FText := nStr;
nData[3].FText := Format('%.2f', [FieldByName('D_Price').AsFloat]);
nData[4].FText := FieldByName('D_Number').AsString;
nNum := nNum + FieldByName('D_Number').AsInteger;
nData[5].FText := FieldByName('D_Man').AsString;
nData[6].FText := DateTime2Str(FieldByName('D_Date').AsDateTime);
FPainter.AddData(nData);
Next;
end;
end;
SetLength(nData, 7);
for nIdx:=Low(nData) to High(nData) do
begin
nData[nIdx].FText := '';
nData[nIdx].FCtrls := nil;
nData[nIdx].FAlign := taCenter;
end;
nData[0].FText := '合计:';
nData[4].FText := Format('%d件', [nNum]);
FPainter.AddData(nData);
finally
FDM.ReleaseDataSet(nDS);
end;
end;
procedure TfFormProductBillDeal.BtnOKClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
end.
|
unit tfwMainDictionary;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwMainDictionary.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TtfwMainDictionary" MUID: (55A0005D02CC)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwDictionaryEx
, tfwScriptingInterfaces
, tfwDictionary
, l3Interfaces
;
type
TtfwMainDictionary = class(TtfwDictionaryEx)
private
f_CompiledCode: TtfwWord;
protected
procedure pm_SetCompiledCode(aValue: TtfwWord);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
function FindInUsedDictionary(anOther: TtfwDictionary;
const aName: Il3CString): TtfwKeyWord; override;
public
function IsMain: Boolean; override;
public
property CompiledCode: TtfwWord
read f_CompiledCode
write pm_SetCompiledCode;
end;//TtfwMainDictionary
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, tfwMainDictionaryWordsPack
//#UC START# *55A0005D02CCimpl_uses*
//#UC END# *55A0005D02CCimpl_uses*
;
procedure TtfwMainDictionary.pm_SetCompiledCode(aValue: TtfwWord);
//#UC START# *55A4E85101BA_55A0005D02CCset_var*
//#UC END# *55A4E85101BA_55A0005D02CCset_var*
begin
//#UC START# *55A4E85101BA_55A0005D02CCset_impl*
aValue.SetRefTo(f_CompiledCode);
//#UC END# *55A4E85101BA_55A0005D02CCset_impl*
end;//TtfwMainDictionary.pm_SetCompiledCode
procedure TtfwMainDictionary.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_55A0005D02CC_var*
//#UC END# *479731C50290_55A0005D02CC_var*
begin
//#UC START# *479731C50290_55A0005D02CC_impl*
CompiledCode := nil;
inherited;
//#UC END# *479731C50290_55A0005D02CC_impl*
end;//TtfwMainDictionary.Cleanup
function TtfwMainDictionary.FindInUsedDictionary(anOther: TtfwDictionary;
const aName: Il3CString): TtfwKeyWord;
//#UC START# *55A3A1E7038F_55A0005D02CC_var*
//#UC END# *55A3A1E7038F_55A0005D02CC_var*
begin
//#UC START# *55A3A1E7038F_55A0005D02CC_impl*
(* if (anOther Is TtfwHLTCLikeDictionary) then
Result := anOther.DRbyCName[aName]
else*)
Result := inherited FindInUsedDictionary(anOther, aName);
//#UC END# *55A3A1E7038F_55A0005D02CC_impl*
end;//TtfwMainDictionary.FindInUsedDictionary
function TtfwMainDictionary.IsMain: Boolean;
//#UC START# *55A531FA016A_55A0005D02CC_var*
//#UC END# *55A531FA016A_55A0005D02CC_var*
begin
//#UC START# *55A531FA016A_55A0005D02CC_impl*
Result := true;
//#UC END# *55A531FA016A_55A0005D02CC_impl*
end;//TtfwMainDictionary.IsMain
{$IfEnd} // NOT Defined(NoScripts)
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.47 1/24/2005 7:35:54 PM JPMugaas
Fixed CopyTIdIPV6Address.
Rev 1.46 1/17/2005 7:28:44 PM JPMugaas
Added Index parameter to several functions so you can use TIdBuffer in a
random access manner instead of in a sequential manner. This is good for
some fixed-packet or data types.
Added functions for reading and writing various types to TIdBuffer which use
Byte Order functions. This should facilitate a lot of development as this
gets used more.
Rev 1.45 27.08.2004 21:58:18 Andreas Hausladen
Speed optimization ("const" for string parameters)
Rev 1.44 2004.07.03 19:41:34 czhower
UTF8, SaveToStream
Rev 1.43 6/11/2004 8:48:12 AM DSiders
Added "Do not Localize" comments.
Rev 1.42 6/9/04 7:46:26 PM RLebeau
Updated ExtractToBytes() to allocate the output buffer only if the buffer
length is smaller than the requested number of bytes.
Rev 1.41 5/29/04 10:44:58 PM RLebeau
Updated ExtractToBytes() to allocate the output buffer regardless of the
AAppend parameter
Added empty string return value to Extract() when AByteCount <= 0
Rev 1.40 2004.05.20 11:39:06 AM czhower
IdStreamVCL
Rev 1.39 2004.05.10 1:19:18 PM czhower
Removed unneeded code.
Rev 1.38 5/3/2004 12:57:00 PM BGooijen
Fixes for 0-based
Rev 1.37 2004.05.03 11:15:42 AM czhower
Changed Find to IndexOf and made 0 based to be consistent.
Rev 1.36 2004.05.01 4:26:52 PM czhower
Added PeekByte
Rev 1.35 2004.04.16 11:30:26 PM czhower
Size fix to IdBuffer, optimizations, and memory leaks
Rev 1.34 2004.04.08 7:06:44 PM czhower
Peek support.
Rev 1.33 2004.04.08 3:56:24 PM czhower
Fixed bug with Intercept byte count. Also removed Bytes from Buffer.
Rev 1.32 2004.04.08 2:03:34 AM czhower
Fixes to Bytes.
Rev 1.31 2004.04.07 3:59:44 PM czhower
Bug fix for WriteDirect.
Rev 1.30 2004.04.07 3:46:30 PM czhower
Compile fix.
Rev 1.29 4/7/2004 1:02:14 PM BGooijen
when extract* is called with -1 or no parameters all data it extracted
Rev 1.28 2004.03.29 9:58:38 PM czhower
Is now buffered. Now takes 2/3rds the time as before.
Rev 1.27 23/03/2004 18:33:44 CCostelloe
Bug fix: ReadLn returns a previously-read line if FBytes also accessed
in-between (causes MoveHeadToStartIfNecessary to be called)
Rev 1.26 18/03/2004 20:24:26 CCostelloe
Speed improvement by adding FHeadIndex: 10 MB base64 decode reduced from 10
hours to 62 seconds.
Rev 1.25 2004.03.03 11:55:02 AM czhower
IdStream change
Rev 1.24 3/1/04 7:33:12 PM RLebeau
Updated Remove() to call the OnBytesRemoved event handler.
Rev 1.23 2004.02.03 4:17:14 PM czhower
For unit name changes.
Rev 1.22 1/11/2004 5:48:48 PM BGooijen
Added AApend parameter to ExtractToBytes
Rev 1.21 1/7/2004 8:36:32 PM BGooijen
Arguments were in wrong order
Rev 1.20 22/11/2003 10:35:04 PM GGrieve
Reverse copy direction in TIdBuffer.ExtractToStream
Rev 1.19 2003.10.24 10:44:54 AM czhower
IdStream implementation, bug fixes.
Rev 1.18 10/15/2003 1:03:40 PM DSiders
Created resource strings for TIdBuffer.Find exceptions.
Rev 1.17 2003.10.14 1:27:06 PM czhower
Uupdates + Intercept support
Rev 1.16 2003.10.11 5:47:00 PM czhower
-VCL fixes for servers
-Chain suport for servers (Super core)
-Scheduler upgrades
-Full yarn support
Rev 1.15 10/5/2003 10:24:20 PM BGooijen
Changed WriteBytes(var ...) to WriteBytes(const ...)
Rev 1.14 10/3/2003 10:46:38 PM BGooijen
Fixed Range Check Exception, and fixed ExtractToStream
Rev 1.13 2003.10.02 8:29:12 PM czhower
Changed names of byte conversion routines to be more readily understood and
not to conflict with already in use ones.
Rev 1.12 2003.10.02 12:44:58 PM czhower
Comment added
Rev 1.11 10/2/2003 5:23:14 PM GGrieve
make Bytes a public property
Rev 1.10 10/2/2003 5:00:38 PM GGrieve
Fix bug in find - can't find last char
Rev 1.9 2003.10.02 10:37:00 AM czhower
Comments
Rev 1.8 10/2/2003 3:54:06 PM GGrieve
Finish cleaning up - no $IFDEFs but still optimal on both win32 and DontNet
Rev 1.7 10/1/2003 10:58:38 PM BGooijen
Removed unused var
Rev 1.6 10/1/2003 8:15:58 PM BGooijen
Fixed Range Check Error on D7
Rev 1.5 10/1/2003 8:02:22 PM BGooijen
Removed some ifdefs and improved code
Rev 1.4 10/1/2003 10:49:02 PM GGrieve
Rework buffer for Octane Compability
Rev 1.3 2003.10.01 2:30:44 PM czhower
.Net
Rev 1.2 2003.10.01 1:37:32 AM czhower
.Net
Rev 1.1 2003.10.01 1:12:32 AM czhower
.Net
Rev 1.0 2003.09.30 10:33:56 PM czhower
Readd after accidental delete.
Rev 1.14 2003.09.30 10:33:16 PM czhower
Updates
Rev 1.13 2003.07.16 5:05:06 PM czhower
Phase 1 of IdBuffer changes for compat.
Rev 1.12 6/29/2003 10:56:22 PM BGooijen
Removed .Memory from the buffer, and added some extra methods
Rev 1.11 2003.06.25 4:29:06 PM czhower
Free --> FreeAndNil
Rev 1.10 2003.01.17 2:18:36 PM czhower
Rev 1.9 12-14-2002 22:08:24 BGooijen
Changed FMemory to FMemory.Memory in some places
Rev 1.8 12-14-2002 22:02:34 BGooijen
changed Memory to FMemory in some places, to remove some issues
Rev 1.7 12/11/2002 04:27:02 AM JPMugaas
Fixed compiler warning.
Rev 1.6 12/11/2002 03:53:44 AM JPMugaas
Merged the buffer classes.
Rev 1.5 2002.12.07 12:26:18 AM czhower
Rev 1.4 12-6-2002 20:34:06 BGooijen
Now compiles on Delphi 5
Rev 1.3 6/12/2002 11:00:14 AM SGrobety
Rev 1.2 12/5/2002 02:55:44 PM JPMugaas
Added AddStream method for reading a stream into the buffer class.
Rev 1.1 23.11.2002 12:59:48 JBerg
fixed packbuffer
Rev 1.0 11/13/2002 08:38:32 AM JPMugaas
}
unit IdBuffer;
{$I IdCompilerDefines.inc}
{
.Net forces us to perform copies from strings to Bytes so that it can do the
proper unicode and other conversions.
IdBuffer is for storing data we cannot deal with right now and we do not know
the size. It must be optimized for adding to the end, and extracting from the
beginning. First pass we are just making it work, later using bubbling we will
optimize it for such tasks.
The copy is a separate issue and we considered several options. For .net we will
always have to copy data to send or to receive to translate it to binary. For
example if we have a string it must be converted to bytes. This conversion
requires a copy. All strings are Unicode and must be converted to single
bytes by a convertor. This is not limited to strings.
In VCL previously all strings were AnsiString so we used a pointer and just
accessed the memory directly from the string. This avoided the overhead of a
copy.
We have come up with several ideas on how to allow the copy on .net, while
avoiding the copy on VCL to keep the performance benefit. However we must do
it in a single source manner and in a manner that does not impact the code
negatively.
For now for VCL we also do a copy. This has the advantage that Byte arrays are
reference counted and automaticaly handled by Delphi. For example:
WriteBytes(StringToBytes(s));
The array returned by this function will automatically be freed by Delphi.
There are other options that are nearly as transparent but have the additional
overhead of requiring class creation. These classes can be used to copy for .net
and proxy on VCL. It all works very nice and has low memory overhead. The
objects can then be freed by default in methods that accept them.
However after analysis, copy on VCL may not be that bad after all. The copy
only really impacts strings. The overhead to copy strings is minimal and only
used in commands etc. The big transfers come from files, streams, or other.
Such transfers have to be mapped into memory in VCL anyways, and if we map
directly into the byte array instead of the previous classes peformance should
be fine.
In short - copy under VCL should be acceptable if we watch for bottlenecks and
fix them appropriately without having to creat proxy classes. The only problem
remains for transmitting large memory blocks. But if this is done against a
fixed copy buffer the performance hit will be neglible and it is not a common
task to transmit large memory blocks.
For such transfers from streams, etc the user can declare a persistent array
of bytes that is not freed between each call to WriteBytes.
-Kudzu
}
interface
uses
Classes,
IdException,
IdGlobal,
SysUtils;
type
EIdNotEnoughDataInBuffer = class(EIdException);
EIdTooMuchDataInBuffer = class(EIdException); // only 2GB is allowed -
TIdBufferBytesRemoved = procedure(ASender: TObject; ABytes: Integer) of object;
// TIdBuffer is used as an internal buffer to isolate Indy from pointers and
// memory allocations. It also allows optimizations to be kept in a single place.
//
// TIdBuffer is primarily used as a read/write buffer for the communication layer.
TIdBuffer = class(TObject)
private
function GetAsString: string;
protected
FBytes: TIdBytes;
FByteEncoding: TIdTextEncoding;
{$IFDEF STRING_IS_ANSI}
FAnsiEncoding: TIdTextEncoding;
{$ENDIF}
FGrowthFactor: Integer;
FHeadIndex: Integer;
FOnBytesRemoved: TIdBufferBytesRemoved;
FSize: Integer;
//
procedure CheckAdd(AByteCount : Integer; const AIndex : Integer);
procedure CheckByteCount(var VByteCount : Integer; const AIndex : Integer);
function GetCapacity: Integer;
procedure SetCapacity(AValue: Integer);
public
procedure Clear;
constructor Create; overload;
constructor Create(AOnBytesRemoved: TIdBufferBytesRemoved); overload;
constructor Create(AGrowthFactor: Integer); overload;
constructor Create(const ABytes : TIdBytes; const ALength : Integer = -1); overload;
procedure CompactHead(ACanShrink: Boolean = True);
destructor Destroy; override;
{
Most of these now have an AIndex parameter. If that is less than 0,
we are accessing data sequentially. That means, read the data from the HeadIndex
and "remove" the data you read.
If AIndex is 0 or greater, the HeadIndex is disregarded and no deletion is done.
You are just reading from a particular location in a random access manner.
}
// will extract number of bytes and decode as specified
function Extract(AByteCount: Integer = -1; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string; {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'Use ExtractToString()'{$ENDIF};{$ENDIF}
function ExtractToString(AByteCount: Integer = -1; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
// all 3 extract routines append to existing data, if any
procedure ExtractToStream(const AStream: TStream; AByteCount: Integer = -1; const AIndex: Integer = -1);
procedure ExtractToIdBuffer(ABuffer: TIdBuffer; AByteCount: Integer = -1; const AIndex : Integer = -1);
procedure ExtractToBytes(var VBytes: TIdBytes; AByteCount: Integer = -1;
AAppend: Boolean = True; AIndex : Integer = -1);
function ExtractToByte(const AIndex : Integer): Byte;
function ExtractToWord(const AIndex : Integer): Word;
function ExtractToLongWord(const AIndex : Integer): LongWord;
function ExtractToInt64(const AIndex : Integer): Int64;
procedure ExtractToIPv6(const AIndex : Integer; var VAddress: TIdIPv6Address);
function IndexOf(const AByte: Byte; AStartPos: Integer = 0): Integer; overload;
function IndexOf(const ABytes: TIdBytes; AStartPos: Integer = 0): Integer; overload;
function IndexOf(const AString: string; AStartPos: Integer = 0;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
): Integer; overload;
function PeekByte(AIndex: Integer): Byte;
procedure Remove(AByteCount: Integer);
procedure SaveToStream(const AStream: TStream);
{ Most of these now have an ADestIndex parameter. If that is less than 0,
we are writing data sequentially.
If ADestIndex is 0 or greater, you are setting bytes in a particular
location in a random access manner.
}
// Write
procedure Write(const AString: string; AByteEncoding: TIdTextEncoding = nil;
const ADestIndex: Integer = -1
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
); overload;
procedure Write(const ABytes: TIdBytes; const ADestIndex: Integer = -1); overload;
procedure Write(const ABytes: TIdBytes; const ALength, AOffset : Integer; const ADestIndex: Integer = -1); overload;
procedure Write(AStream: TStream; AByteCount: Integer = 0); overload;
procedure Write(const AValue: Int64; const ADestIndex: Integer = -1); overload;
procedure Write(const AValue: LongWord; const ADestIndex: Integer = -1); overload;
procedure Write(const AValue: Word; const ADestIndex: Integer = -1); overload;
procedure Write(const AValue: Byte; const ADestIndex: Integer = -1); overload;
procedure Write(const AValue: TIdIPv6Address; const ADestIndex: Integer = -1); overload;
//
//Kudzu: I have removed the Bytes property. Do not add it back - it allowed "internal" access
// which caused compacting or internal knowledge. Access via Extract or other such methods
// instead. Bytes could also be easily confused with FBytes internally and cause issues.
//
// Bytes also allowed direct acces without removing which could cause concurrency issues if
// the reference was kept.
//
property Capacity: Integer read GetCapacity write SetCapacity;
property Encoding: TIdTextEncoding read FByteEncoding write FByteEncoding;
{$IFDEF STRING_IS_ANSI}
property AnsiEncoding: TIdTextEncoding read FAnsiEncoding write FAnsiEncoding;
{$ENDIF}
property GrowthFactor: Integer read FGrowthFactor write FGrowthFactor;
property Size: Integer read FSize;
//useful for testing. returns buffer as string without extraction.
property AsString: string read GetAsString;
end;
implementation
uses
IdResourceStringsCore,
IdStream,
IdStack; //needed for byte order functions
procedure TIdBuffer.CheckAdd(AByteCount : Integer; const AIndex : Integer);
begin
if (MaxInt - AByteCount) < (Size + AIndex) then begin
EIdTooMuchDataInBuffer.Toss(RSTooMuchDataInBuffer);
end;
end;
procedure TIdBuffer.CheckByteCount(var VByteCount : Integer; const AIndex : Integer);
begin
if VByteCount = -1 then begin
VByteCount := Size+AIndex;
end
else if VByteCount > (Size+AIndex) then begin
EIdNotEnoughDataInBuffer.Toss(RSNotEnoughDataInBuffer + ' (' + IntToStr(VByteCount) + '/' + IntToStr(Size) + ')'); {do not localize}
end;
end;
procedure TIdBuffer.Clear;
begin
SetLength(FBytes, 0);
FHeadIndex := 0;
FSize := Length(FBytes);
end;
constructor TIdBuffer.Create(AGrowthFactor: Integer);
begin
Create;
FGrowthFactor := AGrowthFactor;
end;
constructor TIdBuffer.Create(AOnBytesRemoved: TIdBufferBytesRemoved);
begin
Create;
FOnBytesRemoved := AOnBytesRemoved;
end;
constructor TIdBuffer.Create(const ABytes: TIdBytes; const ALength: Integer);
begin
Create;
if ALength < 0 then
begin
FBytes := ABytes;
FSize := Length(ABytes);
end else
begin
SetLength(FBytes, ALength);
if ALength > 0 then
begin
CopyTIdBytes(ABytes, 0, FBytes, 0, ALength);
FSize := ALength;
end;
end;
end;
destructor TIdBuffer.Destroy;
begin
Clear;
inherited Destroy;
//do only at the last moment
TIdStack.DecUsage;
end;
function TIdBuffer.Extract(AByteCount: Integer = -1; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
Result := ExtractToString(AByteCount, AByteEncoding{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF});
end;
function TIdBuffer.ExtractToString(AByteCount: Integer = -1; AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF}
): string;
var
LBytes: TIdBytes;
begin
if AByteCount < 0 then begin
AByteCount := Size;
end;
if AByteCount > 0 then
begin
if AByteEncoding = nil then begin
AByteEncoding := FByteEncoding;
EnsureEncoding(AByteEncoding);
end;
{$IFDEF STRING_IS_ANSI}
if ADestEncoding = nil then begin
ADestEncoding := FAnsiEncoding;
EnsureEncoding(ADestEncoding, encOSDefault);
end;
{$ENDIF}
ExtractToBytes(LBytes, AByteCount);
Result := BytesToString(LBytes, AByteEncoding
{$IFDEF STRING_IS_ANSI}, ADestEncoding{$ENDIF}
);
end else begin
Result := '';
end;
end;
procedure TIdBuffer.ExtractToBytes(var VBytes: TIdBytes; AByteCount: Integer = -1;
AAppend: Boolean = True; AIndex : Integer = -1);
var
LOldSize: Integer;
LIndex : Integer;
begin
if AByteCount < 0 then begin
AByteCount := Size;
end;
LIndex := IndyMax(AIndex, 0);
if AByteCount > 0 then begin
CheckByteCount(AByteCount, LIndex);
if AAppend then begin
LOldSize := Length(VBytes);
SetLength(VBytes, LOldSize + AByteCount);
end else begin
LOldSize := 0;
if Length(VBytes) < AByteCount then begin
SetLength(VBytes, AByteCount);
end;
end;
if AIndex < 0 then
begin
CopyTIdBytes(FBytes, FHeadIndex, VBytes, LOldSize, AByteCount);
Remove(AByteCount);
end else
begin
CopyTIdBytes(FBytes, AIndex, VBytes, LOldSize, AByteCount);
end;
end;
end;
procedure TIdBuffer.ExtractToIdBuffer(ABuffer: TIdBuffer; AByteCount: Integer = -1;
const AIndex: Integer = -1);
var
LBytes: TIdBytes;
begin
if AByteCount < 0 then begin
AByteCount := Size;
end;
//TODO: Optimize this routine to directly copy from one to the other
ExtractToBytes(LBytes, AByteCount, True, AIndex);
ABuffer.Write(LBytes);
end;
procedure TIdBuffer.ExtractToStream(const AStream: TStream; AByteCount: Integer = -1;
const AIndex: Integer = -1);
var
LIndex : Integer;
LBytes : TIdBytes;
begin
if AByteCount < 0 then begin
AByteCount := Size;
end;
LIndex := IndyMax(AIndex, 0);
if AIndex < 0 then
begin
CompactHead;
CheckByteCount(AByteCount, LIndex);
TIdStreamHelper.Write(AStream, FBytes, AByteCount);
Remove(AByteCount);
end else
begin
CheckByteCount(AByteCount, LIndex);
SetLength(LBytes, AByteCount);
CopyTIdBytes(FBytes, AIndex, LBytes, 0, AByteCount);
TIdStreamHelper.Write(AStream, LBytes, AByteCount);
end;
end;
procedure TIdBuffer.Remove(AByteCount: Integer);
begin
if AByteCount >= Size then begin
Clear;
end else begin
Inc(FHeadIndex, AByteCount);
Dec(FSize, AByteCount);
if FHeadIndex > GrowthFactor then begin
CompactHead;
end;
end;
if Assigned(FOnBytesRemoved) then begin
FOnBytesRemoved(Self, AByteCount);
end;
end;
procedure TIdBuffer.CompactHead(ACanShrink: Boolean = True);
begin
// Only try to compact if needed.
if FHeadIndex > 0 then begin
CopyTIdBytes(FBytes, FHeadIndex, FBytes, 0, Size);
FHeadIndex := 0;
if ACanShrink and ((Capacity - Size - FHeadIndex) > GrowthFactor) then begin
SetLength(FBytes, FHeadIndex + Size + GrowthFactor);
end;
end;
end;
procedure TIdBuffer.Write(const ABytes: TIdBytes; const ADestIndex: Integer = -1);
{$IFDEF USE_CLASSINLINE}inline;{$ENDIF}
begin
Write(ABytes, Length(ABytes), 0, ADestIndex);
end;
procedure TIdBuffer.Write(AStream: TStream; AByteCount: Integer);
var
LAdded: Integer;
LLength: Integer;
begin
if AByteCount < 0 then begin
// Copy remaining
LAdded := AStream.Size - AStream.Position;
end else if AByteCount = 0 then begin
// Copy all
AStream.Position := 0;
LAdded := AStream.Size;
end else begin
LAdded := IndyMin(AByteCount, AStream.Size - AStream.Position);
end;
if LAdded > 0 then begin
LLength := Size;
CheckAdd(LAdded, 0);
CompactHead;
SetLength(FBytes, LLength + LAdded);
TIdStreamHelper.ReadBytes(AStream, FBytes, LAdded, LLength);
Inc(FSize, LAdded);
end;
end;
function TIdBuffer.IndexOf(const AString: string; AStartPos: Integer = 0;
AByteEncoding: TIdTextEncoding = nil
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
): Integer;
begin
if AByteEncoding = nil then begin
AByteEncoding := FByteEncoding;
end;
{$IFDEF STRING_IS_ANSI}
if ASrcEncoding = nil then begin
ASrcEncoding := FAnsiEncoding;
end;
{$ENDIF}
Result := IndexOf(
ToBytes(AString, AByteEncoding{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}),
AStartPos);
end;
function TIdBuffer.IndexOf(const ABytes: TIdBytes; AStartPos: Integer = 0): Integer;
var
i, j, LEnd, BytesLen: Integer;
LFound: Boolean;
begin
Result := -1;
// Dont search if it empty
if Size > 0 then begin
if Length(ABytes) = 0 then begin
EIdException.Toss(RSBufferMissingTerminator);
end;
if (AStartPos < 0) or (AStartPos >= Size) then begin
EIdException.Toss(RSBufferInvalidStartPos);
end;
BytesLen := Length(ABytes);
LEnd := FHeadIndex + Size;
for i := FHeadIndex + AStartPos to LEnd - BytesLen do begin
LFound := True;
for j := 0 to BytesLen - 1 do begin
if (i + j) >= LEnd then begin
Break;
end;
if FBytes[i + j] <> ABytes[j] then begin
LFound := False;
Break;
end;
end;
if LFound then begin
Result := i - FHeadIndex;
Break;
end;
end;
end;
end;
function TIdBuffer.IndexOf(const AByte: Byte; AStartPos: Integer = 0): Integer;
var
i: Integer;
begin
Result := -1;
// Dont search if it empty
if Size > 0 then begin
if (AStartPos < 0) or (AStartPos >= Size) then begin
EIdException.Toss(RSBufferInvalidStartPos);
end;
for i := (FHeadIndex + AStartPos) to (FHeadIndex + Size - 1) do begin
if FBytes[i] = AByte then begin
Result := i - FHeadIndex;
Break;
end;
end;
end;
end;
procedure TIdBuffer.Write(const AString: string; AByteEncoding: TIdTextEncoding = nil;
const ADestIndex : Integer = -1
{$IFDEF STRING_IS_ANSI}; ASrcEncoding: TIdTextEncoding = nil{$ENDIF}
);
begin
if AByteEncoding = nil then begin
AByteEncoding := FByteEncoding;
end;
{$IFDEF STRING_IS_ANSI}
if ASrcEncoding = nil then begin
ASrcEncoding := FAnsiEncoding;
end;
{$ENDIF}
Write(
ToBytes(AString, AByteEncoding{$IFDEF STRING_IS_ANSI}, ASrcEncoding{$ENDIF}),
ADestIndex);
end;
function TIdBuffer.GetCapacity: Integer;
begin
Result := Length(FBytes);
end;
procedure TIdBuffer.SetCapacity(AValue: Integer);
begin
if AValue < Size then begin
EIdException.Toss('Capacity cannot be smaller than Size'); {do not localize}
end;
CompactHead;
SetLength(FBytes, AValue);
end;
constructor TIdBuffer.Create;
begin
inherited Create;
FGrowthFactor := 2048;
Clear;
TIdStack.IncUsage;
end;
function TIdBuffer.PeekByte(AIndex: Integer): Byte;
begin
if Size = 0 then begin
EIdException.Toss('No bytes in buffer.'); {do not localize}
end;
if (AIndex < 0) or (AIndex >= Size) then begin
EIdException.Toss('Index out of bounds.'); {do not localize}
end;
Result := FBytes[FHeadIndex + AIndex];
end;
procedure TIdBuffer.SaveToStream(const AStream: TStream);
begin
CompactHead(False);
TIdStreamHelper.Write(AStream, FBytes, Size);
end;
procedure TIdBuffer.ExtractToIPv6(const AIndex: Integer; var VAddress: TIdIPv6Address);
var
LIndex : Integer;
begin
if AIndex < 0 then begin
LIndex := FHeadIndex;
end else begin
LIndex := AIndex;
end;
BytesToIPv6(FBytes, VAddress, LIndex);
VAddress := GStack.NetworkToHost(VAddress);
if AIndex < 0 then begin
Remove(16);
end;
end;
function TIdBuffer.ExtractToInt64(const AIndex: Integer): Int64;
var
LIndex : Integer;
begin
if AIndex < 0 then begin
LIndex := FHeadIndex;
end else begin
LIndex := AIndex;
end;
Result := BytesToInt64(FBytes, LIndex);
Result := GStack.NetworkToHost(Result);
if AIndex < 0 then begin
Remove(8);
end;
end;
function TIdBuffer.ExtractToLongWord(const AIndex: Integer): LongWord;
var
LIndex : Integer;
begin
if AIndex < 0 then begin
LIndex := FHeadIndex;
end else begin
LIndex := AIndex;
end;
Result := BytesToLongWord(FBytes, LIndex);
Result := GStack.NetworkToHost(Result);
if AIndex < 0 then begin
Remove(4);
end;
end;
function TIdBuffer.ExtractToWord(const AIndex: Integer): Word;
var
LIndex : Integer;
begin
if AIndex < 0 then begin
LIndex := FHeadIndex;
end else begin
LIndex := AIndex;
end;
Result := BytesToWord(FBytes, LIndex);
Result := GStack.NetworkToHost(Result);
if AIndex < 0 then begin
Remove(2);
end;
end;
function TIdBuffer.ExtractToByte(const AIndex: Integer): Byte;
var
LIndex : Integer;
begin
if AIndex < 0 then begin
LIndex := FHeadIndex;
end else begin
LIndex := AIndex;
end;
Result := FBytes[LIndex];
if AIndex < 0 then begin
Remove(1);
end;
end;
procedure TIdBuffer.Write(const AValue: Word; const ADestIndex: Integer);
var
LVal : Word;
LIndex : Integer;
begin
if ADestIndex < 0 then
begin
LIndex := FHeadIndex + Size;
SetLength(FBytes, LIndex+2);
end else
begin
LIndex := ADestIndex;
end;
LVal := GStack.HostToNetwork(AValue);
CopyTIdWord(LVal, FBytes, LIndex);
if LIndex >= FSize then begin
FSize := LIndex+2;
end;
end;
procedure TIdBuffer.Write(const AValue: Byte; const ADestIndex: Integer);
var
LIndex : Integer;
begin
if ADestIndex < 0 then
begin
LIndex := FHeadIndex + Size;
SetLength(FBytes, LIndex+1);
end else
begin
LIndex := ADestIndex;
end;
FBytes[LIndex] := AValue;
if LIndex >= FSize then begin
FSize := LIndex+1;
end;
end;
procedure TIdBuffer.Write(const AValue: TIdIPv6Address; const ADestIndex: Integer);
var
LVal : TIdIPv6Address;
LIndex : Integer;
begin
if ADestIndex < 0 then
begin
LIndex := FHeadIndex + Size;
SetLength(FBytes, LIndex + 16);
end else
begin
LIndex := ADestIndex;
end;
LVal := GStack.HostToNetwork(AValue);
CopyTIdIPV6Address(LVal, FBytes, LIndex);
if LIndex >= FSize then begin
FSize := LIndex+16;
end;
end;
procedure TIdBuffer.Write(const AValue: Int64; const ADestIndex: Integer);
var
LVal: Int64;
LIndex: Integer;
LSize: Integer;
begin
LSize := SizeOf(Int64);
if ADestIndex < 0 then
begin
LIndex := FHeadIndex + Size;
SetLength(FBytes, LIndex + LSize);
end else
begin
LIndex := ADestIndex;
end;
LVal := GStack.HostToNetwork(AValue);
CopyTIdInt64(LVal, FBytes, LIndex);
if LIndex >= FSize then begin
FSize := LIndex + LSize;
end;
end;
procedure TIdBuffer.Write(const AValue: LongWord; const ADestIndex: Integer);
var
LVal : LongWord;
LIndex : Integer;
begin
if ADestIndex < 0 then
begin
LIndex := FHeadIndex + Size;
SetLength(FBytes, LIndex + SizeOf(LongWord));
end else
begin
LIndex := ADestIndex;
end;
LVal := GStack.HostToNetwork(AValue);
CopyTIdLongWord(LVal, FBytes, LIndex);
if LIndex >= FSize then begin
FSize := LIndex+4;
end;
end;
procedure TIdBuffer.Write(const ABytes: TIdBytes; const ALength, AOffset : Integer;
const ADestIndex: Integer = -1);
var
LByteLength: Integer;
LIndex : Integer;
begin
LByteLength := IndyLength(ABytes, ALength, AOffset);
if LByteLength = 0 then begin
Exit;
end;
LIndex := IndyMax(ADestIndex, 0);
CheckAdd(LByteLength, LIndex);
if Size = 0 then begin
FHeadIndex := 0;
if ADestIndex < 0 then
begin
FBytes := ToBytes(ABytes, LByteLength, AOffset);
FSize := LByteLength;
end else
begin
FSize := ADestIndex + LByteLength;
SetLength(FBytes, FSize);
CopyTIdBytes(ABytes, AOffset, FBytes, ADestIndex, LByteLength);
end;
end
else if ADestIndex < 0 then
begin
CompactHead(False);
if (Capacity - Size - FHeadIndex) < LByteLength then begin
SetLength(FBytes, Size + LByteLength + GrowthFactor);
end;
CopyTIdBytes(ABytes, AOffset, FBytes, FHeadIndex + Size, LByteLength);
Inc(FSize, LByteLength);
end else
begin
CopyTIdBytes(ABytes, AOffset, FBytes, LIndex, LByteLength);
if LIndex >= FSize then begin
FSize := LIndex + LByteLength;
end;
end;
end;
function TIdBuffer.GetAsString: string;
begin
Result := BytesToString(FBytes, FByteEncoding
{$IFDEF STRING_IS_ANSI}, FAnsiEncoding{$ENDIF}
);
end;
end.
|
unit System.Classes.Helper;
interface
uses System.Classes, System.SysUtils;
Type
IFireEventProc = interface
['{BBC08E72-6518-4BF8-8BEE-0A46FD8B351C}']
procedure SetOnEvent(const Value: TProc<TObject>);
procedure FireEvent(Sender: TObject);
end;
TObjectExt = class(System.TObject)
private
FOnFireEvent: TProc<TObject>;
procedure SetOnFireEvent(const Value: TProc<TObject>);
public
procedure FireEvent; overload;
procedure FireEvent(Sender: TObject); overload;
property OnFireEvent: TProc<TObject> read FOnFireEvent
write SetOnFireEvent;
end;
TObjectHelper = class helper for TObject
private
public
class procedure Using<T>(O: T; Proc: TProc<T>); static;
class function Anonimous<T: Class>(O: T; Proc: TProc<T>): TObject; static;
class procedure Run<T: Class>(O: T; Proc: TProc<T>); static;
class function Queue<T: Class>(O: T; Proc: TProc<T>): TObject;
overload; static;
class function Synchronize<T: Class>(O: T; Proc: TProc<T>): TObject;
overload; static;
class procedure Synchronize(Proc: TProc); overload; static;
class procedure Queue(Proc: TProc); overload; static;
end;
implementation
class procedure TObjectHelper.Using<T>(O: T; Proc: TProc<T>);
var
obj: TObject;
begin
try
Proc(O);
finally
freeAndNil(O);
end;
end;
procedure TObjectExt.FireEvent;
begin
FireEvent(self);
end;
class procedure TObjectHelper.Queue(Proc: TProc);
begin
TThread.Queue(nil, procedure
begin
Proc;
end);
end;
class function TObjectHelper.Queue<T>(O: T; Proc: TProc<T>): TObject;
begin
result := O;
TThread.Queue(nil, procedure
begin
Proc(O);
end);
end;
class procedure TObjectHelper.Run<T>(O: T; Proc: TProc<T>);
begin
TThread.CreateAnonymousThread(procedure
begin
Proc(O);
end).Start;
end;
class procedure TObjectHelper.Synchronize(Proc: TProc);
begin
TThread.Synchronize(nil, procedure
begin
Proc
end);
end;
class function TObjectHelper.Synchronize<T>(O: T; Proc: TProc<T>): TObject;
begin
result := O;
TThread.Synchronize(nil, procedure
begin
Proc(O);
end);
end;
class function TObjectHelper.Anonimous<T>(O: T; Proc: TProc<T>): TObject;
begin
result := O;
Proc(O);
end;
{ TObject }
procedure TObjectExt.FireEvent(Sender: TObject);
begin
if assigned(FOnFireEvent) then
FOnFireEvent(Sender);
end;
procedure TObjectExt.SetOnFireEvent(const Value: TProc<TObject>);
begin
FOnFireEvent := Value;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.