text stringlengths 14 6.51M |
|---|
unit Entities;
interface
uses
SysUtils,
Generics.Collections,
Aurelius.Mapping.Attributes,
Aurelius.Mapping.Metadata,
Aurelius.Types.Blob,
Aurelius.Types.DynamicProperties,
Aurelius.Types.Nullable,
Aurelius.Types.Proxy;
type
TBook = class;
TCategory = class;
[Entity]
[Table('BOOKS')]
[Id('FBookID', TIdGenerator.IdentityOrSequence)]
TBook = class
private
[Column('BOOKID', [TColumnProp.Required, TColumnProp.NoInsert, TColumnProp.NoUpdate])]
FBookID: Integer;
[Column('BOOKNAME', [TColumnProp.Required])]
[DBTypeMemo]
FBookName: String;
[Column('BOOKLINK', [])]
[DBTypeMemo]
FBookLink: Nullable<String>;
[Association([TAssociationProp.Lazy], CascadeTypeAll - [TCascadeType.Remove])]
[JoinColumn('CATEGORYID', [], 'CATEGORYID')]
FCategoryID: Proxy<TCategory>;
private
function GetCategoryID: TCategory;
procedure SetCategoryID(const Value: TCategory);
public
property BookID: Integer read FBookID write FBookID;
property BookName: String read FBookName write FBookName;
property BookLink: Nullable<String> read FBookLink write FBookLink;
property CategoryID: TCategory read GetCategoryID write SetCategoryID;
end;
[Entity]
[Table('CATEGORIES')]
[Id('FCategoryID', TIdGenerator.IdentityOrSequence)]
TCategory = class
private
[Column('CATEGORYID', [TColumnProp.Required, TColumnProp.NoInsert, TColumnProp.NoUpdate])]
FCategoryID: Integer;
[Column('CATEGORYNAME', [TColumnProp.Required])]
[DBTypeMemo]
FCategoryName: String;
[Association([TAssociationProp.Lazy], CascadeTypeAll - [TCascadeType.Remove])]
[JoinColumn('PARENTID', [], 'CATEGORYID')]
FParentID: Proxy<TCategory>;
[ManyValuedAssociation([TAssociationProp.Lazy], [TCascadeType.SaveUpdate, TCascadeType.Merge], 'FCategoryID')]
FBooks: Proxy<TList<TBook>>;
private
function GetParentID: TCategory;
procedure SetParentID(const Value: TCategory);
function GetBooks: TList<TBook>;
public
constructor Create;
destructor Destroy; override;
property CategoryID: Integer read FCategoryID write FCategoryID;
property CategoryName: String read FCategoryName write FCategoryName;
property ParentID: TCategory read GetParentID write SetParentID;
property Books: TList<TBook> read GetBooks;
end;
implementation
{ TBook}
function TBook.GetCategoryID: TCategory;
begin
result := FCategoryID.Value;
end;
procedure TBook.SetCategoryID(const Value: TCategory);
begin
FCategoryID.Value := Value;
end;
{ TCategory}
function TCategory.GetParentID: TCategory;
begin
result := FParentID.Value;
end;
procedure TCategory.SetParentID(const Value: TCategory);
begin
FParentID.Value := Value;
end;
constructor TCategory.Create;
begin
inherited;
FBooks.SetInitialValue(TList<TBook>.Create);
end;
destructor TCategory.Destroy;
begin
FBooks.DestroyValue;
inherited;
end;
function TCategory.GetBooks: TList<TBook>;
begin
result := FBooks.Value;
end;
end.
|
unit Kafka.Helper;
interface
uses
System.SysUtils, System.Classes, System.Diagnostics, System.DateUtils,
Kafka.Types,
Kafka.Lib;
type
EKafkaError = class(Exception);
TOnLog = procedure(const Values: TStrings) of object;
TOperationTimer = record
private
FStopwatch: TStopwatch;
FOperation: String;
public
constructor Create(const Operation: String); overload;
constructor Create(const Operation: String; Args: Array of const); overload;
procedure Start(const Operation: String); overload;
procedure Start(const Operation: String; Args: Array of const); overload;
procedure Stop;
// class operator Finalize(var ADest: TOperationTimer);
end;
TKafkaUtils = class
public
class function PointerToStr(const Value: Pointer; const Len: Integer; const Encoding: TEncoding): String; static;
class function PointerToBytes(const Value: Pointer; const Len: Integer): TBytes; static;
class function StrToBytes(const Value: String; const Encoding: TEncoding): TBytes; static;
class procedure StringsToConfigArrays(const Values: TStrings; out NameArr, ValueArr: TArray<String>); static;
class function StringsToIntegerArray(const Value: String): TArray<Integer>;
class function DateTimeToStrMS(const Value: TDateTime): String; static;
end;
TKafkaHelper = class
private
class var FLogStrings: TStringList;
class var FOnLog: TOnLog;
class procedure CheckKeyValues(const Keys, Values: TArray<String>); static;
protected
class procedure DoLog(const Text: String; const LogType: TKafkaLogType);
public
class constructor Create;
class destructor Destroy;
class procedure Log(const Text: String; const LogType: TKafkaLogType);
// Wrappers
class function NewConfiguration(const DefaultCallBacks: Boolean = True): prd_kafka_conf_t; overload; static;
class function NewConfiguration(const Keys, Values: TArray<String>; const DefaultCallBacks: Boolean = True): prd_kafka_conf_t; overload; static;
class procedure SetConfigurationValue(var Configuration: prd_kafka_conf_t; const Key, Value: String); static;
class procedure DestroyConfiguration(const Configuration: Prd_kafka_conf_t); static;
class function NewTopicConfiguration: prd_kafka_topic_conf_t; overload; static;
class function NewTopicConfiguration(const Keys, Values: TArray<String>): prd_kafka_topic_conf_t; overload; static;
class procedure SetTopicConfigurationValue(var TopicConfiguration: prd_kafka_topic_conf_t; const Key, Value: String); static;
class procedure DestroyTopicConfiguration(const TopicConfiguration: Prd_kafka_topic_conf_t); static;
class function NewProducer(const Configuration: prd_kafka_conf_t): prd_kafka_t; overload; static;
class function NewProducer(const ConfigKeys, ConfigValues: TArray<String>): prd_kafka_t; overload; static;
class function NewConsumer(const Configuration: prd_kafka_conf_t): prd_kafka_t; overload; static;
class procedure ConsumerClose(const KafkaHandle: prd_kafka_t); static;
class procedure DestroyHandle(const KafkaHandle: prd_kafka_t); static;
class function NewTopic(const KafkaHandle: prd_kafka_t; const TopicName: String; const TopicConfiguration: prd_kafka_topic_conf_t = nil): prd_kafka_topic_t;
class function Produce(const Topic: prd_kafka_topic_t; const Payload: Pointer; const PayloadLength: NativeUInt; const Key: Pointer = nil; const KeyLen: NativeUInt = 0; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
class function Produce(const Topic: prd_kafka_topic_t; const Payloads: TArray<Pointer>; const PayloadLengths: TArray<Integer>; const Key: Pointer = nil; const KeyLen: NativeUInt = 0; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
class function Produce(const Topic: prd_kafka_topic_t; const Payload: String; const Key: String; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
class function Produce(const Topic: prd_kafka_topic_t; const Payload: String; const Key: String; const Encoding: TEncoding; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
class function Produce(const Topic: prd_kafka_topic_t; const Payloads: TArray<String>; const Key: String; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
class function Produce(const Topic: prd_kafka_topic_t; const Payloads: TArray<String>; const Key: String; const Encoding: TEncoding; const Partition: Int32 = RD_KAFKA_PARTITION_UA; const MsgFlags: Integer = RD_KAFKA_MSG_F_COPY; const MsgOpaque: Pointer = nil): Integer; overload;
class procedure Flush(const KafkaHandle: prd_kafka_t; const Timeout: Integer = 1000);
// Utils
class function IsKafkaError(const Error: rd_kafka_resp_err_t): Boolean; static;
// Internal
class procedure FlushLogs;
class property OnLog: TOnLog read FOnLog write FOnLog;
end;
implementation
resourcestring
StrLogCallBackFac = 'Log_CallBack - fac = %s, buff = %s';
StrMessageSendResult = 'Message send result = %d';
StrErrorCallBackReaso = 'Error = %s';
StrUnableToCreateKaf = 'Unable to create Kafka Handle - %s';
StrKeysAndValuesMust = 'Keys and Values must be the same length';
StrMessageNotQueued = 'Message not Queued';
StrInvalidConfiguratio = 'Invalid configuration key';
StrInvalidTopicConfig = 'Invalid topic configuration key';
StrCriticalError = 'Critical Error: ';
// Global callbacks
procedure ProducerCallBackLogger(rk: prd_kafka_t; rkmessage: prd_kafka_message_t;
opaque: Pointer); cdecl;
begin
if rkmessage <> nil then
begin
TKafkaHelper.Log(format(StrMessageSendResult, [Integer(rkmessage.err)]), TKafkaLogType.kltProducer);
end;
end;
procedure LogCallBackLogger(rk: prd_kafka_t; level: integer; fac: PAnsiChar;
buf: PAnsiChar); cdecl;
begin
TKafkaHelper.Log(format(StrLogCallBackFac, [String(fac), String(buf)]), TKafkaLogType.kltLog);
end;
procedure ErrorCallBackLogger(rk: prd_kafka_t; err: integer; reason: PAnsiChar;
opaque: Pointer); cdecl;
begin
TKafkaHelper.Log(format(StrErrorCallBackReaso, [String(reason)]), kltError);
end;
{ TOperationTimer }
constructor TOperationTimer.Create(const Operation: String);
begin
Start(Operation);
end;
constructor TOperationTimer.Create(const Operation: String; Args: Array of const);
begin
Create(format(Operation, Args));
end;
procedure TOperationTimer.Start(const Operation: String);
begin
Stop;
FOperation := Operation;
TKafkaHelper.Log('Started - ' + FOperation, TKafkaLogType.kltDebug);
FStopwatch.Start;
end;
procedure TOperationTimer.Start(const Operation: String; Args: Array of const);
begin
Start(format(Operation, Args));
end;
procedure TOperationTimer.Stop;
begin
if FStopwatch.IsRunning then
begin
FStopwatch.Stop;
TKafkaHelper.Log('Finished - ' + FOperation + ' in ' + FStopwatch.ElapsedMilliseconds.ToString + 'ms', TKafkaLogType.kltDebug);
end;
end;
//class operator TOperationTimer.Finalize(var ADest: TOperationTimer);
//begin
// if ADest.FStopwatch.IsRunning then
// begin
// ADest.FStopwatch.Stop;
//
// TKafkaHelper.Log('Finished - ' + ADest.FOperation + ' in ' + ADest.FStopwatch.ElapsedMilliseconds.ToString + 'ms', TKafkaLogType.kltDebug);
// end;
//end;
{ TKafkaUtils }
class procedure TKafkaUtils.StringsToConfigArrays(const Values: TStrings; out NameArr, ValueArr: TArray<String>);
var
i: Integer;
KeyValue: TArray<String>;
begin
for i := 0 to pred(Values.Count) do
begin
if pos('=', Values[i]) <> 0 then
begin
KeyValue := Values[i].Split(['='], 2);
NameArr := NameArr + [KeyValue[0]];
ValueArr := ValueArr + [KeyValue[1]];
end;
end;
end;
class function TKafkaUtils.StringsToIntegerArray(const Value: String): TArray<Integer>;
var
StrArray: TArray<String>;
i: Integer;
begin
StrArray := Value.Split([',']);
SetLength(Result, length(StrArray));
for i := Low(StrArray) to High(StrArray) do
begin
Result[i] := StrToInt(StrArray[i]);
end;
end;
class function TKafkaUtils.DateTimeToStrMS(const Value: TDateTime): String;
begin
Result := DateTimeToStr(Value) + '.' + MilliSecondOf(Value).ToString.PadLeft(3, '0');
end;
class function TKafkaUtils.StrToBytes(const Value: String; const Encoding: TEncoding): TBytes;
begin
if Value = '' then
begin
Result := [];
end
else
begin
Result := Encoding.GetBytes(Value);
end;
end;
class function TKafkaUtils.PointerToStr(const Value: Pointer; const Len: Integer; const Encoding: TEncoding): String;
var
Data: TBytes;
begin
SetLength(Data, Len);
Move(Value^, Pointer(Data)^, Len);
Result := Encoding.GetString(Data);
end;
class function TKafkaUtils.PointerToBytes(const Value: Pointer; const Len: Integer): TBytes;
begin
SetLength(Result, Len);
Move(Value^, Pointer(Result)^, Len);
end;
{ TKafkaHelper }
class procedure TKafkaHelper.ConsumerClose(const KafkaHandle: prd_kafka_t);
begin
rd_kafka_consumer_close(KafkaHandle);
end;
class procedure TKafkaHelper.DestroyHandle(const KafkaHandle: prd_kafka_t);
begin
rd_kafka_destroy(KafkaHandle);
end;
class constructor TKafkaHelper.Create;
begin
FLogStrings := TStringList.Create;
end;
class destructor TKafkaHelper.Destroy;
begin
FreeAndNil(FLogStrings);
end;
class procedure TKafkaHelper.DoLog(const Text: String; const LogType: TKafkaLogType);
begin
TMonitor.Enter(TKafkaHelper.FLogStrings);
try
TKafkaHelper.FLogStrings.AddObject(Text, TObject(LogType));
finally
TMonitor.Exit(TKafkaHelper.FLogStrings);
end;
end;
class procedure TKafkaHelper.Flush(const KafkaHandle: prd_kafka_t; const Timeout: Integer);
begin
TOperationTimer.Create('Flushing');
rd_kafka_flush(KafkaHandle, Timeout);
end;
class procedure TKafkaHelper.FlushLogs;
begin
TMonitor.Enter(TKafkaHelper.FLogStrings);
try
if Assigned(FOnLog) then
begin
FOnLog(TKafkaHelper.FLogStrings);
end;
TKafkaHelper.FLogStrings.Clear;
finally
TMonitor.Exit(TKafkaHelper.FLogStrings);
end;
end;
class procedure TKafkaHelper.Log(const Text: String; const LogType: TKafkaLogType);
begin
DoLog(Text, LogType);
end;
class procedure TKafkaHelper.DestroyConfiguration(const Configuration: Prd_kafka_conf_t);
begin
rd_kafka_conf_destroy(Configuration);
end;
class procedure TKafkaHelper.DestroyTopicConfiguration(const TopicConfiguration: Prd_kafka_topic_conf_t);
begin
rd_kafka_topic_conf_destroy(TopicConfiguration);
end;
class function TKafkaHelper.NewConfiguration(const Keys: TArray<String>; const Values: TArray<String>; const DefaultCallBacks: Boolean): prd_kafka_conf_t;
var
i: Integer;
begin
CheckKeyValues(Keys, Values);
Result := rd_kafka_conf_new();
for i := Low(keys) to High(Keys) do
begin
SetConfigurationValue(
Result,
Keys[i],
Values[i]);
end;
if DefaultCallBacks then
begin
rd_kafka_conf_set_dr_msg_cb(Result, @ProducerCallBackLogger);
rd_kafka_conf_set_log_cb(Result, @LogCallBackLogger);
rd_kafka_conf_set_error_cb(Result, @ErrorCallBackLogger);
end;
end;
class function TKafkaHelper.NewProducer(const ConfigKeys, ConfigValues: TArray<String>): prd_kafka_t;
var
Configuration: prd_kafka_conf_t;
begin
Configuration := TKafkaHelper.NewConfiguration(
ConfigKeys,
ConfigValues);
Result := NewProducer(Configuration);
end;
class function TKafkaHelper.NewConsumer(const Configuration: prd_kafka_conf_t): prd_kafka_t;
var
ErrorStr: TKafkaErrorArray;
begin
Result := rd_kafka_new(
RD_KAFKA_CONSUMER,
Configuration,
ErrorStr,
Sizeof(ErrorStr));
if Result = nil then
begin
raise EKafkaError.CreateFmt(StrUnableToCreateKaf, [String(ErrorStr)]);
end;
end;
class function TKafkaHelper.NewProducer(const Configuration: prd_kafka_conf_t): prd_kafka_t;
var
ErrorStr: TKafkaErrorArray;
begin
Result := rd_kafka_new(
RD_KAFKA_PRODUCER,
Configuration,
ErrorStr,
Sizeof(ErrorStr));
if Result = nil then
begin
raise EKafkaError.CreateFmt(StrUnableToCreateKaf, [String(ErrorStr)]);
end;
end;
class function TKafkaHelper.NewTopic(const KafkaHandle: prd_kafka_t; const TopicName: String; const TopicConfiguration: prd_kafka_topic_conf_t): prd_kafka_topic_t;
begin
Result := rd_kafka_topic_new(
KafkaHandle,
PAnsiChar(AnsiString(TopicName)),
TopicConfiguration);
if Result = nil then
begin
raise EKafkaError.Create(String(rd_kafka_err2str(rd_kafka_last_error)));
end;
end;
class function TKafkaHelper.NewTopicConfiguration: prd_kafka_topic_conf_t;
begin
Result := NewTopicConfiguration([], []);
end;
class procedure TKafkaHelper.CheckKeyValues(const Keys, Values: TArray<String>);
begin
if length(keys) <> length(values) then
begin
raise EKafkaError.Create(StrKeysAndValuesMust);
end;
end;
class function TKafkaHelper.NewTopicConfiguration(const Keys, Values: TArray<String>): prd_kafka_topic_conf_t;
var
i: Integer;
begin
Result := rd_kafka_topic_conf_new;
CheckKeyValues(Keys, Values);
for i := Low(keys) to High(Keys) do
begin
SetTopicConfigurationValue(
Result,
Keys[i],
Values[i]);
end;
end;
class function TKafkaHelper.Produce(const Topic: prd_kafka_topic_t; const Payloads: TArray<Pointer>; const PayloadLengths: TArray<Integer>; const Key: Pointer;
const KeyLen: NativeUInt; const Partition: Int32; const MsgFlags: Integer; const MsgOpaque: Pointer): Integer;
var
i: Integer;
Msgs: TArray<rd_kafka_message_t>;
Msg: rd_kafka_message_t;
begin
if length(Payloads) = 0 then
begin
Result := 0;
end
else
begin
SetLength(Msgs, length(Payloads));
for i := Low(Payloads) to High(Payloads) do
begin
Msg.partition := Partition;
Msg.rkt := Topic;
Msg.payload := Payloads[i];
Msg.len := PayloadLengths[i];
Msg.key := Key;
Msg.key_len := KeyLen;
Msgs[i] := Msg;
end;
Result := rd_kafka_produce_batch(
Topic,
Partition,
MsgFlags,
@Msgs[0],
length(Payloads));
if Result <> length(Payloads) then
begin
raise EKafkaError.Create(StrMessageNotQueued);
end;
end;
end;
class function TKafkaHelper.Produce(const Topic: prd_kafka_topic_t; const Payloads: TArray<String>; const Key: String; const Encoding: TEncoding;
const Partition: Int32; const MsgFlags: Integer; const MsgOpaque: Pointer): Integer;
var
PayloadPointers: TArray<Pointer>;
PayloadLengths: TArray<Integer>;
KeyBytes, PayloadBytes: TBytes;
i: Integer;
KeyData: TBytes;
Timer: TOperationTimer;
begin
{$IFDEF DEBUG}Timer := TOperationTimer.Create('Formatting %d messages', [Length(Payloads)]);{$ENDIF}
SetLength(PayloadPointers, length(Payloads));
SetLength(PayloadLengths, length(Payloads));
KeyData := TEncoding.UTF8.GetBytes(Key);
KeyBytes := TKafkaUtils.StrToBytes(Key, Encoding);
for i := Low(Payloads) to High(Payloads) do
begin
PayloadBytes := TKafkaUtils.StrToBytes(Payloads[i], Encoding);
PayloadPointers[i] := @PayloadBytes[0];
PayloadLengths[i] := Length(PayloadBytes);
end;
{$IFDEF DEBUG}Timer.Start('Producing %d messages', [Length(Payloads)]);{$ENDIF}
Result := Produce(
Topic,
PayloadPointers,
PayloadLengths,
@KeyBytes[0],
Length(KeyBytes),
Partition,
MsgFlags,
MsgOpaque);
end;
class function TKafkaHelper.Produce(const Topic: prd_kafka_topic_t; const Payload: String; const Key: String; const Encoding: TEncoding;
const Partition: Int32; const MsgFlags: Integer; const MsgOpaque: Pointer): Integer;
var
KeyBytes, PayloadBytes: TBytes;
begin
KeyBytes := TKafkaUtils.StrToBytes(Key, TEncoding.UTF8);
PayloadBytes := TKafkaUtils.StrToBytes(Payload, TEncoding.UTF8);
Result := Produce(
Topic,
@PayloadBytes[0],
length(PayloadBytes),
@KeyBytes[0],
length(KeyBytes),
Partition,
MsgFlags,
MsgOpaque)
end;
class function TKafkaHelper.Produce(const Topic: prd_kafka_topic_t; const Payload: String; const Key: String; const Partition: Int32;
const MsgFlags: Integer; const MsgOpaque: Pointer): Integer;
begin
Result := Produce(
Topic,
Payload,
Key,
TEncoding.UTF8,
Partition,
MsgFlags,
MsgOpaque);
end;
class function TKafkaHelper.Produce(const Topic: prd_kafka_topic_t; const Payload: Pointer; const PayloadLength: NativeUInt;
const Key: Pointer; const KeyLen: NativeUInt; const Partition: Int32; const MsgFlags: Integer; const MsgOpaque: Pointer): Integer;
begin
Result := rd_kafka_produce(
Topic,
Partition,
MsgFlags,
Payload,
PayloadLength,
Key,
KeyLen,
MsgOpaque);
if Result = -1 then
begin
raise EKafkaError.Create(StrMessageNotQueued);
end;
end;
class function TKafkaHelper.NewConfiguration(const DefaultCallBacks: Boolean): prd_kafka_conf_t;
begin
Result := NewConfiguration([], [], DefaultCallBacks);
end;
class procedure TKafkaHelper.SetConfigurationValue(var Configuration: prd_kafka_conf_t; const Key, Value: String);
var
ErrorStr: TKafkaErrorArray;
begin
if Value = '' then
begin
raise EKafkaError.Create(StrInvalidConfiguratio);
end;
if rd_kafka_conf_set(
Configuration,
PAnsiChar(AnsiString(Key)),
PAnsiChar(AnsiString(Value)),
ErrorStr,
Sizeof(ErrorStr)) <> RD_KAFKA_CONF_OK then
begin
raise EKafkaError.Create(String(ErrorStr));
end;
end;
class procedure TKafkaHelper.SetTopicConfigurationValue(var TopicConfiguration: prd_kafka_topic_conf_t; const Key, Value: String);
var
ErrorStr: TKafkaErrorArray;
begin
if Value = '' then
begin
raise EKafkaError.Create(StrInvalidTopicConfig);
end;
if rd_kafka_topic_conf_set(
TopicConfiguration,
PAnsiChar(AnsiString(Key)),
PAnsiChar(AnsiString(Value)),
ErrorStr,
Sizeof(ErrorStr)) <> RD_KAFKA_CONF_OK then
begin
raise EKafkaError.Create(String(ErrorStr));
end;
end;
class function TKafkaHelper.IsKafkaError(const Error: rd_kafka_resp_err_t): Boolean;
begin
Result :=
(Error <> RD_KAFKA_RESP_ERR_NO_ERROR) and
(Error <> RD_KAFKA_RESP_ERR__PARTITION_EOF);
end;
class function TKafkaHelper.Produce(const Topic: prd_kafka_topic_t; const Payloads: TArray<String>; const Key: String; const Partition: Int32;
const MsgFlags: Integer; const MsgOpaque: Pointer): Integer;
begin
Result := Produce(
Topic,
Payloads,
Key,
TEncoding.UTF8,
Partition,
MsgFlags,
MsgOpaque);
end;
end.
|
unit BCEditor.Editor.Minimap.Colors;
interface
uses
Classes, Graphics, BCEditor.Consts;
type
TBCEditorMinimapColors = class(TPersistent)
strict private
FBookmark: TColor;
FVisibleLines: TColor;
FOnChange: TNotifyEvent;
procedure SetBookmark(const Value: TColor);
procedure SetVisibleLines(const Value: TColor);
procedure DoChange;
public
constructor Create;
procedure Assign(Source: TPersistent); override;
published
property VisibleLines: TColor read FVisibleLines write SetVisibleLines default clMinimapVisibleLines;
property Bookmark: TColor read FBookmark write SetBookmark default clMinimapBookmark;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
{ TBCEditorMinimapColors }
constructor TBCEditorMinimapColors.Create;
begin
inherited;
FBookmark := clMinimapBookmark;
FVisibleLines := clMinimapVisibleLines;
end;
procedure TBCEditorMinimapColors.Assign(Source: TPersistent);
begin
if Source is TBCEditorMinimapColors then
with Source as TBCEditorMinimapColors do
begin
Self.FBookmark := FBookmark;
Self.FVisibleLines := FVisibleLines;
Self.DoChange;
end
else
inherited;
end;
procedure TBCEditorMinimapColors.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBCEditorMinimapColors.SetBookmark(const Value: TColor);
begin
if Value <> FBookmark then
begin
FBookmark := Value;
DoChange;
end;
end;
procedure TBCEditorMinimapColors.SetVisibleLines(const Value: TColor);
begin
if Value <> FVisibleLines then
begin
FVisibleLines := Value;
DoChange;
end;
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_NavMeshPruneTool;
interface
uses Classes, Controls, StdCtrls, RN_Sample, RN_DetourNavMesh, RN_DetourNavMeshHelper, Unit_FramePruneTool;
// Prune navmesh to accessible locations from a point.
type
PTileFlags = ^TTileFlags;
TTileFlags = record
flags: PByte;
nflags: Integer;
base: TdtPolyRef;
procedure purge;
end;
TNavmeshFlags = class
private
m_nav: TdtNavMesh;
m_tiles: PTileFlags;
m_ntiles: Integer;
public
destructor Destroy; override;
function init(nav: TdtNavMesh): Boolean;
procedure clearAllFlags;
function getFlags(ref: TdtPolyRef): Byte;
procedure setFlags(ref: TdtPolyRef; flags: Byte);
end;
TNavMeshPruneTool = class (TSampleTool)
private
fFrame: TFramePruneTool;
m_sample: TSample;
m_flags: TNavmeshFlags;
m_hitPos: array [0..2] of Single;
m_hitPosSet: Boolean;
public
constructor Create(aOwner: TWinControl);
destructor Destroy; override;
procedure init(sample: TSample); override;
procedure reset(); override;
procedure handleMenu(Sender: TObject); override;
procedure handleClick(s,p: PSingle; shift: Boolean); override;
procedure handleToggle(); override;
procedure handleStep(); override;
procedure handleUpdate(dt: Single); override;
procedure handleRender(); override;
procedure handleRenderOverlay(proj, model: PDouble; view: PInteger); override;
end;
implementation
uses Math,
RN_InputGeom, RN_SampleInterfaces, RN_DebugDraw,
RN_Recast, RN_RecastHelper, RN_RecastDebugDraw,
RN_DetourNavMeshBuilder, RN_DetourNavMeshQuery, RN_DetourStatus, RN_DetourDebugDraw, RN_DetourCommon;
// Copy/paste from Recast int array
type
TPolyRefArray = class
private
m_size, m_cap: Integer;
//inline PolyRefArray(const PolyRefArray&);
//inline PolyRefArray& operator=(const PolyRefArray&);
public
m_data: PdtPolyRef;
constructor Create; overload;
constructor Create(n: Integer); overload;
destructor Destroy; override;
procedure resize(n: Integer);
procedure push(item: TdtPolyRef);
function pop: TdtPolyRef;
function size: Integer;
end;
constructor TPolyRefArray.Create;
begin
end;
constructor TPolyRefArray.Create(n: Integer);
begin
resize(n);
end;
destructor TPolyRefArray.Destroy;
begin
FreeMem(m_data);
inherited;
end;
procedure TPolyRefArray.resize(n: Integer);
var newData: PdtPolyRef;
begin
if (n > m_cap) then
begin
if (m_cap = 0) then m_cap := n;
while (m_cap < n) do m_cap := m_cap * 2;
GetMem(newData, m_cap*sizeof(TdtPolyRef));
if (m_size <> 0) and (newData <> nil) then Move(m_data^, newData^, m_size*sizeof(TdtPolyRef));
FreeMem(m_data);
m_data := newData;
end;
m_size := n;
end;
procedure TPolyRefArray.push(item: TdtPolyRef);
begin
resize(m_size+1); m_data[m_size-1] := item;
end;
function TPolyRefArray.Pop: TdtPolyRef;
begin
if (m_size > 0) then Dec(m_size); Result := m_data[m_size];
end;
function TPolyRefArray.size: Integer;
begin
Result := m_size;
end;
procedure TTileFlags.purge; begin FreeMem(flags); end;
destructor TNavmeshFlags.Destroy;
var i: Integer;
begin
for i := 0 to m_ntiles - 1 do
m_tiles[i].purge;
FreeMem(m_tiles);
inherited;
end;
function TNavmeshFlags.init(nav: TdtNavMesh): Boolean;
var i: Integer; tile: PdtMeshTile; tf: PTileFlags;
begin
m_ntiles := nav.getMaxTiles;
if (m_ntiles = 0) then
Exit(true);
GetMem(m_tiles, sizeof(TTileFlags)*m_ntiles);
if (m_tiles = nil) then
begin
Exit(false);
end;
FillChar(m_tiles[0], sizeof(TTileFlags)*m_ntiles, 0);
// Alloc flags for each tile.
for i := 0 to nav.getMaxTiles - 1 do
begin
tile := nav.getTile(i);
if (tile.header = nil) then continue;
tf := @m_tiles[i];
tf.nflags := tile.header.polyCount;
tf.base := nav.getPolyRefBase(tile);
if (tf.nflags <> 0) then
begin
GetMem(tf.flags, tf.nflags);
if (tf.flags = nil) then
Exit(false);
FillChar(tf.flags[0], tf.nflags, 0);
end;
end;
m_nav := nav;
Result := false;
end;
procedure TNavmeshFlags.clearAllFlags;
var i: Integer; tf: PTileFlags;
begin
for i := 0 to m_ntiles - 1 do
begin
tf := @m_tiles[i];
if (tf.nflags <> 0) then
FillChar(tf.flags[0], tf.nflags, 0);
end;
end;
function TNavmeshFlags.getFlags(ref: TdtPolyRef): Byte;
var salt, it, ip: Cardinal;
begin
Assert(m_nav <> nil);
Assert(m_ntiles <> 0);
// Assume the ref is valid, no bounds checks.
m_nav.decodePolyId(ref, @salt, @it, @ip);
Result := m_tiles[it].flags[ip];
end;
procedure TNavmeshFlags.setFlags(ref: TdtPolyRef; flags: Byte);
var salt, it, ip: Cardinal;
begin
Assert(m_nav <> nil);
Assert(m_ntiles <> 0);
// Assume the ref is valid, no bounds checks.
m_nav.decodePolyId(ref, @salt, @it, @ip);
m_tiles[it].flags[ip] := flags;
end;
procedure floodNavmesh(nav: TdtNavMesh; flags: TNavmeshFlags; start: TdtPolyRef; flag: Byte);
var openList: TPolyRefArray; ref,neiRef: TdtPolyRef; tile: PdtMeshTile; poly: PdtPoly; i: Cardinal;
begin
// If already visited, skip.
if (flags.getFlags(start) <> 0) then
Exit;
openList := TPolyRefArray.Create;
openList.push(start);
while (openList.size <> 0) do
begin
ref := openList.pop;
// Get current poly and tile.
// The API input has been cheked already, skip checking internal data.
tile := nil;
poly := nil;
nav.getTileAndPolyByRefUnsafe(ref, @tile, @poly);
// Visit linked polygons.
i := poly.firstLink;
while (i <> DT_NULL_LINK) do
begin
neiRef := tile.links[i].ref;
// Skip invalid and already visited.
if (neiRef = 0) or (flags.getFlags(neiRef) <> 0) then
begin i := tile.links[i].next; continue; end;
// Mark as visited
flags.setFlags(neiRef, flag);
// Visit neighbours
openList.push(neiRef);
i := tile.links[i].next;
end;
end;
end;
procedure disableUnvisitedPolys(nav: TdtNavMesh; flags: TNavmeshFlags);
var i,j: Integer; tile: PdtMeshTile; base,ref: TdtPolyRef; f: Word;
begin
for i := 0 to nav.getMaxTiles - 1 do
begin
tile := nav.getTile(i);
if (tile.header = nil) then continue;
base := nav.getPolyRefBase(tile);
for j := 0 to tile.header.polyCount - 1 do
begin
ref := base or j;
if (flags.getFlags(ref) = 0) then
begin
f := 0;
nav.getPolyFlags(ref, @f);
nav.setPolyFlags(ref, f or SAMPLE_POLYFLAGS_DISABLED);
end;
end;
end;
end;
constructor TNavMeshPruneTool.Create(aOwner: TWinControl);
begin
inherited Create;
&type := TOOL_NAVMESH_PRUNE;
fFrame := TFramePruneTool.Create(aOwner);
fFrame.Align := alClient;
fFrame.Parent := aOwner;
fFrame.Visible := True;
fFrame.btnClearSelection.OnClick := handleMenu;
fFrame.btnPruneUnselected.OnClick := handleMenu;
end;
destructor TNavMeshPruneTool.Destroy;
begin
m_flags.Free;
fFrame.Free;
inherited;
end;
procedure TNavMeshPruneTool.init(sample: TSample);
begin
m_sample := sample;
end;
procedure TNavMeshPruneTool.reset();
begin
m_hitPosSet := false;
m_flags.Free;
m_flags := nil;
end;
procedure TNavMeshPruneTool.handleMenu(Sender: TObject);
var nav: TdtNavMesh;
begin
nav := m_sample.getNavMesh;
if (nav = nil) then Exit;
if (m_flags = nil) then Exit;
if Sender = fFrame.btnClearSelection then
begin
m_flags.clearAllFlags();
end;
if Sender = fFrame.btnPruneUnselected then
begin
disableUnvisitedPolys(nav, m_flags);
m_flags.Free;
m_flags := nil;
end;
end;
procedure TNavMeshPruneTool.handleClick(s,p: PSingle; shift: Boolean);
var geom: TInputGeom; nav: TdtNavMesh; query: TdtNavMeshQuery; ext: array [0..2] of Single; filter: TdtQueryFilter; ref: TdtPolyRef;
begin
//rcIgnoreUnused(s);
//rcIgnoreUnused(shift);
if (m_sample = nil) then Exit;
geom := m_sample.getInputGeom;
if (geom = nil) then Exit;
nav := m_sample.getNavMesh;
if (nav = nil) then Exit;
query := m_sample.getNavMeshQuery;
if (query = nil) then Exit;
dtVcopy(@m_hitPos[0], p);
m_hitPosSet := true;
if (m_flags = nil) then
begin
m_flags := TNavmeshFlags.Create;
m_flags.init(nav);
end;
ext[0] := 2; ext[1] := 4; ext[2] := 2;
// Delphi: Assume C++ invokes constructor
filter := TdtQueryFilter.Create;
ref := 0;
query.findNearestPoly(p, @ext[0], filter, @ref, nil);
floodNavmesh(nav, m_flags, ref, 1);
// Delphi: Assume C++ does the same when var goes out of scope
filter.Free;
end;
procedure TNavMeshPruneTool.handleToggle();
begin
end;
procedure TNavMeshPruneTool.handleStep();
begin
end;
procedure TNavMeshPruneTool.handleUpdate(dt: Single);
begin
end;
procedure TNavMeshPruneTool.handleRender();
var dd: TDebugDrawGL; s: Single; col: Cardinal; nav: TdtNavMesh; i,j: Integer; tile: PdtMeshTile; base,ref: TdtPolyRef;
begin
dd := TDebugDrawGL.Create;
if (m_hitPosSet) then
begin
s := m_sample.getAgentRadius;
col := duRGBA(255,255,255,255);
dd.&begin(DU_DRAW_LINES);
dd.vertex(m_hitPos[0]-s,m_hitPos[1],m_hitPos[2], col);
dd.vertex(m_hitPos[0]+s,m_hitPos[1],m_hitPos[2], col);
dd.vertex(m_hitPos[0],m_hitPos[1]-s,m_hitPos[2], col);
dd.vertex(m_hitPos[0],m_hitPos[1]+s,m_hitPos[2], col);
dd.vertex(m_hitPos[0],m_hitPos[1],m_hitPos[2]-s, col);
dd.vertex(m_hitPos[0],m_hitPos[1],m_hitPos[2]+s, col);
dd.&end();
end;
nav := m_sample.getNavMesh;
if (m_flags <> nil) and (nav <> nil) then
begin
for i := 0 to nav.getMaxTiles - 1 do
begin
tile := nav.getTile(i);
if (tile.header = nil) then continue;
base := nav.getPolyRefBase(tile);
for j := 0 to tile.header.polyCount - 1 do
begin
ref := base or j;
if (m_flags.getFlags(ref) <> 0) then
begin
duDebugDrawNavMeshPoly(dd, nav, ref, duRGBA(255,255,255,128));
end;
end;
end;
end;
dd.Free;
end;
procedure TNavMeshPruneTool.handleRenderOverlay(proj, model: PDouble; view: PInteger);
begin
//rcIgnoreUnused(model);
//rcIgnoreUnused(proj);
// Tool help
//const int h := view[3];
//imguiDrawText(280, h-40, IMGUI_ALIGN_LEFT, "LMB: Click fill area.", imguiRGBA(255,255,255,192));
end;
end. |
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLPerlin<p>
Classes for generating perlin noise.<p>
The components and classes in the unit are a base to generate textures and heightmaps from,
A Perlin Height Data Source have been included as an example. Use this combined with a terrain renderer for an infinite random landscape <p>
<b>History : </b><font size=-1><ul>
<li>20/05/10 - Yar - Fixes for Linux x64
<li>31/03/07 - DaStr - Added $I GLScene.inc
<li>28/03/07 - DaStr - Added explicit pointer dereferencing
(thanks Burkhard Carstens) (Bugtracker ID = 1678644)
<li>08/07/04 - LR - Correction for Linux
<li>29/01/03 - JaJ - Submitted to GLScene.
</ul></font>
}
unit GLPerlin;
interface
{$I GLScene.inc}
uses
Classes, SysUtils,
GLVectorGeometry, GLPerlinBase, GLHeightData,
GLCrossPlatform;
Type
TGLPerlinInterpolation = (pi_none, pi_simple, pi_linear, pi_Smoothed,
pi_Cosine, pi_cubic);
TGLBasePerlinOctav = class
private
FAmplitude: Double;
FScale: Double;
FInterpolation: TGLPerlinInterpolation;
FSmoothing: TGLPerlinInterpolation;
public
Procedure Generate; dynamic; abstract;
property Interpolation: TGLPerlinInterpolation read FInterpolation
write FInterpolation;
property Smoothing: TGLPerlinInterpolation read FSmoothing write FSmoothing;
property Amplitude: Double read FAmplitude write FAmplitude;
property Scale: Double read FScale write FScale;
End;
TGLPerlinOctav = class of TGLBasePerlinOctav;
TGLBasePerlin = class(TComponent)
private
FPersistence: Double;
FNumber_Of_Octaves: Integer;
FOctaves: TList;
FOctavClass: TGLPerlinOctav;
FInterpolation: TGLPerlinInterpolation;
FSmoothing: TGLPerlinInterpolation;
protected
function PerlinNoise_1D(x: Double): Double;
function PerlinNoise_2D(x, y: Double): Double;
function GetOctave(index: Integer): TGLBasePerlinOctav;
Procedure SetPersistence(val: Double);
Procedure Set_Number_Of_Octaves(val: Integer);
public
Constructor Create(AOwner: TComponent); override;
Procedure Generate; dynamic; abstract;
Property Octaves[index: Integer]: TGLBasePerlinOctav read GetOctave;
published
property Smoothing: TGLPerlinInterpolation read FSmoothing write FSmoothing;
property Interpolation: TGLPerlinInterpolation read FInterpolation
write FInterpolation;
property Persistence: Double read FPersistence write SetPersistence;
property Number_Of_Octaves: Integer read FNumber_Of_Octaves
write Set_Number_Of_Octaves;
End;
TGL1DPerlin = class(TGLBasePerlin)
Function GetPerlinValue_1D(x: Double): Double;
published
End;
TGL2DPerlinOctav = class(TGLBasePerlinOctav)
public
Data: T2DPerlinArray;
Width, Height: Integer;
XStart, YStart: Integer;
XStep, YStep: Integer;
YRate: Integer;
Procedure Generate; override;
Function GetDataSmoothed(x, y: Integer): Double;
Function GetData(x, y: Integer): Double;
Function GetCubic(x, y: Double): Double;
Function GetCosine(x, y: Double): Double;
Function GetPerling(x, y: Double): Double;
Procedure Generate_CubicInterpolate;
Procedure Generate_SmoothInterpolate;
Procedure Generate_NonInterpolated;
End;
TGL2DPerlin = class(TGLBasePerlin)
private
public
Width, Height: Integer;
XStart, YStart: Integer;
XStep, YStep: Integer;
MaxValue, MinValue: Double;
Constructor Create(AOwner: TComponent); override;
Procedure Generate; override;
Function GetPerlinValue_2D(x, y: Double): Double;
Procedure MakeBitmap(Param: TGLBitmap);
Procedure SetHeightData(heightData: THeightData);
End;
TGLPerlinHDS = class(THeightDataSource)
private
FInterpolation: TGLPerlinInterpolation;
FSmoothing: TGLPerlinInterpolation;
FPersistence: Double;
FNumber_Of_Octaves: Integer;
FLines: TStrings;
FLinesChanged: Boolean;
FXStart, FYStart: Integer;
public
MaxValue, MinValue: Double;
Stall: Boolean;
Constructor Create(AOwner: TComponent); override;
procedure StartPreparingData(heightData: THeightData); override;
procedure WaitFor;
property Lines: TStrings read FLines;
property LinesChanged: Boolean read FLinesChanged write FLinesChanged;
published
property Interpolation: TGLPerlinInterpolation read FInterpolation
write FInterpolation;
property Smoothing: TGLPerlinInterpolation read FSmoothing write FSmoothing;
property Persistence: Double read FPersistence write FPersistence;
property Number_Of_Octaves: Integer read FNumber_Of_Octaves
write FNumber_Of_Octaves;
property MaxPoolSize;
property XStart: Integer read FXStart write FXStart;
property YStart: Integer read FYStart write FYStart;
End;
TGLPerlinHDSThread = class(THeightDataThread)
Perlin: TGL2DPerlin;
PerlinSource: TGLPerlinHDS;
Procedure OpdateOutSide;
Procedure Execute; override;
end;
implementation
function TGLBasePerlin.PerlinNoise_1D(x: Double): Double;
Var
int_x: Integer;
frac_x: Double;
Begin
int_x := Round(Int(x));
frac_x := x - int_x;
case Interpolation of
pi_none:
Result := 0;
pi_simple:
Result := Perlin_Random1(int_x);
pi_linear:
Result := Linear_Interpolate(Perlin_Random1(int_x),
Perlin_Random1(int_x + 1), frac_x);
pi_cubic:
Result := Cubic_Interpolate(Perlin_Random1(int_x - 1),
Perlin_Random1(int_x), Perlin_Random1(int_x + 1),
Perlin_Random1(int_x + 2), frac_x);
pi_Cosine:
Result := Cosine_Interpolate(Perlin_Random1(int_x),
Perlin_Random1(int_x + 1), frac_x);
else
raise exception.Create
('TGLBasePerlin.PerlinNoise_1D, Interpolation not implemented!');
End;
End;
function TGLBasePerlin.PerlinNoise_2D(x, y: Double): Double;
Var
int_x, int_y: Integer;
// frac_y,
frac_x: Double;
Begin
int_x := Round(Int(x));
int_y := Round(Int(y));
frac_x := x - int_x;
// frac_y := y-int_y;
case Interpolation of
pi_none:
Result := 0;
pi_simple:
Result := Perlin_Random2(int_x, int_y);
pi_linear:
Result := Linear_Interpolate(Perlin_Random1(int_x),
Perlin_Random1(int_x + 1), frac_x);
pi_cubic:
Result := Cubic_Interpolate(Perlin_Random1(int_x - 1),
Perlin_Random1(int_x), Perlin_Random1(int_x + 1),
Perlin_Random1(int_x + 2), frac_x);
pi_Cosine:
Result := Cosine_Interpolate(Perlin_Random1(int_x),
Perlin_Random1(int_x + 1), frac_x);
else
raise exception.Create
('TGLBasePerlin.PerlinNoise_1D, Interpolation not implemented!');
End;
End;
function TGLBasePerlin.GetOctave(index: Integer): TGLBasePerlinOctav;
Begin
Result := TGLBasePerlinOctav(FOctaves[index]);
End;
Procedure TGLBasePerlin.Set_Number_Of_Octaves(val: Integer);
Var
XC: Integer;
NewScale: Integer;
Octav: TGLBasePerlinOctav;
Begin
If val <> FNumber_Of_Octaves then
Begin
FNumber_Of_Octaves := val;
For XC := FOctaves.Count to FNumber_Of_Octaves - 1 do
Begin
Octav := FOctavClass.Create;
If FPersistence = 0 then
Octav.FAmplitude := 0
else
Octav.FAmplitude := exp(ln(FPersistence) * (XC + 1));
Octav.FInterpolation := Interpolation;
Octav.FSmoothing := Smoothing;
FOctaves.Add(Octav);
End;
For XC := FOctaves.Count - 1 downto FNumber_Of_Octaves do
Begin
Octav := Octaves[XC];
FOctaves.Delete(XC);
Octav.Free;
End;
NewScale := 1;
For XC := FOctaves.Count - 1 downto 0 do
Begin
Octaves[XC].Scale := NewScale;
NewScale := NewScale shl 1;
End;
End;
end;
Procedure TGLBasePerlin.SetPersistence(val: Double);
Var
XC: Integer;
Begin
If FPersistence <> val then
Begin
FPersistence := val;
For XC := FOctaves.Count to FNumber_Of_Octaves - 1 do
Begin
Octaves[XC].FAmplitude := exp(ln(FPersistence) * XC);
End;
End;
End;
Constructor TGLBasePerlin.Create(AOwner: TComponent);
Begin
inherited;
FOctaves := TList.Create;
FNumber_Of_Octaves := 0;
FInterpolation := pi_Cosine;
FSmoothing := pi_cubic;
End;
Function TGL1DPerlin.GetPerlinValue_1D(x: Double): Double;
Var
total, p, frequency, Amplitude: Double;
n, i: Integer;
Begin
total := 0;
p := Persistence;
n := Number_Of_Octaves - 1;
For i := 0 to n do
Begin
frequency := 2 * i;
Amplitude := p * i;
total := total + PerlinNoise_1D(x * frequency) * Amplitude;
end;
Result := total;
End;
Procedure TGL2DPerlinOctav.Generate;
Var
YC: Integer;
Begin
SetLength(Data, Height + 3); // needed for smoothing
For YC := 0 to Height + 2 do
SetLength(Data[YC], Width + 3); // needed for smoothing
case Smoothing of
pi_cubic:
Begin
Generate_CubicInterpolate;
End;
pi_Smoothed:
Begin
Generate_SmoothInterpolate;
End;
pi_none:
;
pi_simple:
Begin
Generate_NonInterpolated;
End;
End;
End;
Function TGL2DPerlinOctav.GetPerling(x, y: Double): Double;
Begin
Result := 0;
case Interpolation of
pi_cubic:
Begin
Result := GetCubic(x, y);
End;
pi_Smoothed:
Begin
End;
pi_Cosine:
Begin
Result := GetCosine(x, y);
End;
End;
End;
Procedure TGL2DPerlinOctav.Generate_CubicInterpolate;
Var
B1, B2, B3, B4, T1: T1DPerlinArray;
StripWidth: Integer;
Offset: Integer;
YC: Integer;
Begin
T1 := Nil;
StripWidth := Width + 6;
SetLength(B1, StripWidth);
SetLength(B2, StripWidth);
SetLength(B3, StripWidth);
SetLength(B4, StripWidth);
Offset := (XStart - 1) + (YStart - 1) * YStep * YRate;
Perlin_Random1DStrip(Offset, StripWidth, XStep, FAmplitude, B1);
inc(Offset, YRate * YStep);
Perlin_Random1DStrip(Offset, StripWidth, XStep, FAmplitude, B2);
inc(Offset, YRate * YStep);
Perlin_Random1DStrip(Offset, StripWidth, XStep, FAmplitude, B3);
inc(Offset, YRate * YStep);
For YC := 0 to Height + 2 do
Begin
Perlin_Random1DStrip(Offset, StripWidth, XStep, FAmplitude, B4);
inc(Offset, YRate * YStep);
Cubic_Interpolate_Strip(B1, B2, B3, B4, Data[YC], Width + 3);
T1 := B1;
B1 := B2;
B2 := B3;
B3 := B4;
B4 := T1;
End;
SetLength(B1, 0);
SetLength(B2, 0);
SetLength(B3, 0);
SetLength(B4, 0);
End;
Procedure TGL2DPerlinOctav.Generate_SmoothInterpolate;
Var
B1, B2, B3, T1: T1DPerlinArray;
StripWidth: Integer;
Offset: Integer;
YC: Integer;
Begin
T1 := Nil;
StripWidth := Width + 5;
SetLength(B1, StripWidth);
SetLength(B2, StripWidth);
SetLength(B3, StripWidth);
Offset := (XStart - 1) + (YStart - 1) * YStep * YRate;
Perlin_Random1DStrip(Offset, StripWidth, XStep, FAmplitude, B1);
inc(Offset, YRate * YStep);
Perlin_Random1DStrip(Offset, StripWidth, XStep, FAmplitude, B2);
inc(Offset, YRate * YStep);
For YC := 0 to Height + 2 do
Begin
Perlin_Random1DStrip(Offset, StripWidth, XStep, FAmplitude, B3);
inc(Offset, YRate * YStep);
Smooth_Interpolate_Strip(B1, B2, B3, Data[YC], Width + 3);
T1 := B1;
B1 := B2;
B2 := B3;
B3 := T1;
End;
SetLength(B1, 0);
SetLength(B2, 0);
SetLength(B3, 0);
End;
Procedure TGL2DPerlinOctav.Generate_NonInterpolated;
Var
Offset: Integer;
YC: Integer;
Begin
Offset := XStart + YStart * YStep * YRate;
For YC := 0 to Height + 2 do
Begin
Perlin_Random1DStrip(Offset, Width + 3, XStep, FAmplitude, Data[YC]);
inc(Offset, YRate * YStep);
End;
End;
Function TGL2DPerlinOctav.GetDataSmoothed(x, y: Integer): Double;
Begin
Result := (Data[y][x] + Data[y][x + 2] + Data[y + 2][x] + Data[y + 2][x + 2])
/ 16 + (Data[y + 1][x] + Data[y + 1][x + 2] + Data[y][x + 1] + Data[y + 2]
[x + 1]) / 8 + Data[y + 1][x + 1] / 4; { }
End;
Function TGL2DPerlinOctav.GetData(x, y: Integer): Double;
Begin
Result := Data[y][x];
End;
Function TGL2DPerlinOctav.GetCubic(x, y: Double): Double;
Var
X_Int: Integer;
Y_Int: Integer;
X_Frac, Y_Frac: Double;
Begin
X_Int := Round(Int(x));
Y_Int := Round(Int(y));
X_Frac := x - X_Int;
Y_Frac := y - Y_Int;
Result := (Cubic_Interpolate(GetData(X_Int, Y_Int + 1), GetData(X_Int + 1,
Y_Int + 1), GetData(X_Int + 2, Y_Int + 1), GetData(X_Int + 3, Y_Int + 1),
X_Frac) + Cubic_Interpolate(GetData(X_Int + 1, Y_Int), GetData(X_Int + 1,
Y_Int + 1), GetData(X_Int + 1, Y_Int + 2), GetData(X_Int + 1, Y_Int + 3),
Y_Frac)) / 2;
End;
Function TGL2DPerlinOctav.GetCosine(x, y: Double): Double;
Var
X_Int: Integer;
Y_Int: Integer;
X_Frac, Y_Frac: Double;
Begin
X_Int := Round(Int(x));
Y_Int := Round(Int(y));
X_Frac := x - X_Int;
Y_Frac := y - Y_Int;
Result := Cosine_Interpolate(Cosine_Interpolate(GetData(X_Int, Y_Int),
GetData(X_Int + 1, Y_Int), X_Frac),
Cosine_Interpolate(GetData(X_Int, Y_Int + 1), GetData(X_Int + 1, Y_Int + 1),
X_Frac), Y_Frac);
End;
Constructor TGL2DPerlin.Create(AOwner: TComponent);
Begin
inherited;
Width := 256;
Height := 256;
XStart := 0;
YStart := 0;
XStep := 1;
YStep := 1;
FOctavClass := TGL2DPerlinOctav;
End;
Procedure TGL2DPerlin.Generate;
Var
i: Integer;
Begin
For i := 0 to Number_Of_Octaves - 1 do
With TGL2DPerlinOctav(Octaves[i]) do
Begin
Width := Round(Ceil(self.Width / Scale));
Height := Round(Ceil(self.Height / Scale));
XStart := Round(self.XStart / Scale);
YStart := Round(self.YStart / Scale);
XStep := self.XStep;
YStep := self.YStep;
YRate := 243 * 57 * 57;
Generate;
end;
End;
Function TGL2DPerlin.GetPerlinValue_2D(x, y: Double): Double;
Var
total, frequency, Amplitude: Double;
i: Integer;
Begin
total := 0;
For i := 0 to Number_Of_Octaves - 1 do
Begin
frequency := 2 * i;
Amplitude := Persistence * i;
total := total + PerlinNoise_2D(x * frequency, y * frequency) * Amplitude;
end;
Result := total;
End;
Procedure TGL2DPerlin.MakeBitmap(Param: TGLBitmap);
Var
XC, YC: Integer;
Octaver: Integer;
Posi: PByte;
B: Integer;
Value: Double;
S: String;
Begin
MaxValue := -1;
MinValue := 100;
Param.Width := Width;
Param.Height := Height;
For YC := 0 to Height - 1 do
Begin
Posi := BitmapScanLine(Param, YC);
For XC := 0 to Width - 1 do
Begin
Value := 0;
For Octaver := 0 to FNumber_Of_Octaves - 1 do
With TGL2DPerlinOctav(Octaves[Octaver]) do
Value := Value + GetPerling(XC / Scale, YC / Scale);
Value := Value + 0.5;
If MaxValue < Value then
MaxValue := Value;
If MinValue > Value then
MinValue := Value;
If Value > 1.0 then
Begin
S := '';
For Octaver := 0 to FNumber_Of_Octaves - 1 do
With TGL2DPerlinOctav(Octaves[Octaver]) do
S := S + FloatToStr(GetPerling(XC / Scale, YC / Scale)) + ' ,';
Delete(S, Length(S) - 1, 2);
// raise Exception.create('In Cubic_Interpolate_Strip a value greater than 1 occured! value = '+FloatToStr(Value)+' values=['+S+']');
End;
B := Round(Value * $FF) and $FF;
Posi^ := B;
inc(Posi);
End;
End;
End;
Procedure TGL2DPerlin.SetHeightData(heightData: THeightData);
Var
XC, YC: Integer;
Octaver: Integer;
Posi: PSmallInt;
Value: Double;
S: String;
Begin
MaxValue := -1;
MinValue := 100;
heightData.Allocate(hdtSmallInt);
Posi := @heightData.SmallIntData^[0];
For YC := 0 to Height - 1 do
Begin
For XC := 0 to Width - 1 do
Begin
Value := 0;
For Octaver := 0 to FNumber_Of_Octaves - 1 do
With TGL2DPerlinOctav(Octaves[Octaver]) do
Value := Value + GetPerling(XC / Scale, YC / Scale);
// value = [-0,5 .. 0,5]
Posi^ := Round(Value * 256 * 100);
// 100 instead of 128 to keep it well in range!
If MaxValue < Value then
MaxValue := Value;
If MinValue > Value then
MinValue := Value;
If Value > 1.0 then
Begin
S := '';
For Octaver := 0 to FNumber_Of_Octaves - 1 do
With TGL2DPerlinOctav(Octaves[Octaver]) do
S := S + FloatToStr(GetPerling(XC / Scale, YC / Scale)) + ' ,';
Delete(S, Length(S) - 1, 2);
// raise Exception.create('In Cubic_Interpolate_Strip a value greater than 1 occured! value = '+FloatToStr(Value)+' values=['+S+']');
End;
inc(Posi);
End;
End;
End;
Constructor TGLPerlinHDS.Create(AOwner: TComponent);
Begin
inherited;
FLines := TStringList.Create;
FInterpolation := pi_Cosine;
FSmoothing := pi_cubic;
FPersistence := 0.4;
FNumber_Of_Octaves := 6;
MaxValue := -MaxInt;
MinValue := MaxInt;
MaxThreads := 1;
End;
procedure TGLPerlinHDS.StartPreparingData(heightData: THeightData);
Var
Perlin: TGL2DPerlin;
Thread: TGLPerlinHDSThread;
Begin
If Stall then
heightData.DataState := hdsNone
else
heightData.DataState := hdsPreparing;
Perlin := TGL2DPerlin.Create(self);
Perlin.Width := heightData.Size;
Perlin.Height := heightData.Size;
Perlin.XStart := heightData.XLeft + XStart;
Perlin.YStart := heightData.YTop + YStart;
Perlin.Interpolation := Interpolation;
Perlin.Smoothing := Smoothing;
Perlin.Persistence := Persistence;
Perlin.Number_Of_Octaves := Number_Of_Octaves;
If MaxThreads > 1 then
Begin
Thread := TGLPerlinHDSThread.Create(True);
Thread.FreeOnTerminate := True;
heightData.Thread := Thread;
Thread.FHeightData := heightData;
Thread.Perlin := Perlin;
Thread.PerlinSource := self;
Thread.Start;
End
else
Begin
Perlin.Generate;
Perlin.SetHeightData(heightData);
heightData.DataState := hdsReady;
If MaxValue < Perlin.MaxValue then
MaxValue := Perlin.MaxValue;
If MinValue < Perlin.MinValue then
MinValue := Perlin.MinValue;
Perlin.Free;
end;
Lines.Add('Prepared Perlin (' + IntToStr(Perlin.XStart) + ',' +
IntToStr(Perlin.YStart) + ') size ' + IntToStr(Perlin.Width));
LinesChanged := True;
End;
procedure TGLPerlinHDS.WaitFor;
Var
HDList: TList;
HD: THeightData;
XC: Integer;
Begin
Repeat
HDList := Data.LockList;
try
HD := Nil;
For XC := 0 to HDList.Count - 1 do
Begin
HD := THeightData(HDList[XC]);
If HD.DataState <> hdsReady then
Break;
End;
If Assigned(HD) then
If HD.DataState = hdsReady then
Break;
finally
Data.UnlockList;
End;
Sleep(10);
Until False;
End;
Procedure TGLPerlinHDSThread.Execute;
Begin
Perlin.Generate;
Perlin.SetHeightData(FHeightData);
FHeightData.DataState := hdsReady;
If PerlinSource.MaxValue < Perlin.MaxValue then
PerlinSource.MaxValue := Perlin.MaxValue;
If PerlinSource.MinValue < Perlin.MinValue then
PerlinSource.MinValue := Perlin.MinValue;
Perlin.Free;
end;
Procedure TGLPerlinHDSThread.OpdateOutSide;
Begin
End;
initialization
RegisterClasses([TGLPerlinHDS]);
end.
|
unit Dialogs4D.Modal.Intf;
interface
type
IDialogModal = interface
['{FDEBC19E-3E6F-4887-A1CB-3B0CB35C58A9}']
/// <summary>
/// Displays a dialog box for the user with a message.
/// </summary>
/// <param name="Content">
/// Message to be displayed to the user.
/// </param>
procedure Show(const Content: string);
end;
IDialogModalConfirm = interface
['{E843C494-FD4C-46D5-8168-07D46541E19F}']
/// <summary>
/// Displays a dialog box for the user with a question.
/// </summary>
/// <param name="Content">
/// Question to be displayed to the user.
/// </param>
/// <returns>
/// Returns true if the user has confirmed the question.
/// </returns>
function Show(const Content: string): Boolean;
end;
implementation
end.
|
// Delphi <-> FSUIPC/WideFS Communication Version 1.004
// Copyright © 2000 by Pelle F. S. Liljendal pelle@liljendal.dk
// All Rights Reserved
//
// FPCuser.pas
//
// This unit is based on C-Source by Peter Dowson (and Adam Szofran). It makes
// it possible for Delphi programmers to interact with (MS) FlightSimulator
// through FSUIPC and/or WideFS (both by Peter Dowson).
//
//-----------------------------------------------------------------------------
Unit FPCuser;
//=============================================================================
Interface
//=============================================================================
Uses
Windows, SysUtils;
{$I FPCuserIntf.INC}
Var
//--- IPC Client Stuff ---
m_hWnd : hwnd; // FS6 window handle
m_msg : uint; // id of registered window message
m_atom : atom; // global atom containing name of file-mapping object
m_hMap : thandle; // handle of file-mapping object
m_pView : pointer; // pointer to view of file-mapping object
m_pNext : pointer;
Procedure FSUIPC_Close;
Function FSUIPC_Open(dwFSReq : DWORD; var dwResult : DWORD) : Boolean;
Function FSUIPC_Process(var dwResult : DWORD) : Boolean;
Function FSUIPC_Read(dwOffset : DWORD; dwSize : DWORD; pDest : Pointer; var dwResult : DWORD) : Boolean;
Function FSUIPC_Write(dwOffset : DWORD; dwSize : DWORD; pSrce : Pointer; var dwResult : DWORD) : Boolean;
//=============================================================================
Implementation
//=============================================================================
{$I FPCuserImpl.INC}
//--- Stop the Client ---------------------------------------------------------
Procedure FSUIPC_Close;
begin
m_hWnd := 0;
m_msg := 0;
m_pNext := Nil;
if (m_atom <> 0) then begin
GlobalDeleteAtom(m_atom);
m_atom := 0;
end;
if (m_pView <> Nil) then begin
UnmapViewOfFile(m_pView);
m_pView := Nil;
end;
if (m_hMap <> 0) then begin
CloseHandle(m_hMap);
m_hMap := 0;
end;
end;
//--- Start the Client --------------------------------------------------------
// returns TRUE if successful, FALSE otherwise,
// if FALSE dwResult contains the "error-code"
Function FSUIPC_Open(dwFSReq : DWORD; var dwResult : DWORD) : Boolean;
var
szName : AnsiString;
fWideFS : Boolean;
nTry : Integer;
i : Integer;
begin
nTry := 0;
fWideFS := False;
i := 0;
// abort if already started
if (m_pView <> Nil) then
begin
dwResult := FSUIPC_ERR_OPEN;
Result := False;
Exit;
end;
// Clear version information, so know when connected
FSUIPC_Version := 0;
FSUIPC_FS_Version := 0;
// Connect via FSUIPC, wich is known to be FSUIPC's own
// and isn't subject to user modification
m_hWnd := FindWindowEx(0, 0, PChar('UIPCMAIN'), Nil);
if (m_hWnd = 0) then begin
// If there's no UIPCMAIN, we may be using WideClient
// which only simulates FS98
m_hWnd := FindWindowEx(0, 0, PChar('FS98MAIN'), Nil);
fWideFS := TRUE;
if (m_hWnd = 0) then begin
dwResult := FSUIPC_ERR_NOFS;
Result := FALSE;
Exit;
end;
end;
// register the window message
m_msg := RegisterWindowMessage(FS6IPC_MSGNAME1);
if (m_msg = 0) then begin
dwResult := FSUIPC_ERR_REGMSG;
Result := FALSE;
Exit;
end;
// create the name of our file-mapping object
Inc(nTry); // Ensures a unique string is used in case user closes and reopens
szName := Format('%s:%X:%X', [FS6IPC_MSGNAME1, GetCurrentProcessId, nTry]);
// stuff the name into a global atom
m_atom := GlobalAddAtom(PChar(szName));
if (m_atom = 0) then begin
dwResult := FSUIPC_ERR_ATOM;
FSUIPC_Close;
Result := FALSE;
Exit;
end;
// create the file-mapping object
m_hMap := CreateFileMapping(THANDLE($FFFFFFFF), // use system paging file
Nil, // security
PAGE_READWRITE, // protection
0, MAX_SIZE+256, // size
PChar(szName)); // name
if ((m_hMap = 0) or (GetLastError = ERROR_ALREADY_EXISTS)) then begin
dwResult := FSUIPC_ERR_MAP;
FSUIPC_Close;
Result := FALSE;
Exit;
end;
// get a view of the file-mapping object
m_pView := MapViewOfFile(m_hMap, FILE_MAP_WRITE, 0, 0, 0);
if (m_pView = Nil) then begin
dwResult := FSUIPC_ERR_VIEW;
FSUIPC_Close;
Result := FALSE;
Exit;
end;
// Okay, now determine FSUIPC version AND FS type
m_pNext := m_pView;
// Try up to 5 times with a 100msec rest between each
// Note that WideClient returns zeros initially, whilst waiting
// for the Server to get the data
while ((i < 5) and ((FSUIPC_Version = 0) or (FSUIPC_FS_Version = 0))) do begin
Inc(i);
// Read FSUIPC version
if (not FSUIPC_Read($3304, 4, @FSUIPC_Version, dwResult)) then begin
FSUIPC_Close;
Result := FALSE;
Exit;
end;
// and FS version and validity check pattern
if (not FSUIPC_Read($3308, 4, @FSUIPC_FS_Version, dwResult)) then begin
FSUIPC_Close;
Result := FALSE;
Exit;
end;
// write our Library version number to a special read-only offset
// This is to assist diagnosis from FSUIPC logging
// But only do this on first try
if (i<2) and (not FSUIPC_Write($330A, 2, @FSUIPC_Lib_Version, dwResult)) then begin
FSUIPC_Close;
Result := FALSE;
Exit;
end;
// Actually send the request ang get the responses ("process")
if not(FSUIPC_Process(dwResult)) then begin
FSUIPC_Close;
Result := FALSE;
Exit;
end;
// Maybe running on WideClient, and need another try
Sleep(100); // Give it a chance
end;
// Only allow running on FSUIPC 1.998e or later
// with correct check pattern $FADE
if ((FSUIPC_Version < $19980005) or ((FSUIPC_FS_Version and $FFFF0000) <> $FADE0000)) then begin
if fWideFS then dwResult := FSUIPC_ERR_RUNNING
else dwResult := FSUIPC_ERR_VERSION;
FSUIPC_Close();
Result := FALSE;
Exit;
end;
FSUIPC_FS_Version := (FSUIPC_FS_Version and $ffff); // Isolates the FS version number
// Optional user specific FS request
if (dwFSReq <> 0) and (dwFSReq <> FSUIPC_FS_Version) then begin
dwResult := FSUIPC_ERR_WRONGFS;
FSUIPC_Close;
Result := FALSE;
Exit;
end;
dwResult := FSUIPC_ERR_OK;
Result := TRUE;
end;
//--- Process read/write ------------------------------------------------------
Function FSUIPC_Process(var dwResult : DWORD) : Boolean;
var
dwError : DWORD;
pdw : ^DWORD; //Pointer;
pHdrR : ^FS6IPC_READSTATEDATA_HDR;
pHdrW : ^FS6IPC_WRITESTATEDATA_HDR;
i : Integer;
begin
i := 0;
if (m_pView = Nil) then
begin
dwResult := FSUIPC_ERR_NOTOPEN;
Result := FALSE;
Exit;
end;
if (m_pView = m_pNext) then
begin
dwResult := FSUIPC_ERR_NODATA;
Result := FALSE;
Exit;
end;
ZeroMemory(m_pNext, 4); // Terminator
m_pNext := m_pView;
// send the request (allow up to 9 tries)
while (i < 10) and ((SendMessageTimeout(
m_hWnd, // FS6 window handle
m_msg, // our registered message id
m_atom, // wParam: name of file-mapping object
0, // lParam: offset of request into file-mapping obj
SMTO_BLOCK, // halt this thread until we get a response
2000, // time out interval
dwError)) = 0) do
begin // return value
Inc(i);
Sleep(100); // Allow for things to happen
end;
if (i >= 10) then
begin // Failed all tries
if GetLastError = 0 then dwResult := FSUIPC_ERR_TIMEOUT
else dwResult := FSUIPC_ERR_SENDMSG;
Result := FALSE;
Exit;
end;
if (dwError <> FS6IPC_MESSAGE_SUCCESS) then
begin // FSUIPC didn't like something in the data!
dwResult := FSUIPC_ERR_DATA;
Result := FALSE;
Exit;
end;
// Decode and store results of Read requests
pdw := m_pView;
while (pdw <> Nil) and Boolean(pdw^) do
begin
case pdw^ of
FS6IPC_READSTATEDATA_ID :
begin
pHdrR := Pointer(pdw);
DWORD(m_pNext) := DWORD(m_pNext) + sizeof(FS6IPC_READSTATEDATA_HDR);
if (pHdrR^.pDest <> Nil) and (pHdrR^.nBytes <> 0) then
begin
CopyMemory(pHdrR^.pDest, m_pNext, pHdrR^.nBytes);
end;
DWORD(m_pNext) := DWORD(m_pNext) + pHdrR^.nBytes;
end;
FS6IPC_WRITESTATEDATA_ID :
begin
// This is a write, so there's no returned data to store
pHdrW := Pointer(pdw);
DWORD(m_pNext) := DWORD(m_pNext) + sizeof(FS6IPC_WRITESTATEDATA_HDR) +
pHdrW^.nBytes;
end;
else
// Error! So terminate the scan
pdw := Nil;
end;
pdw := m_pNext;
end;
m_pNext := m_pView;
dwResult := FSUIPC_ERR_OK;
Result := TRUE;
end;
//--- Read Data ---------------------------------------------------------------
Function FSUIPC_Read(dwOffset : DWORD; dwSize : DWORD; pDest : Pointer; var dwResult : DWORD) : Boolean;
var
pHdr : ^FS6IPC_READSTATEDATA_HDR;
begin
pHdr := m_pNext;
// Check link is open
if (m_pView = Nil) then
begin
dwResult := FSUIPC_ERR_NOTOPEN;
Result := FALSE;
Exit;
end;
// Check have space for this request (including terminator)
if (((DWORD(m_pNext) - DWORD(m_pView)) + 4 + (dwSize + sizeof(FS6IPC_READSTATEDATA_HDR))) > MAX_SIZE) then
begin
dwResult := FSUIPC_ERR_SIZE;
Result := FALSE;
Exit;
end;
// Initialise header for read request
pHdr^.dwId := FS6IPC_READSTATEDATA_ID;
pHdr^.dwOffset := dwOffset;
pHdr^.nBytes := dwSize;
pHdr^.pDest := pDest;
// Move pointer past the Record
DWORD(m_pNext) := DWORD(m_pNext) + sizeof(FS6IPC_READSTATEDATA_HDR);
if (dwSize <> 0) then
begin
// Zero the reception area, so rubbish won't be returned
ZeroMemory(m_pNext, dwSize);
// Update the pointer ready for more data
DWORD(m_pNext) := DWORD(m_pNext) + dwSize;
end;
dwResult := FSUIPC_ERR_OK;
Result := TRUE;
end;
//--- Write Data --------------------------------------------------------------
Function FSUIPC_Write(dwOffset : DWORD; dwSize : DWORD; pSrce : Pointer; var dwResult : DWORD) : Boolean;
var
pHdr : ^FS6IPC_WRITESTATEDATA_HDR;
begin
pHdr := m_pNext;
if (m_pView = Nil) then
begin
dwResult := FSUIPC_ERR_NOTOPEN;
Result := FALSE;
Exit;
end;
// Check have space for this request (including terminator)
if (((DWORD(m_pNext) - DWORD(m_pView)) + 4 +(dwSize + sizeof(FS6IPC_WRITESTATEDATA_HDR))) > MAX_SIZE) then
begin
dwResult := FSUIPC_ERR_SIZE;
Result := FALSE;
Exit;
end;
// Initialise header for write request
pHdr^.dwId := FS6IPC_WRITESTATEDATA_ID;
pHdr^.dwOffset := dwOffset;
pHdr^.nBytes := dwSize;
// Move pointer past the Record
DWORD(m_pNext) := DWORD(m_pNext) + sizeof(FS6IPC_WRITESTATEDATA_HDR);
if (dwSize <> 0) then
begin // Copy in the data to be written
CopyMemory(m_pNext, pSrce, dwSize); // Update the pointer ready for more data
DWORD(m_pNext) := DWORD(m_pNext) + dwSize;
end;
dwResult := FSUIPC_ERR_OK;
Result := TRUE;
end;
Initialization
//--- Initialize global variables ---
FSUIPC_Version := 0;
FSUIPC_FS_Version := 0;
FSUIPC_Lib_Version := LIB_VERSION;
FSUIPC_Class_Version := 0;
//--- IPC Client Stuff ---
m_hWnd := 0; // FS6 window handle
m_msg := 0; // id of registered window message
m_atom := 0; // global atom containing name of file-mapping object
m_hMap := 0; // handle of file-mapping object
m_pView := Nil; // pointer to view of file-mapping object
m_pNext := Nil;
finalization
//--- Automatic "close" if programmer "forgets" ---
FSUIPC_Close;
end.
|
unit KHelp;
{$include KControls.inc}
{$WEAKPACKAGEUNIT ON}
interface
uses
Windows, Forms, ShellApi, Classes, SysUtils,
HelpIntfs;
resourcestring
sHelpErrorCaption = 'Help system error';
sHelpError = 'Cannot find help file "%s"!';
const
HH_DISPLAY_TOC = $0001;
HH_DISPLAY_INDEX = $0002;
HH_DISPLAY_TOPIC = $0000;
HH_CLOSE_ALL = $0012;
procedure KHtmlHelp(uCommand: UINT; dwData: PDWORD; HelpFile: string = '');
implementation
uses
KFunctions, KMessageBox;
function HtmlHelp(hwndCaller: HWND; pszFile: PChar; uCommand: UINT;
dwData: PDWORD): HWND; stdcall; external 'hhctrl.ocx' Name 'HtmlHelpA';
procedure KHtmlHelp(uCommand: UINT; dwData: PDWORD; HelpFile: string = '');
begin
if HelpFile = '' then
HelpFile := Application.HelpFile;
if HtmlHelp(0, PChar(HelpFile), uCommand, dwData) = 0 then
AppMsgBox(sHelpErrorCaption, Format(sHelpError, [Application.HelpFile]), MB_OK + MB_ICONEXCLAMATION);
end;
end.
|
unit TipoRecursoDataUn;
interface
uses
SysUtils, Classes, FMTBcd, DB, Provider, osSQLDataSetProvider, SqlExpr, osUtils,
osCustomDataSetProvider, osSQLDataSet;
type
TTipoRecursoData = class(TDataModule)
MasterDataSet: TosSQLDataset;
MasterProvider: TosSQLDataSetProvider;
MasterDataSetIDTIPORECURSO: TIntegerField;
MasterDataSetDESCRICAO: TStringField;
private
public
procedure Validate(PDataSet: TDataSet);
end;
var
TipoRecursoData: TTipoRecursoData;
implementation
uses osErrorHandler, SQLMainData;
{$R *.dfm}
procedure TTipoRecursoData.Validate(PDataSet: TDataSet);
begin
with PDataSet, HError do
begin
Clear;
CheckEmpty(FieldByName('Descricao'));
Check;
end;
end;
initialization
OSRegisterClass(TTipoRecursoData);
end.
|
unit SDSOS;
interface
uses SysUtils, Classes, Windows, Math, CPort;
type
TCmdProc = procedure(Params : TStrings) of object;
TSmallDeviceOS = class(TObject)
protected
FCmdList : TStringList;
FDeviceStream : TStream;
FCurrentDIR : string;
protected
procedure RegisterCmd(Name, Description : string; Proc : TCmdProc);
procedure osWriteStr(Str : PChar); virtual;
procedure osWriteLn(Str : PChar);
public
constructor Create(DeviceStream : TStream);
destructor Destroy; override;
procedure Execute(Cmd : string);
procedure osMountDevice;
procedure osHELP(Params : TStrings);
procedure osDIR(Params : TStrings);
procedure osCD(Params : TStrings);
procedure osUPLOAD(Params : TStrings);
procedure osDOWNLOAD(Params : TStrings);
end;
type
TSmallDeviceTerminalOS = class(TSmallDeviceOS)
private
FComPort : TCustomComPort;
FIncomingLine : string;
protected
procedure TerminalRxChar(Sender: TObject; Count: Integer);
procedure ProcessIncomingLine;
procedure osWriteStr(Str : PChar); override;
procedure osWritePrompt;
public
constructor Create(DeviceStream : TStream; AComPort : TCustomComPort);
destructor Destroy; override;
procedure Run;
procedure Stop;
end;
var
SmallDeviceDemoStream : TStream;
implementation
type
TosFileRec = record // Total 32 bytes for Small Device
Next : Cardinal; // 2 Next record
Child : Cardinal; // 2 Child recod
Start : Cardinal; // 2 Start of file
Size : Integer; // 2 File size (-1 if unknown)
FileDate : TDateTime; // 4
Name : string; // 12 8.3 format
Attr : word; // 2 File attrs
Extra : Array[0..5] of byte; // 6 bytes
end;
type
TOsCmd = class(TObject)
private
FName : string;
FDescription : string;
FProc : TCmdProc;
public
constructor Create(Name, Description : String; Proc : TCmdProc);
procedure Execute(Params : TStrings);
property Name : string read FName;
property Description : string read FDescription write FDescription;
end;
Type
TInquiryEvent = procedure(Sender : TObject; var Device, Params : string);
TPicDemoStream = class(TStream)
private
FReadBuf : PByteArray;
FReadLen : Integer;
FRAM : PByteArray;
FFlash : PWordArray;
FEE : PByteArray;
FOnInquiry : TInquiryEvent;
protected
procedure Respond(Str : string);
procedure osInquiry; // Inquiry command
procedure osReadRAM(Addrs : word); // Read Register
procedure osWriteRAM(Addrs : word; B : Byte); // Write Register
public
constructor Create;
destructor Destroy; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Read(var Buffer; Count: Longint): Longint; override;
public
property OnInquiry : TInquiryEvent read FOnInquiry write FOnInquiry;
end;
constructor TPicDemoStream.Create;
const
Welcome = 'Microchip PIC demo'#13;
begin
inherited Create;
GetMem(FReadBuf, 512);
GetMem(FRAM, 4*128);
GetMem(FFlash, 8192*2);
GetMem(FEE, 256);
FReadLen := 0;
FOnInquiry := nil;
Respond(Welcome);
end;
destructor TPicDemoStream.Destroy;
begin
FreeMem(FEE);
FreeMem(FFlash);
FreeMem(FRAM);
FreeMem(FReadBuf);
inherited Destroy;
end;
function TPicDemoStream.Write(const Buffer; Count: Longint): Longint;
var
B : TByteArray absolute Buffer;
begin
Case Char(B[0]) of
'@' : osInquiry;
'A' : osReadRAM(B[1]+256*B[2]);
'B' : osWriteRAM(B[1]+256*B[2], B[3]);
end;
result := Count;
end;
function TPicDemoStream.Read(var Buffer; Count: Longint): Longint;
begin
Count := Min(Count, FReadLen);
Move(FReadBuf^, Buffer, Count);
if Count<FReadLen then Move(FReadBuf^[Count], FReadBuf^, FReadLen-Count);
Dec(FReadLen, Count);
result := Count;
end;
procedure TPicDemoStream.Respond(Str : string);
begin
Move(Str[1], FReadBuf^[FReadLen], Length(Str));
Inc(FReadLen, Length(Str));
end;
procedure TPicDemoStream.osInquiry; // Inquiry
var
Device, Params : string;
begin
Device := 'PIC16F877';
Params := '-B-LAB';
If Assigned(FOnInquiry) then FOnInquiry(Self, Device, Params);
Respond(Device+' '+Params+#13);
end;
procedure TPicDemoStream.osReadRAM(Addrs : word);
begin
if Addrs<4*128 then
Respond(Char(FRAM^[Addrs]))
else
Respond(#$FF);
end;
procedure TPicDemoStream.osWriteRAM(Addrs : word; B : Byte);
begin
if Addrs>=4*128 then exit;
FRAM^[Addrs] := B;
end;
{*****************************************************************************}
constructor TOsCmd.Create(Name, Description : String; Proc : TCmdProc);
begin
inherited Create;
FName := Name;
FDescription := Description;
FProc := Proc;
end;
procedure TOsCmd.Execute(Params : TStrings);
begin
if Assigned(FProc) then FProc(Params);
end;
constructor TSmallDeviceOS.Create(DeviceStream : TStream);
begin
inherited Create;
FCmdList := TStringList.Create;
FCmdList.Sorted := true;
FCurrentDIR := '';
FDeviceStream := DeviceStream;
RegisterCmd('HELP', 'Type HELP cmd for more informations', osHELP);
RegisterCmd('DIR', 'Directory listing', osDIR);
RegisterCmd('LS', 'Directory listing', osDIR);
RegisterCmd('CD', 'Change directory', osCD);
RegisterCmd('UPLOAD', 'Upload a file', osUPLOAD);
RegisterCmd('DOWNLOAD','Download a file', osDOWNLOAD);
end;
destructor TSmallDeviceOS.Destroy;
begin
FCmdList.Free;
end;
procedure TSmallDeviceOS.RegisterCmd(Name, Description : string; Proc : TCmdProc);
var
osCmd : TosCmd;
begin
osCmd := TosCmd.Create(Name, Description, Proc);
FCmdList.AddObject(Name, osCmd);
end;
procedure TSmallDeviceOS.osWriteStr(Str : PChar);
begin
MessageBox(0, Str, 'Small Device Scalable OS', MB_OK);
end;
procedure TSmallDeviceOS.osWriteLn(Str : PChar);
begin
osWriteStr(Str);
osWriteStr(#13);
end;
procedure TSmallDeviceOS.osMountDevice;
var
Buffer : PChar;
Len : Integer;
S : TStringList;
const
cmdInquiry : char = '@';
begin
Buffer := StrAlloc(1024);
S := TStringList.Create;
Len := FDeviceStream.Read(Buffer^, 1023);
Buffer[Len] := #0;
osWriteStr(Buffer);
FDeviceStream.Write(cmdInquiry, 1);
Len := FDeviceStream.Read(Buffer^, 1023);
Buffer[Len] := #0;
ExtractStrings([' ', '-', '/'], [' '], Buffer, S);
FCurrentDIR := S[0]+'/';
osWriteStr(Buffer);
S.Free;
StrDispose(Buffer);
end;
procedure TSmallDeviceOS.Execute(Cmd : string);
var
i : integer;
S : TStringList;
begin
S := TStringList.Create;
if ExtractStrings([' ', '-', '/'], [' '], PChar(Cmd), S) = 0 then exit;
if FCmdList.Find(S[0], i) then
TosCmd(FCmdList.Objects[i]).Execute(S);
osWriteLn('');
S.Free;
end;
procedure TSmallDeviceOS.osHELP(Params : TStrings);
var
i : integer;
begin
i := 0;
while i<FCmdList.Count do begin
with TosCmd(FCmdList.Objects[i]) do begin
osWriteStr(PChar(Name));
osWriteStr(PChar(StringOfChar(' ', 10-Length(Name))));
osWriteLn(PChar(Description));
end;
Inc(i);
end;
end;
procedure TSmallDeviceOS.osDIR(Params : TStrings);
const
fmtDateTime = 'dd.mm.yyyy hh:nn';
fmtDir = '%-12.12s <DIR>';
fmtFile = '%-12.12s %s';
fmtDev = '%-12.12s <DEV>';
begin
osWriteLn(PChar('Directory of '+FCurrentDIR));
osWriteLn(PChar(Format(fmtDev, ['I2C'])));
osWriteLn(PChar(Format(fmtDir, ['EEPROM'])));
osWriteLn(PChar(Format(fmtFile, ['OS.hex', FormatDateTime(fmtDateTime, Now())])));
osWriteLn(PChar(Format(fmtFile, ['Main.hex', FormatDateTime(fmtDateTime, Now())])));
osWriteLn(PChar(Format(fmtFile, ['Readme.htm', FormatDateTime(fmtDateTime, Now())])));
end;
procedure TSmallDeviceOS.osCD(Params : TStrings);
begin
if Params.Count<>2 then exit;
if Params[1]='.' then exit;
if Params[1]='..' then exit;
FCurrentDIR := FCurrentDIR+Params[1]+'/';
end;
procedure TSmallDeviceOS.osUPLOAD(Params : TStrings);
begin
osWriteLn('-> Upload file with ZModem protocol');
end;
procedure TSmallDeviceOS.osDOWNLOAD(Params : TStrings);
begin
osWriteLn('-> Download file with ZModem protocol');
end;
{**************************************************************}
constructor TSmallDeviceTerminalOS.Create(DeviceStream : TStream; AComPort : TCustomComPort);
begin
inherited Create(DeviceStream);
FIncomingLine := '';
FComPort := AComPort;
FComPort.OnRxChar := TerminalRxChar;
end;
destructor TSmallDeviceTerminalOS.Destroy;
begin
FComPort.OnRxChar := nil;
inherited Destroy;
end;
procedure TSmallDeviceTerminalOS.TerminalRxChar(Sender: TObject; Count: Integer);
var
C : char;
begin
while Count>0 do begin
FComPort.Read(C, 1);
case C of
#8 : if Length(FIncomingLine)>0 then begin // Backspace
Delete(FIncomingLine, Length(FIncomingLine), 1);
FComPort.WriteStr(#8' '#8);
end else
FComPort.WriteStr(#7); // Bell
#13 : begin
FComPort.WriteStr(#13); // CR
ProcessIncomingLine;
end;
else begin
FComPort.Write(C, 1); // Echo
FIncomingLine := FIncomingLine+C;
end;
end;
Dec(Count);
end;
end;
procedure TSmallDeviceTerminalOS.ProcessIncomingLine;
begin
Execute(FIncomingLine);
FIncomingLine := '';
osWritePrompt;
end;
procedure TSmallDeviceTerminalOS.osWritePrompt;
begin
osWriteStr(PChar(FCurrentDIR+' $ '));
end;
procedure TSmallDeviceTerminalOS.osWriteStr(Str : PChar);
begin
FComPort.WriteStr(Str);
end;
procedure TSmallDeviceTerminalOS.Run;
begin
FComPort.Open;
osWriteLn('Small Device Scalable OS - Terminal Server');
osMountDevice;
osWriteLn('Type ''help'' to know available commands');
osWritePrompt;
end;
procedure TSmallDeviceTerminalOS.Stop;
begin
osWriteLn(#13'Terminal Server : shut down');
FComPort.Close;
end;
initialization
SmallDeviceDemoStream := TPicDemoStream.Create;
end.
|
////////////////////////////////////////////
// Конфигурационный файл
////////////////////////////////////////////
unit AppConfigFile;
interface
uses Windows, GMGlobals, IniFiles, ConnParamsStorage;
type
TGMIniFileType = (iftINI, iftXML, iftError);
TGMMainConfigFile = class
private
function ExpandConfigFileName(fn: string): string;
function LookForCmdLineConfigParam(ext: string): string;
protected
procedure ReportError(const msg: string; isFatal: bool); virtual;
public
function GetMainINIFileName(): string; virtual; abstract;
function CheckMainINIFile(): TGMIniFileType;
function ReadSQLConnectionParams(var params: TZConnectionParams): bool;
end;
TGMMainConfigFileClass = class of TGMMainConfigFile;
TGMClientMainConfigFile = class(TGMMainConfigFile)
private
function IniToXml(const fn: string): bool;
function IsClientINI(const fn: string): bool;
function ParseAlarms(f: TINIFile): string;
function ParseBigWindow(f: TINIFile; n: int): string;
function ParseBigWindowChannel(f: TINIFile; const section,
Prefix: string): string;
function ParseBigWindows(f: TINIFile): string;
function ParseCommon(f: TINIFile): string;
function ParseObject(f: TINIFile; n: int): string;
function ParseObjectChannel(f: TINIFile; const section, Prefix: string;
num: int): string;
function ParseObjects(f: TINIFile): string;
public
function GetMainINIFileName(): string; override;
end;
TGMServerMainConfigFile = class(TGMMainConfigFile)
public
function GetMainINIFileName(): string; override;
end;
TGMServiceConfigFile = class(TGMServerMainConfigFile)
protected
procedure ReportError(const msg: string; isFatal: bool); override;
public
function GetMainINIFileName(): string; override;
end;
function GMMainConfigFile(): TGMMainConfigFile;
procedure SetMainConfigFileClass(AMainConfigFileClass: TGMMainConfigFileClass);
implementation
uses SysUtils, Forms, Classes, ProgramLogFile;
var MainConfigFile: TGMMainConfigFile = nil;
MainConfigFileClass: TGMMainConfigFileClass = nil;
function GMMainConfigFile(): TGMMainConfigFile;
begin
if (MainConfigFile = nil) and (MainConfigFileClass <> nil) then
MainConfigFile := MainConfigFileClass.Create();
Result := MainConfigFile;
end;
procedure SetMainConfigFileClass(AMainConfigFileClass: TGMMainConfigFileClass);
begin
if MainConfigFile <> nil then
FreeAndNil(MainConfigFile);
MainConfigFileClass := AMainConfigFileClass;
end;
function TGMMainConfigFile.ExpandConfigFileName(fn: string): string;
begin
if ExtractFileDir(fn) <> '' then
Result := IncludeTrailingPathDelimiter(ExtractFileDir(Application.ExeName)) + fn
else
Result := fn;
end;
function TGMMainConfigFile.LookForCmdLineConfigParam(ext: string): string;
var i: int;
begin
Result := '';
for i := 1 to ParamCount() do
begin
if ext = LowerCase(ExtractFileExt(ParamStr(i))) then
begin
Result := ExpandConfigFileName(ParamStr(i));
Exit;
end;
end;
end;
function TGMMainConfigFile.ReadSQLConnectionParams(var params: TZConnectionParams): bool;
var f: TIniFile;
begin
Result := CheckMainINIFile() = iftINI;
if Result then
begin
f := TIniFile.Create(GetMainINIFileName());
try
Params.Host := f.ReadString('SQL', 'POSTGRES_SRV', '127.0.0.1');
Params.Port := f.ReadInteger('SQL', 'POSTGRES_PORT', 5432);
Params.Database := f.ReadString('SQL', 'DB', '');
Params.Login := f.ReadString('SQL', 'LOGIN', '');
Params.Password := f.ReadString('SQL', 'PASS', '');
finally
f.Free();
end;
end;
end;
procedure TGMMainConfigFile.ReportError(const msg: string; isFatal: bool);
begin
ShowMessageBox(msg, MB_ICONSTOP);
if isFatal then
Application.Terminate();
end;
function TGMMainConfigFile.CheckMainINIFile(): TGMIniFileType;
var fn: string;
begin
Result := iftError;
fn := GetMainINIFileName();
try
if not FileExists(fn) then
begin
ReportError('Файл ' + fn + ' не найден!', true);
Exit;
end;
if LowerCase(ExtractFileExt(fn)) = '.ini' then
Result := iftINI
else
if LowerCase(ExtractFileExt(fn)) = '.xml' then
Result := iftXML;
except
on e: Exception do
begin
ReportError('Ошибка чтения файла ' + fn + #13#10 + e.Message, true);
end;
end;
end;
{ TGMServerMainConfigFile }
function TGMServerMainConfigFile.GetMainINIFileName: string;
begin
Result := LookForCmdLineConfigParam('.ini');
if Result = '' then
Result := ChangeFileExt(Application.ExeName, '.ini');
Result := ExpandFileName(Result);
end;
{ TGMClientMainConfigFile }
function TGMClientMainConfigFile.ParseObjectChannel(f: TINIFile; const section, Prefix: string; num: int): string;
begin
Result := Format(' <channel num="%d" id_prm="%d" dmax="%s" dmin="%s" prefix=%s postfix=%s diagram="%d" barfloat="%s" pump_prm="%d" pump_signal="%d" digits="%d" showtype="%d" />'#13#10,
[ num,
f.ReadInteger(section, Prefix + 'ID_PRM', 0),
MyFloatToStr(MyStrToFloatDef(f.ReadString(section, Prefix+'DIAGRAMMAX', ''), 100)),
MyFloatToStr(MyStrToFloatDef(f.ReadString(section, Prefix+'DIAGRAMMIN', ''), 0)),
AnsiQuotedStr(f.ReadString(section, Prefix + 'TEXT1', ''), '"'),
AnsiQuotedStr(f.ReadString(section, Prefix + 'TEXT2', ''), '"'),
f.ReadInteger(section, Prefix + 'DIAGRAM', 0),
f.ReadString(section, Prefix + 'BARFLOAT', ''),
f.ReadInteger(section, Prefix + 'ID_PUMPDOWNPRM', 0),
f.ReadInteger(section, Prefix + 'PUMPDOWNSIGNAL', 1),
f.ReadInteger(section, Prefix + 'DIGITS', 0),
f.ReadInteger(section, Prefix + 'SHOWTYPE', 0)
]);
end;
function TGMClientMainConfigFile.ParseObject(f: TINIFile; n: int): string;
var section: string;
begin
section := 'OBJECT' + IntToStr(n);
Result := Format(' <object name=%s x="%d" y="%d" ticks="%d" color="%d" squeeze="%d" id_obj="%d">'#13#10,
[ AnsiQuotedStr(f.ReadString(section, 'NAME', ''), '"'),
f.ReadInteger(section, 'X', 0),
f.ReadInteger(section, 'Y', 0),
f.ReadInteger(section, 'DIAGRAM_TICKS', 0),
f.ReadInteger(section, 'COLOR', 1),
f.ReadInteger(section, 'SQUEEZE', 100),
f.ReadInteger(section, 'ID', 0)
]);
Result := Result + ' <channels>'#13#10;
Result := Result + ParseObjectChannel(f, section, 'BAR_', 0);
Result := Result + ParseObjectChannel(f, section, 'VAL1_', 1);
Result := Result + ParseObjectChannel(f, section, 'VAL2_', 2);
Result := Result + ParseObjectChannel(f, section, 'VAL3_', 3);
Result := Result + ParseObjectChannel(f, section, 'VAL4_', 4);
Result := Result + ' </channels>'#13#10;
Result := Result + ' </object>'#13#10;
end;
function TGMClientMainConfigFile.ParseObjects(f: TINIFile): string;
var i: int;
begin
Result := Result + ' <objects>'#13#10;
i := 1;
while f.SectionExists('OBJECT' + IntToStr(i)) do
begin
Result := Result + ParseObject(f, i);
inc(i);
end;
Result := Result + ' </objects>'#13#10;
end;
function TGMClientMainConfigFile.ParseAlarms(f: TINIFile): string;
var sl: TStringList;
i, prm: int;
begin
sl := TStringList.Create();
try
Result := Result + ' <alarms>'#13#10;
f.ReadSection('ALARMS', sl);
for i := 0 to sl.Count - 1 do
begin
prm := f.ReadInteger('ALARMS', sl[i], 0);
if prm > 0 then
Result := Result + ' <alarm id_prm="' + IntToStr(prm) + '" />'#13#10;
end;
Result := Result + ' </alarms>'#13#10;
finally
sl.Free();
end;
end;
function TGMClientMainConfigFile.ParseCommon(f: TINIFile): string;
var sl: TStringList;
i: int;
s: string;
begin
sl := TStringList.Create();
try
Result := ' <common>'#13#10;
f.ReadSection('COMMON', sl);
for i := 0 to sl.Count - 1 do
begin
s := LowerCase(sl[i]);
Result := Result + Format(' <%s>%s</%s>'#13#10, [s, f.ReadString('COMMON', s, ''), s]);
end;
Result := Result + ' </common>'#13#10;
finally
sl.Free();
end;
end;
function TGMClientMainConfigFile.ParseBigWindowChannel(f: TINIFile; const section, Prefix: string): string;
begin
Result := Format(' <diagram id_prm="%d" dmax="%s" dmin="%s" text=%s diagram="%d" colwidth="%d" />'#13#10,
[ f.ReadInteger(section, Prefix, 0),
MyFloatToStr(f.ReadFloat(section, Prefix + '_DMAX', 100)),
MyFloatToStr(f.ReadFloat(section, Prefix + '_DMIN', 0)),
AnsiQuotedStr(f.ReadString(section, Prefix + '_TITLE', ''), '"'),
f.ReadInteger(section, Prefix + '_WANTDIAGRAM', 1),
f.ReadInteger(section, Prefix + '_COLWIDTH', 0) ]);
end;
function TGMClientMainConfigFile.ParseBigWindow(f: TINIFile; n: int): string;
var section: string;
i: int;
begin
section := 'BIGWINDOW' + IntToStr(n);
Result := Format(' <bigwindow name=%s>'#13#10,
[ AnsiQuotedStr(f.ReadString(section, 'NAME', ''), '"') ]);
Result := Result + ' <diagrams>'#13#10;
for i := 0 to f.ReadInteger(section, 'PRM_COUNT', 0) - 1 do
Result := Result + ParseBigWindowChannel(f, section, 'PRM_' + IntToStr(i));
Result := Result + ' </diagrams>'#13#10;
Result := Result + ' </bigwindow>'#13#10;
end;
function TGMClientMainConfigFile.ParseBigWindows(f: TINIFile): string;
var i: int;
begin
Result := Result + ' <bigwindows>'#13#10;
i := 1;
while f.SectionExists('BIGWINDOW' + IntToStr(i)) do
begin
Result := Result + ParseBigWindow(f, i);
inc(i);
end;
Result := Result + ' </bigwindows>'#13#10;
end;
function TGMClientMainConfigFile.IniToXml(const fn: string): bool;
var f: TINIFile;
xml: string;
begin
Result := false;
try
f := TIniFile.Create(fn);
xml := '<?xml version="1.0" encoding="Windows-1251"?>'#13#10 +
'<config>'#13#10;
xml := xml + ParseCommon(f);
xml := xml + ParseObjects(f);
xml := xml + ParseAlarms(f);
xml := xml + ParseBigWindows(f);
xml := xml + '</config>';
SaveStringToFile(xml, ChangeFileExt(ExpandFileName(fn), '.xml'));
f.free();
Result := true;
except
end;
end;
function TGMClientMainConfigFile.IsClientINI(const fn: string): bool;
var f: TINIFile;
begin
Result := false;
try
f := TIniFile.Create(fn);
Result := f.SectionExists('ALARMS')
or f.SectionExists('OBJECT1')
or f.SectionExists('BIGWINDOW1')
or f.SectionExists('BIGWINDOW1');
Result := Result and not f.SectionExists('SQL');
f.free();
except
end;
end;
function TGMClientMainConfigFile.GetMainINIFileName: string;
var xmlname, ininame: string;
begin
Result := LookForCmdLineConfigParam('.xml');
if Result = '' then
Result := LookForCmdLineConfigParam('.ini');
if Result = '' then
begin
Result := ChangeFileExt(Application.ExeName, '.xml');
if not FileExists(Result) then
begin
ininame := ChangeFileExt(Result, '.ini');
if FileExists(ininame) then
Result := ininame;
end;
end;
if (ExtractFileExt(Result) = '.ini') and IsClientINI(Result) then
begin
xmlname := ChangeFileExt(Result, '.xml');
if not FileExists(xmlname) then
IniToXml(Result);
Result := xmlname;
end;
end;
{ TGMServiceConfigFile }
function TGMServiceConfigFile.GetMainINIFileName: string;
begin
Result := inherited GetMainINIFileName();
if (Result = '') or not FileExists(Result) then // не нашли свою - поищем от сервера
Result := IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0))) + 'GMIOPSrv.ini';
end;
procedure TGMServiceConfigFile.ReportError(const msg: string; isFatal: bool);
begin
ProgramLog.AddError(msg);
end;
initialization
finalization
if Assigned(MainConfigFile) then
GMMainConfigFile.Free();
end.
|
unit ncShellStart;
interface
uses
Windows,
SysUtils,
ShellApi;
procedure ShellStart(aCmd: String; aParams: String=''; aDirectory: String=''; FormHWND: HWND = 0);
procedure ShellStartCustom(aCmd, aParams, aDir: String; FormHWND: HWND; nShow: Integer = SW_SHOWNORMAL; aVerb: String = 'open');
implementation
procedure ShellStart(aCmd: String; aParams: String=''; aDirectory: String=''; FormHWND: HWND = 0);
begin
ShellStartCustom(aCmd, aParams, aDirectory, FormHWND);
end;
procedure ShellStartCustom(aCmd, aParams, aDir: String; FormHWND: HWND; nShow: Integer = SW_SHOWNORMAL; aVerb: String = 'open');
var
ExecInfo: TShellExecuteInfo;
begin
if Trim(aCmd)='' then Exit;
ExecInfo.hProcess := 0;
ExecInfo.cbSize := SizeOf(TShellExecuteInfo);
ExecInfo.fMask := SEE_MASK_NOCLOSEPROCESS;
ExecInfo.Wnd := FormHWND;
ExecInfo.lpVerb := PChar(aVerb);
ExecInfo.lpFile := PChar(aCmd);
ExecInfo.lpParameters := PChar(aParams);
ExecInfo.lpDirectory := PChar(aDir);
ExecInfo.nShow := nShow;
//open - execute the specified file
ShellExecuteEx(@ExecInfo);
if ExecInfo.hProcess<>0 then CloseHandle(ExecInfo.hProcess);
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLTextureCombiners<p>
Texture combiners setup utility functions.<p>
<b>History : </b><font size=-1><ul>
<li>05/03/11 - Yar - Added combiner's commands cache
<li>23/08/10 - Yar - Added OpenGLTokens to uses
<li>18/06/10 - Yar - Replaced OpenGL functions to OpenGLAdapter
<li>02/04/07 - DaStr - Added $I GLScene.inc
<li>17/12/03 - EG - Alpha and RGB channels separate combination now supported
<li>23/05/03 - EG - All tex units now accepted as target
<li>22/05/03 - EG - Fixed GL_ADD_SIGNED_ARB parsing, better error reporting
<li>16/05/03 - EG - Creation
</ul></font>
}
unit GLTextureCombiners;
interface
{$I GLScene.inc}
uses
SysUtils, Classes,
OpenGLTokens,
GLContext;
type
TCombinerCommand = record
ActiveUnit: Integer;
Arg1: Integer;
Arg2: Integer;
end;
TCombinerCache = array of TCombinerCommand;
// ETextureCombinerError
//
ETextureCombinerError = class(Exception)
;
{: Parses a TC text description and setups combiners accordingly.<p>
*experimental*<br>
Knowledge of texture combiners is a requirement<br>
Syntax: pascal-like, one instruction per line, use '//' for comment.<p>
Examples:<ul>
<li>Tex1:=Tex0; // replace texture 1 with texture 0
<li>Tex1:=Tex0+Tex1; // additive blending between textures 0 and 1
<li>Tex1:=Tex0-Tex1; // subtractive blending between textures 0 and 1
<li>Tex1:=Tex0*Tex1; // modulation between textures 0 and 1
<li>Tex1:=Tex0+Tex1-0.5; // signed additive blending between textures 0 and 1
<li>Tex1:=Interpolate(Tex0, Tex1, PrimaryColor); // interpolation between textures 0 and 1 using primary color as factor
<li>Tex1:=Dot3(Tex0, Tex1); // dot3 product between textures 0 and 1
</ul><p>
Accepted tokens:<ul>
<li>Tex0, Tex1, etc. : texture unit
<li>PrimaryColor, Col : the primary color
<li>ConstantColor, EnvCol : texture environment constant color
</ul><br>
Tokens can be qualified with '.a' or '.alpha' to specify the alpha channel
explicitly, and '.rgb' to specify color channels (default). You cannot mix
alpha and rgb tokens in the same line.
}
function GetTextureCombiners(const tcCode: TStringList): TCombinerCache;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
var
vActiveUnit: Integer;
vCommandCache: TCombinerCache;
// TCAssertCheck
//
procedure TCAssertCheck(const b: Boolean; const errMsg: string);
begin
if not b then
raise ETextureCombinerError.Create(errMsg);
end;
// RemoveSpaces
//
function RemoveSpaces(const str: string): string;
var
c: Char;
i, p, n: Integer;
begin
n := Length(str);
SetLength(Result, n);
p := 1;
for i := 1 to n do
begin
c := str[i];
if c <> ' ' then
begin
Result[p] := c;
Inc(p);
end;
end;
SetLength(Result, p - 1);
end;
// ProcessTextureCombinerArgument
//
procedure ProcessTextureCombinerArgument(arg: string; sourceEnum, operandEnum: Integer;
const dest: string);
var
sourceValue, operandValue, n, p: Integer;
origArg, qualifier: string;
cmd: TCombinerCommand;
begin
origArg := arg;
p := Pos('.', arg);
if p > 0 then
begin
qualifier := Copy(arg, p + 1, MaxInt);
arg := Copy(arg, 1, p - 1);
end
else
qualifier := 'rgb';
if qualifier = 'rgb' then
begin
if Copy(arg, 1, 1) = '~' then
begin
operandValue := GL_ONE_MINUS_SRC_COLOR;
arg := Copy(arg, 2, MaxInt);
end
else if Copy(arg, 1, 2) = '1-' then
begin
operandValue := GL_ONE_MINUS_SRC_COLOR;
arg := Copy(arg, 3, MaxInt);
end
else
operandValue := GL_SRC_COLOR;
end
else if Copy(qualifier, 1, 1) = 'a' then
begin
if Copy(arg, 1, 1) = '~' then
begin
operandValue := GL_ONE_MINUS_SRC_ALPHA;
arg := Copy(arg, 2, MaxInt);
end
else if Copy(arg, 1, 2) = '1-' then
begin
operandValue := GL_ONE_MINUS_SRC_ALPHA;
arg := Copy(arg, 3, MaxInt);
end
else
operandValue := GL_SRC_ALPHA;
end
else
operandValue := 0;
sourceValue := 0;
if (arg = 'tex') or (arg = dest) then
sourceValue := GL_TEXTURE
else if ((arg = 'tex0') and (dest = 'tex1')) or ((arg = 'tex1') and (dest = 'tex2'))
or ((arg = 'tex2') and (dest = 'tex3')) then
sourceValue := GL_PREVIOUS_ARB
else if (arg = 'col') or (arg = 'col0') or (arg = 'primarycolor') then
sourceValue := GL_PRIMARY_COLOR_ARB
else if (arg = 'envcol') or (arg = 'constcol') or (arg = 'constantcolor') then
sourceValue := GL_CONSTANT_COLOR_ARB
else if Copy(arg, 1, 3) = 'tex' then
begin
TCAssertCheck(GL.ARB_texture_env_crossbar or GL.NV_texture_env_combine4,
'Requires GL_ARB_texture_env_crossbar or NV_texture_env_combine4');
n := StrToIntDef(Copy(arg, 4, MaxInt), -1);
if n in [0..7] then
sourceValue := GL_TEXTURE0_ARB + n;
end;
TCAssertCheck((operandValue > 0) and (sourceValue > 0),
'invalid argument : "' + origArg + '"');
SetLength(vCommandCache, Length(vCommandCache)+2);
cmd.ActiveUnit := vActiveUnit;
cmd.Arg1 := sourceEnum;
cmd.Arg2 := sourceValue;
vCommandCache[High(vCommandCache)-1] := cmd;
cmd.ActiveUnit := vActiveUnit;
cmd.Arg1 := operandEnum;
cmd.Arg2 := operandValue;
vCommandCache[High(vCommandCache)] := cmd;
end;
// ProcessTextureCombinerLine
//
procedure ProcessTextureCombinerLine(const tcLine: string);
var
line, dest, arg1, arg2, arg3, funcname: string;
p: Integer;
destEnum, operEnum: Integer;
sourceBaseEnum, operandBaseEnum: Integer;
sl: TStrings;
cmd: TCombinerCommand;
begin
// initial filtering
line := LowerCase(RemoveSpaces(Trim(tcLine)));
if Copy(line, 1, 2) = '//' then
Exit;
if line = '' then
Exit;
if line[Length(line)] = ';' then
begin
line := Trim(Copy(line, 1, Length(line) - 1));
if line = '' then
Exit;
end;
// Parse destination
p := Pos(':=', line);
dest := Copy(line, 1, p - 1);
line := Copy(line, p + 2, MaxInt);
p := Pos('.', dest);
destEnum := GL_COMBINE_RGB_ARB;
sourceBaseEnum := GL_SOURCE0_RGB_ARB;
operandBaseEnum := GL_OPERAND0_RGB_ARB;
if p > 0 then
begin
if Copy(dest, p + 1, 1) = 'a' then
begin
destEnum := GL_COMBINE_ALPHA_ARB;
sourceBaseEnum := GL_SOURCE0_ALPHA_ARB;
operandBaseEnum := GL_OPERAND0_ALPHA_ARB;
end;
dest := Copy(dest, 1, p - 1);
end;
if Copy(dest, 1, 3) = 'tex' then
begin
p := StrToIntDef(Copy(dest, 4, MaxInt), -1);
TCAssertCheck(p >= 0, 'Invalid destination texture unit "' + dest + '"');
vActiveUnit := p;
end
else
TCAssertCheck(False, 'Invalid destination "' + dest + '"');
// parse combiner operator
operEnum := 0;
arg1 := '';
arg2 := '';
arg3 := '';
p := Pos('+', line);
if p > 0 then
begin
// ADD & ADD_SIGNED operators
if Copy(line, Length(line) - 3, 4) = '-0.5' then
begin
operEnum := GL_ADD_SIGNED_ARB;
SetLength(line, Length(line) - 4);
end
else
operEnum := GL_ADD;
arg1 := Copy(line, 1, p - 1);
arg2 := Copy(line, p + 1, MaxInt);
end;
p := Pos('*', line);
if p > 0 then
begin
// MODULATE operator
operEnum := GL_MODULATE;
arg1 := Copy(line, 1, p - 1);
arg2 := Copy(line, p + 1, MaxInt);
line := '';
end;
p := Pos('(', line);
if p > 0 then
begin
// function
sl := TStringList.Create;
try
funcName := Copy(line, 1, p - 1);
p := Pos('(', line);
line := Copy(line, p + 1, MaxInt);
p := Pos(')', line);
sl.CommaText := Copy(line, 1, p - 1);
if funcName = 'interpolate' then
begin
// INTERPOLATE operator
TCAssertCheck(sl.Count = 3, 'Invalid parameter count');
operEnum := GL_INTERPOLATE_ARB;
arg1 := sl[0];
arg2 := sl[1];
arg3 := sl[2];
end
else if funcName = 'dot3' then
begin
// DOT3 operator
TCAssertCheck(sl.Count = 2, 'Invalid parameter count');
TCAssertCheck(GL.ARB_texture_env_dot3, 'Requires GL_ARB_texture_env_dot3');
operEnum := GL_DOT3_RGB_ARB;
arg1 := sl[0];
arg2 := sl[1];
end
else
TCAssertCheck(False, 'Invalid function "' + funcName + '"');
finally
sl.Free;
end;
line := '';
end;
p := Pos('-', line);
if p > 0 then
begin
// SUBTRACT operator
operEnum := GL_SUBTRACT_ARB;
arg1 := Copy(line, 1, p - 1);
arg2 := Copy(line, p + 1, MaxInt);
line := '';
end;
if operEnum = 0 then
begin
// REPLACE by default
operEnum := GL_REPLACE;
arg1 := line;
end;
cmd.ActiveUnit := vActiveUnit;
cmd.Arg1 := destEnum;
cmd.Arg2 := operEnum;
SetLength(vCommandCache, Length(vCommandCache)+1);
vCommandCache[High(vCommandCache)] := cmd;
// parse arguments
if arg1 <> '' then
ProcessTextureCombinerArgument(arg1, sourceBaseEnum, operandBaseEnum, dest);
if arg2 <> '' then
ProcessTextureCombinerArgument(arg2, sourceBaseEnum + 1, operandBaseEnum + 1, dest);
if arg3 <> '' then
ProcessTextureCombinerArgument(arg3, sourceBaseEnum + 2, operandBaseEnum + 2, dest);
end;
// SetupTextureCombiners
//
function GetTextureCombiners(const tcCode: TStringList): TCombinerCache;
var
i: Integer;
sl: TStringList;
begin
vCommandCache := nil;
TCAssertCheck(GL.ARB_texture_env_combine, 'Requires GL_ARB_texture_env_combine support');
sl := TStringList.Create;
try
sl.Assign(tcCode);
for i := 0 to sl.Count - 1 do
ProcessTextureCombinerLine(sl[i]);
finally
sl.Free;
end;
Result := vCommandCache;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSServerReg;
interface
uses ToolsAPI, DSSource, DesignEditors, DesignIntf;
type
TPEMFilePropertyEditor = class(TStringProperty)
protected
function GetFilter: string; virtual;
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
TPEMKeyFilePropertyEditor = class(TPEMFilePropertyEditor)
protected
function GetFilter: string; override;
end;
procedure Register;
function CreateServerMethodsModule(const APersonality, APrefix, AAncestorName: string; ASourceFlags: TSourceFlags): IOTAModule;
implementation
uses
Classes, SysUtils, DSServer, DSHTTP, DSNames,
Windows, DMForm, DSCommonServer, DbxTransport, StrEdit, DSHTTPCommon,
DSCreators, InetReg, DBXPlatform, Controls, DBXCommon, DSCommonReg, DSService, DSAuth,
DSServerDsnResStrs, Dialogs, Forms, InetDesignResStrs, PlatformAPI, TypInfo;
type
TCtxEnabledProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
end;
TCtxEnabledPropertyInt = class(TIntegerProperty)
public
function GetAttributes: TPropertyAttributes; override;
end;
TDSLifeCycleProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TDSCommunicationProtocolProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TDSServerModuleCreator = class(TModuleCreator, IOTAModuleCreator, IOTACreator)
private
FPrefix: string;
FPersonality: string;
FAncestorName: string;
FSourceFlags: TSourceFlags;
public
constructor Create(const APersonality, APrefix, AAncestorName: string; ASourceFlags: TSourceFlags);
{ IOTACreator }
function GetCreatorType: string;
{ IOTAModuleCreator }
function GetAncestorName: string;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
protected
function GetModuleAndClassNamePrefix: String; override;
end;
TDSServerModuleWizard = class(TNotifierObject, IOTANotifier, IOTAWizard,
IOTARepositoryWizard, IOTARepositoryWizard80, IOTARepositoryWizard160,
IOTAFormWizard)
protected
FWizardIcon: THandle;
FPersonality: string;
{ IOTAWizard }
function GetName: string;
function GetIDString: string;
procedure Execute;
{ IOTARepositoryWizard }
function GetAuthor: string;
function GetComment: string;
function GetPage: string;
function GetGlyph: Cardinal;
function GetState: TWizardState;
{ IOTARepositoryWizard60 }
function GetDesigner: string;
{ IOTARepositoryWizard80 }
function GetGalleryCategory: IOTAGalleryCategory;
function GetPersonality: string;
{ IOTARepositoryWizard160 }
function GetFrameworkTypes: TArray<string>;
function GetPlatforms: TArray<string>;
private
constructor Create(const APersonality: string);
end;
TDSClientCallbackManagerSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
TDSHTTPServiceSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
TDSServerTransportEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
TDSFilterIdProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TDSCustomRoleItemProperty = class(TStringListProperty)
public
function GetValue: string; override;
end;
TDSCustomFilterItemProperty = class(TValueListProperty)
public
function GetValue: string; override;
end;
var
WizardId: Integer;
WizardIdCpp: Integer;
procedure Register;
begin
RegisterComponents(rsDatasnapServer, [TDSServer, TDSServerClass, TDSHTTPService, TDSCertFiles,
TDSAuthenticationManager,
TDSClientCallbackChannelManager, TDSHTTPServiceFileDispatcher]);
RegisterPropertyEditor(TypeInfo(UnicodeString), TDSServerClass, 'LifeCycle', TDSLifeCycleProperty);
RegisterPropertyEditor(TypeInfo(UnicodeString), TDSClientCallbackChannelManager, 'CommunicationProtocol', TDSCommunicationProtocolProperty);
RegisterPropertyEditor(TypeInfo(string), TDSClientCallbackChannelManager, 'ProxyHost', TCtxEnabledProperty);
RegisterPropertyEditor(TypeInfo(Integer), TDSClientCallbackChannelManager, 'ProxyPort', TCtxEnabledPropertyInt);
RegisterPropertyEditor(TypeInfo(string), TDSClientCallbackChannelManager, 'ProxyUsername', TCtxEnabledProperty);
RegisterPropertyEditor(TypeInfo(string), TDSClientCallbackChannelManager, 'ProxyPassword', TCtxEnabledProperty);
RegisterPropertyEditor(TypeInfo(TStrings), TDSCustomRoleItem, '', TDSCustomRoleItemProperty);
RegisterSelectionEditor(TDSClientCallbackChannelManager, TDSClientCallbackManagerSelectionEditor);
RegisterSelectionEditor(TDSServerTransport, TDSServerTransportEditor);
RegisterPropertyEditor(TypeInfo(TStrings), TTransportFilterItem, 'Properties', TDSCustomFilterItemProperty);
RegisterPropertyEditor(TypeInfo(UnicodeString), TTransportFilterItem, 'FilterId', TDSFilterIdProperty);
RegisterSelectionEditor(TDSHTTPService, TDSHTTPServiceSelectionEditor);
RegisterPropertyEditor(TypeInfo(string), TDSCustomCertFiles, 'RootCertFile',
TPEMFilePropertyEditor);
RegisterPropertyEditor(TypeInfo(string), TDSCustomCertFiles, 'CertFile',
TPEMFilePropertyEditor);
RegisterPropertyEditor(TypeInfo(string), TDSCustomCertFiles, 'KeyFile',
TPEMKeyFilePropertyEditor);
RegisterCustomModule(TDSServerModule, TDataModuleCustomModule);
WizardId := (BorlandIDEServices as IOTAWizardServices).AddWizard(TDSServerModuleWizard.Create(sDelphiPersonality) as IOTAWizard);
WizardIdCpp := (BorlandIDEServices as IOTAWizardServices).AddWizard(TDSServerModuleWizard.Create(sCBuilderPersonality) as IOTAWizard);
end;
function CreateDSServerModule(const APersonality, APrefix: string; ASourceFlags: TSourceFlags): IOTAModule;
begin
Result := CreateServerMethodsModule(APersonality, APrefix, Copy(TDSServerModule.ClassName, 2, MaxInt),
ASourceFlags);
end;
function CreateServerMethodsModule(const APersonality, APrefix, AAncestorName: string; ASourceFlags: TSourceFlags): IOTAModule;
var
ModuleCreator: IOTAModuleCreator;
begin
ModuleCreator := TDSServerModuleCreator.Create(APersonality, APrefix, AAncestorName, ASourceFlags);
Result := (BorlandIDEServices as IOTAModuleServices).CreateModule(ModuleCreator);
end;
{ TLifeCycleProperty }
function TDSLifeCycleProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList, paMultiSelect];
end;
procedure TDSLifeCycleProperty.GetValues(Proc: TGetStrProc);
begin
Proc(TDSLifeCycle.Server);
Proc(TDSLifeCycle.Session);
Proc(TDSLifeCycle.Invocation);
// Proc(TDSLifeCycle.Pool);
end;
{ TDSServerModuleCreator }
constructor TDSServerModuleCreator.Create(const APersonality, APrefix, AAncestorName: string; ASourceFlags: TSourceFlags);
begin
inherited Create;
FPersonality := APersonality;
FPrefix := APrefix;
FAncestorName := AAncestorName;
FSourceFlags := ASourceFlags;
if FAncestorName = '' then
FAncestorName := Copy(TDSServerModule.ClassName, 2, MaxInt);
end;
function TDSServerModuleCreator.GetAncestorName: string;
begin
Result := FAncestorName;
end;
function TDSServerModuleCreator.GetCreatorType: string;
begin
Result := sForm;
end;
function TDSServerModuleCreator.GetModuleAndClassNamePrefix: String;
begin
Result := FPrefix;
end;
function TDSServerModuleCreator.GetShowForm: Boolean;
begin
Result := False;
end;
function TDSServerModuleCreator.GetShowSource: Boolean;
begin
Result := True;
end;
function TDSServerModuleCreator.NewImplSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
var
Source: string;
begin
Source := GetSourceFromTemplate(FPersonality, stDSServerModuleTemplate, nil, FSourceFlags);
Result := StringToIOTAFile(Format(Source, [ModuleIdent, FormIdent, AncestorIdent]));
end;
function TDSServerModuleCreator.NewIntfSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
var
Source: string;
begin
if FPersonality = sCBuilderPersonality then
begin
Source := GetSourceFromTemplate(FPersonality, stDSServerModuleTemplateIntf, nil, FSourceFlags);
Result := StringToIOTAFile(Format(Source, [ModuleIdent, FormIdent, AncestorIdent]));
end
else
Result := nil;
end;
{ TDSServerModuleWizard }
constructor TDSServerModuleWizard.Create(const APersonality: string);
begin
inherited Create;
FPersonality := APersonality;
end;
procedure TDSServerModuleWizard.Execute;
var
NewModule: IOTAModule;
begin
NewModule := CreateDSServerModule(GetPersonality, '', []); // Use default form name
end;
function TDSServerModuleWizard.GetAuthor: string;
begin
Result := 'Embarcadero'; { do not localize }
end;
function TDSServerModuleWizard.GetComment: string;
begin
Result := rsServerModuleComment;
end;
function TDSServerModuleWizard.GetDesigner: string;
begin
Result := dVCL;
end;
function TDSServerModuleWizard.GetFrameworkTypes: TArray<string>;
begin
Result := TArray<string>.Create();
end;
function TDSServerModuleWizard.GetGalleryCategory: IOTAGalleryCategory;
begin
Result := nil;
end;
function TDSServerModuleWizard.GetGlyph: Cardinal;
begin
Result := LoadIcon(HInstance, PChar('SERVERDMICON'));
end;
function TDSServerModuleWizard.GetIDString: string;
begin
Result := 'DataSnap.ServerModule' + '.' + FPersonality; {do not localize}
end;
function TDSServerModuleWizard.GetName: string;
begin
Result := rsServerModule;
end;
function TDSServerModuleWizard.GetPage: string;
begin
Result := rsDataSnapServerPage;
end;
function TDSServerModuleWizard.GetPersonality: string;
begin
Result := FPersonality;
end;
function TDSServerModuleWizard.GetPlatforms: TArray<string>;
begin
Result := TArray<string>.Create(cWin32Platform, cWin64Platform);
end;
function TDSServerModuleWizard.GetState: TWizardState;
begin
Result := [];
end;
{ TDSFilterIdProperty }
function TDSFilterIdProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList, paMultiSelect];
end;
procedure TDSFilterIdProperty.GetValues(Proc: TGetStrProc);
var
FilterId: string;
begin
for FilterId in TTransportFilterFactory.RegisteredFiltersId do
Proc(FilterId);
end;
{ TDSClientCallbackManagerSelectionEditor }
procedure TDSClientCallbackManagerSelectionEditor.RequiresUnits(
Proc: TGetStrProc);
var
i: Integer;
LIPImplementationID: string;
ChannelManager: TDSClientCallbackChannelManager;
begin
for i := 0 to Designer.Root.ComponentCount - 1 do
begin
if Designer.Root.Components[i] is TDSClientCallbackChannelManager then
begin
ChannelManager := TDSClientCallbackChannelManager(Designer.Root.Components[i]);
LIPImplementationID := ChannelManager.IPImplementationID;
if LIPImplementationID = '' then
Proc('IndyPeerImpl')
else
Proc(LIPImplementationID);
end;
end;
end;
{ TDSServerTransportEditor }
procedure TDSServerTransportEditor.RequiresUnits(Proc: TGetStrProc);
var
i, j: Integer;
FilterUnit: string;
LIPImplementationID: string;
Transport: TDSServerTransport;
TransportFilter: TTransportFilter;
begin
for i := 0 to Designer.Root.ComponentCount - 1 do
begin
if Designer.Root.Components[i] is TDSServerTransport then
begin
Transport := TDSServerTransport(Designer.Root.Components[i]);
LIPImplementationID := Transport.IPImplementationID;
if LIPImplementationID = '' then
Proc('IndyPeerImpl')
else
Proc(LIPImplementationID);
for j := 0 to Transport.Filters.Count - 1 do
begin
TransportFilter := Transport.Filters.GetFilter(j);
if TransportFilter <> nil then
begin
FilterUnit := TransportFilter.GetParameterValue('FilterUnit');
if FilterUnit <> EmptyStr then
Proc(FilterUnit);
end;
end;
end;
end;
end;
{ TDSCommunicationProtocolProperty }
function TDSCommunicationProtocolProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueEditable, paValueList, paSortList];
end;
procedure TDSCommunicationProtocolProperty.GetValues(Proc: TGetStrProc);
begin
GetDesignerAvailableProtocolValues(Proc);
end;
{ TCustomRoleItemProperty }
function TDSCustomRoleItemProperty.GetValue: string;
var
LStrings: TStrings;
begin
LStrings := GetStrings;
// Display value in object inspector
Result := LStrings.DelimitedText;
end;
{ TCustomFilterItemProperty }
function TDSCustomFilterItemProperty.GetValue: string;
var
LStrings: TStrings;
begin
LStrings := GetStrings;
Result := LStrings.DelimitedText;
end;
{ TPEMFilePropertyEditor }
procedure TPEMFilePropertyEditor.Edit;
var
Dialog: Dialogs.TOpenDialog;
begin
Dialog := Dialogs.TOpenDialog.Create(Application);
with Dialog do
try
Title := sPEMOpenFileTitle;
Filename := GetValue;
Filter := GetFilter;
HelpContext := 0;
Options := Options + [ofShowHelp, ofPathMustExist, ofHideReadonly, ofFileMustExist];
if Dialog.Execute then
SetValue(Filename);
finally
Free;
end;
end;
function TPEMFilePropertyEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paRevertable, paVCL];
end;
function TPEMFilePropertyEditor.GetFilter: string;
begin
Result := sPEMFileFilter;
end;
{ TPEMKeyFilePropertyEditor }
function TPEMKeyFilePropertyEditor.GetFilter: string;
begin
Result := sPEMKeyFileFilter;
end;
{ TCtxEnabledProperty }
function TCtxEnabledProperty.GetAttributes: TPropertyAttributes;
var
comp: TPersistent;
Proto: String;
begin
Result := inherited;
comp := GetComponent(0);
if (comp <> nil) and (comp is TDSClientCallbackChannelManager) then
begin
Proto := TDSClientCallbackChannelManager(comp).CommunicationProtocol;
if (not AnsiSameText('http', Proto)) and (not AnsiSameText('https', Proto)) then
Result := Result + [paReadOnly, paDisplayReadOnly];
end;
end;
{ TCtxEnabledPropertyInt }
function TCtxEnabledPropertyInt.GetAttributes: TPropertyAttributes;
var
comp: TPersistent;
Proto: String;
begin
Result := inherited;
comp := GetComponent(0);
if (comp <> nil) and (comp is TDSClientCallbackChannelManager) then
begin
Proto := TDSClientCallbackChannelManager(comp).CommunicationProtocol;
if (not AnsiSameText('http', Proto)) and (not AnsiSameText('https', Proto)) then
Result := Result + [paReadOnly, paDisplayReadOnly];
end;
end;
{ TDSHTTPServiceSelectionEditor }
procedure TDSHTTPServiceSelectionEditor.RequiresUnits(Proc: TGetStrProc);
var
i: Integer;
LService: TDSHTTPService;
m: TMethod;
begin
for i := 0 to Designer.Root.ComponentCount - 1 do
begin
if Designer.Root.Components[i] is TDSHTTPService then
begin
LService := TDSHTTPService(Designer.Root.Components[i]);
m := GetMethodProp(LService, 'FormatResult');
if Assigned(m.Code) then
begin
Proc('Data.DBXJSON');
Proc('Data.DBXCommon');
break;
end;
end;
end;
end;
initialization
finalization
(BorlandIDEServices as IOTAWizardServices).RemoveWizard(WizardId);
(BorlandIDEServices as IOTAWizardServices).RemoveWizard(WizardIdCpp);
end.
|
unit ncaFrmTax;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ncaFrmBaseCadastroMT, Data.DB,
kbmMemTable, dxBar, cxClasses, LMDControl, LMDCustomControl, LMDCustomPanel,
LMDCustomBevelPanel, LMDSimplePanel, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, dxLayoutContainer, dxLayoutControl, cxContainer,
cxEdit, dxLayoutcxEditAdapters, cxTextEdit, cxMaskEdit, cxSpinEdit, cxDBEdit,
cxDropDownEdit, cxImageComboBox, cxLabel, cxCurrencyEdit, cxButtonEdit, nxdb, ncaFrmPesqCFOP,
cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator,
cxDBData, cxCheckBox, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGridLevel, cxGridCustomView, cxGrid,
dxLayoutControlAdapters, Vcl.StdCtrls, cxRadioGroup;
type
TFrmTax = class(TFrmBaseCadastroMT)
LCGroup_Root: TdxLayoutGroup;
LC: TdxLayoutControl;
edCod: TcxDBSpinEdit;
lcCod: TdxLayoutItem;
edNome: TcxDBTextEdit;
lcNome: TdxLayoutItem;
edPerc: TcxDBCurrencyEdit;
lcTax: TdxLayoutItem;
tItens: TnxTable;
MTnome: TWideStringField;
MTincluido: TBooleanField;
MTperc: TFloatField;
MTgrupo: TBooleanField;
MTtax_id: TIntegerField;
lgrTaxa: TdxLayoutGroup;
edGrupo: TcxDBCheckBox;
lcGrupo: TdxLayoutItem;
dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup;
panItens: TLMDSimplePanel;
lcItens: TdxLayoutItem;
cxLabel1: TcxLabel;
TV: TcxGridDBTableView;
GL: TcxGridLevel;
grid: TcxGrid;
mtItens: TkbmMemTable;
mtItensIncluir: TBooleanField;
mtItensItem: TIntegerField;
mtItensNome: TStringField;
dsItens: TDataSource;
TVIncluir: TcxGridDBColumn;
TVNome: TcxGridDBColumn;
tTax: TnxTable;
rbIncluido: TcxRadioButton;
dxLayoutItem1: TdxLayoutItem;
rbNaoIncluido: TcxRadioButton;
dxLayoutItem2: TdxLayoutItem;
tTaxtax_id: TUnsignedAutoIncField;
tTaxnome: TWideStringField;
tTaxincluido: TBooleanField;
tTaxperc: TFloatField;
tTaxgrupo: TBooleanField;
tItensgrupo: TLongWordField;
tItensitem: TLongWordField;
procedure lcNomeCaptionClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edGrupoClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure cmGravarClick(Sender: TObject);
private
{ Private declarations }
slItens: TStrings;
procedure Atualiza;
function MarcouAlgumItem: Boolean;
public
{ Public declarations }
function ExceptFields: String; override;
procedure LoadItens;
procedure Validar; override;
end;
var
FrmTax: TFrmTax;
implementation
{$R *.dfm}
uses ncaFrmPri, ncaDM, ncaStrings;
procedure TFrmTax.Atualiza;
begin
lgrTaxa.Visible := not edGrupo.Checked;
lcItens.Visible := not lgrTaxa.Visible;
end;
procedure TFrmTax.cmGravarClick(Sender: TObject);
var I : Integer;
begin
Validar;
InitTran(Dados.DB, [TnxTable(Tab), tItens], True);
try
if not Novo then begin
if not Tab.Locate('tax_id', mttax_id.Value, []) then Exit;
Tab.Edit;
end else
Tab.Append;
MTIncluido.Value := rbIncluido.Checked;
TransfDadosEsp(MT, Tab, ExceptFields);
Tab.Post;
if MTGrupo.Value then begin
if not Novo then
for I := 0 to slItens.Count-1 do
if not mtItens.Locate('item', slItens[I], []) then
if tItens.FindKey([Tab.FieldByName('tax_id').AsInteger, slItens[i]]) then tItens.Delete;
mtItens.First;
while not mtItens.Eof do begin
if mtItensIncluir.Value then
if slItens.IndexOf(mtItensItem.AsString)<0 then begin
tItens.Append;
tItensGrupo.Value := Tab.FieldByName('tax_id').AsInteger;
tItensItem.Value := mtItensItem.Value;
tItens.Post;
end;
mtItens.Next;
end;
end else
if not Novo then
while tItens.FindKey([mttax_id.Value]) do tItens.Delete;
Dados.DB.Commit;
finally
if Dados.DB.InTransaction then
Dados.DB.Rollback;
end;
Close;
end;
procedure TFrmTax.edGrupoClick(Sender: TObject);
begin
inherited;
Atualiza;
end;
function TFrmTax.ExceptFields: String;
begin
Result := '|tax_id|';
end;
procedure TFrmTax.FormCreate(Sender: TObject);
begin
inherited;
slItens := TStringList.Create;
end;
procedure TFrmTax.FormDestroy(Sender: TObject);
begin
inherited;
slItens.Free;
end;
procedure TFrmTax.FormShow(Sender: TObject);
begin
inherited;
LoadItens;
rbIncluido.Checked := mtIncluido.Value;
rbNaoIncluido.Checked := not rbIncluido.Checked;
lcGrupo.Visible := (not mtItens.IsEmpty) or (mtGrupo.Value);
Atualiza;
end;
procedure TFrmTax.lcNomeCaptionClick(Sender: TObject);
begin
inherited;
edNome.SetFocus;
end;
procedure TFrmTax.LoadItens;
begin
mtItens.Active := False;
mtItens.Active := True;
slItens.Clear;
if not Novo then begin
tItens.SetRange([mttax_id.Value], [mttax_id.Value]);
tItens.First;
while not tItens.Eof do begin
slItens.Add(tItensItem.AsString);
tItens.Next;
end;
end;
tTax.First;
while not tTax.Eof do begin
if (not tTaxGrupo.Value) and (tTaxtax_id.Value<>mttax_id.Value) then begin
mtItens.Append;
mtItensIncluir.Value := (slItens.IndexOf(tTaxtax_id.AsString)>=0);
mtItensItem.Value := tTaxtax_id.Value;
mtItensNome.Value := tTaxNome.Value;
mtItens.Post;
end;
tTax.next;
end;
mtItens.First;
end;
function TFrmTax.MarcouAlgumItem: Boolean;
begin
Result := True;
mtItens.First;
while not mtItens.Eof do begin
if mtItensIncluir.Value then Exit;
mtItens.Next;
end;
Result := False;
end;
procedure TFrmTax.Validar;
begin
inherited;
if lcGrupo.Visible then
edGrupo.SetFocus else
edPerc.SetFocus;
edNome.SetFocus;
if Trim(edNome.Text)='' then begin
edNome.SetFocus;
raise exception.Create(rsNomeTribNecessario);
end;
if MTgrupo.Value then begin
if not MarcouAlgumItem then
raise Exception.Create(rsMarcarTaxa);
end else begin
if MTperc.IsNull or (MTperc.Value < 0.01) then begin
edPerc.SetFocus;
raise Exception.Create(rsInformarPerc);
end;
end;
end;
end.
|
unit TestSelfParse;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is TestSelfParse, released August 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 2003 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
{
AFS 24 August 2004
test parsing own source
ie all files under the base directory, or it's subdirs, to depth 2 }
uses
TestFrameWork;
type
TTestSelfParse = class(TTestCase)
private
procedure TestParseFile(const psInFileName: string);
procedure TestParseDir(const psDir: string; const piDepth: integer);
published
procedure TestSelfParse;
end;
implementation
uses
{ delphi }
SysUtils, Windows, Classes,
{ jcl }
JclFileUtils,
{ local }
ConvertTypes, FileConverter, TestConstants,
JcfSettings, JcfRegistrySettings;
const
MAX_DIR_DEPTH = 2;
procedure TTestSelfParse.TestParseDir(const psDir: string; const piDepth: integer);
var
liLoop: integer;
lcFiles: TStringList;
lcSubdirs: TStringList;
begin
{ test parse all the .pas, .dpr, .dpk files in this dir }
lcFiles := TStringList.Create;
try
// get files
BuildFileList(psDir + '*.pas', 0, lcFiles);
BuildFileList(psDir + '*.dpr', 0, lcFiles);
BuildFileList(psDir + '*.dpk', 0, lcFiles);
// parse them
for liLoop := 0 to lcFiles.Count - 1 do
TestParseFile(psDir + lcFiles.Strings[liLoop]);
finally
lcFiles.Free;
end;
{ go further down? }
if piDepth > 0 then
begin
lcSubdirs := TStringList.Create;
try
// get dirs
BuildFileList(psDir + '*.*', faDirectory, lcSubdirs);
// recurse - parse them
for liLoop := 0 to lcSubdirs.Count - 1 do
TestParseDir(psDir + lcSubdirs.Strings[liLoop] + DirDelimiter, piDepth - 1);
finally
lcSubdirs.Free;
end;
end;
end;
procedure TTestSelfParse.TestParseFile(const psInFileName: string);
var
lcConverter: TFileConverter;
lsOutFileName: string;
begin
Check(FileExists(psInFileName), 'input file ' + psInFileName + ' not found');
lcConverter := TFileConverter.Create;
try
lcConverter.YesAll := True;
lcConverter.GuiMessages := False;
// init and read the format settings
GetRegSettings.FormatConfigFileName := GetTestSettingsFileName;
JcfFormatSettings.Obfuscate.Enabled := False;
lcConverter.SourceMode := fmSingleFile;
lcConverter.BackupMode := cmSeparateOutput;
GetRegSettings.OutputExtension := 'out';
GetRegSettings.ShowParseTreeOption := eShowNever;
lcConverter.Input := psInFileName;
lcConverter.Convert;
lsOutFileName := lcConverter.OutFileName;
Check( not lcConverter.ConvertError, 'Convert failed for ' +
ExtractFileName(psInFileName));
lsOutFileName := lcConverter.OutFileName;
Check(lsOutFileName <> '', 'No output file');
Check(FileExists(lsOutFileName), 'output file ' + lsOutFileName + ' not found');
// clean up
if FileExists(lsOutFileName) then
SysUtils.DeleteFile(lsOutFileName);
finally
lcConverter.Free;
end;
end;
procedure TTestSelfParse.TestSelfParse;
begin
TestParseDir(GetBaseDir, MAX_DIR_DEPTH);
end;
initialization
TestFramework.RegisterTest(TTestSelfParse.Suite);
end.
|
// Процедура заполнения полей структуры PIXELFORMATDESCRIPTOR
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPIXELFORMATDESCRIPTOR; // данные формата пикселей
nPixelFormat : Integer;
Begin
With pfd do
begin
nSize := sizeof (TPIXELFORMATDESCRIPTOR); // размер структуры
nVersion := 1; // номер версии
dwFlags := PFD_DRAW_TO_WINDOW OR PFD_SUPPORT_OPENGL; // множество битовых флагов, определяющих устройство и интерфейс
iPixelType := PFD_TYPE_RGBA; // режим для изображения цветов
cColorBits := 16; // число битовых плоскостей в каждом буфере цвета
cRedBits := 0; // число битовых плоскостей красного в каждом буфере RGBA
cRedShift := 0; // смещение от начала числа битовых плоскостей красного в каждом буфере RGBA
cGreenBits := 0; // число битовых плоскостей зелёного в каждом буфере RGBA
cGreenShift := 0; // смещение от начала числа битовых плоскостей зелёного в каждом буфере RGBA
cBlueBits := 0; // число битовых плоскостей синего в каждом буфере RGBA
cBlueShift := 0; // смещение от начала числа битовых плоскостей синего в каждом буфере RGBA
cAlphaBits := 0; // число битовых плоскостей альфа в каждом буфере RGBA
cAlphaShift := 0; // смещение от начала числа битовых плоскостей альфа в каждом буфере RGBA
cAccumBits := 0; // общее число битовых плоскостей в буфере аккумулятора
cAccumRedBits := 0; // число битовых плоскостей красного в буфере аккумулятора
cAccumGreenBits := 0; // число битовых плоскостей зелёного в буфере аккумулятора
cAccumBlueBits := 0; // число битовых плоскостей синего в буфере аккумулятора
cAccumAlphaBits := 0; // число битовых плоскостей альфа в буфере аккумулятора
cDepthBits := 32; // размер буфера глубины (ось z)
cStencilBits := 0; // размер буфера трафарета
cAuxBuffers := 0; // число вспомогательных буферов
iLayerType := PFD_MAIN_PLANE;// тип плоскости
bReserved := 0; // число плоскостей переднего и заднего плана
dwLayerMask := 0; //
dwVisibleMask := 0; // индекс или цвет прозрачности нижней плоскости
dwDamageMask := 0; // игнорируется
end;
nPixelFormat := ChoosePixelFormat (hdc, @pfd); // запрос системе - поддерживается ли выбранный формат пикселей
SetPixelFormat (hdc, nPixelFormat, @pfd); // устанавливаем формат пикселей в контексте устройства
End;
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXSybaseASAMetaDataReader;
interface
uses
Data.DBXCommon,
Data.DBXCommonTable,
Data.DBXMetaDataNames,
Data.DBXMetaDataReader,
Data.DBXPlatform;
type
/// <summary> TDBXSybaseASACustomMetaDataReader contains custom code for Adaptive Server Anywhere.
/// </summary>
TDBXSybaseASACustomMetaDataReader = class(TDBXBaseMetaDataReader)
public
type
/// <summary> TDBXSybaseASAForeignKeyColumnsCursor is a filter for a cursor providing foreign key columns.
/// </summary>
/// <remarks> In Adaptive Server Anywhere version 9.* and earlier the primary key columns were not included
/// in the SYSIXCOL system table. Instead each column in the primary key has a flag set in the
/// SYSCOLUMN system table. The ordinal value of each foreign key column referencing a primary key
/// is simply not maintained. This filter will assign reasonable values to the ordinal column.
/// </remarks>
TDBXSybaseASAForeignKeyColumnsCursor = class(TDBXCustomMetaDataTable)
public
destructor Destroy; override;
function Next: Boolean; override;
protected
constructor Create(const Provider: TDBXSybaseASACustomMetaDataReader; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable);
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
FSchemaName: string;
FPrevSchemaName: string;
FTableName: string;
FPrevTableName: string;
FIndexId: Int64;
FPrevIndexId: Int64;
FRunningOrdinal: Integer;
FOrdinalValue: TDBXWritableValue;
private
const ForeignkeyColumnIndexIndicator = TDBXForeignKeyColumnsIndex.Last + 1;
const NullIndexId = -1;
end;
public
/// <summary> Overrides the implementation in TDBXBaseMetaDataProvider.
/// </summary>
/// <remarks> A custom filter is added to correct the Ordinal column which could not be correctly expressed in SQL.
/// </remarks>
/// <seealso cref="TDBXSybaseASAForeignKeyColumnsCursor"/>
function FetchForeignKeyColumns(const Catalog: string; const Schema: string; const Table: string; const ForeignKeyName: string; const PrimaryCatalog: string; const PrimarySchema: string; const PrimaryTable: string; const PrimaryKeyName: string): TDBXTable; override;
protected
procedure SetContext(const Context: TDBXProviderContext); override;
private
FVendorLibPath: string;
FSupportsNLSDataType: Boolean;
FIsServerCharsetUTF8: Boolean;
FIsCharUnicode: Boolean;
public
property VendorLibPath : string read FVendorLibPath;
property SupportsNLSDataType: Boolean read FSupportsNLSDataType;
property IsServerCharsetUTF8: Boolean read FIsServerCharsetUTF8;
property IsCharUnicode: Boolean read FIsCharUnicode;
property DefaultCharSetUnicode: Boolean read FIsServerCharsetUTF8;
private
const VendorLibPathPropertyName = 'VendorLibPath';
const SupportsNLSDataTypePropertyName = 'SupportsNLSDataType';
const IsServerCharsetUTF8PropertyName = 'IsServerCharsetUTF8';
const IsCharUnicodePropertyName = 'IsCharUnicode';
const UnicodeEncodingPropertyName = 'UnicodeEncoding';
end;
TDBXSybaseASAMetaDataReader = class(TDBXSybaseASACustomMetaDataReader)
public
function FetchCatalogs: TDBXTable; override;
function FetchColumnConstraints(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable; override;
function FetchSynonyms(const CatalogName: string; const SchemaName: string; const SynonymName: string): TDBXTable; override;
function FetchPackages(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable; override;
function FetchPackageProcedures(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable; override;
function FetchPackageProcedureParameters(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable; override;
function FetchPackageSources(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable; override;
protected
function AreSchemasSupported: Boolean; override;
function GetProductName: string; override;
function GetTableType: string; override;
function GetViewType: string; override;
function GetSystemTableType: string; override;
function GetSystemViewType: string; override;
function IsLowerCaseIdentifiersSupported: Boolean; override;
function IsSetRowSizeSupported: Boolean; override;
function IsUpperCaseIdentifiersSupported: Boolean; override;
function GetSqlForSchemas: string; override;
function GetSqlForTables: string; override;
function GetSqlForViews: string; override;
function GetSqlForColumns: string; override;
function GetSqlForIndexes: string; override;
function GetSqlForIndexColumns: string; override;
function GetSqlForForeignKeys: string; override;
function GetSqlForForeignKeyColumns: string; override;
function GetSqlForProcedures: string; override;
function GetSqlForProcedureSources: string; override;
function GetSqlForProcedureParameters: string; override;
function GetSqlForUsers: string; override;
function GetSqlForRoles: string; override;
function GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; override;
function GetReservedWords: TDBXStringArray; override;
end;
implementation
uses
System.SysUtils;
function TDBXSybaseASACustomMetaDataReader.FetchForeignKeyColumns(const Catalog: string; const Schema: string; const Table: string; const ForeignKeyName: string; const PrimaryCatalog: string; const PrimarySchema: string; const PrimaryTable: string; const PrimaryKeyName: string): TDBXTable;
var
ParameterNames, ParameterValues: TDBXStringArray;
Cursor: TDBXTable;
Columns: TDBXValueTypeArray;
begin
if CompareVersion(TDBXVersion.FVersion10) >= 0 then
Result := inherited FetchForeignKeyColumns(Catalog, Schema, Table, ForeignKeyName, PrimaryCatalog, PrimarySchema, PrimaryTable, PrimaryKeyName)
else
begin
SetLength(ParameterNames,8);
ParameterNames[0] := TDBXParameterName.CatalogName;
ParameterNames[1] := TDBXParameterName.SchemaName;
ParameterNames[2] := TDBXParameterName.TableName;
ParameterNames[3] := TDBXParameterName.ForeignKeyName;
ParameterNames[4] := TDBXParameterName.PrimaryCatalogName;
ParameterNames[5] := TDBXParameterName.PrimarySchemaName;
ParameterNames[6] := TDBXParameterName.PrimaryTableName;
ParameterNames[7] := TDBXParameterName.PrimaryKeyName;
SetLength(ParameterValues,8);
ParameterValues[0] := Catalog;
ParameterValues[1] := Schema;
ParameterValues[2] := Table;
ParameterValues[3] := ForeignKeyName;
ParameterValues[4] := PrimaryCatalog;
ParameterValues[5] := PrimarySchema;
ParameterValues[6] := PrimaryTable;
ParameterValues[7] := PrimaryKeyName;
Cursor := Context.ExecuteQuery(SqlForForeignKeyColumns, ParameterNames, ParameterValues);
Columns := TDBXMetaDataCollectionColumns.CreateForeignKeyColumnsColumns;
Result := TDBXSybaseASACustomMetaDataReader.TDBXSybaseASAForeignKeyColumnsCursor.Create(self, Columns, Cursor);
end;
end;
constructor TDBXSybaseASACustomMetaDataReader.TDBXSybaseASAForeignKeyColumnsCursor.Create(const Provider: TDBXSybaseASACustomMetaDataReader; const Columns: TDBXValueTypeArray; const Cursor: TDBXTable);
begin
inherited Create(Provider.Context, TDBXMetaDataCollectionName.ForeignKeyColumns, Columns, Cursor);
FSchemaName := NullString;
FTableName := NullString;
FIndexId := NullIndexId;
end;
destructor TDBXSybaseASACustomMetaDataReader.TDBXSybaseASAForeignKeyColumnsCursor.Destroy;
begin
FreeAndNil(FOrdinalValue);
inherited Destroy;
end;
function TDBXSybaseASACustomMetaDataReader.TDBXSybaseASAForeignKeyColumnsCursor.Next: Boolean;
begin
if not FCursor.Next then
Exit(False);
if FOrdinalValue = nil then
FOrdinalValue := TDBXWritableValue(TDBXValue.CreateValue(TDBXValueType(inherited GetWritableValue(TDBXForeignKeyColumnsIndex.Ordinal).ValueType.Clone())));
FPrevSchemaName := FSchemaName;
FPrevTableName := FTableName;
FPrevIndexId := FIndexId;
FSchemaName := inherited GetWritableValue(TDBXForeignKeyColumnsIndex.SchemaName).AsString;
FTableName := inherited GetWritableValue(TDBXForeignKeyColumnsIndex.TableName).AsString;
if FCursor.Value[ForeignkeyColumnIndexIndicator].IsNull then
FIndexId := NullIndexId
else
FIndexId := FCursor.Value[ForeignkeyColumnIndexIndicator].AsInt64;
if (FSchemaName = FPrevSchemaName) and (FTableName = FPrevTableName) and (FIndexId = FPrevIndexId) then
IncrAfter(FRunningOrdinal)
else
FRunningOrdinal := 1;
if FIndexId <> NullIndexId then
FOrdinalValue.AsInt32 := FRunningOrdinal
else
FOrdinalValue.SetNull;
Result := True;
end;
function TDBXSybaseASACustomMetaDataReader.TDBXSybaseASAForeignKeyColumnsCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
if Ordinal = TDBXForeignKeyColumnsIndex.Ordinal then
Exit(FOrdinalValue);
Result := inherited GetWritableValue(Ordinal);
end;
procedure TDBXSybaseASACustomMetaDataReader.SetContext(const Context: TDBXProviderContext);
begin
inherited SetContext(Context);
FVendorLibPath := Context.GetVendorProperty(VendorLibPathPropertyName);
FSupportsNLSDataType := (Context.GetVendorProperty(SupportsNLSDataTypePropertyName) = 'true');
FIsServerCharsetUTF8 := (Context.GetVendorProperty(IsServerCharsetUTF8PropertyName) = 'true');
FIsCharUnicode := (Context.GetVendorProperty(IsCharUnicodePropertyName) = 'true');
end;
function TDBXSybaseASAMetaDataReader.AreSchemasSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASAMetaDataReader.GetProductName: string;
begin
Result := 'Adaptive Server Anywhere';
end;
function TDBXSybaseASAMetaDataReader.GetTableType: string;
begin
Result := 'BASE';
end;
function TDBXSybaseASAMetaDataReader.GetViewType: string;
begin
Result := 'VIEW';
end;
function TDBXSybaseASAMetaDataReader.GetSystemTableType: string;
begin
Result := 'BASE';
end;
function TDBXSybaseASAMetaDataReader.GetSystemViewType: string;
begin
Result := 'VIEW';
end;
function TDBXSybaseASAMetaDataReader.IsLowerCaseIdentifiersSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASAMetaDataReader.IsSetRowSizeSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASAMetaDataReader.IsUpperCaseIdentifiersSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASAMetaDataReader.FetchCatalogs: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateCatalogsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Catalogs, Columns);
end;
function TDBXSybaseASAMetaDataReader.GetSqlForSchemas: string;
begin
Result := 'SELECT DB_NAME(), NAME FROM SYS.SYSUSERLIST WHERE RESOURCEAUTH=''Y'' ORDER BY 1, 2';
end;
function TDBXSybaseASAMetaDataReader.GetSqlForTables: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(CREATOR), TABLE_NAME, CASE WHEN USER_NAME(CREATOR) = ''SYS'' OR USER_NAME(CREATOR) = ''rs_systabgroup'' THEN ''SYSTEM '' ELSE '''' END || CASE TABLE_TYPE WHEN ''BASE'' THEN ''TABLE'' ELSE ''VIEW'' END ' +
'FROM SYS.SYSTABLE ' +
'WHERE TABLE_TYPE IN (''BASE'',''VIEW'') ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
' AND (TABLE_TYPE=CASE WHEN USER_NAME(CREATOR) = ''SYS'' OR USER_NAME(CREATOR) = ''rs_systabgroup'' THEN :SYSTEM_TABLES ELSE :TABLES END OR TABLE_TYPE=CASE WHEN USER_NAME(CREATOR) = ''SYS'' OR USER_NAME(CREATOR) = ''rs_systabgroup'' THEN :SYSTEM_VIEWS ELSE :VIEWS ' + 'END) ' +
'ORDER BY 1,2,3';
end;
function TDBXSybaseASAMetaDataReader.GetSqlForViews: string;
begin
Result := 'SELECT DB_NAME(), VCREATOR, VIEWNAME, VIEWTEXT ' +
'FROM SYS.SYSVIEWS ' +
'WHERE (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (VCREATOR = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (VIEWNAME = :VIEW_NAME OR (:VIEW_NAME IS NULL)) ' +
'ORDER BY 1,2,3';
end;
function TDBXSybaseASAMetaDataReader.GetSqlForColumns: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(T.CREATOR), T.TABLE_NAME, C.COLUMN_NAME, D.DOMAIN_NAME, C.WIDTH, C.SCALE, C.COLUMN_ID, CASE WHEN C."DEFAULT" = ''autoincrement'' THEN NULL ELSE C."DEFAULT" END, CASE WHEN C.NULLS=''Y'' THEN 1 ELSE 0 END, CASE WHEN C."DEFAULT"=''auto' + 'increment'' THEN 1 ELSE 0 END, NULL ' +
'FROM SYS.SYSCOLUMN C, SYS.SYSTABLE T, SYS.SYSDOMAIN D ' +
'WHERE C.TABLE_ID=T.TABLE_ID AND C.DOMAIN_ID=D.DOMAIN_ID ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(T.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (T.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 1,2,3,C.COLUMN_ID';
end;
function TDBXSybaseASAMetaDataReader.FetchColumnConstraints(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateColumnConstraintsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ColumnConstraints, Columns);
end;
function TDBXSybaseASAMetaDataReader.GetSqlForIndexes: string;
var
CurrentVersion: string;
begin
CurrentVersion := Version;
if CurrentVersion >= '10.00.0000' then
Result := 'SELECT DB_NAME(), USER_NAME(T.CREATOR), T.TABLE_NAME, I.INDEX_NAME, C.CONSTRAINT_NAME, CASE I.INDEX_CATEGORY WHEN 1 THEN 1 ELSE 0 END, CASE WHEN I."UNIQUE" IN (1,2) THEN 1 ELSE 0 END, 1 ' +
'FROM SYS.SYSIDX I JOIN SYS.SYSTAB T ON I.TABLE_ID=T.TABLE_ID LEFT OUTER JOIN SYS.SYSCONSTRAINT C ON C.TABLE_OBJECT_ID=T.OBJECT_ID AND C.REF_OBJECT_ID=I.OBJECT_ID ' +
'WHERE I.TABLE_ID=T.TABLE_ID AND I.INDEX_CATEGORY IN (1,3) ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(T.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (T.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 1,2,3,4'
else
Result := 'SELECT DB_NAME(), USER_NAME(T.CREATOR), T.TABLE_NAME, I.INDEX_NAME, C.CONSTRAINT_NAME, 0, CASE WHEN I."UNIQUE" IN (''Y'',''U'') THEN 1 ELSE 0 END, 1 ' +
'FROM SYS.SYSINDEX I LEFT OUTER JOIN SYS.SYSCONSTRAINT C ON C.TABLE_ID=I.TABLE_ID AND C.INDEX_ID=I.INDEX_ID, SYS.SYSTABLE T ' +
'WHERE I.TABLE_ID=T.TABLE_ID ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(T.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (T.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'UNION ALL ' +
'SELECT DB_NAME(), USER_NAME(T.CREATOR), T.TABLE_NAME, C.CONSTRAINT_NAME, C.CONSTRAINT_NAME, 1, 1, 1 ' +
'FROM SYS.SYSCONSTRAINT C, SYS.SYSTABLE T ' +
'WHERE C.TABLE_ID=T.TABLE_ID AND C.CONSTRAINT_TYPE=''P'' ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(T.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (T.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 1,2,3,4';
end;
function TDBXSybaseASAMetaDataReader.GetSqlForIndexColumns: string;
var
CurrentVersion: string;
begin
CurrentVersion := Version;
if CurrentVersion >= '10.00.0000' then
Result := 'SELECT DB_NAME(), USER_NAME(T.CREATOR), T.TABLE_NAME, I.INDEX_NAME, C.COLUMN_NAME, IC.SEQUENCE+1, CASE WHEN IC."ORDER"=''A'' THEN 1 ELSE 0 END ' +
'FROM SYS.SYSIDXCOL IC, SYS.SYSIDX I, SYS.SYSTABCOL C, SYS.SYSTAB T ' +
'WHERE IC.TABLE_ID=I.TABLE_ID AND IC.INDEX_ID=I.INDEX_ID AND IC.TABLE_ID=T.TABLE_ID AND C.COLUMN_ID=IC.COLUMN_ID AND C.TABLE_ID=T.TABLE_ID AND I.INDEX_CATEGORY IN (1,3) ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(T.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (T.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (I.INDEX_NAME = :INDEX_NAME OR (:INDEX_NAME IS NULL)) ' +
'ORDER BY 1,2,3,4,6'
else
Result := 'SELECT DB_NAME(), USER_NAME(T.CREATOR), T.TABLE_NAME, I.INDEX_NAME, C.COLUMN_NAME, IC.SEQUENCE+1, CASE WHEN IC."ORDER"=''A'' THEN 1 ELSE 0 END ' +
'FROM SYS.SYSIXCOL IC, SYS.SYSINDEX I, SYS.SYSCOLUMN C, SYS.SYSTABLE T ' +
'WHERE IC.TABLE_ID=I.TABLE_ID AND IC.INDEX_ID=I.INDEX_ID AND IC.TABLE_ID=T.TABLE_ID AND C.COLUMN_ID=IC.COLUMN_ID AND C.TABLE_ID=T.TABLE_ID ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(T.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (T.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (I.INDEX_NAME = :INDEX_NAME OR (:INDEX_NAME IS NULL)) ' +
'UNION ALL ' +
'SELECT DB_NAME(), USER_NAME(T.CREATOR), T.TABLE_NAME, SC.CONSTRAINT_NAME, C.COLUMN_NAME, C.COLUMN_ID, 1 ' +
'FROM SYS.SYSCOLUMN C, SYS.SYSTABLE T, SYS.SYSCONSTRAINT SC ' +
'WHERE C.TABLE_ID=T.TABLE_ID AND T.TABLE_ID=SC.TABLE_ID AND SC.CONSTRAINT_TYPE=''P'' AND C.PKEY=''Y'' ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(T.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (T.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (SC.CONSTRAINT_NAME = :INDEX_NAME OR (:INDEX_NAME IS NULL)) ' +
'ORDER BY 1,2,3,4,6';
end;
function TDBXSybaseASAMetaDataReader.GetSqlForForeignKeys: string;
var
CurrentVersion: string;
begin
CurrentVersion := Version;
if CurrentVersion >= '10.00.0000' then
Result := 'SELECT DB_NAME(), USER_NAME(FT.CREATOR), FT.TABLE_NAME, COALESCE(FKC.CONSTRAINT_NAME,FI.INDEX_NAME) ' +
'FROM SYS.SYSFKEY FK ' +
' JOIN SYS.SYSTABLE FT ON FK.FOREIGN_TABLE_ID=FT.TABLE_ID ' +
' JOIN SYS.SYSIDX FI ON FK.FOREIGN_TABLE_ID=FI.TABLE_ID AND FK.FOREIGN_INDEX_ID=FI.INDEX_ID ' +
' LEFT JOIN SYS.SYSCONSTRAINT FKC ON FT.OBJECT_ID=FKC.TABLE_OBJECT_ID AND FI.OBJECT_ID=FKC.REF_OBJECT_ID ' +
'WHERE (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(FT.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (FT.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 1,2,3,4'
else
Result := 'SELECT DB_NAME(), USER_NAME(FT.CREATOR), FT.TABLE_NAME, FK.ROLE ' +
'FROM SYS.SYSFOREIGNKEY FK, SYS.SYSTABLE FT ' +
'WHERE FK.FOREIGN_TABLE_ID=FT.TABLE_ID ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(FT.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (FT.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 1,2,3,4';
end;
function TDBXSybaseASAMetaDataReader.GetSqlForForeignKeyColumns: string;
var
CurrentVersion: string;
begin
CurrentVersion := Version;
if CurrentVersion >= '10.00.0000' then
Result := 'SELECT DB_NAME(), USER_NAME(FT.CREATOR), FT.TABLE_NAME, COALESCE(FKC.CONSTRAINT_NAME,FI.INDEX_NAME), FC.COLUMN_NAME, DB_NAME(), USER_NAME(PT.CREATOR), PT.TABLE_NAME, COALESCE(PKC.CONSTRAINT_NAME,PI.INDEX_NAME), PC.COLUMN_NAME, FIC.SEQUENCE+1 ' +
'FROM SYS.SYSFKEY FK ' +
' JOIN SYS.SYSTABLE FT ON FK.FOREIGN_TABLE_ID=FT.TABLE_ID ' +
' JOIN SYS.SYSTABLE PT ON FK.PRIMARY_TABLE_ID=PT.TABLE_ID ' +
' JOIN SYS.SYSIDX FI ON FK.FOREIGN_TABLE_ID=FI.TABLE_ID AND FK.FOREIGN_INDEX_ID=FI.INDEX_ID ' +
' JOIN SYS.SYSIDX PI ON FK.PRIMARY_TABLE_ID=PI.TABLE_ID AND FK.PRIMARY_INDEX_ID=PI.INDEX_ID ' +
' JOIN SYS.SYSIDXCOL FIC ON FI.TABLE_ID=FIC.TABLE_ID AND FI.INDEX_ID=FIC.INDEX_ID ' +
' JOIN SYS.SYSIDXCOL PIC ON PI.TABLE_ID=PIC.TABLE_ID AND PI.INDEX_ID=PIC.INDEX_ID AND PIC.SEQUENCE=FIC.SEQUENCE ' +
' JOIN SYS.SYSCOLUMN FC ON FIC.TABLE_ID=FC.TABLE_ID AND FIC.COLUMN_ID=FC.COLUMN_ID ' +
' JOIN SYS.SYSCOLUMN PC ON PIC.TABLE_ID=PC.TABLE_ID AND PIC.COLUMN_ID=PC.COLUMN_ID ' +
' LEFT JOIN SYS.SYSCONSTRAINT FKC ON FT.OBJECT_ID=FKC.TABLE_OBJECT_ID AND FI.OBJECT_ID=FKC.REF_OBJECT_ID ' +
' LEFT JOIN SYS.SYSCONSTRAINT PKC ON PT.OBJECT_ID=PKC.TABLE_OBJECT_ID AND PI.OBJECT_ID=PKC.REF_OBJECT_ID ' +
'WHERE (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(FT.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (FT.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (COALESCE(FKC.CONSTRAINT_NAME,FI.INDEX_NAME) = :FOREIGN_KEY_NA' + 'ME OR (:FOREIGN_KEY_NAME IS NULL)) ' +
' AND (DB_NAME() = :PRIMARY_CATALOG_NAME OR (:PRIMARY_CATALOG_NAME IS NULL)) AND (USER_NAME(PT.CREATOR) = :PRIMARY_SCHEMA_NAME OR (:PRIMARY_SCHEMA_NAME IS NULL)) AND (PT.TABLE_NAME = :PRIMARY_TABLE_NAME OR (:PRIMARY_TABLE_NAME IS NULL)) AND (COALESCE(PKC.' + 'CONSTRAINT_NAME,PI.INDEX_NAME) = :PRIMARY_KEY_NAME OR (:PRIMARY_KEY_NAME IS NULL)) ' +
'ORDER BY 1,2,3,4,11'
else
Result := 'SELECT DB_NAME(), USER_NAME(FT.CREATOR), FT.TABLE_NAME, FK.ROLE, FC.COLUMN_NAME, DB_NAME(), USER_NAME(PT.CREATOR), PT.TABLE_NAME, COALESCE(I.INDEX_NAME,C.CONSTRAINT_NAME), PC.COLUMN_NAME, COALESCE(IC.SEQUENCE+1,PC.COLUMN_ID), I.INDEX_ID ' +
'FROM SYS.SYSFKCOL FKC ' +
' JOIN SYS.SYSFOREIGNKEY FK ON FKC.FOREIGN_TABLE_ID=FK.FOREIGN_TABLE_ID AND FKC.FOREIGN_KEY_ID=FK.FOREIGN_KEY_ID ' +
' JOIN SYS.SYSTABLE FT ON FK.FOREIGN_TABLE_ID=FT.TABLE_ID ' +
' JOIN SYS.SYSCOLUMN FC ON FT.TABLE_ID=FC.TABLE_ID AND FKC.FOREIGN_COLUMN_ID=FC.COLUMN_ID ' +
' JOIN SYS.SYSTABLE PT ON FK.PRIMARY_TABLE_ID=PT.TABLE_ID ' +
' JOIN SYS.SYSCOLUMN PC ON PT.TABLE_ID=PC.TABLE_ID AND FKC.PRIMARY_COLUMN_ID=PC.COLUMN_ID ' +
' LEFT OUTER JOIN SYS.SYSIXCOL IC ON FK.PRIMARY_TABLE_ID=IC.TABLE_ID AND FK.PRIMARY_INDEX_ID=IC.INDEX_ID AND PC.COLUMN_ID=IC.COLUMN_ID ' +
' LEFT OUTER JOIN SYS.SYSINDEX I ON FK.PRIMARY_TABLE_ID=I.TABLE_ID AND FK.PRIMARY_INDEX_ID=I.INDEX_ID ' +
' LEFT OUTER JOIN SYS.SYSCONSTRAINT C ON FK.PRIMARY_TABLE_ID=C.TABLE_ID AND C.CONSTRAINT_TYPE=''P'' ' +
'WHERE (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(FT.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (FT.TABLE_NAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (FK.ROLE = :FOREIGN_KEY_NAME OR (:FOREIGN_KEY_NAME IS NULL)) ' +
' AND (DB_NAME() = :PRIMARY_CATALOG_NAME OR (:PRIMARY_CATALOG_NAME IS NULL)) AND (USER_NAME(PT.CREATOR) = :PRIMARY_SCHEMA_NAME OR (:PRIMARY_SCHEMA_NAME IS NULL)) AND (PT.TABLE_NAME = :PRIMARY_TABLE_NAME OR (:PRIMARY_TABLE_NAME IS NULL)) AND (COALESCE(I.IN' + 'DEX_NAME,C.CONSTRAINT_NAME) = :PRIMARY_KEY_NAME OR (:PRIMARY_KEY_NAME IS NULL)) ' +
'ORDER BY 1,2,3,4,11';
end;
function TDBXSybaseASAMetaDataReader.FetchSynonyms(const CatalogName: string; const SchemaName: string; const SynonymName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateSynonymsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Synonyms, Columns);
end;
function TDBXSybaseASAMetaDataReader.GetSqlForProcedures: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(CREATOR), PROC_NAME, ''PROCEDURE'' ' +
'FROM SYS.SYSPROCEDURE ' +
'WHERE (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (PROC_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (''PROCEDURE'' = :PROCEDURE_TYPE OR (:PROCEDURE_TYPE IS NULL)) ' +
'ORDER BY 1,2,3';
end;
function TDBXSybaseASAMetaDataReader.GetSqlForProcedureSources: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(CREATOR), PROC_NAME, ''PROCEDURE'', PROC_DEFN, NULL ' +
'FROM SYS.SYSPROCEDURE ' +
'WHERE (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (PROC_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) ' +
'ORDER BY 1,2,3';
end;
function TDBXSybaseASAMetaDataReader.GetSqlForProcedureParameters: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(P.CREATOR), P.PROC_NAME, C.PARM_NAME, CASE WHEN PARM_TYPE>0 THEN ''RESULT'' WHEN PARM_MODE_IN=''Y'' AND PARM_MODE_OUT=''Y'' THEN ''INOUT'' WHEN PARM_MODE_OUT=''Y'' THEN ''OUT'' ELSE ''IN'' END, D.DOMAIN_NAME, C.WIDTH, C.SCALE, C.PARM_ID, C."' + 'DEFAULT", 1 ' +
'FROM SYS.SYSPROCEDURE P, SYS.SYSPROCPARM C, SYS.SYSDOMAIN D ' +
'WHERE P.PROC_ID = C.PROC_ID AND C.DOMAIN_ID=D.DOMAIN_ID ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(P.CREATOR) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (P.PROC_NAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (C.PARM_NAME = :PARAMETER_NAME OR (:PARAMETER_NAME IS NULL' + ')) ' +
'ORDER BY 1,2,3,C.PARM_ID';
end;
function TDBXSybaseASAMetaDataReader.FetchPackages(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackagesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Packages, Columns);
end;
function TDBXSybaseASAMetaDataReader.FetchPackageProcedures(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProceduresColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedures, Columns);
end;
function TDBXSybaseASAMetaDataReader.FetchPackageProcedureParameters(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProcedureParametersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedureParameters, Columns);
end;
function TDBXSybaseASAMetaDataReader.FetchPackageSources(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageSourcesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageSources, Columns);
end;
function TDBXSybaseASAMetaDataReader.GetSqlForUsers: string;
begin
Result := 'SELECT NAME FROM SYS.SYSUSERLIST WHERE USER_GROUP=''N'' ORDER BY 1';
end;
function TDBXSybaseASAMetaDataReader.GetSqlForRoles: string;
begin
Result := 'SELECT NAME FROM SYS.SYSUSERLIST WHERE USER_GROUP=''Y'' AND NAME <> ''PUBLIC'' ORDER BY 1';
end;
function TDBXSybaseASAMetaDataReader.GetDataTypeDescriptions: TDBXDataTypeDescriptionArray;
var
Types: TDBXDataTypeDescriptionArray;
begin
SetLength(Types,23);
Types[0] := TDBXDataTypeDescription.Create('bigint', TDBXDataTypes.Int64Type, 19, 'bigint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[1] := TDBXDataTypeDescription.Create('binary', TDBXDataTypes.BytesType, 32767, 'binary({0})', 'Precision', -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[2] := TDBXDataTypeDescription.Create('bit', TDBXDataTypes.BooleanType, 1, 'bit', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Searchable);
if IsCharUnicode then
Types[3] := TDBXDataTypeDescription.Create('char', TDBXDataTypes.WideStringType, 8191, 'char({0})', 'Precision', -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode)
else
Types[3] := TDBXDataTypeDescription.Create('char', TDBXDataTypes.AnsiStringType, 32767, 'char({0})', 'Precision', -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[4] := TDBXDataTypeDescription.Create('nchar', TDBXDataTypes.WideStringType, 8191, 'nchar({0})', 'Precision', -1, -1, '''', '''', NullString, '10.00.0000', TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode);
Types[5] := TDBXDataTypeDescription.Create('date', TDBXDataTypes.DateType, 4, 'date', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[6] := TDBXDataTypeDescription.Create('decimal', TDBXDataTypes.BcdType, 38, 'decimal({0}, {1})', 'Precision,Scale', 38, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[7] := TDBXDataTypeDescription.Create('double', TDBXDataTypes.DoubleType, 53, 'double', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[8] := TDBXDataTypeDescription.Create('float', TDBXDataTypes.SingleType, 48, 'float({0})', 'Precision', -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[9] := TDBXDataTypeDescription.Create('integer', TDBXDataTypes.Int32Type, 10, 'integer', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[10] := TDBXDataTypeDescription.Create('long binary', TDBXDataTypes.BlobType, 2147483647, 'long binary', NullString, -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
if IsCharUnicode then
Types[11] := TDBXDataTypeDescription.Create('long varchar', TDBXDataTypes.WideStringType, 2147483647, 'long varchar', NullString, -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode)
else
Types[11] := TDBXDataTypeDescription.Create('long varchar', TDBXDataTypes.AnsiStringType, 2147483647, 'long varchar', NullString, -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[12] := TDBXDataTypeDescription.Create('long nvarchar', TDBXDataTypes.WideStringType, 2147483647, 'long nvarchar', NullString, -1, -1, '0x', NullString, NullString, '10.00.0000', TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode);
Types[13] := TDBXDataTypeDescription.Create('numeric', TDBXDataTypes.BcdType, 38, 'numeric({0}, {1})', 'Precision,Scale', 38, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[14] := TDBXDataTypeDescription.Create('smallint', TDBXDataTypes.Int16Type, 5, 'smallint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[15] := TDBXDataTypeDescription.Create('time', TDBXDataTypes.TimeType, 8, 'time', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[16] := TDBXDataTypeDescription.Create('timestamp', TDBXDataTypes.TimeStampType, 8, 'timestamp', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[17] := TDBXDataTypeDescription.Create('tinyint', TDBXDataTypes.UInt8Type, 1, 'tinyint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.Unsigned);
Types[18] := TDBXDataTypeDescription.Create('varbinary', TDBXDataTypes.VarBytesType, 32767, 'varbinary({0})', 'Precision', -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
if IsCharUnicode then
Types[19] := TDBXDataTypeDescription.Create('varchar', TDBXDataTypes.WideStringType, 8191, 'varchar({0})', 'Precision', -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode)
else
Types[19] := TDBXDataTypeDescription.Create('varchar', TDBXDataTypes.AnsiStringType, 32767, 'varchar({0})', 'Precision', -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[20] := TDBXDataTypeDescription.Create('nvarchar', TDBXDataTypes.WideStringType, 8191, 'nvarchar({0})', 'Precision', -1, -1, '''', '''', NullString, '10.00.0000', TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode);
Types[21] := TDBXDataTypeDescription.Create('xml', TDBXDataTypes.WideStringType, 2147483647, 'xml', NullString, -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[22] := TDBXDataTypeDescription.Create('TIMESTAMP WITH TIME ZONE', TDBXDataTypes.TimeStampOffsetType, 34, 'TIMESTAMP({0} WITH TIME ZONE)', 'Precision', -1, -1, '{ts ''', '''}', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.LiteralSupported);
// Types[22] := TDBXDataTypeDescription.Create('uniqueidentifierstr', TDBXDataTypes.AnsiStringType, 36, 'char({0})', 'Precision', -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Result := Types;
end;
function TDBXSybaseASAMetaDataReader.GetReservedWords: TDBXStringArray;
var
Words: TDBXStringArray;
begin
SetLength(Words,223);
Words[0] := 'add';
Words[1] := 'all';
Words[2] := 'alter';
Words[3] := 'and';
Words[4] := 'any';
Words[5] := 'as';
Words[6] := 'asc';
Words[7] := 'backup';
Words[8] := 'begin';
Words[9] := 'between';
Words[10] := 'bigint';
Words[11] := 'binary';
Words[12] := 'bit';
Words[13] := 'bottom';
Words[14] := 'break';
Words[15] := 'by';
Words[16] := 'call';
Words[17] := 'capability';
Words[18] := 'cascade';
Words[19] := 'case';
Words[20] := 'cast';
Words[21] := 'char';
Words[22] := 'char_convert';
Words[23] := 'character';
Words[24] := 'check';
Words[25] := 'checkpoint';
Words[26] := 'close';
Words[27] := 'comment';
Words[28] := 'commit';
Words[29] := 'connect';
Words[30] := 'constraint';
Words[31] := 'contains';
Words[32] := 'continue';
Words[33] := 'convert';
Words[34] := 'create';
Words[35] := 'cross';
Words[36] := 'cube';
Words[37] := 'current';
Words[38] := 'current_timestamp';
Words[39] := 'current_user';
Words[40] := 'cursor';
Words[41] := 'date';
Words[42] := 'dbspace';
Words[43] := 'deallocate';
Words[44] := 'dec';
Words[45] := 'decimal';
Words[46] := 'declare';
Words[47] := 'default';
Words[48] := 'delete';
Words[49] := 'deleting';
Words[50] := 'desc';
Words[51] := 'distinct';
Words[52] := 'do';
Words[53] := 'double';
Words[54] := 'drop';
Words[55] := 'dynamic';
Words[56] := 'else';
Words[57] := 'elseif';
Words[58] := 'encrypted';
Words[59] := 'end';
Words[60] := 'endif';
Words[61] := 'escape';
Words[62] := 'except';
Words[63] := 'exception';
Words[64] := 'exec';
Words[65] := 'execute';
Words[66] := 'existing';
Words[67] := 'exists';
Words[68] := 'externlogin';
Words[69] := 'fetch';
Words[70] := 'first';
Words[71] := 'float';
Words[72] := 'for';
Words[73] := 'force';
Words[74] := 'foreign';
Words[75] := 'forward';
Words[76] := 'from';
Words[77] := 'full';
Words[78] := 'goto';
Words[79] := 'grant';
Words[80] := 'group';
Words[81] := 'having';
Words[82] := 'holdlock';
Words[83] := 'identified';
Words[84] := 'if';
Words[85] := 'in';
Words[86] := 'index';
Words[87] := 'index_lparen';
Words[88] := 'inner';
Words[89] := 'inout';
Words[90] := 'insensitive';
Words[91] := 'insert';
Words[92] := 'inserting';
Words[93] := 'install';
Words[94] := 'instead';
Words[95] := 'int';
Words[96] := 'integer';
Words[97] := 'integrated';
Words[98] := 'intersect';
Words[99] := 'into';
Words[100] := 'iq';
Words[101] := 'is';
Words[102] := 'isolation';
Words[103] := 'join';
Words[104] := 'key';
Words[105] := 'lateral';
Words[106] := 'left';
Words[107] := 'like';
Words[108] := 'lock';
Words[109] := 'login';
Words[110] := 'long';
Words[111] := 'match';
Words[112] := 'membership';
Words[113] := 'message';
Words[114] := 'mode';
Words[115] := 'modify';
Words[116] := 'natural';
Words[117] := 'new';
Words[118] := 'no';
Words[119] := 'noholdlock';
Words[120] := 'not';
Words[121] := 'notify';
Words[122] := 'null';
Words[123] := 'numeric';
Words[124] := 'of';
Words[125] := 'off';
Words[126] := 'on';
Words[127] := 'open';
Words[128] := 'option';
Words[129] := 'options';
Words[130] := 'or';
Words[131] := 'order';
Words[132] := 'others';
Words[133] := 'out';
Words[134] := 'outer';
Words[135] := 'over';
Words[136] := 'passthrough';
Words[137] := 'precision';
Words[138] := 'prepare';
Words[139] := 'primary';
Words[140] := 'print';
Words[141] := 'privileges';
Words[142] := 'proc';
Words[143] := 'procedure';
Words[144] := 'publication';
Words[145] := 'raiserror';
Words[146] := 'readtext';
Words[147] := 'real';
Words[148] := 'reference';
Words[149] := 'references';
Words[150] := 'release';
Words[151] := 'remote';
Words[152] := 'remove';
Words[153] := 'rename';
Words[154] := 'reorganize';
Words[155] := 'resource';
Words[156] := 'restore';
Words[157] := 'restrict';
Words[158] := 'return';
Words[159] := 'revoke';
Words[160] := 'right';
Words[161] := 'rollback';
Words[162] := 'rollup';
Words[163] := 'save';
Words[164] := 'savepoint';
Words[165] := 'scroll';
Words[166] := 'select';
Words[167] := 'sensitive';
Words[168] := 'session';
Words[169] := 'set';
Words[170] := 'setuser';
Words[171] := 'share';
Words[172] := 'smallint';
Words[173] := 'some';
Words[174] := 'sqlcode';
Words[175] := 'sqlstate';
Words[176] := 'start';
Words[177] := 'stop';
Words[178] := 'subtrans';
Words[179] := 'subtransaction';
Words[180] := 'synchronize';
Words[181] := 'syntax_error';
Words[182] := 'table';
Words[183] := 'temporary';
Words[184] := 'then';
Words[185] := 'time';
Words[186] := 'timestamp';
Words[187] := 'tinyint';
Words[188] := 'to';
Words[189] := 'top';
Words[190] := 'tran';
Words[191] := 'trigger';
Words[192] := 'truncate';
Words[193] := 'tsequal';
Words[194] := 'unbounded';
Words[195] := 'union';
Words[196] := 'unique';
Words[197] := 'unknown';
Words[198] := 'unsigned';
Words[199] := 'update';
Words[200] := 'updating';
Words[201] := 'user';
Words[202] := 'using';
Words[203] := 'validate';
Words[204] := 'values';
Words[205] := 'varbinary';
Words[206] := 'varchar';
Words[207] := 'variable';
Words[208] := 'varying';
Words[209] := 'view';
Words[210] := 'wait';
Words[211] := 'waitfor';
Words[212] := 'when';
Words[213] := 'where';
Words[214] := 'while';
Words[215] := 'window';
Words[216] := 'with';
Words[217] := 'with_cube';
Words[218] := 'with_lparen';
Words[219] := 'with_rollup';
Words[220] := 'within';
Words[221] := 'work';
Words[222] := 'writetext';
Result := Words;
end;
end.
|
unit Ths.Erp.Database.Table.AyarStkStokTipi;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TAyarStkStokTipi = class(TTable)
private
FTip: TFieldDB;
FIsDefault: TFieldDB;
FIsStokHareketiYap: TFieldDB;
protected
procedure BusinessInsert(out pID: Integer; var pPermissionControl: Boolean); override;
procedure BusinessUpdate(pPermissionControl: Boolean); override;
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property Tip: TFieldDB read FTip write FTip;
Property IsDefault: TFieldDB read FIsDefault write FIsDefault;
Property IsStokHareketiYap: TFieldDB read FIsStokHareketiYap write FIsStokHareketiYap;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TAyarStkStokTipi.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'ayar_stk_stok_tipi';
SourceCode := '1000';
FTip := TFieldDB.Create('tip', ftString, '');
FIsDefault := TFieldDB.Create('is_default', ftBoolean, 0);
FIsStokHareketiYap := TFieldDB.Create('is_stok_hareketi_yap', ftBoolean, 0);
end;
procedure TAyarStkStokTipi.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
getRawDataByLang(TableName, FTip.FieldName),
TableName + '.' + FIsDefault.FieldName,
TableName + '.' + FIsStokHareketiYap.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FTip.FieldName).DisplayLabel := 'Tip';
Self.DataSource.DataSet.FindField(FIsDefault.FieldName).DisplayLabel := 'Default?';
Self.DataSource.DataSet.FindField(FIsStokHareketiYap.FieldName).DisplayLabel := 'Stok Hareketi Yap?';
end;
end;
end;
procedure TAyarStkStokTipi.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
getRawDataByLang(TableName, FTip.FieldName),
TableName + '.' + FIsDefault.FieldName,
TableName + '.' + FIsStokHareketiYap.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FTip.Value := FormatedVariantVal(FieldByName(FTip.FieldName).DataType, FieldByName(FTip.FieldName).Value);
FIsDefault.Value := FormatedVariantVal(FieldByName(FIsDefault.FieldName).DataType, FieldByName(FIsDefault.FieldName).Value);
FIsStokHareketiYap.Value := FormatedVariantVal(FieldByName(FIsStokHareketiYap.FieldName).DataType, FieldByName(FIsStokHareketiYap.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TAyarStkStokTipi.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FTip.FieldName,
FIsDefault.FieldName,
FIsStokHareketiYap.FieldName
]);
NewParamForQuery(QueryOfInsert, FTip);
NewParamForQuery(QueryOfInsert, FIsDefault);
NewParamForQuery(QueryOfInsert, FIsStokHareketiYap);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TAyarStkStokTipi.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FTip.FieldName,
FIsDefault.FieldName,
FIsStokHareketiYap.FieldName
]);
NewParamForQuery(QueryOfUpdate, FTip);
NewParamForQuery(QueryOfUpdate, FIsDefault);
NewParamForQuery(QueryOfUpdate, FIsStokHareketiYap);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
procedure TAyarStkStokTipi.BusinessInsert(out pID: Integer;
var pPermissionControl: Boolean);
var
vStokTipi: TAyarStkStokTipi;
n1: Integer;
begin
if FormatedVariantVal(Self.IsDefault.FieldType, Self.IsDefault.Value) = True then
begin
vStokTipi := TAyarStkStokTipi.Create(Database);
try
vStokTipi.SelectToList(' and ' + vStokTipi.TableName + '.' + vStokTipi.FIsDefault.FieldName + '=True', False, False);
for n1 := 0 to vStokTipi.List.Count-1 do
begin
TAyarStkStokTipi(vStokTipi.List[n1]).IsDefault.Value := False;
TAyarStkStokTipi(vStokTipi.List[n1]).Update();
end;
finally
vStokTipi.Free;
end;
Self.Insert(pID);
end
else
Self.Insert(pID);
end;
procedure TAyarStkStokTipi.BusinessUpdate(pPermissionControl: Boolean);
var
vStokTipi: TAyarStkStokTipi;
n1: Integer;
begin
if FormatedVariantVal(Self.IsDefault.FieldType, Self.IsDefault.Value) = True then
begin
vStokTipi := TAyarStkStokTipi.Create(Database);
try
vStokTipi.SelectToList(' and ' + vStokTipi.TableName + '.' + vStokTipi.FIsDefault.FieldName + '=True', False, False);
for n1 := 0 to vStokTipi.List.Count-1 do
begin
TAyarStkStokTipi(vStokTipi.List[n1]).IsDefault.Value := False;
TAyarStkStokTipi(vStokTipi.List[n1]).Update();
end;
finally
vStokTipi.Free;
end;
Self.Update();
end
else
Self.Update;
end;
function TAyarStkStokTipi.Clone():TTable;
begin
Result := TAyarStkStokTipi.Create(Database);
Self.Id.Clone(TAyarStkStokTipi(Result).Id);
FTip.Clone(TAyarStkStokTipi(Result).FTip);
FIsDefault.Clone(TAyarStkStokTipi(Result).FIsDefault);
FIsStokHareketiYap.Clone(TAyarStkStokTipi(Result).FIsStokHareketiYap);
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
{/*
* multiscreendoor.c
* Celeste Fowler, 1997
*
* An example of using screen-door transparency with multiple objects.
*
*/}
unit frmMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC: HDC;
hrc: HGLRC;
cone, base, qsphere : GLUquadricObj;
procedure draw_cone;
procedure draw_sphere(angle : GLdouble);
procedure SetDCPixelFormat;
procedure Init;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
Angle : GLfloat = 0;
time : LongInt;
implementation
uses DGLUT;
{$R *.DFM}
type
TPattern = Array [0..31] of GLuint;
var
spherePattern, conePattern : TPattern;
procedure create_stipple_pattern(var pat : TPattern; opacity : GLfloat);
var
x, y : GLint;
begin
For y := 0 to 31 do begin
pat[y] := 0;
For x := 0 to 31 do
If (random > 0.6) then pat[y] := pat[y] xor (1 shl x);
end;
end;
procedure TfrmGL.Init;
const
lightpos : Array [0..3] of GLfloat = (0.5, 0.75, 1.5, 1.0);
begin
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_POSITION, @lightpos);
cone := gluNewQuadric;
base := gluNewQuadric;
qsphere := gluNewQuadric;
gluQuadricOrientation(base, GLU_INSIDE);
create_stipple_pattern(spherePattern, 0.5);
create_stipple_pattern(conePattern, 0.5);
end;
procedure draw_room;
const
//* material for the walls, floor, ceiling */
wall_mat : Array [0..3] of GLfloat = (1.0, 1.0, 1.0, 1.0);
begin
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @wall_mat);
glBegin(GL_QUADS);
//* floor */
glNormal3f(0, 1, 0);
glVertex3f(-1, -1, 1);
glVertex3f(1, -1, 1);
glVertex3f(1, -1, -1);
glVertex3f(-1, -1, -1);
//* ceiling */
glNormal3f(0, -1, 0);
glVertex3f(-1, 1, -1);
glVertex3f(1, 1, -1);
glVertex3f(1, 1, 1);
glVertex3f(-1, 1, 1);
//* left wall */
glNormal3f(1, 0, 0);
glVertex3f(-1, -1, -1);
glVertex3f(-1, -1, 1);
glVertex3f(-1, 1, 1);
glVertex3f(-1, 1, -1);
//* right wall */
glNormal3f(-1, 0, 0);
glVertex3f(1, 1, -1);
glVertex3f(1, 1, 1);
glVertex3f(1, -1, 1);
glVertex3f(1, -1, -1);
//* far wall */
glNormal3f(0, 0, 1);
glVertex3f(-1, -1, -1);
glVertex3f(1, -1, -1);
glVertex3f(1, 1, -1);
glVertex3f(-1, 1, -1);
glEnd();
end;
procedure TfrmGL.draw_cone;
const
cone_mat : Array [0..3] of GLfloat = (0.0, 0.5, 1.0, 1.0);
begin
glPushMatrix();
glTranslatef(0, -1, 0);
glRotatef(-90, 1, 0, 0);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @cone_mat);
gluCylinder(cone, 0.3, 0, 1.25, 20, 1);
gluDisk(base, 0.0, 0.3, 20, 1);
glPopMatrix();
end;
procedure TfrmGL.draw_sphere(angle : GLdouble);
const
sphere_mat : Array [0..3] of GLfloat = (1.0, 0.5, 0.0, 0.5);
begin
glPushMatrix();
glTranslatef(0, -0.3, 0);
glRotatef(angle, 0, 1, 0);
glTranslatef(0, 0, 0.6);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @sphere_mat);
gluSphere(qsphere, 0.3, 20, 20);
glPopMatrix();
end;
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
Init;
time := GetTickCount;
end;
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(60, 1, 0.01, 10);
gluLookAt(0, 0, 2.577, 0, 0, -5, 0, 1, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
InvalidateRect(Handle, nil, False);
end;
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
draw_room;
glEnable(GL_POLYGON_STIPPLE);
glPolygonStipple(@conePattern);
draw_cone;
glPolygonStipple(@spherePattern);
draw_sphere(Angle);
glDisable(GL_POLYGON_STIPPLE);
SwapBuffers(DC);
EndPaint(Handle, ps);
Angle := Angle + 0.25 * (GetTickCount - time) * 360 / 1000;
If Angle >= 360.0 then Angle := 0.0;
time := GetTickCount;
InvalidateRect(Handle, nil, False);
end;
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
gluDeleteQuadric (cone);
gluDeleteQuadric (base);
gluDeleteQuadric (qsphere);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2015-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.IOS.Beacon;
interface
uses
System.Beacon;
type
/// <summary>
/// Implements TBeaconManager for the iOS platform, for the Standard beacon types
/// </summary>
TPlatformBeaconManager = class(TBeaconManager)
public
class function GetInstance(AMode: TBeaconScanMode): TBeaconManager; override;
end;
implementation
uses
iOSapi.CoreLocation, System.iOS.Sensors, iOSapi.Foundation, Macapi.Helpers, Macapi.ObjectiveC, System.NetConsts, System.Bluetooth,
Macapi.ObjCRuntime, System.Generics.Collections, System.SysUtils, System.Classes, System.DateUtils, System.Math, System.Beacon.Common;
const
DistanceMeanItems = 10;
ProximityMeanItems = 10;
type
TBeaconErrorCallbabk = procedure(const AError: string) of object;
TBeaconRegionCallback = procedure(const UUID: TGUID; Major: Integer; Minor : Integer) of object;
TBeaconRangeCallback = procedure(const ACLBeacon: CLBeacon) of object;
TAutorizationChangeCallback = procedure(ACode: NativeUInt) of object;
TBeaconRegion = record
Inside: Boolean;
GUID: TGUID;
Major: Integer;
Minor: Integer;
function GetRegion: CLBeaconRegion;
procedure Initialilize(const AGUID: TGUID; AMajor: Integer; AMinor: Integer); overload;
function BeaconBelongs(const ABeacon: IBeacon): Boolean; inline;
function IsRegion(const AGUID: TGUID; AMajor: Integer; AMinor: Integer): Boolean; inline;
end;
TiOSBeaconManager = class(TBeaconManager)
private
FCoreLocationManager: TBeaconManager;
FCommonManager: TBeaconManager;
FCurrentBeaconList: TBeaconList;
private
FScanning: Boolean;
procedure DoiOSBeaconEnter(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList);
procedure DoiOSBeaconExit(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList);
procedure DoiOSBeaconChangedProximity(const Sender: TObject; const ABeacon: IBeacon; CurrentProximity: TBeaconProximity);
procedure DoiOSRegionEnter(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Integer);
procedure DoiOSBeaconsRegionEnter(const Sender: TObject; const ABeaconRegion: TBeaconsRegion);
procedure DoiOSRegionExit(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Integer);
procedure DoiOSBeaconsRegionExit(const Sender: TObject; const ABeaconRegion: TBeaconsRegion);
procedure DoiOSBeaconCalcDistance(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Word;
ATxPower: Integer; ARssi: Integer; var NewDistance: Double); overload;
procedure DoiOSBeaconCalcDistance(const Sender: TObject; const ABeacon: IBeacon; ATxPower, ARssi: Integer; var NewDistance: Double); overload;
procedure DoiOSParseManufacturerData(const Sender: TObject; const AData: TManufacturerRawData; var BeaconInfo: TBeaconInfo; var Handled: Boolean);
procedure DoiOSParseServiceData(const Sender: TObject; const AData: TServiceDataRawData; var BeaconInfo: TBeaconInfo; var Handled: Boolean);
procedure DoiOSNewEddystoneURL(const Sender: TObject; const ABeacon: IBeacon; const AEddystoneURL: TEddystoneURL);
procedure DoiOSNewEddystoneTLM(const Sender: TObject; const ABeacon: IBeacon; const AEddystoneTLM: TEddystoneTLM);
procedure DoiOSNewBLEScanFilter(const Sender: TObject; AKindofScanFilter: TKindofScanFilter;
const ABluetoothLEScanFilter: TBluetoothLEScanFilter);
procedure CheckEvents;
protected
function DoRegisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons;
AManufacturerId: Integer = MANUFATURER_ID_ALL): Boolean; overload; override;
function DoRegisterBeacon(const AGUID: TGUID; Major: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons;
AManufacturerId: Integer = MANUFATURER_ID_ALL): Boolean; overload; override;
function DoRegisterBeacon(const AGUID: TGUID; Major, Minor: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons;
AManufacturerId: Integer = MANUFATURER_ID_ALL): Boolean; overload; override;
function DoRegisterEddyBeacon(const ANamespace: TNamespace): Boolean; overload; override;
function DoRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean; overload; override;
function DoUnregisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons): Boolean; overload; override;
function DoUnregisterBeacon(const AGUID: TGUID; Major: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons): Boolean; overload; override;
function DoUnregisterBeacon(const AGUID: TGUID; Major, Minor: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons): Boolean; overload; override;
function DoUnRegisterEddyBeacon(const ANamespace: TNamespace): Boolean; overload; override;
function DoUnRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean; overload; override;
function DoNearest: IBeacon; override;
function DoStartScan: Boolean; override;
function DoStopScan: Boolean; override;
procedure SetBeaconDeathTime(AValue: Integer); override;
procedure SetScanningSleepingTime(AValue: Integer); override;
procedure SetScanningTime(AValue: Integer); override;
procedure SetSPC(AValue: Single); override;
procedure SetBeaconType(AValue: Word); override;
function GetNumberofBeaconsRegistered: Integer; override;
procedure DoSetKindofBeacons(AValue: TKindofBeacons); override;
function GeTKindofBeacons: TKindofBeacons; override;
class function GetInstance(AMode: TBeaconScanMode): TBeaconManager; override;
public
constructor Create(AMode: TBeaconScanMode);
property IsScanning: Boolean read FScanning;
end;
TiOSBeaconManagerCoreLocation = class(TBeaconManager)
private
class var DeathTime: Integer;
class constructor Create;
private
FRssiAccumulatedDiff: Single;
FLockObject: TObject;
FCurrentBeaconList: TBeaconList;
FLocationManager: CLLocationManager;
FLocationDelegate: CLLocationManagerDelegate;
FRegisteredRegions: TList<TBeaconRegion>;
FCurrentBeaconCount: Integer;
function IsMonitoringAvailable: Boolean;
procedure RemoveBeaconsFromRegion(const ARegion: TBeaconRegion);
procedure EnterRegion(const UUID: TGUID; Major: Integer; Minor : Integer);
procedure ExitRegion(const UUID: TGUID; Major: Integer; Minor : Integer);
procedure RangeBeacon(const ACLBeacon: CLBeacon);
procedure AutorizationChange(ACode: NativeUInt);
procedure UnRegisterBeacon(const AGUID: TGUID; Major, Minor: Integer; AKindofBeacon: TKindofBeacon);
function RegisterBeacon(const AGUID: TGUID; Major: Integer; Minor: Integer; AKindofBeacon: TKindofBeacon): Boolean;
procedure CheckBeaconListSanity;
procedure DoEnterExitRegion(RegionIndex: Integer; Enter: Boolean);
procedure CheckEnterRegion(const ANewBeacon: IBeacon);
procedure CheckExitRegion(const AExitedBeacon: IBeacon);
function AddRegionToList(const ARegion: TBeaconRegion): Boolean;
// procedure SetAllowBackgroundUpdates;
protected
function DoRegisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons;
AManufacturerId: Integer = MANUFATURER_ID_ALL): Boolean; overload; override;
function DoRegisterBeacon(const AGUID: TGUID; Major: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons;
AManufacturerId: Integer = MANUFATURER_ID_ALL): Boolean; overload; override;
function DoRegisterBeacon(const AGUID: TGUID; Major, Minor: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons;
AManufacturerId: Integer = MANUFATURER_ID_ALL): Boolean; overload; override;
function DoRegisterEddyBeacon(const ANamespace: TNamespace): Boolean; overload; override;
function DoRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean; overload; override;
function DoUnregisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons): Boolean; overload; override;
function DoUnregisterBeacon(const AGUID: TGUID; Major: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons): Boolean; overload; override;
function DoUnregisterBeacon(const AGUID: TGUID; Major, Minor: Word; const AKindofBeacon: TKindofBeacon = TKindofBeacon.iBAltBeacons): Boolean; overload; override;
function DoUnRegisterEddyBeacon(const ANamespace: TNamespace): Boolean; overload; override;
function DoUnRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean; overload; override;
function DoNearest: IBeacon; override;
function DoStartScan: Boolean; override;
function DoStopScan: Boolean; override;
procedure SetBeaconDeathTime(AValue: Integer); override;
procedure SetScanningSleepingTime(AValue: Integer); override;
procedure SetScanningTime(AValue: Integer); override;
procedure SetSPC(AValue: Single); override;
procedure SetBeaconType(AValue: Word); override;
function GetNumberofBeaconsRegistered: Integer; override;
procedure DoSetKindofBeacons(AValue: TKindofBeacons); override;
function GeTKindofBeacons: TKindofBeacons; override;
class function GetInstance(AMode: TBeaconScanMode): TBeaconManager; override;
public
constructor Create;
destructor Destroy; override;
end;
TBeaconLocationManagerDelegate = class(TOCLocal, CLLocationManagerDelegate)
private
FRangeBeaconCallback: TBeaconRangeCallback;
FEnterRegionCallback: TBeaconRegionCallback;
FErrorCallback: TBeaconErrorCallbabk;
FExitRegionCallback: TBeaconRegionCallback;
FAutorizationChangeCallback: TAutorizationChangeCallback;
function GetBeaconRegionFrom(const ARegion: CLRegion): CLBeaconRegion;
public
procedure locationManager(manager: CLLocationManager; didFailWithError: NSError); overload; cdecl;
procedure locationManager(manager: CLLocationManager; didUpdateHeading: CLHeading); overload; cdecl;
procedure locationManager(manager: CLLocationManager; didUpdateToLocation: CLLocation; fromLocation: CLLocation); overload; cdecl;
procedure locationManager(manager: CLLocationManager; monitoringDidFailForRegion: CLRegion; withError: NSError); overload; cdecl;
procedure locationManager(manager: CLLocationManager; didChangeAuthorizationStatus: CLAuthorizationStatus); overload; cdecl;
function locationManagerShouldDisplayHeadingCalibration(manager: CLLocationManager): Boolean; cdecl;
[MethodName('locationManager:didUpdateLocations:')]
procedure locationManagerDidUpdateLocations(manager: CLLocationManager; locations: NSArray); cdecl;
[MethodName('locationManager:didFinishDeferredUpdatesWithError:')]
procedure locationManagerDidFinishDeferredUpdatesWithError(manager: CLLocationManager; error: NSError); cdecl;
procedure locationManagerDidPauseLocationUpdates(manager: CLLocationManager); cdecl;
procedure locationManagerDidResumeLocationUpdates(manager: CLLocationManager); cdecl;
[MethodName('locationManager:didEnterRegion:')]
procedure locationManagerDidEnterRegion(manager: CLLocationManager; region: CLRegion); cdecl;
[MethodName('locationManager:didExitRegion:')]
procedure locationManagerDidExitRegion(manager: CLLocationManager; region: CLRegion); cdecl;
[MethodName('locationManager:didDetermineState:forRegion:')]
procedure locationManagerDidDetermineStateForRegion(manager: CLLocationManager; state: CLRegionState; region: CLRegion); cdecl;
[MethodName('locationManager:didStartMonitoringForRegion:')]
procedure locationManagerDidStartMonitoringForRegion(manager: CLLocationManager; region: CLRegion); cdecl;
[MethodName('locationManager:didRangeBeacons:inRegion:')]
procedure locationManagerDidRangeBeaconsInRegion(manager: CLLocationManager; beacons: NSArray; region: CLBeaconRegion); cdecl;
[MethodName('locationManager:rangingBeaconsDidFailForRegion:withError:')]
procedure locationManagerRangingBeaconsDidFailForRegionWithError(manager: CLLocationManager; region: CLBeaconRegion; error: NSError); cdecl;
end;
TiOSBeacon = class(TInterfacedObject, IiBeacon)
private type
TCalcDistanceEvent = function (const UUID: TGUID; AMajor, AMinor: Word; AtxPower: Integer;
ARssi: Integer; var NewDistance: Double): Boolean of object;
TCalcDistancesEvent = function (const Abeacon: IBeacon; ATxPower: Integer; ARssi: Integer;
var NewDistance: Double): Boolean of object;
private
FLastUpdateTime: TDateTime;
FKindofBeacon: TKindofBeacon;
FEddystoneBeacon: TEddystoneBeaconInfo;
FGUID: TGUID;
FMinor: Word;
FMajor: Word;
FProximity: TMeanCalculator<Integer>;
FDistance: TMeanCalculator<Double>;
FRssi: Integer;
FCalcDistance: TCalcDistanceEvent;
FCalcDistances: TCalcDistancesEvent;
FCalcMode: TBeaconCalcMode;
FCalculatedDistance: Double;
public
function GetGUID: TGUID; inline;
function GetMajor: Word; inline;
function GetMinor: Word; inline;
function GetRssi: Integer; inline;
function GetDistance: Double; inline;
function GetEddystoneBeacon: TEddystoneBeaconInfo;
function GetDeviceIdentifier: string;
function GetProximity: TBeaconProximity; inline;
function GetAdditionalData: TBytes;
function ItsAlive:Boolean; inline;
function IsEqualTo(const AGUID: TGUID; AMajor, AMinor: Word): Boolean; overload;
function IsEqualTo(const ANamespace: TNamespace; const AInstance: TInstance): Boolean; overload;
function IsEqualTo(const AIBeacon: IBeacon): Boolean; overload;
procedure SetBeaconInfo(const ABeacon: CLBeacon; IsMoving: Boolean);
function GetKindofBeacon: TKindofBeacon;
constructor Create(AMode: TBeaconCalcMode);
end;
function CheckOSVersion: Boolean;
begin
Result := TOSVersion.Check(8);
end;
function CLProximityToTProximity(const AProximity: CLProximity): TBeaconProximity;
begin
case AProximity of
CLProximityUnknown: Result := TBeaconProximity.Away;
CLProximityImmediate: Result := TBeaconProximity.Immediate;
CLProximityNear: Result := TBeaconProximity.Near;
CLProximityFar: Result := TBeaconProximity.Far;
else
Result := TBeaconProximity.Away;
end;
end;
function GetOwnCalcProximity(ADistance: Double): Integer;
begin
if ADistance < PROXIMITY_IMMEDIATE then
Result := Integer(Immediate)
else
if ADistance < PROXIMITY_NEAR then
Result := Integer(Near)
else
if ADistance < PROXIMITY_FAR then
Result := Integer(Far)
else
Result := Integer(Away);
end;
{ TBeaconLocationManagerDelegate }
procedure TBeaconLocationManagerDelegate.locationManager(manager: CLLocationManager; monitoringDidFailForRegion: CLRegion;
withError: NSError);
begin
if Assigned(FErrorCallback) then
FErrorCallback(NSStrToStr(withError.localizedDescription));
end;
procedure TBeaconLocationManagerDelegate.locationManager(manager: CLLocationManager;
didChangeAuthorizationStatus: CLAuthorizationStatus);
begin
if Assigned(FAutorizationChangeCallback) then
FAutorizationChangeCallback(didChangeAuthorizationStatus);
end;
procedure TBeaconLocationManagerDelegate.locationManager(manager: CLLocationManager; didUpdateToLocation, fromLocation: CLLocation);
begin
// For debug purposes
end;
procedure TBeaconLocationManagerDelegate.locationManager(manager: CLLocationManager; didFailWithError: NSError);
begin
if Assigned(FErrorCallback) then
FErrorCallback(NSStrToStr(didFailWithError.localizedDescription));
end;
procedure TBeaconLocationManagerDelegate.locationManager(manager: CLLocationManager; didUpdateHeading: CLHeading);
begin
// For debug purposes
end;
procedure TBeaconLocationManagerDelegate.locationManagerDidDetermineStateForRegion(manager: CLLocationManager; state: CLRegionState;
region: CLRegion);
begin
// For debug purposes
end;
procedure TBeaconLocationManagerDelegate.locationManagerDidEnterRegion(manager: CLLocationManager; region: CLRegion);
var
LBeaconRegion: CLBeaconRegion;
LUUID: string;
LMajor: Integer;
LMinor: Integer;
begin
if Assigned(FEnterRegionCallback) then
begin
LBeaconRegion := GetBeaconRegionFrom(region);
if LBeaconRegion <> nil then
begin
LUUID := NSStrToStr(LBeaconRegion.proximityUUID.UUIDString);
if LBeaconRegion.major <> nil then
LMajor := LBeaconRegion.major.unsignedShortValue
else
LMajor := -1;
if LBeaconRegion.minor <> nil then
LMinor := LBeaconRegion.minor.unsignedShortValue
else
LMinor := -1;
FEnterRegionCallback(TGUID.Create('{' + LUUID + '}'), LMajor, LMinor);
end;
end;
end;
function TBeaconLocationManagerDelegate.GetBeaconRegionFrom(const ARegion: CLRegion): CLBeaconRegion;
begin
Result := nil;
if NSInheritsFrom(ARegion, TCLBeaconRegion.OCClass) then
begin
ARegion.retain;
Result := TCLBeaconRegion.Wrap((ARegion as ILocalObject).GetObjectID);
Result.retain;
end;
end;
procedure TBeaconLocationManagerDelegate.locationManagerDidExitRegion(manager: CLLocationManager; region: CLRegion);
var
LBeaconRegion: CLBeaconRegion;
LUUID: string;
LMajor: Integer;
LMinor: Integer;
begin
if Assigned(FExitRegionCallback) then
begin
LBeaconRegion := GetBeaconRegionFrom(region);
if LBeaconRegion <> nil then
begin
LUUID := NSStrToStr(LBeaconRegion.proximityUUID.UUIDString);
if LBeaconRegion.major <> nil then
LMajor := LBeaconRegion.major.unsignedShortValue
else
LMajor := -1;
if LBeaconRegion.minor <> nil then
LMinor := LBeaconRegion.minor.unsignedShortValue
else
LMinor := -1;
FExitRegionCallback(TGUID.Create('{' + LUUID + '}'), LMajor, LMinor);
end;
end;
end;
procedure TBeaconLocationManagerDelegate.locationManagerDidFinishDeferredUpdatesWithError(manager: CLLocationManager; error: NSError);
begin
if Assigned(FErrorCallback) then
FErrorCallback(NSStrToStr(error.localizedDescription));
end;
procedure TBeaconLocationManagerDelegate.locationManagerDidPauseLocationUpdates(manager: CLLocationManager);
begin
// For debug purposes
end;
procedure TBeaconLocationManagerDelegate.locationManagerDidResumeLocationUpdates(manager: CLLocationManager);
begin
// For debug purposes
end;
procedure TBeaconLocationManagerDelegate.locationManagerDidStartMonitoringForRegion(manager: CLLocationManager; region: CLRegion);
begin
// For debug purposes
end;
procedure TBeaconLocationManagerDelegate.locationManagerDidUpdateLocations(manager: CLLocationManager; locations: NSArray);
begin
// For debug purposes
end;
procedure TBeaconLocationManagerDelegate.locationManagerDidRangeBeaconsInRegion(manager: CLLocationManager; beacons: NSArray; region: CLBeaconRegion);
var
LBeacon: CLBeacon;
I: Integer;
LCount: Integer;
begin
if Assigned(FRangeBeaconCallback) then
begin
LCount := beacons.count;
if LCount > 0 then
begin
for I := 0 to LCount - 1 do
begin
Lbeacon := TCLBeacon.Wrap(beacons.objectAtIndex(I));
if Assigned(FRangeBeaconCallback) then
FRangeBeaconCallback(LBeacon);
end;
end
else
FRangeBeaconCallback(nil);
end;
end;
procedure TBeaconLocationManagerDelegate.locationManagerRangingBeaconsDidFailForRegionWithError(manager: CLLocationManager;
region: CLBeaconRegion; error: NSError);
begin
if Assigned(FErrorCallback) then
FErrorCallback(NSStrToStr(error.localizedDescription));
end;
function TBeaconLocationManagerDelegate.locationManagerShouldDisplayHeadingCalibration(manager: CLLocationManager): Boolean;
begin
// For debug purposes
Result := False;
end;
{ TiOSBeaconManager }
procedure TiOSBeaconManager.DoiOSBeaconEnter(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList);
begin
TMonitor.Enter(Self);
try
SetLength(FCurrentBeaconList, Length(FCurrentBeaconList) + 1);
FCurrentBeaconList[Length(FCurrentBeaconList) - 1] := ABeacon;
DoBeaconEnter(ABeacon, FCurrentBeaconList);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSBeaconExit(const Sender: TObject; const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList);
var
I: Integer;
LBLength: Integer;
LTailElements: Integer;
begin
TMonitor.Enter(Self);
try
LBLength := Length(FCurrentBeaconList);
for I := 0 to LBLength - 1 do
if FCurrentBeaconList[I].IsEqualTo(ABeacon) then
begin
LTailElements := LBLength - (I + 1);
FCurrentBeaconList[I] := nil;
if LTailElements > 0 then
Move(FCurrentBeaconList[I + 1], FCurrentBeaconList[I], SizeOf(IBeacon) * LTailElements);
Initialize(FCurrentBeaconList[LBLength - 1]);
SetLength(FCurrentBeaconList, LBLength - 1);
Break;
end;
DoBeaconExit(ABeacon, FCurrentBeaconList);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSBeaconChangedProximity(const Sender: TObject; const ABeacon: IBeacon; CurrentProximity: TBeaconProximity);
begin
TMonitor.Enter(Self);
try
DoBeaconChangedProximity(ABeacon, CurrentProximity);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSRegionEnter(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Integer);
begin
TMonitor.Enter(Self);
try
DoRegionEnter(UUID, AMajor, AMinor);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSBeaconsRegionEnter(const Sender: TObject; const ABeaconRegion: TBeaconsRegion);
begin
TMonitor.Enter(Self);
try
DoBeaconsRegionEnter(ABeaconRegion);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSRegionExit(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Integer);
begin
TMonitor.Enter(Self);
try
DoRegionExit(UUID, AMajor, AMinor);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSBeaconsRegionExit(const Sender: TObject; const ABeaconRegion: TBeaconsRegion);
begin
TMonitor.Enter(Self);
try
DoBeaconsRegionExit(ABeaconRegion);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSNewBLEScanFilter(const Sender: TObject; AKindofScanFilter: TKindofScanFilter;
const ABluetoothLEScanFilter: TBluetoothLEScanFilter);
begin
TMonitor.Enter(Self);
try
DoNewBLEScanFilter(AKindofScanFilter, ABluetoothLEScanFilter);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSBeaconCalcDistance(const Sender: TObject; const UUID: TGUID; AMajor, AMinor: Word;
ATxPower: Integer; ARssi: Integer; var NewDistance: Double);
begin
TMonitor.Enter(Self);
try
DoBeaconCalcDistance(UUID, AMajor, AMinor, ATxPower,ARssi, NewDistance);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSBeaconCalcDistance(const Sender: TObject; const ABeacon: IBeacon; ATxPower, ARssi: Integer;
var NewDistance: Double);
begin
TMonitor.Enter(Self);
try
DoBeaconCalcDistance(ABeacon, ATxPower, ARssi, NewDistance);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSParseManufacturerData(const Sender: TObject; const AData: TManufacturerRawData; var BeaconInfo: TBeaconInfo; var Handled: Boolean);
begin
TMonitor.Enter(Self);
try
DoParseManufacturerData(TBytes(AData), BeaconInfo, Handled);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSParseServiceData(const Sender: TObject; const AData: TServiceDataRawData; var BeaconInfo: TBeaconInfo; var Handled: Boolean);
begin
TMonitor.Enter(Self);
try
DoParseServiceData(AData, BeaconInfo, Handled);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSNewEddystoneURL(const Sender: TObject; const ABeacon: IBeacon; const AEddystoneURL: TEddystoneURL);
begin
TMonitor.Enter(Self);
try
DoNewEddystoneURL(ABeacon, AEddystoneURL);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.DoiOSNewEddystoneTLM(const Sender: TObject; const ABeacon: IBeacon; const AEddystoneTLM: TEddystoneTLM);
begin
TMonitor.Enter(Self);
try
DoNewEddystoneTLM(ABeacon, AEddystoneTLM);
finally
TMonitor.Exit(Self);
end;
end;
procedure TiOSBeaconManager.CheckEvents;
begin
if FCoreLocationManager <> nil then
begin
FCoreLocationManager.OnBeaconEnter := DoiOSBeaconEnter;
FCoreLocationManager.OnBeaconExit := DoiOSBeaconExit;
if Assigned(FOnBeaconProximity) then
FCoreLocationManager.OnBeaconProximity := DoiOSBeaconChangedProximity
else
FCoreLocationManager.OnBeaconProximity := nil;
FCoreLocationManager.OnEnterRegion := DoiOSRegionEnter;
FCoreLocationManager.OnExitRegion := DoiOSRegionExit;
FCoreLocationManager.OnBeaconsEnterRegion := DoiOSBeaconsRegionEnter;
FCoreLocationManager.OnBeaconsExitRegion := DoiOSBeaconsRegionExit;
if Assigned(FOnCalculateDistances) then
FCoreLocationManager.OnCalculateDistances := DoiOSBeaconCalcDistance
else
begin
FCoreLocationManager.OnCalculateDistances := nil;
if Assigned(FOnCalcDistance) then
FCoreLocationManager.OnCalcDistance := DoiOSBeaconCalcDistance
else
FCoreLocationManager.OnCalcDistance := nil;
end;
if Assigned(FOnParseManufacturerData) then
FCoreLocationManager.OnParseManufacturerData := DoiOSParseManufacturerData
else
FCoreLocationManager.OnParseManufacturerData := nil;
FCoreLocationManager.OnParseServiceData := nil;
FCoreLocationManager.OnNewEddystoneTLM := nil;
FCoreLocationManager.OnNewEddystoneURL := nil;
FCoreLocationManager.OnNewBLEScanFilterEvent := nil;
end;
if FCommonManager <> nil then
begin
FCommonManager.OnBeaconEnter := DoiOSBeaconEnter;
FCommonManager.OnBeaconExit := DoiOSBeaconExit;
if Assigned(FOnBeaconProximity) then
FCommonManager.OnBeaconProximity := DoiOSBeaconChangedProximity
else
FCommonManager.OnBeaconProximity := nil;
FCommonManager.OnEnterRegion := DoiOSRegionEnter;
FCommonManager.OnExitRegion := DoiOSRegionExit;
FCommonManager.OnBeaconsEnterRegion := DoiOSBeaconsRegionEnter;
FCommonManager.OnBeaconsExitRegion := DoiOSBeaconsRegionExit;
FCommonManager.OnNewBLEScanFilterEvent := DoiOSNewBLEScanFilter;
if Assigned(FOnCalculateDistances) then
FCommonManager.OnCalculateDistances := DoiOSBeaconCalcDistance
else
begin
FCommonManager.OnCalculateDistances := nil;
if Assigned(FOnCalcDistance) then
FCommonManager.OnCalcDistance := DoiOSBeaconCalcDistance
else
FCommonManager.OnCalcDistance := nil;
end;
if Assigned(FOnParseManufacturerData) then
FCommonManager.OnParseManufacturerData := DoiOSParseManufacturerData
else
FCommonManager.OnParseManufacturerData := nil;
if Assigned(FOnParseServiceData) then
FCommonManager.OnParseServiceData := DoiOSParseServiceData
else
FCommonManager.OnParseServiceData := nil;
FCommonManager.OnNewEddystoneTLM := DoiOSNewEddystoneTLM;
FCommonManager.OnNewEddystoneURL := DoiOSNewEddystoneURL;
end;
end;
constructor TiOSBeaconManager.Create(AMode: TBeaconScanMode);
begin
FScanMode := AMode;
FCoreLocationManager := TiOSBeaconManagerCoreLocation.GetInstance(AMode);
FCommonManager := System.Beacon.Common.TPlatformBeaconManager.GetInstance(AMode);
CheckEvents;
FBeaconDeathTime := FCommonManager.BeaconDeathTime;
FSPC := FCommonManager.SPC;
FScanningTime := FCommonManager.ScanningTime;
FScanningSleepingTime := FCommonManager.ScanningSleepingTime;
FCalcMode := FCommonManager.CalcMode;
FScanMode := FCommonManager.ScanMode;
FBeaconType := FCommonManager.BeaconType;
end;
function TiOSBeaconManager.DoNearest: IBeacon;
var
LIBeacon: IBeacon;
begin
Result := nil;
if FCoreLocationManager <> nil then
LIBeacon := FCoreLocationManager.Nearest;
if FCommonManager <> nil then
Result := FCommonManager.Nearest;
if (LIBeacon <> nil) then
if (Result <> nil) then
begin
if LIBeacon.Distance < Result.Distance then
Result := LIBeacon;
end
else
Result := LIBeacon;
end;
function TiOSBeaconManager.DoRegisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon; AManufacturerId: Integer): Boolean;
begin
Result := False;
if (AKindofBeacon = TKindofBeacon.iBeacons) or (AKindofBeacon = TKindofBeacon.iBAltBeacons) then
begin
if FCoreLocationManager = nil then
FCoreLocationManager := TiOSBeaconManagerCoreLocation.GetInstance(FScanMode);
Result := FCoreLocationManager.RegisterBeacon(AGUID, AKindofBeacon);
if Result and IsScanning then
DoStartScan;
end;
if AKindofBeacon <> TKindofBeacon.iBeacons then
begin
if FCommonManager = nil then
FCommonManager := System.Beacon.Common.TPlatformBeaconManager.GetInstance(FScanMode);
Result := FCommonManager.RegisterBeacon(AGUID, AKindofBeacon);
end;
end;
function TiOSBeaconManager.DoRegisterBeacon(const AGUID: TGUID; Major: Word; const AKindofBeacon: TKindofBeacon;
AManufacturerId: Integer): Boolean;
begin
Result := False;
if (AKindofBeacon = TKindofBeacon.iBeacons) or (AKindofBeacon = TKindofBeacon.iBAltBeacons) then
begin
if FCoreLocationManager = nil then
FCoreLocationManager := TiOSBeaconManagerCoreLocation.GetInstance(FScanMode);
Result := FCoreLocationManager.RegisterBeacon(AGUID, Major, AKindofBeacon);
if Result and IsScanning then
DoStartScan;
end;
if AKindofBeacon <> TKindofBeacon.iBeacons then
begin
if FCommonManager = nil then
FCommonManager := System.Beacon.Common.TPlatformBeaconManager.GetInstance(FScanMode);
Result := FCommonManager.RegisterBeacon(AGUID, Major, AKindofBeacon);
end;
end;
function TiOSBeaconManager.DoRegisterBeacon(const AGUID: TGUID; Major, Minor: Word;
const AKindofBeacon: TKindofBeacon; AManufacturerId: Integer): Boolean;
begin
Result := False;
if (AKindofBeacon = TKindofBeacon.iBeacons) or (AKindofBeacon = TKindofBeacon.iBAltBeacons) then
begin
if FCoreLocationManager = nil then
FCoreLocationManager := TiOSBeaconManagerCoreLocation.GetInstance(FScanMode);
Result := FCoreLocationManager.RegisterBeacon(AGUID, Major, Minor, AKindofBeacon);
if Result and IsScanning then
DoStartScan;
end;
if AKindofBeacon <> TKindofBeacon.iBeacons then
begin
if FCommonManager = nil then
FCommonManager := System.Beacon.Common.TPlatformBeaconManager.GetInstance(FScanMode);
Result := FCommonManager.RegisterBeacon(AGUID, Major, Minor, AKindofBeacon);
end;
end;
function TiOSBeaconManager.DoRegisterEddyBeacon( const ANamespace: TNamespace): Boolean;
var
LBeaconsRegion: TBeaconsRegion;
begin
if FCommonManager = nil then
FCommonManager := System.Beacon.Common.TPlatformBeaconManager.GetInstance(FScanMode);
LBeaconsRegion.KindofBeacon := TKindofBeacon.Eddystones;
LBeaconsRegion.EddysUIDRegion.Initialize(ANamespace);
Result := FCommonManager.RegisterBeacons(LBeaconsRegion);
end;
function TiOSBeaconManager.DoRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean;
var
LBeaconsRegion: TBeaconsRegion;
begin
if FCommonManager = nil then
FCommonManager := System.Beacon.Common.TPlatformBeaconManager.GetInstance(FScanMode);
LBeaconsRegion.KindofBeacon := TKindofBeacon.Eddystones;
LBeaconsRegion.EddysUIDRegion.Initialize(ANamespace, AInstance);
Result := FCommonManager.RegisterBeacons(LBeaconsRegion);
end;
function TiOSBeaconManager.DoStartScan: Boolean;
function BeaconInLocation: Boolean;
begin
Result := False;
if FScanMode = TBeaconScanMode.Standard then
Exit(True);
if (FScanMode = TBeaconScanMode.Extended) and ((TKindofBeacon.iBeacons in KindofBeacons)
or (TKindofBeacon.iBAltBeacons in KindofBeacons)) then
Exit(True);
end;
function BeaconInCommon: Boolean;
begin
Result := False;
if (FScanMode = TBeaconScanMode.Alternative) or (FScanMode = TBeaconScanMode.Eddystone) then
Exit(True);
if (FScanMode = TBeaconScanMode.Extended) and ((TKindofBeacon.AltBeacons in KindofBeacons) or
(TKindofBeacon.Eddystones in KindofBeacons) or (TKindofBeacon.iBAltBeacons in KindofBeacons)) then
Exit(True);
end;
begin
CheckEvents;
Result := False;
FScanning := False;
if FCoreLocationManager <> nil then
if BeaconInLocation then
begin
FCoreLocationManager.CalcMode := FCalcMode;
FCoreLocationManager.KindofBeacons := FKindofBeacons;
Result := FCoreLocationManager.StartScan
end
else
if FCoreLocationManager.NumberofBeaconsRegistered = 0 then
FCoreLocationManager := nil;
if FCommonManager <> nil then
if BeaconInCommon then
begin
FCommonManager.CalcMode := FCalcMode;
FCommonManager.KindofBeacons := FKindofBeacons;
Result := FCommonManager.StartScan;
end
else
if FCommonManager.NumberofBeaconsRegistered = 0 then
FCommonManager := nil;
if (FScanMode = TBeaconScanMode.Extended) and (iBeacons in FKindofBeacons)
and ((FCoreLocationManager = nil) or (FCoreLocationManager.NumberofBeaconsRegistered = 0)) then
raise EBeaconManagerException.Create(SiOSiBeaconMustBeRegistered);
if (FScanMode <> TBeaconScanMode.Extended)
and ((FCommonManager = nil) or (FCommonManager.NumberofBeaconsRegistered = 0))
and ((FCoreLocationManager = nil) or (FCoreLocationManager.NumberofBeaconsRegistered = 0)) then
raise EBeaconManagerException.Create(SBeaconNoDeviceRegister);
if not Result then
begin
if FCommonManager <> nil then
FCommonManager.StopScan;
if FCoreLocationManager <> nil then
FCoreLocationManager.StopScan;
end
else
FScanning := True;
end;
function TiOSBeaconManager.DoStopScan: Boolean;
begin
Result := False;
if FCoreLocationManager <> nil then
Result := FCoreLocationManager.StopScan;
if FCommonManager <> nil then
Result := Result or FCommonManager.StopScan;
FScanning := False;
end;
function TiOSBeaconManager.DoUnregisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon): Boolean;
begin
Result := False;
if (FCoreLocationManager <> nil) and
((AKindofBeacon = TKindofBeacon.iBeacons) or (AKindofBeacon = TKindofBeacon.iBAltBeacons)) then
Result := FCoreLocationManager.UnRegisterBeacon(AGUID, AKindofBeacon);
if (FCommonManager <> nil) and (AKindofBeacon <> TKindofBeacon.iBeacons) then
Result := FCommonManager.UnRegisterBeacon(AGUID, AKindofBeacon);
end;
function TiOSBeaconManager.DoUnregisterBeacon(const AGUID: TGUID; Major: Word; const AKindofBeacon: TKindofBeacon): Boolean;
begin
Result := False;
if (FCoreLocationManager <> nil) and
((AKindofBeacon = TKindofBeacon.iBeacons) or (AKindofBeacon = TKindofBeacon.iBAltBeacons)) then
Result := FCoreLocationManager.UnRegisterBeacon(AGUID, Major, AKindofBeacon);
if (FCommonManager <> nil) and (AKindofBeacon <> TKindofBeacon.iBeacons) then
Result := FCommonManager.UnRegisterBeacon(AGUID, Major, AKindofBeacon);
end;
function TiOSBeaconManager.DoUnregisterBeacon(const AGUID: TGUID; Major, Minor: Word;
const AKindofBeacon: TKindofBeacon): Boolean;
begin
Result := False;
if (FCoreLocationManager <> nil) and
((AKindofBeacon = TKindofBeacon.iBeacons) or (AKindofBeacon = TKindofBeacon.iBAltBeacons)) then
Result := FCoreLocationManager.UnRegisterBeacon(AGUID, Major, Minor, AKindofBeacon);
if (FCommonManager <> nil) and (AKindofBeacon <> TKindofBeacon.iBeacons) then
Result := FCommonManager.UnRegisterBeacon(AGUID, Major, Minor, AKindofBeacon);
end;
function TiOSBeaconManager.DoUnRegisterEddyBeacon( const ANamespace: TNamespace): Boolean;
var
LBeaconsRegion: TBeaconsRegion;
begin
if (FCommonManager <> nil) then
begin
LBeaconsRegion.KindofBeacon := TKindofBeacon.Eddystones;
LBeaconsRegion.EddysUIDRegion.Initialize(ANamespace);
Result := FCommonManager.UnRegisterBeacons(LBeaconsRegion);
end
else
Result := False;
end;
function TiOSBeaconManager.DoUnRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean;
var
LBeaconsRegion: TBeaconsRegion;
begin
if (FCommonManager <> nil) then
begin
LBeaconsRegion.KindofBeacon := TKindofBeacon.Eddystones;
LBeaconsRegion.EddysUIDRegion.Initialize(ANamespace, AInstance);
Result := FCommonManager.UnRegisterBeacons(LBeaconsRegion);
end
else
Result := False;
end;
class function TiOSBeaconManager.GetInstance(AMode: TBeaconScanMode): TBeaconManager;
begin
Result := TiOSBeaconManager.Create(AMode);
end;
function TiOSBeaconManager.GeTKindofBeacons: TKindofBeacons;
begin
Result := FKindofBeacons;
end;
function TiOSBeaconManager.GetNumberofBeaconsRegistered: Integer;
begin
Result := 0;
if FCoreLocationManager <> nil then
Result := FCoreLocationManager.NumberofBeaconsRegistered;
if FCommonManager <> nil then
Result := Result + FCommonManager.NumberofBeaconsRegistered;
end;
procedure TiOSBeaconManager.SetBeaconDeathTime(AValue: Integer);
begin
if (FCommonManager <> nil) then
FCommonManager.BeaconDeathTime := AValue;
if (FCoreLocationManager <> nil) then
FCoreLocationManager.BeaconDeathTime := AValue;
FBeaconDeathTime := AValue;
end;
procedure TiOSBeaconManager.SetBeaconType(AValue: Word);
begin
if (FCommonManager <> nil) and (FCommonManager.BeaconType <> AValue) then
FCommonManager.BeaconType := AValue;
if (FCoreLocationManager <> nil) and (FCoreLocationManager.BeaconType <> AValue) then
FCoreLocationManager.BeaconType := AValue;
FBeaconType := AValue;
end;
procedure TiOSBeaconManager.DoSetKindofBeacons(AValue: TKindofBeacons);
begin
FKindofBeacons := AValue;
end;
procedure TiOSBeaconManager.SetScanningSleepingTime(AValue: Integer);
begin
if (FCommonManager <> nil) then
FCommonManager.ScanningSleepingTime := AValue;
if (FCoreLocationManager <> nil) then
FCoreLocationManager.ScanningSleepingTime := AValue;
FScanningSleepingTime := AValue;
end;
procedure TiOSBeaconManager.SetScanningTime(AValue: Integer);
begin
if (FCommonManager <> nil) then
FCommonManager.ScanningTime := AValue;
if (FCoreLocationManager <> nil) then
FCoreLocationManager.ScanningTime := AValue;
FScanningTime := AValue;
end;
procedure TiOSBeaconManager.SetSPC(AValue: Single);
begin
if (FCommonManager <> nil) then
FCommonManager.SPC := AValue;
if (FCoreLocationManager <> nil) then
FCoreLocationManager.SPC := AValue;
FSPC := AValue;
end;
{ TiOSBeaconManagerCoreLocation }
class constructor TiOSBeaconManagerCoreLocation.Create;
begin
DeathTime := KBEACONDEATHTIME;
end;
procedure TiOSBeaconManagerCoreLocation.UnRegisterBeacon(const AGUID: TGUID; Major, Minor: Integer; AKindofBeacon: TKindofBeacon);
var
LRegion: CLBeaconRegion;
LBeaconRegion: TBeaconRegion;
I: Integer;
begin
LBeaconRegion.Initialilize(AGUID, Major, Minor);
TMonitor.Enter(FRegisteredRegions);
try
I := FRegisteredRegions.Count - 1;
while I >= 0 do
begin
if FRegisteredRegions[I].IsRegion(AGUID, Major, Minor) then
begin
FRegisteredRegions.Delete(I);
Break;
end;
Dec(I);
end;
finally
TMonitor.Exit(FRegisteredRegions);
end;
LRegion := LBeaconRegion.GetRegion;
FLocationManager.stopMonitoringForRegion(LRegion);
FLocationManager.stopRangingBeaconsInRegion(LRegion);
RemoveBeaconsFromRegion(LBeaconRegion);
end;
function TiOSBeaconManagerCoreLocation.DoUnregisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon): Boolean;
begin
UnregisterBeacon(AGUID, MAJOR_REGION_ALL, MINOR_REGION_ALL, AKindofBeacon);
Result := True;
end;
function TiOSBeaconManagerCoreLocation.DoUnregisterBeacon(const AGUID: TGUID; Major: Word; const AKindofBeacon: TKindofBeacon): Boolean;
begin
UnregisterBeacon(AGUID, Major, MINOR_REGION_ALL, AKindofBeacon);
Result := True;
end;
function TiOSBeaconManagerCoreLocation.DoUnregisterBeacon(const AGUID: TGUID; Major, Minor: Word; const AKindofBeacon: TKindofBeacon): Boolean;
begin
UnRegisterBeacon(AGUID, Major, Minor, AKindofBeacon);
Result := True;
end;
function TiOSBeaconManagerCoreLocation.DoUnRegisterEddyBeacon(const ANamespace: TNamespace): Boolean;
begin
Result := False;
end;
function TiOSBeaconManagerCoreLocation.DoUnRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean;
begin
Result := False;
end;
class function TiOSBeaconManagerCoreLocation.GetInstance(AMode: TBeaconScanMode): TBeaconManager;
begin
Result := TiOSBeaconManagerCoreLocation.Create;
end;
function TiOSBeaconManagerCoreLocation.GeTKindofBeacons: TKindofBeacons;
begin
Result := FKindofBeacons;
end;
function TiOSBeaconManagerCoreLocation.GetNumberofBeaconsRegistered: Integer;
begin
if FRegisteredRegions <> nil then
Result := FRegisteredRegions.count
else
Result := 0;
end;
procedure TiOSBeaconManagerCoreLocation.CheckBeaconListSanity;
var
I: Integer;
LRemovedBeacon: IBeacon;
J: Integer;
begin
TMonitor.Enter(FLockObject);
try
I := FCurrentBeaconCount - 1;
while I >= 0 do
begin
if not FCurrentBeaconList[I].ItsAlive then
begin
LRemovedBeacon := FCurrentBeaconList[I];
for J := I to FCurrentBeaconCount - 2 do
FCurrentBeaconList[J] := FCurrentBeaconList[J + 1];
Dec(FCurrentBeaconCount);
SetLength(FCurrentBeaconList, FCurrentBeaconCount);
DoBeaconExit(LRemovedBeacon, FCurrentBeaconList);
CheckExitRegion(LRemovedBeacon);
end;
Dec(I);
end;
finally
TMonitor.Exit(FLockObject);
end;
end;
procedure TiOSBeaconManagerCoreLocation.DoEnterExitRegion(RegionIndex: Integer; Enter: Boolean);
var
LRegion: TBeaconRegion;
LsRegion: TBeaconsRegion;
begin
LRegion := FRegisteredRegions[RegionIndex];
LRegion.Inside := Enter;
FRegisteredRegions[RegionIndex] := LRegion;
LsRegion.KindofBeacon := TKindofBeacon.iBeacons;
LsRegion.iBAltBeaconRegion.Initialize(LRegion.GUID, LRegion.Major, LRegion.Minor, TKindofBeacon.iBeacons, APPLEINC);
if Enter then
begin
DoBeaconsRegionEnter(LsRegion);
DoRegionEnter(LRegion.GUID, LRegion.Major, LRegion.Minor)
end
else
begin
DoBeaconsRegionExit(LsRegion);
DoRegionExit(LRegion.GUID, LRegion.Major, LRegion.Minor);
end;
end;
procedure TiOSBeaconManagerCoreLocation.CheckEnterRegion(const ANewBeacon: IBeacon);
var
I: Integer;
begin
TMonitor.Enter(FRegisteredRegions);
try
if ANewBeacon <> nil then // check if we entered in a new region
begin
for I := 0 to FRegisteredRegions.Count - 1 do
if FRegisteredRegions[I].BeaconBelongs(ANewBeacon) then
begin
if not FRegisteredRegions[I].Inside then
DoEnterExitRegion(I, True);
Break;
end;
end;
finally
TMonitor.Exit(FRegisteredRegions);
end;
end;
procedure TiOSBeaconManagerCoreLocation.CheckExitRegion(const AExitedBeacon: IBeacon);
var
I, J: Integer;
LStillInside: Boolean;
begin
TMonitor.Enter(FRegisteredRegions);
try
for I := 0 to FRegisteredRegions.Count - 1 do
begin
if FRegisteredRegions[I].Inside and FRegisteredRegions[I].BeaconBelongs(AExitedBeacon) then
begin
LStillInside := False;
for J := 0 to FCurrentBeaconCount - 1 do
begin
if FCurrentBeaconList[J] <> AExitedBeacon then
LStillInside := FRegisteredRegions[I].BeaconBelongs(FCurrentBeaconList[J]);
if LStillInside then
Break;
end;
if not LStillInside then
begin
DoEnterExitRegion(I, False);
Break;
end;
end;
end;
finally
TMonitor.Exit(FRegisteredRegions);
end;
end;
constructor TiOSBeaconManagerCoreLocation.Create;
begin
inherited;
FLocationManager := TCLLocationManager.Create;
// SetAllowBackgroundUpdates;
FLocationDelegate := TBeaconLocationManagerDelegate.Create;
FLocationManager.setDelegate((FLocationDelegate as ILocalObject).GetObjectID );
if CheckOSVersion then
FLocationManager.requestWhenInUseAuthorization;
TBeaconLocationManagerDelegate(FLocationDelegate).FEnterRegionCallback := EnterRegion;
TBeaconLocationManagerDelegate(FLocationDelegate).FExitRegionCallback := ExitRegion;
TBeaconLocationManagerDelegate(FLocationDelegate).FRangeBeaconCallback := RangeBeacon;
TBeaconLocationManagerDelegate(FLocationDelegate).FAutorizationChangeCallback := AutorizationChange;
FRegisteredRegions := TList<TBeaconRegion>.Create;
FLockObject := TObject.Create;
FScanMode := TBeaconScanMode.Standard;
FBeaconType := BEACON_ST_TYPE;
FSPC := SIGNAL_PROPAGATION_CONSTANT;
FScanningTime := SCANNING_TIME;
FScanningSleepingTime := SCANNING_SLEEPINGTIME;
CalcMode := TBeaconCalcMode.Stabilized;
FRssiAccumulatedDiff := ACCUMMULATE_DIFF_START_VALUE;
FBeaconDeathTime := KBEACONDEATHTIME;
end;
destructor TiOSBeaconManagerCoreLocation.Destroy;
begin
FLocationManager.setDelegate(nil);
FRegisteredRegions.Free;
FLockObject.Free;
inherited;
end;
function TiOSBeaconManagerCoreLocation.DoNearest: IBeacon;
var
I: Integer;
LNearestDistance: Double;
begin
Result := nil;
if FCurrentBeaconCount > 0 then
begin
LNearestDistance := FCurrentBeaconList[0].Distance;
Result := FCurrentBeaconList[0];
for I := 1 to FCurrentBeaconCount - 1 do
begin
if LNearestDistance > FCurrentBeaconList[I].Distance then
begin
LNearestDistance := FCurrentBeaconList[I].Distance;
Result := FCurrentBeaconList[I];
end;
end;
end;
end;
function TiOSBeaconManagerCoreLocation.IsMonitoringAvailable: Boolean;
var
ACLClass: Pointer;
begin
Result := True;
ACLClass := objc_getClass('CLBeaconRegion'); // do not localize
if ACLClass <> nil then
Result := TCLLocationManager.OCClass.isMonitoringAvailableForClass(ACLClass);
end;
procedure TiOSBeaconManagerCoreLocation.AutorizationChange(ACode: NativeUInt);
begin
if ACode in [kCLAuthorizationStatusRestricted, kCLAuthorizationStatusDenied] then
raise EBeaconManagerException.Create(SNotAllowedLocationServices);
end;
procedure TiOSBeaconManagerCoreLocation.EnterRegion(const UUID: TGUID; Major, Minor: Integer);
var
I: Integer;
begin
TMonitor.Enter(FRegisteredRegions);
try
for I := 0 to FRegisteredRegions.Count - 1 do
if not FRegisteredRegions[I].Inside and FRegisteredRegions[I].IsRegion(UUID, Major, Minor) then
begin
DoEnterExitRegion(I, True);
Break;
end;
finally
TMonitor.Exit(FRegisteredRegions);
end;
end;
procedure TiOSBeaconManagerCoreLocation.RangeBeacon(const ACLBeacon: CLBeacon);
var
LNewBeacon: TiOSBeacon;
I: Integer;
LFound: Boolean;
LUUID: string;
LMajor: Word;
LMinor: Word;
LOldProximity: TBeaconProximity;
LRSSIDiff: Integer;
LiIBeacon: IiBeacon;
begin
LFound := False;
if ACLBeacon <> nil then
begin
LUUID := '{' + NSStrToStr(ACLBeacon.proximityUUID.UUIDString) + '}';
LMajor := ACLBeacon.major.unsignedShortValue;
LMinor := ACLBeacon.minor.unsignedShortValue;
TMonitor.Enter(FLockObject);
try
for I := 0 to FCurrentBeaconCount - 1 do
begin
if FCurrentBeaconList[I].IsEqualTo(TGUID.Create(LUUID), LMajor, LMinor) then
begin
LRSSIDiff := Abs(FCurrentBeaconList[I].Rssi - ACLBeacon.rssi);
if (FCurrentBeaconCount > 0) then
FRssiAccumulatedDiff := ((FRssiAccumulatedDiff / FCurrentBeaconCount) * (FCurrentBeaconCount - 1)) + LRSSIDiff / FCurrentBeaconCount;
LOldProximity := TiOSBeacon(FCurrentBeaconList[I]).GetProximity;
TiOSBeacon(FCurrentBeaconList[I]).SetBeaconInfo(ACLBeacon, FRssiAccumulatedDiff >= DIFFERENTIAL_FILTER_BOUNDARY);
if FCurrentBeaconList[I].GetProximity <> LOldProximity then
DoBeaconChangedProximity(FCurrentBeaconList[I], FCurrentBeaconList[I].GetProximity);
LFound := True;
Break;
end;
end;
if (not LFound) and (ACLBeacon.rssi <> 0) then
begin
LNewBeacon := TiOSBeacon.Create(CalcMode);
LNewBeacon.FCalcDistance := DoBeaconCalcDistance;
LNewBeacon.FCalcDistances := DoBeaconCalcDistance;
LNewBeacon.SetBeaconInfo(ACLBeacon, False);
FCurrentBeaconCount := Length(FCurrentBeaconList) + 1;
SetLength(FCurrentBeaconList, FCurrentBeaconCount);
if Supports(LNewBeacon, IiBeacon, LiIBeacon) then
begin
FCurrentBeaconList[FCurrentBeaconCount - 1] := LiIBeacon;
CheckEnterRegion(LiIBeacon);
DoBeaconEnter(LiIBeacon, FCurrentBeaconList);
end;
end;
finally
TMonitor.Exit(FLockObject);
end;
end;
CheckBeaconListSanity;
end;
procedure TiOSBeaconManagerCoreLocation.RemoveBeaconsFromRegion(const ARegion: TBeaconRegion);
var
I,J: Integer;
LRemovedBeacon: IBeacon;
begin
TMonitor.Enter(FLockObject);
try
I := FCurrentBeaconCount - 1;
while I >= 0 do
begin
if ARegion.BeaconBelongs(FCurrentBeaconList[I]) then
begin
LRemovedBeacon := FCurrentBeaconList[I];
for J := I to FCurrentBeaconCount - 2 do
FCurrentBeaconList[J] := FCurrentBeaconList[J + 1];
Dec(FCurrentBeaconCount);
SetLength(FCurrentBeaconList, FCurrentBeaconCount);
DoBeaconExit(LRemovedBeacon, FCurrentBeaconList);
end;
Dec(I);
end;
finally
TMonitor.Exit(FLockObject);
end;
end;
procedure TiOSBeaconManagerCoreLocation.SetBeaconType(AValue: Word);
begin
raise EBeaconManagerException.Create(SCannotChangeBeaconType);
end;
procedure TiOSBeaconManagerCoreLocation.DoSetKindofBeacons(AValue: TKindofBeacons);
begin
FKindofBeacons := AValue;
end;
procedure TiOSBeaconManagerCoreLocation.ExitRegion(const UUID: TGUID; Major, Minor: Integer);
var
LRegion: TBeaconRegion;
I: Integer;
begin
LRegion.Initialilize(UUID, Major, Minor);
RemoveBeaconsFromRegion(LRegion);
TMonitor.Enter(FRegisteredRegions);
try
for I := 0 to FRegisteredRegions.Count - 1 do
if FRegisteredRegions[I].Inside and FRegisteredRegions[I].IsRegion(UUID, Major, Minor) then
begin
DoEnterExitRegion(I, False);
Break;
end;
finally
TMonitor.Exit(FRegisteredRegions);
end;
end;
function TiOSBeaconManagerCoreLocation.AddRegionToList(const ARegion: TBeaconRegion):Boolean;
var
I: Integer;
begin
TMonitor.Enter(FRegisteredRegions);
try
I := FRegisteredRegions.Count - 1;
while I > 0 do
begin
if FRegisteredRegions[I].GUID = ARegion.GUID then
begin
FLocationManager.stopMonitoringForRegion(FRegisteredRegions[I].GetRegion);
FLocationManager.stopRangingBeaconsInRegion(FRegisteredRegions[I].GetRegion);
FRegisteredRegions.Delete(I);
Break;
end;
Dec(I);
end;
FRegisteredRegions.Add(ARegion);
finally
TMonitor.Exit(FRegisteredRegions);
Result := True;
end;
end;
//procedure TiOSBeaconManagerCoreLocation.SetAllowBackgroundUpdates;
//var
// LBundle: NSBundle;
// LBackModes: Pointer;
// LModes: NSArray;
// I: Integer;
//begin
// if (FLocationManager <> nil) and TOSVersion.Check(9) then
// begin
// LBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle);
// LBackModes := LBundle.infoDictionary.valueForKey(StrToNSStr('UIBackgroundModes'));
// if LBackModes <> nil then
// begin
// LModes := TNSArray.Wrap(LBackModes);
// for I := 0 to LModes.count - 1 do
// if NSStrToStr(TNSString.Wrap(LModes.objectAtIndex(I))) = 'location' then
// begin
// FLocationManager.setAllowsBackgroundLocationUpdates(True);
// Break;
// end;
// end;
// end;
//end;
function TiOSBeaconManagerCoreLocation.DoRegisterBeacon(const AGUID: TGUID; const AKindofBeacon: TKindofBeacon; AManufacturerId: Integer): Boolean;
begin
Result := RegisterBeacon(AGUID, MAJOR_REGION_ALL, MINOR_REGION_ALL, AKindofBeacon);
end;
function TiOSBeaconManagerCoreLocation.DoRegisterBeacon(const AGUID: TGUID; Major: Word; const AKindofBeacon: TKindofBeacon;
AManufacturerId: Integer): Boolean;
begin
Result := RegisterBeacon(AGUID, Major, MINOR_REGION_ALL, AKindofBeacon);
end;
function TiOSBeaconManagerCoreLocation.DoRegisterBeacon(const AGUID: TGUID; Major, Minor: Word; const AKindofBeacon: TKindofBeacon;
AManufacturerId: Integer): Boolean;
begin
Result := RegisterBeacon(AGUID, Major, Minor, AKindofBeacon);
end;
function TiOSBeaconManagerCoreLocation.DoRegisterEddyBeacon(const ANamespace: TNamespace): Boolean;
begin
Result := False;
end;
function TiOSBeaconManagerCoreLocation.DoRegisterEddyBeacon(const ANamespace: TNamespace; const AInstance: TInstance): Boolean;
begin
Result := False;
end;
function TiOSBeaconManagerCoreLocation.DoStartScan: Boolean;
var
LBeaconIdentifier: TBeaconRegion;
begin
if IsMonitoringAvailable then
begin
TMonitor.Enter(FRegisteredRegions);
try
for LBeaconIdentifier in FRegisteredRegions do
begin
FLocationManager.startMonitoringForRegion(LBeaconIdentifier.GetRegion);
FLocationManager.startRangingBeaconsInRegion(LBeaconIdentifier.GetRegion);
end;
Result := True;
finally
TMonitor.Exit(FRegisteredRegions);
end;
end
else
raise EBeaconManagerException.Create(SMonitoringNotAvailable);
end;
function TiOSBeaconManagerCoreLocation.DoStopScan: Boolean;
var
LBeaconRegion: TBeaconRegion;
LRegion: CLBeaconRegion;
begin
Result := False;
if IsMonitoringAvailable then
begin
TMonitor.Enter(FRegisteredRegions);
try
if FLocationManager.monitoredRegions.count > 0 then
Result := True;
for LBeaconRegion in FRegisteredRegions do
begin
LRegion := LBeaconRegion.GetRegion;
FLocationManager.stopMonitoringForRegion(LRegion);
FLocationManager.stopRangingBeaconsInRegion(LRegion);
end;
finally
TMonitor.Exit(FRegisteredRegions);
end;
end;
end;
procedure TiOSBeaconManagerCoreLocation.SetBeaconDeathTime(AValue: Integer);
begin
FBeaconDeathTime := AValue;
TiOSBeaconManagerCoreLocation.DeathTime := FBeaconDeathTime;
end;
procedure TiOSBeaconManagerCoreLocation.SetScanningSleepingTime(AValue: Integer);
begin
FScanningSleepingTime := AValue;
end;
procedure TiOSBeaconManagerCoreLocation.SetScanningTime(AValue: Integer);
begin
FScanningTime := AValue;
end;
procedure TiOSBeaconManagerCoreLocation.SetSPC(AValue: Single);
begin
FSPC := AValue;
end;
{ TBeaconIdentifier }
function TBeaconRegion.GetRegion: CLBeaconRegion;
var
LGUID: string;
LNSUUID: NSUUID;
LIniGUID: string;
begin
LIniGUID := GUID.ToString;
LGUID := Copy(LIniGUID, 2, Length(LIniGUID) - 2);
LNSUUID := TNSUUID.Alloc.initWithUUIDString(StrToNSStr(LGUID));
if (Major = MAJOR_REGION_ALL) and (Minor = MINOR_REGION_ALL) then
Result := TCLBeaconRegion.Wrap(TCLBeaconRegion.Alloc.initWithProximityUUIDIdentifier(LNSUUID, StrToNSStr(LIniGUID)))
else if (Major <> MAJOR_REGION_ALL) and (Minor = MINOR_REGION_ALL) then
Result := TCLBeaconRegion.Wrap(TCLBeaconRegion.Alloc.initWithProximityUUIDMajorIdentifier(LNSUUID, Major, StrToNSStr(LIniGUID)))
else
Result := TCLBeaconRegion.Wrap(TCLBeaconRegion.Alloc.initWithProximityUUIDMajorMinorIdentifier(LNSUUID, Major, Minor, StrToNSStr(LIniGUID)))
end;
procedure TBeaconRegion.Initialilize(const AGUID: TGUID; AMajor, AMinor: Integer);
begin
GUID := AGUID;
Major := AMajor;
Minor := AMinor;
Inside := False;
end;
function TBeaconRegion.BeaconBelongs(const ABeacon: IBeacon): Boolean;
begin
Result := (ABeacon.GUID = GUID) and ((ABeacon.Major = Major) or (Major = MAJOR_REGION_ALL)) and
((ABeacon.Minor = Minor) or (Minor = MINOR_REGION_ALL));
end;
function TBeaconRegion.IsRegion(const AGUID: TGUID; AMajor: Integer; AMinor: Integer): Boolean;
begin
Result := (AGUID = GUID) and (AMajor = Major) and (AMinor = Minor);
end;
{ TIOsBeacon }
constructor TiOSBeacon.Create(AMode: TBeaconCalcMode);
begin
inherited Create;
FLastUpdateTime := Now;
FProximity := TMeanCalculator<Integer>.Create(ProximityMeanItems);
FDistance := TMeanCalculator<Double>.Create(DistanceMeanItems);
FCalcMode := AMode;
end;
function TiOSBeacon.GetDeviceIdentifier: string;
begin
Result := '';
end;
function TiOSBeacon.GetDistance: Double;
begin
Result := System.Math.RoundTo(FCalculatedDistance, DISTANCE_DECIMALS);
end;
function TiOSBeacon.GetEddystoneBeacon: TEddystoneBeaconInfo;
begin
Result := FEddystoneBeacon;
end;
function TiOSBeacon.GetGUID: TGUID;
begin
Result := FGUID;
end;
function TiOSBeacon.GetKindofBeacon: TKindofBeacon;
begin
Result := FKindofBeacon;
end;
function TiOSBeacon.GetMajor: Word;
begin
Result := FMajor;
end;
function TiOSBeacon.GetMinor: Word;
begin
Result := FMinor;
end;
function TiOSBeacon.GetProximity: TBeaconProximity;
begin
if FCalcMode = TBeaconCalcMode.Raw then
Result := TBeaconProximity(FProximity.GetLast)
else
Result := TBeaconProximity(FProximity.Get);
end;
function TiOSBeacon.GetAdditionalData: TBytes;
begin
SetLength(Result, 0);
end;
function TiOSBeacon.GetRssi: Integer;
begin
Result := FRssi;
end;
function TiOSBeacon.IsEqualTo(const AGUID: TGUID; AMajor,AMinor: Word): Boolean;
begin
Result := (GetMinor = AMinor) and (GetMajor = AMajor) and (GetGUID = AGUID);
end;
function TiOSBeacon.IsEqualTo(const ANamespace: TNamespace; const AInstance: TInstance): Boolean;
begin // iOS Core Location just plays iBeacon
Result := False;
end;
function TiOSBeacon.IsEqualTo(const AIBeacon: IBeacon): Boolean;
begin
if (AIBeacon.KindofBeacon = TKindofBeacon.iBeacons) then
Result := IsEqualTo(AIBeacon.GUID, AIBeacon.Major, AIBeacon.Minor)
else
Result := False;
end;
function TiOSBeacon.ItsAlive: Boolean;
begin
Result := SecondsBetween(now, FLastUpdateTime) < TiOSBeaconManagerCoreLocation.DeathTime;
end;
procedure TiOSBeacon.SetBeaconInfo(const ABeacon: CLBeacon; IsMoving: Boolean);
var
LDistance: Double;
begin
FKindofBeacon := TKindofBeacon.iBeacons;
FGUID := TGUID.Create('{' + NSStrToStr(ABeacon.proximityUUID.UUIDString) + '}');
if ABeacon.minor <> nil then
FMinor := ABeacon.minor.unsignedShortValue;
if ABeacon.major <> nil then
FMajor := ABeacon.major.unsignedShortValue;
if Abeacon.rssi <> 0 then
FRssi := ShortInt(Abeacon.rssi);
if (Assigned(FCalcDistances) and FCalcDistances(IiBeacon(Self), TXPOWER_IDETERMINATED, FRssi, LDistance))
or (Assigned(FCalcDistance) and FCalcDistance(FGUID, FMajor, FMinor, TXPOWER_IDETERMINATED, FRssi, LDistance)) then
begin
FCalcMode := TBeaconCalcMode.Raw;
FCalculatedDistance := LDistance;
FProximity.AddGetValue(GetOwnCalcProximity(FCalculatedDistance), IsMoving);
end
else
begin
FProximity.AddGetValue(Integer(CLProximityToTProximity(ABeacon.proximity)), IsMoving);
LDistance := ABeacon.accuracy;
if FCalcMode = TBeaconCalcMode.Stabilized then
LDistance := FDistance.AddGetValue(LDistance, IsMoving);
FCalculatedDistance := LDistance;
end;
FLastUpdateTime := Now;
end;
function TiOSBeaconManagerCoreLocation.RegisterBeacon(const AGUID: TGUID; Major, Minor: Integer; AKindofBeacon: TKindofBeacon): Boolean;
var
LBeaconRegion: TBeaconRegion;
begin
Result := False;
if IsMonitoringAvailable then
begin
LBeaconRegion.Initialilize(AGUID, Major, Minor);
Result := AddRegionToList(LBeaconRegion);
end;
end;
{ TPlatformBeaconManager }
class function TPlatformBeaconManager.GetInstance(AMode: TBeaconScanMode): TBeaconManager;
begin
Result := TiOSBeaconManager.GetInstance(AMode);
end;
end.
|
unit ncsFrmRecuperaReg;
interface
uses
Windows, ncErros, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLabel, cxControls, cxContainer, cxEdit, cxTextEdit, StdCtrls,
cxRadioGroup, Menus, cxLookAndFeelPainters, cxButtons, cxGraphics,
cxLookAndFeels;
type
TFrmRecReg = class(TForm)
rbEmail: TcxRadioButton;
rbComputador: TcxRadioButton;
Label1: TLabel;
edEmail: TcxTextEdit;
cxLabel1: TcxLabel;
btnCancelar: TcxButton;
btnOk: TcxButton;
procedure btnOkClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmRecReg: TFrmRecReg;
implementation
uses ncServAtualizaLic, uLicEXECryptor;
{$R *.dfm}
procedure TFrmRecReg.btnOkClick(Sender: TObject);
var
dmLic: TdmAtualizaLic;
S: String;
begin
if rbEmail.Checked then begin
if Trim(edEmail.Text)='' then
raise ENexCafe.Create('É necessário informar o seu endereço de e-mail');
dmLic := TdmAtualizaLic.Create(Self);
try
if dmLic.ObtemContaPorEmail(Trim(edEmail.Text)) then begin
ShowMessage('As informações de registros foram enviadas para o e-mail informado');
ShowMessage('Caso não receba o e-mail em sua caixa de entrada confira se não está em sua caixa de SPAM ou Lixo Eletrônico');
end else
raise ENexCafe.create('Não foi encontrado um registro de loja com o e-mail informado');
finally
dmLic.Free;
end;
end else begin
dmLic := TdmAtualizaLic.Create(Self);
try
S := RegistroGlobal.GetCodEquip(RegistroGlobal.GetSerialHD);
S := dmLic.ObtemContaPorEquip(S);
if S>'' then begin
ShowMessage('As informações de registros foram enviadas para: '+sLineBreak+sLineBreak+S);
ShowMessage('Caso não receba o e-mail em sua caixa de entrada confira se não está em sua caixa de SPAM ou Lixo Eletrônico');
end else
raise ENexCafe.create('Não foi encontrado um registro anterior do NexCafé para esse computador');
finally
dmLic.Free;
end;
end;
Close;
end;
procedure TFrmRecReg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
end.
|
unit ansi_from_unicode_2;
interface
implementation
var
SA: AnsiString;
SU: string;
procedure Test;
begin
SU := 'hello_ansi';
SA := SU;
end;
initialization
Test();
finalization
Assert(SA = 'hello_ansi');
end. |
(* udir.pas -- (c) 1990 by Tom Swan *)
unit udir;
interface
uses dos, ulist, uselect;
type
fileNameStr = string[12]; { e.g. '*.PAS' or 'MYFILE.TXT' }
fileItemPtr = ^fileItem;
fileItem = object( selectableItem )
constructor init( sr : searchRec );
end; { fileItem }
directory = object( selectionList )
sr : searchRec; { From the DOS unit }
wildCard : fileNameStr;
constructor init( wc : fileNameStr; x1, y1, x2, y2 : word );
procedure resetDirectory; virtual;
procedure putWildCard( wc : fileNameStr );
end; { directory }
implementation
{ ----- Initialize fileItem object. }
constructor fileItem.init( sr : searchRec );
var
junk : dirStr; { Required by fSplit(); ignored }
fileName : nameStr; { File name without extension }
fileExt : extStr; { File name extension with leading '.' }
begin
fSplit( sr.name, junk, fileName, fileExt ); { Parse file name }
selectableItem.init( fileName + fileExt, TRUE ) { Init ancestor }
end; { fileItem.init }
{ ----- Initialize directory object. }
constructor directory.init( wc : fileNameStr; x1, y1, x2, y2 : word );
begin
selectionList.init( x1, y1, x2, y2 );
putWildCard( wc ) { Assign wild card and read directory }
end; { directory.init }
{ ----- Reread current directory. }
procedure directory.resetDirectory;
begin
disposeList; { Dispose an existing directory list }
findFirst( wildCard, 0, sr );
while dosError = 0 do
begin
insertItem( new( fileItemPtr, init( sr ) ) );
findNext( sr )
end
end; { directory.resetDirectory }
{ ----- Change wild card specification. }
procedure directory.putWildCard( wc : fileNameStr );
begin
wildCard := wc;
resetDirectory
end; { directory.putWildCard }
end. { udir }
|
unit MediaProcessing.Convertor.HHAU.PCM;
interface
uses SysUtils,Windows,Classes,MediaProcessing.Definitions,MediaProcessing.Global;
type
TMediaProcessor_Convertor_HhAu_Pcm=class (TMediaProcessor,IMediaProcessor_Convertor_HhAu_Pcm)
protected
protected
procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override;
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
class function MetaInfo:TMediaProcessorInfo; override;
public
constructor Create; override;
destructor Destroy; override;
function HasCustomProperties: boolean; override;
procedure ShowCustomProperiesDialog;override;
end;
implementation
uses Controls,uBaseClasses,MediaProcessing.Convertor.HHAU.PCM.SettingsDialog;
{ TMediaProcessor_Convertor_HhAu_Pcm }
constructor TMediaProcessor_Convertor_HhAu_Pcm.Create;
begin
inherited;
end;
destructor TMediaProcessor_Convertor_HhAu_Pcm.Destroy;
begin
inherited;
end;
function TMediaProcessor_Convertor_HhAu_Pcm.HasCustomProperties: boolean;
begin
result:=true;
end;
class function TMediaProcessor_Convertor_HhAu_Pcm.MetaInfo: TMediaProcessorInfo;
begin
result.Clear;
result.TypeID:=IMediaProcessor_Convertor_HhAu_Pcm;
result.Name:='Конвертор HH->PCM';
result.Description:='Преобразует аудиокадры формата HH (камеры Beward) в формат PCM';
result.SetInputStreamType(stHHAU);
result.OutputStreamType:=stPCM;
result.ConsumingLevel:=9;
end;
procedure TMediaProcessor_Convertor_HhAu_Pcm.LoadCustomProperties(const aReader: IPropertiesReader);
begin
inherited;
end;
procedure TMediaProcessor_Convertor_HhAu_Pcm.SaveCustomProperties(const aWriter: IPropertiesWriter);
begin
inherited;
end;
procedure TMediaProcessor_Convertor_HhAu_Pcm.ShowCustomProperiesDialog;
var
aDialog: TfmMediaProcessingSettingsHhAu_Pcm;
begin
aDialog:=TfmMediaProcessingSettingsHhAu_Pcm.Create(nil);
try
if aDialog.ShowModal=mrOK then
begin
end;
finally
aDialog.Free;
end;
end;
initialization
MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Convertor_HhAu_Pcm);
end.
|
unit UnitFilesManager;
interface
uses
Windows, ShellAPI, ShlObj, ThreadUnit, UnitConstants, UnitVariables, UnitFunctions,
UnitConnection, StreamUnit;
type
TSearchFileThread = class(TThread)
private
StartDir, FileMask: string;
SubDir: Boolean;
protected
procedure Execute; override;
public
constructor Create(xStartDir, xFileMask: string; xSubDir: Boolean);
end;
var
SearchFileThread: TSearchFileThread;
StopSearching: Boolean;
function DeleteAllFilesAndDir(FilesOrDir: string): Boolean;
function ListDirectory(Path: string; DirOnly: Boolean): string;
function MyRenameFile_Dir(oldPath, NewPath : string): Boolean;
function CopyDirectory(const Hwd : LongWord; const SourcePath, DestPath : string): boolean;
function ListSpecialFolders: string;
function ListDrives: string;
function ListSharedFolders: string;
implementation
var
SearchResults: string;
function ListSpecialFolders: string;
var
i: Integer;
TmpStr: string;
begin
for i := 0 to 48 do
begin
TmpStr := GetSpecialFolder(i);
if TmpStr <> '' then Result := Result + TmpStr + '|';
end;
end;
function DriveVolumeName(Drive: widestring): widestring;
var
FSSysFlags,maxCmpLen: DWord;
pFileSystem: PWideChar;
pVolName: PWideChar;
begin
GetMem(pVolName, MAX_PATH);
ZeroMemory(pVolName, MAX_PATH);
GetVolumeInformationW(PWideChar(Drive), pVolName, MAX_PATH, nil, maxCmpLen, FSSysFlags, nil, 0);
result := (pVolName);
FreeMem(pVolName, MAX_PATH);
end;
function DriveAttrib(Drive: widestring): widestring;
var
FSSysFlags, maxCmpLen: DWord;
pFSBuf: PWideChar;
begin
GetMem(pFSBuf, MAX_PATH);
ZeroMemory(pFSBuf, MAX_PATH);
GetVolumeInformationW(pWidechar(Drive), nil, 0, nil, maxCmpLen, FSSysFlags, pFSBuf, MAX_PATH);
result := (pFSBuf);
FreeMem(pFSBuf, MAX_PATH);
end;
function GetDiskFreeSpaceEx(Directory: PWideChar; var FreeAvailable,
TotalSpace: TLargeInteger; TotalFree: PLargeInteger): Bool; stdcall;
var
SectorsPerCluster, BytesPerSector, FreeClusters, TotalClusters: LongWord;
Temp: Int64;
Dir: PWideChar;
begin
if Directory <> nil then Dir := Directory else Dir := nil;
Result := GetDiskFreeSpaceW(Dir, SectorsPerCluster, BytesPerSector,
FreeClusters, TotalClusters);
Temp := SectorsPerCluster * BytesPerSector;
FreeAvailable := Temp * FreeClusters;
TotalSpace := Temp * TotalClusters;
end;
function DriveType(Drive: PWideChar): WideString;
begin
case GetDriveTypeW(Drive) of
DRIVE_REMOVABLE: Result := 'Removable';
DRIVE_FIXED: Result := 'Fixed';
DRIVE_REMOTE: Result := 'Remote';
DRIVE_CDROM: Result := 'CDROM';
else
Result := 'Unknown';
end;
end;
function MyGetLogicalDriveStringsW(nBufferLength: DWORD;
lpBuffer: PWideChar): DWORD; stdcall; external 'kernel32.dll' name 'GetLogicalDriveStringsW';
function ListDrives: string;
var
pDrive, Drive: PWideChar;
dName, dAttrib, dType: WideString;
TmpSize, FreeSize, TotalSize: Int64;
begin
GetMem(Drive, 10000);
MyGetLogicalDriveStringsW(10000, Drive);
pDrive := Drive;
while pDrive^ <> #0 do
begin
dType := DriveType(pDrive);
dName := DriveVolumeName(pDrive);
if dName = '' then dName := 'Unknown';
dAttrib := DriveAttrib(pDrive);
TmpSize := 0;
Totalsize := 0;
Freesize := 0;
GetDiskFreeSpaceEx(pDrive, TmpSize, Totalsize, @Freesize);
Result := Result + pDrive + '|';
Result := Result + dType + '|';
Result := Result + dName + '|';
Result := Result + dAttrib + '|';
Result := Result + ByteSize(TotalSize) + '|';
Result := Result + ByteSize(TmpSize) + '|' + #13#10;
Inc(pDrive, 4);
end;
end;
function EnumFuncLAN(NetResource: PNetResource): string;
var
Enum: THandle;
Count, BufferSize: DWORD;
Buffer: array[0..16384 div SizeOf(TNetResource)] of TNetResource;
i: Integer;
begin
Result := '';
if WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, NetResource, Enum) = NO_ERROR then
try
Count := $FFFFFFFF;
BufferSize := SizeOf(Buffer);
while WNetEnumResource(Enum, Count, @Buffer, BufferSize) = NO_ERROR do
for i := 0 to Count - 1 do
begin
if Buffer[i].dwType = RESOURCETYPE_DISK then
Result := Result + Buffer[i].lpRemoteName + '|';
if (Buffer[i].dwUsage and RESOURCEUSAGE_CONTAINER) > 0 then
Result := Result + EnumFuncLan(@Buffer[i]);
end;
finally
WNetCloseEnum(Enum);
end;
end;
function ListSharedFolders: string;
begin
Result := EnumFuncLAN(nil);
end;
function ListDirectory(Path: string; DirOnly: Boolean): string;
var
DirList, FilesList: string;
DirStream, FilesStream: TMemoryStream;
FindData: TWin32FindData;
hFind: THandle;
begin
DirList := '';
FilesList := '';
if Path = '' then Exit;
if Path[Length(Path)] <> '\' then Path := Path + '\';
Path := Path + '*.*';
DirStream := TMemoryStream.Create;
FilesStream := TMemoryStream.Create;
hFind := FindFirstFile(PChar(Path), FindData);
if hFind = INVALID_HANDLE_VALUE then Exit;
if FindData.dwFileAttributes and $00000010 <> 0 then
DirStream.WriteBuffer(FindData, SizeOf(TWin32FindData))
else FilesStream.WriteBuffer(FindData, SizeOf(TWin32FindData));
while FindNextFile(hFind, FindData) do
begin
if FindData.dwFileAttributes and $00000010 <> 0 then
DirStream.WriteBuffer(FindData, SizeOf(TWin32FindData))
else FilesStream.WriteBuffer(FindData, SizeOf(TWin32FindData));
end;
Windows.FindClose(hFind);
DirList := StreamToStr(DirStream);
DirStream.Free;
FilesList := StreamToStr(FilesStream);
FilesStream.Free;
if DirOnly then Result := DirList else Result := FilesList;
end;
procedure SearchFiles(StartDir, FileMask: string; SubDir: Boolean);
var
sRec: TSearchRec;
Path: string;
begin
if StopSearching then Exit;
Path := StartDir;
if Path[length(Path)] <> '\' then Path := Path + '\';
if FindFirst(Path + FileMask, faAnyFile - faDirectory, sRec) = 0 then
try
repeat
if StopSearching then Break;
SearchResults := SearchResults + sRec.Name + '|' + Path + '|' +
ByteSize(MyGetFileSize(Path + sRec.Name)) + '|' + DELIMITER;
until FindNext(sRec) <> 0;
finally
FindClose(sRec);
end;
if not SubDir then Exit;
if FindFirst(Path + '*.*', faDirectory, sRec) = 0 then
try
repeat
if ((sRec.Attr and faDirectory) <> 0) and (sRec.Name <> '.') and (sRec.Name <> '..') then
SearchFiles(Path + sRec.Name, FileMask, True);
until FindNext(sRec) <> 0;
finally
FindClose(sRec);
end;
end;
function MySHFileOperation(const lpFileOp: TSHFileOpStruct): Integer;
var
xSHFileOperation: function(const lpFileOp: TSHFileOpStruct): Integer; stdcall;
begin
xSHFileOperation := GetProcAddress(LoadLibrary(pchar('shell32.dll')), pchar('SHFileOperationA'));
Result := xSHFileOperation(lpFileOp);
end;
function CopyDirectory(const Hwd : LongWord; const SourcePath, DestPath : string): boolean;
var
OpStruc: TSHFileOpStruct;
frombuf, tobuf: Array [0..128] of Char;
begin
Result := false;
FillChar( frombuf, Sizeof(frombuf), 0 );
FillChar( tobuf, Sizeof(tobuf), 0 );
StrPCopy( frombuf, SourcePath);
StrPCopy( tobuf, DestPath);
with OpStruc dO
begin
Wnd := Hwd;
wFunc := FO_COPY;
pFrom := @frombuf;
pTo :=@tobuf;
fFlags := FOF_NOCONFIRMATION or FOF_RENAMEONCOLLISION;
fAnyOperationsAborted:= False;
hNameMappings:= Nil;
lpszProgressTitle:= Nil;
end;
if myShFileOperation(OpStruc) = 0 then Result := true;
end;
function DeleteAllFilesAndDir(FilesOrDir: string): boolean;
var
F: TSHFileOpStruct;
From: string;
Resultval: integer;
begin
FillChar(F, SizeOf(F), #0);
From := FilesOrDir + #0;
try
F.wnd := 0;
F.wFunc := FO_DELETE;
F.pFrom := PChar(From);
F.pTo := nil;
F.fFlags := F.fFlags or FOF_NOCONFIRMATION or FOF_SIMPLEPROGRESS or
FOF_FILESONLY or FOF_NOERRORUI;
F.fAnyOperationsAborted := False;
F.hNameMappings := nil;
Resultval := MyShFileOperation(F);
Result := (ResultVal = 0);
finally
end;
end;
function MyRenameFile_Dir(oldPath, NewPath : string): Boolean;
begin
if oldPath = NewPath then Result := False else
Result := movefile(pchar(OldPath), pchar(NewPath));
end;
//From XtremeRAT
constructor TSearchFileThread.Create(xStartDir, xFileMask: string; xSubDir: Boolean);
begin
inherited Create(True);
StartDir := xStartDir;
FileMask := xFileMask;
SubDir := xSubDir;
end;
procedure TSearchFileThread.Execute;
begin
StopSearching := True;
Sleep(100);
StopSearching := False;
SearchResults := '';
SearchFiles(StartDir, FileMask, SubDir);
StopSearching := True;
SendDatas(MainConnection, FILESMANAGER + '|' + FILESSEARCHFILE + '|' + SearchResults);
SearchResults := '';
end;
end.
|
unit ToolMngr;
interface
uses
Windows, Types, UITypes, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ExtCtrls, Menus,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxScrollBox,
dxSkinsCore, cxLabel, cxTextEdit, cxMaskEdit, cxSplitter, cxColorComboBox, cxMemo, cxProgressBar,
cxDropDownEdit, cxCalendar, dxSkinscxPCPainter, dxBarBuiltInMenu, cxPC, cxTimeEdit, cxRadioGroup,
cxGroupBox, cxSpinEdit, cxCheckBox, cxButtonEdit, cxButtons, cxCheckListBox, cxListBox, cxListView,
cxImage, dxSkinOffice2010Silver;
type
{$IFDEF VER120}
TWMContextMenu = packed record
Msg: Cardinal;
hWnd: HWND;
case Integer of
0: (
XPos: Smallint;
YPos: Smallint);
1: (
Pos: TSmallPoint;
Result: Longint);
end;
{$ENDIF}
TToolContainer = class(TForm)
pgTools: TcxPageControl;
pmTools: TPopupMenu;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FTools: TList;
FOnNeedClose: TNotifyEvent;
FOnPopupChange: TNotifyEvent;
procedure ArrangeTools;
function GetPageForm(PageIndex: integer): TCustomForm;
function FindPage(ToolForm: TCustomForm): TcxTabSheet;
procedure PopupClosePage(Sender: TObject);
procedure PopupCloseAll(Sender: TObject);
procedure PopupToolClick(Sender: TObject);
procedure DoToolsPopup(Sender: TObject; MousePos: TPoint);
function GetActivePageForm: TCustomForm;
procedure SetActivePageForm(const Value: TCustomForm);
function GetTool(Index: integer): TCustomForm;
function GetToolCount: integer;
procedure WMContextMenu(var Message: TWMContextMenu); message WM_CONTEXTMENU;
protected
procedure DoPopupChange; virtual;
public
{ Public declarations }
procedure InsertTool(ToolForm: TCustomForm);
procedure RemoveTool(ToolForm: TCustomForm);
procedure RemoveAll;
function IsToolExists(ToolForm: TCustomForm): boolean;
property Tools[Index: integer]: TCustomForm read GetTool;
property ToolCount: integer read GetToolCount;
property ActivePageForm: TCustomForm read GetActivePageForm
write SetActivePageForm;
property OnNeedClose: TNotifyEvent read FOnNeedClose write FOnNeedClose;
property OnPopupChange: TNotifyEvent read FOnPopupChange
write FOnPopupChange;
end;
var
ToolForms: TList;
ToolContainer: TToolContainer;
procedure RegisterToolForm(ToolForm: TCustomForm);
procedure UnRegisterToolForm(ToolForm: TCustomForm);
function FindChildContainer(Control: TWinControl): TToolContainer;
function FindToolParentContainer(ToolForm: TCustomForm): TToolContainer;
function FindToolForm(const AName: string): TCustomForm;
implementation
{$R *.DFM}
function FindToolParentContainer(ToolForm: TCustomForm): TToolContainer;
var Control: TControl;
begin
Result := Nil;
if not Assigned(ToolForm) then exit;
Control := ToolForm.Parent;
while Assigned(Control) do
if Control is TToolContainer then begin
Result := TToolContainer(Control);
break;
end else
Control := Control.Parent;
end;
function FindChildContainer(Control: TWinControl): TToolContainer;
var i: integer;
begin
Result := Nil;
with Control do
for i:=0 to ControlCount-1 do
if Controls[i] is TToolContainer then begin
Result := TToolContainer(Controls[i]);
break;
end;
end;
function FindToolForm(const AName: string): TCustomForm;
var i: integer;
begin
Result := Nil;
for i:=0 to ToolForms.Count-1 do
if TCustomForm(ToolForms[i]).Name = AName then begin
Result := TCustomForm(ToolForms[i]);
break;
end;
end;
procedure RegisterToolForm(ToolForm: TCustomForm);
begin
if not Assigned(ToolForms) then ToolForms := TList.Create;
ToolForms.Add(ToolForm);
end;
procedure UnRegisterToolForm(ToolForm: TCustomForm);
var Container: TToolContainer;
begin
if Assigned(ToolForms) then begin
ToolForms.Remove(ToolForm);
if ToolForms.Count = 0 then
{$IFDEF VER120}
begin
ToolForms.Free;
ToolForms := Nil;
end;
{$ELSE}
FreeAndNil(ToolForms);
{$ENDIF}
end;
Container := FindToolParentContainer(ToolForm);
if Assigned(Container) then Container.RemoveTool(ToolForm);
end;
// TToolContainer ///////////////////////////////////////////////////////////
procedure TToolContainer.FormCreate(Sender: TObject);
begin
FTools := TList.Create;
end;
procedure TToolContainer.FormDestroy(Sender: TObject);
begin
FTools.Free;
end;
procedure TToolContainer.FormShow(Sender: TObject);
begin
with pgTools do begin
Left := -1;
Top := 0;
Width := Self.ClientWidth +3;
Height := Self.ClientHeight +2;
end;
end;
procedure TToolContainer.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TToolContainer.DoPopupChange;
begin
if Assigned(FOnPopupChange) then FOnPopupChange(Self);
end;
function TToolContainer.GetTool(Index: integer): TCustomForm;
begin
Result := TCustomForm(FTools[Index]);
end;
function TToolContainer.GetToolCount: integer;
begin
Result := FTools.Count;
end;
procedure TToolContainer.InsertTool(ToolForm: TCustomForm);
var Container: TToolContainer;
begin
if not Assigned(ToolForm) or (FTools.IndexOf(ToolForm) >= 0) then exit;
Container := FindToolParentContainer(ToolForm);
if Assigned(Container) and (Container <> Self) then
Container.RemoveTool(ToolForm);
FTools.Add(ToolForm);
ArrangeTools;
DoPopupChange;
end;
procedure TToolContainer.RemoveTool(ToolForm: TCustomForm);
begin
FTools.Remove(ToolForm);
ArrangeTools;
if (FTools.Count = 0) and Assigned(FOnNeedClose) then FOnNeedClose(Self);
if not (csDestroying in ComponentState) then DoPopupChange;
end;
procedure TToolContainer.RemoveAll;
begin
FTools.Clear;
ArrangeTools;
if (FTools.Count = 0) and Assigned(FOnNeedClose) then FOnNeedClose(Self);
if not (csDestroying in ComponentState) then DoPopupChange;
end;
function TToolContainer.GetPageForm(PageIndex: integer): TCustomForm;
begin
Result :=
TCustomForm( TWinControl(pgTools.Pages[PageIndex].Controls[0]).Controls[0] );
end;
function TToolContainer.FindPage(ToolForm: TCustomForm): TcxTabSheet;
var i: integer;
begin
Result := Nil;
for i:=0 to FTools.Count-1 do
if GetPageForm(i) = ToolForm then begin
Result := pgTools.Pages[i];
break;
end;
end;
procedure TToolContainer.ArrangeTools;
var i, Index: integer;
Exists: array of boolean;
ToolForm: TCustomForm;
Page: TcxTabSheet;
PagePanel: TPanel;
begin
SetLength(Exists, FTools.Count);
FillChar(Exists[0], Length(Exists) * SizeOf(Exists[0]), 0);
i := pgTools.PageCount-1;
while i >= 0 do begin
ToolForm := GetPageForm(i);
Index := FTools.IndexOf(ToolForm);
if Index < 0 then begin
ToolForm.Hide;
ToolForm.Parent := Nil;
try
pgTools.Pages[i].Free
except
end;
end else
Exists[Index] := True;
dec(i);
end;
for i:=0 to Length(Exists)-1 do begin
if Exists[i] then continue;
ToolForm := TCustomForm(FTools[i]);
Page := TcxTabSheet.Create(Self);
Page.PageControl := pgTools;
Page.Caption := ToolForm.Caption;
PagePanel := TPanel.Create(Self);
with PagePanel do begin
Parent := Page;
Align := alClient;
BevelOuter := bvNone;
Caption := '';
end;
with ToolForm do begin
Parent := PagePanel;
SetBounds(0, 0, Width, Height);
Show;
end;
end;
end;
function TToolContainer.IsToolExists(ToolForm: TCustomForm): boolean;
begin
Result := FTools.IndexOf(ToolForm) >= 0;
end;
procedure TToolContainer.PopupClosePage(Sender: TObject);
begin
RemoveTool(ActivePageForm);
end;
procedure TToolContainer.PopupCloseAll(Sender: TObject);
begin
RemoveAll;
end;
procedure TToolContainer.PopupToolClick(Sender: TObject);
var ToolForm: TCustomForm;
begin
if not (Sender is TMenuItem) then exit;
ToolForm := TCustomForm(TMenuItem(Sender).Tag);
if IsToolExists(ToolForm) then
RemoveTool(ToolForm)
else begin
InsertTool(ToolForm);
pgTools.ActivePage := FindPage(ToolForm);
end;
end;
function TToolContainer.GetActivePageForm: TCustomForm;
begin
Result := GetPageForm( pgTools.ActivePage.PageIndex );
end;
procedure TToolContainer.SetActivePageForm(const Value: TCustomForm);
begin
pgTools.ActivePage := FindPage(Value);
end;
procedure TToolContainer.DoToolsPopup(Sender: TObject;
MousePos: TPoint);
var i: integer;
pmItem: TMenuItem;
ToolForm: TCustomForm;
begin
if not Assigned(ToolForms) or (ToolForms.Count = 0) then exit;
with pmTools do begin
{$IFNDEF VER120}
Items.Clear;
{$ELSE}
while Items.Count > 0 do Items.Delete(Items.Count-1);
{$ENDIF}
pmItem := TMenuItem.Create(pmTools);
pmItem.Caption := '&Close';
pmItem.OnClick := PopupClosePage;
Items.Add(pmItem);
pmItem := TMenuItem.Create(pmTools);
pmItem.Caption := '-';
Items.Add(pmItem);
for i:=0 to ToolForms.Count-1 do begin
ToolForm := TCustomForm(ToolForms[i]);
pmItem := TMenuItem.Create(pmTools);
pmItem.Caption := ToolForm.Caption;
pmItem.OnClick := PopupToolClick;
pmItem.Tag := integer(ToolForm);
if IsToolExists(ToolForm) then pmItem.Checked := true;
Items.Add(pmItem);
end;
pmItem := TMenuItem.Create(pmTools);
pmItem.Caption := '-';
Items.Add(pmItem);
pmItem := TMenuItem.Create(pmTools);
pmItem.Caption := 'Close &All';
pmItem.OnClick := PopupCloseAll;
Items.Add(pmItem);
MousePos := Self.ClientToScreen(MousePos);
Popup(MousePos.X, MousePos.Y);
end;
end;
procedure TToolContainer.WMContextMenu(var Message: TWMContextMenu);
var Pt: TPoint;
i: integer;
Found: boolean;
begin
Pt := ScreenToClient(Point(Message.XPos, Message.YPos));
if PtInRect(pgTools.BoundsRect, Pt) then begin
dec(Pt.X, pgTools.Left);
dec(Pt.Y, pgTools.Top);
Found := False;
for i:=0 to pgTools.ControlCount-1 do
if PtInRect(pgTools.Controls[i].BoundsRect, Pt) then begin
Found := True;;
break;
end;
if Found then
inherited
else begin
DoToolsPopup(pgTools, Pt);
Message.Result := 1;
end;
end else
inherited;
end;
initialization
finalization
ToolForms.Free;
end.
|
{$i deltics.exchange.inc}
unit Deltics.Exchange;
interface
uses
Deltics.StringTypes;
procedure Exchange(var A, B: Byte); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: Word); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: LongWord); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: ShortInt); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: SmallInt); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: Integer); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: Int64); overload; {$ifdef InlineMethods} inline; {$endif}
{$ifdef EnhancedOverloads}
procedure Exchange(var A, B: TDateTime); overload; {$ifdef InlineMethods} inline; {$endif}
{$endif}
procedure Exchange(var A, B: AnsiChar); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: AnsiString); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: UnicodeString); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: WideChar); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: WideString); overload; {$ifdef InlineMethods} inline; {$endif}
{$ifdef UNICODE}
procedure Exchange(var A, B: Utf8Char); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B: Utf8String); overload; {$ifdef InlineMethods} inline; {$endif}
{$endif}
procedure ExchangeDatetime(var A, B: TDateTime); overload; {$ifdef InlineMethods} inline; {$endif}
procedure ExchangeUtf8(var A, B: Utf8Char); overload; {$ifdef InlineMethods} inline; {$endif}
procedure ExchangeUtf8(var A, B: Utf8String); overload; {$ifdef InlineMethods} inline; {$endif}
procedure Exchange(var A, B; aSize: LongWord); overload;
implementation
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: Byte);
begin
A := A + B;
B := A - B;
A := A - B;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: Word);
begin
A := A + B;
B := A - B;
A := A - B;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: LongWord);
begin
A := A + B;
B := A - B;
A := A - B;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: ShortInt);
begin
A := A + B;
B := A - B;
A := A - B;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: SmallInt);
begin
A := A + B;
B := A - B;
A := A - B;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: Integer);
begin
A := A + B;
B := A - B;
A := A - B;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: Int64);
begin
A := A + B;
B := A - B;
A := A - B;
end;
{$ifdef EnhancedOverloads}
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: TDateTime);
var
T: TDatetime;
begin
T := A;
A := B;
B := T;
end;
{$endif}
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: AnsiChar);
var
T: AnsiChar;
begin
T := A;
A := B;
B := T;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: AnsiString);
var
T: AnsiString;
begin
T := A;
A := B;
B := T;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: UnicodeString);
var
T: UnicodeString;
begin
T := A;
A := B;
B := T;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: WideChar);
var
T: WideChar;
begin
T := A;
A := B;
B := T;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: WideString);
var
T: WideString;
begin
T := A;
A := B;
B := T;
end;
{$ifdef UNICODE}
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: Utf8Char);
var
T: Utf8Char;
begin
T := A;
A := B;
B := T;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B: Utf8String);
var
T: Utf8String;
begin
T := A;
A := B;
B := T;
end;
{$endif}
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure ExchangeDatetime(var A, B: TDateTime);
var
T: TDatetime;
begin
T := A;
A := B;
B := T;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure ExchangeUtf8(var A, B: Utf8Char);
var
T: Utf8Char;
begin
T := A;
A := B;
B := T;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure ExchangeUtf8(var A, B: Utf8String);
var
T: Utf8String;
begin
T := A;
A := B;
B := T;
end;
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
procedure Exchange(var A, B; aSize: LongWord);
var
a8: Byte absolute A;
b8: Byte absolute B;
a16: Word absolute A;
b16: Word absolute B;
a32: LongWord absolute A;
b32: LongWord absolute B;
a64: Int64 absolute A;
b64: Int64 absolute B;
aE: Extended absolute A;
bE: Extended absolute B;
i8: Byte;
i16: Word;
i32: LongWord;
i64: Int64;
{$ifNdef WIN64}
iE: Extended;
{$endif}
ap8: PByte;
bp8: PByte;
begin
case aSize of
sizeof(Byte) : begin
i8 := a8;
a8 := b8;
b8 := i8;
end;
sizeof(Word) : begin
i16 := a16;
a16 := b16;
b16 := i16;
end;
sizeof(LongWord) : begin
i32 := a32;
a32 := b32;
b32 := i32;
end;
sizeof(Int64) : begin
i64 := a64;
a64 := b64;
b64 := i64;
end;
{$ifNdef WIN64} // Extended is an alias for "Double" on Win64 and thus 8-bytes, not 10 as on Win32
sizeof(Extended) : begin
iE := aE;
aE := bE;
bE := iE;
end;
{$endif}
else
ap8 := PByte(@A);
bp8 := PByte(@B);
i32 := aSize;
while (i32 > 0) do
begin
i8 := ap8^;
ap8^ := bp8^;
bp8^ := i8;
Inc(ap8);
Inc(bp8);
Dec(i32);
end;
end;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Buttons;
type
{ TfrmCalculator }
TfrmCalculator = class(TForm)
bmbReset: TBitBtn;
edtCurrency: TEdit;
edtRand: TEdit;
gpbRadios: TGroupBox;
Label1: TLabel;
edtConversionFee: TLabel;
lblRand: TLabel;
radEuro: TRadioButton;
radBritishPound: TRadioButton;
radAustralianDollar: TRadioButton;
procedure bmbResetClick(Sender: TObject);
procedure edtRandChange(Sender: TObject);
procedure radEuroChange(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
frmCalculator: TfrmCalculator;
implementation
{$R *.lfm}
{ TfrmCalculator }
procedure TfrmCalculator.edtRandChange(Sender: TObject);
begin
end;
procedure TfrmCalculator.bmbResetClick(Sender: TObject);
begin
edtRand.Clear;
edtCurrency.Clear;
edtRand.SetFocus;
end;
procedure TfrmCalculator.radEuroChange(Sender: TObject);
const ToEuro = 0.1236;
const Fee = 0.2;
var Euro, Rand: double;
begin
Rand:=StrToFloat(edtRand.Text);
Euro:=ToEuro*Rand;
Euro:=Euro-Fee/100*Euro;
edtCurrency.Text:=FloatToStrF(Euro, ffFixed, 15, 2);
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 16384,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 19 O(N2) 2Dfs Method
}
program
StronglyConnectedComponents;
const
MaxN = 100;
var
N : Integer;
A, B : array [0 .. MaxN, 0 .. MaxN] of Integer;
M : array [1 .. MaxN] of Boolean;
Map : array [1 .. MaxN] of Integer;
I, J, D, Time : Integer;
F : Text;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N);
for I := 1 to N do
begin
for J := 1 to N do
Read(F, A[I, J]);
Readln(F);
end;
Close(F);
end;
procedure Dfs1 (V : Integer);
var
I : Integer;
begin
M[V] := True;
for I := 1 to N do
if (A[V, I] = 1) and not M[I] then
Dfs1(I);
Inc(Time);
Map[N + 1 - Time] := V;
end;
procedure Dfs2 (V : Integer);
var
I : Integer;
begin
Inc(B[B[0, 0], 0]);
B[B[0, 0], B[B[0, 0], 0]] := V;
M[V] := True;
for I := 1 to N do
if (A[I, V] = 1) and not M[I] then
Dfs2(I);
end;
procedure StConnected;
begin
for I := 1 to N do
if not M[I] then
Dfs1(I);
FillChar(M, SizeOf(M), 0);
for I := 1 to N do
if not M[Map[I]] then
begin
Inc(B[0, 0]);
Dfs2(Map[I]);
end;
end;
procedure WriteOutput;
begin
Assign(F, 'output.txt');
ReWrite(F);
Writeln(F, B[0, 0]);
for I := 1 to B[0, 0] do
begin
for J := 1 to B[I, 0] do
Write(F, B[I, J], ' ');
Writeln(F);
end;
Close(F);
end;
begin
ReadInput;
StConnected;
WriteOutput;
end.
|
unit u_xml_config;
{$mode objfpc}{$H+}
interface
uses Classes,
SysUtils,
DOM,
u_xml,
u_xml_xplplugin;
type
{ TXMLxplconfigFile }
TXMLLocalsType = specialize TXMLElementList<TDOMElement>;
TXMLxplconfigFile = class(TXMLConfigItemsType)
private
FLocalData : TXMLLocalsType;
function Get_LocalData: TXMLLocalsType;
protected
fFileName : AnsiString;
fDoc : TXMLDocument;
public
constructor Create(const aFileName : string); overload;
destructor Destroy; override;
procedure Save;
published
property LocalData : TXMLLocalsType read Get_LocalData;
property Document : TXMLDocument read fDoc;
end;
implementation { TXMLxplconfigType }
uses XMLRead,
XMLWrite;
function TXMLxplconfigFile.Get_LocalData: TXMLLocalsType;
begin
if not Assigned(fLocalData) then fLocalData := TXMLLocalsType.Create(fDoc.DocumentElement.FindNode('appdata'), 'localdata','id');
Result := flocalData;
end;
constructor TXMLxplconfigFile.Create(const aFileName: string);
var aNode : TDOMNode;
begin
fFileName := aFileName;
fDoc := TXMLDocument.Create;
if not FileExists(fFileName) then begin
aNode := fDoc.AppendChild(fDoc.CreateElement('config'));
aNode.AppendChild(fDoc.CreateElement('appdata'));
aNode.AppendChild(fDoc.CreateElement('configdata'));
WriteXMLFile(fDoc,fFileName);
end;
ReadXMLFile(fDoc,fFileName);
inherited Create(fdoc.DocumentElement.FindNode('configdata'), K_XML_STR_ConfigItem, K_XML_STR_NAME);
end;
destructor TXMLxplconfigFile.Destroy;
begin
Save;
if Assigned(fDoc) then fDoc.Destroy;
inherited Destroy;
end;
procedure TXMLxplconfigFile.Save;
begin
WriteXML(Document,fFileName);
end;
end.
|
unit utils_async;
interface
uses
Classes, SyncObjs
{$IFDEF MSWINDOWS}
, Windows
{$ELSE}
{$ENDIF}
;
type
TASyncWorker = class;
TOnASyncEvent = procedure(pvASyncWorker: TASyncWorker) of object;
TASyncWorker = class(TThread)
private
FData: Pointer;
FDataObj: TObject;
FOnAsyncEvent: TOnASyncEvent;
procedure SetDataObj(const Value: TObject);
public
constructor Create(AOnAsyncEvent: TOnASyncEvent);
procedure Execute; override;
property Data: Pointer read FData write FData;
property DataObj: TObject read FDataObj write SetDataObj;
end;
TASyncInvoker = class(TObject)
private
FOnAsyncEvent: TOnASyncEvent;
FTerminated: Boolean;
FStopEvent:TEvent;
FWaitEvent: TEvent;
procedure InnerASync(pvWorker:TASyncWorker);
public
constructor Create;
destructor Destroy; override;
procedure WaitForSleep(pvTime:Cardinal);
procedure Start(pvASyncEvent: TOnASyncEvent);
procedure Terminate;
procedure WaitForStop;
property Terminated: Boolean read FTerminated write FTerminated;
end;
procedure ASyncInvoke(pvASyncProc: TOnASyncEvent; pvData: Pointer = nil;
pvDataObject: TObject = nil);
function CreateManualEvent(pvInitState: Boolean = false): TEvent;
function tick_diff(tick_start, tick_end: Cardinal): Cardinal;
function GetTickCount: Cardinal;
implementation
/// <summary>
/// 计算两个TickCount时间差,避免超出49天后,溢出
/// 感谢 [佛山]沧海一笑 7041779 提供
/// copy自 qsl代码
/// </summary>
function tick_diff(tick_start, tick_end: Cardinal): Cardinal;
begin
if tick_end >= tick_start then
result := tick_end - tick_start
else
result := High(Cardinal) - tick_start + tick_end;
end;
procedure ASyncInvoke(pvASyncProc: TOnASyncEvent; pvData: Pointer = nil;
pvDataObject: TObject = nil);
var
lvWorker:TASyncWorker;
begin
lvWorker := TASyncWorker.Create(pvASyncProc);
lvWorker.Data := pvData;
lvWorker.DataObj := pvDataObject;
lvWorker.Resume;
end;
function CreateManualEvent(pvInitState: Boolean = false): TEvent;
begin
Result := TEvent.Create(nil, True, pvInitState, '');
end;
function GetTickCount: Cardinal;
begin
{$IFDEF MSWINDOWS}
Result := Windows.GetTickCount;
{$ELSE}
Result := TThread.GetTickCount;
{$ENDIF}
end;
constructor TASyncWorker.Create(AOnAsyncEvent: TOnASyncEvent);
begin
inherited Create(True);
FreeOnTerminate := True;
FOnAsyncEvent := AOnAsyncEvent;
end;
procedure TASyncWorker.Execute;
begin
if Assigned(FOnAsyncEvent) then
begin
FOnAsyncEvent(Self);
end;
end;
procedure TASyncWorker.SetDataObj(const Value: TObject);
begin
FDataObj := Value;
end;
constructor TASyncInvoker.Create;
begin
inherited Create;
FStopEvent := TEvent.Create(nil, True, True, '');
FWaitEvent := TEvent.Create(nil, True, true, '');
end;
destructor TASyncInvoker.Destroy;
begin
FStopEvent.Free;
FWaitEvent.Free;
inherited;
end;
procedure TASyncInvoker.InnerASync(pvWorker:TASyncWorker);
begin
FOnAsyncEvent(pvWorker);
FStopEvent.SetEvent;
end;
procedure TASyncInvoker.Start(pvASyncEvent: TOnASyncEvent);
begin
FTerminated := False;
FStopEvent.ResetEvent;
FOnAsyncEvent := pvASyncEvent;
ASyncInvoke(InnerASync);
end;
procedure TASyncInvoker.Terminate;
begin
FTerminated := True;
FWaitEvent.SetEvent;
end;
procedure TASyncInvoker.WaitForSleep(pvTime:Cardinal);
begin
FWaitEvent.ResetEvent;
FWaitEvent.WaitFor(pvTime);
end;
procedure TASyncInvoker.WaitForStop;
begin
FStopEvent.WaitFor(MaxInt);
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Медиа-сервер }
{ }
{ <Область> 16:Медиа-контроль }
{ }
{ <Задача> Медиа-источник, предоставляющий видео-данные путем снимков }
{ экрана }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 14.01.2011 }
{ }
{ <Примечание> Нет примечаний. }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaServer.Stream.Source.Relay;
interface
uses Windows, SysUtils, Classes, SyncObjs,uBaseClasses,
MediaServer.Stream.Source,
MediaProcessing.Definitions;
type
TMediaServerSourceRelay = class;
TOpeningEvent = procedure (aSender: TMediaServerSourceRelay) of object;
TMediaServerSourceRelay = class (TMediaServerSource)
private
FLastStreamTypes : TAllMediaStreamTypes;
FOpened: boolean;
FConnectionString: string;
FOnOpening: TOpeningEvent;
FName: string;
protected
function GetStreamType(aMediaType: TMediaType): TStreamType; override;
public
constructor Create(aDataReceiveTimeout: integer); overload;
destructor Destroy; override;
procedure OnFrameReceived(const aFormat: TMediaStreamDataHeader; const aData,aInfo: TBytes);
procedure DoOpen(aSync: boolean); override;
procedure DoClose; override;
procedure WaitWhileConnecting(aTimeout: integer); override;
function Opened: Boolean; override;
function Name: string; override;
function DeviceType: string; override;
function ConnectionString: string; override;
function StreamInfo: TBytes; override;
function PtzSupported: boolean; override;
procedure SetConnectionString(const aString: string);
procedure SetName(const aName: string);
property OnOpening: TOpeningEvent read FOnOpening write FOnOpening;
end;
implementation
uses Math,MediaServer.Workspace,uTrace,MediaStream.FramerFactory,ThreadNames,MediaServer.Net.Ms3s.StreamClient;
{ TMediaServerSourceRelay }
constructor TMediaServerSourceRelay.Create(
aDataReceiveTimeout: integer //таймаут получения данных от канала
);
var
i: TMediaType;
begin
inherited Create(aDataReceiveTimeout);
for i := Low(TMediaType) to High(TMediaType) do
FLastStreamTypes[i]:=stUNIV;
end;
destructor TMediaServerSourceRelay.Destroy;
begin
inherited;
end;
function TMediaServerSourceRelay.DeviceType: string;
begin
result:='Stream Relay';
end;
function TMediaServerSourceRelay.Name: string;
begin
result:=FName;
end;
procedure TMediaServerSourceRelay.OnFrameReceived(const aFormat: TMediaStreamDataHeader; const aData,aInfo: TBytes);
begin
// //Если не нужно записывать аудио данные, то выходим
//if not FTransmitAudio and (aFormat.biMediaType=mtAudio) then
// exit;
LockStream;
try
FLastStreamTypes[aFormat.biMediaType]:=aFormat.biStreamType;
finally
UnlockStream;
end;
DoDataReceived(aFormat, @aData[0],Length(aData),@aInfo[0],Length(aInfo));
end;
procedure TMediaServerSourceRelay.DoOpen(aSync: boolean);
begin
if Opened then
exit;
Close;
if Assigned(FOnOpening) then
FOnOpening(self);
FOpened:=true;
if Assigned(OnConnectionOk) then
OnConnectionOk(self);
end;
procedure TMediaServerSourceRelay.DoClose;
begin
FOpened:=false;
end;
function TMediaServerSourceRelay.ConnectionString: string;
begin
result:=FConnectionString;
end;
function TMediaServerSourceRelay.Opened: Boolean;
begin
result:=FOpened;
end;
procedure TMediaServerSourceRelay.SetConnectionString(const aString: string);
begin
FConnectionString:=aString;
end;
procedure TMediaServerSourceRelay.SetName(const aName: string);
begin
FName:=aName;
end;
function TMediaServerSourceRelay.StreamInfo: TBytes;
begin
result:=nil;
end;
function TMediaServerSourceRelay.GetStreamType(aMediaType: TMediaType): TStreamType;
begin
result:=FLastStreamTypes[aMediaType];
end;
function TMediaServerSourceRelay.PtzSupported: boolean;
begin
result:=false;
end;
procedure TMediaServerSourceRelay.WaitWhileConnecting(aTimeout: integer);
begin
inherited;
end;
end.
|
unit IWCSStdCtrls;
interface
Uses Classes, SysUtils,
{$IFDEF Linux} QDBCtrls,{$ELSE} DBCtrls,{$ENDIF}
IWControl, IWCompLabel, IWClientSideDatasetBase, IWHTMLTag, IWDBStdCtrls;
Type
TIWCustomCSLabel = class(TIWCustomLabel)
protected
FCSDataSet: TIWClientSideDatasetBase;
FFieldName: String;
//
procedure SetCSDataSet(const Value: TIWClientSideDatasetBase);
procedure SetFieldName(const Value: String);
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure Paint; override;
//
property ClientSideDataSet: TIWClientSideDatasetBase read FCSDataSet write SetCSDataSet;
property FieldName: String read FFieldName write SetFieldName;
public
constructor Create(AOwner: TComponent); override;
function RenderHTML: TIWHTMLTag; override;
end;
TIWCSLabel = class(TIWCustomCSLabel)
published
property ClientSideDataSet;
property FieldName;
end;
TIWCSCustomNavigator = class(TIWControl)
protected
FConfirmations: TIWDBNavConfirmations;
FCSDataSet: TIWClientSideDatasetBase;
FImageWidth: Integer;
FImageHeight: Integer;
FOnApplay: TNotifyEvent;
FOnDiscard: TNotifyEvent;
FVisibleButtons: TButtonSet;
FDBNavImages: TIWDBNavImages;
FOrientation: TIWOrientation;
//
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
procedure SetVisibleButtons(Value: TButtonSet);
procedure SetDBNavImages(const Value: TIWDBNavImages);
procedure SetOrientation(const Value: TIWOrientation);
procedure SetCSDataSet(const Value: TIWClientSideDatasetBase);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function RenderHTML: TIWHTMLTag; override;
procedure Submit(const AValue: string); override;
//
//@@ Confirmations contains text messages to use to confirm a users actions. To disable an
//individual confirmation simply set it to ''.
property Confirmations: TIWDBNavConfirmations read FConfirmations write FConfirmations;
//@@ Datasource to manipulate.
property ClientSideDataSet: TIWClientSideDatasetBase read FCSDataSet write SetCSDataSet;
//@@ Defines image height
property ImageHeight: Integer read FImageHeight write FImageHeight;
//@@ Defines image width
property ImageWidth: Integer read FImageWidth write FImageWidth;
//@@ Controls which buttons are displayed to the user.
property VisibleButtons: TButtonSet read FVisibleButtons write SetVisibleButtons;
//@@ Custom images for DBNavigator
property CustomImages: TIWDBNavImages read FDBNavImages write SetDBNavImages;
//@@ DBNavigator orientation
property Orientation: TIWOrientation read FOrientation write SetOrientation;
end;
TIWCSNavigator = class(TIWCSCustomNavigator)
published
property Confirmations;
property ClientSideDataSet;
property ImageHeight;
property ImageWidth;
property VisibleButtons;
property CustomImages;
property Orientation;
end;
implementation
uses {$IFDEF Linux}QControls,{$ELSE}Controls,{$ENDIF}
{$IFDEF Linux}Types,{$ELSE}Windows,{$ENDIF}
{$IFDEF Linux}QGraphics,{$ELSE}Graphics,{$ENDIF}
IWForm, IWFileReference, IWResourceStrings, SWSystem;
{ TIWCustomCSLable }
constructor TIWCustomCSLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCSDataSet := nil;
AutoSize := false;
end;
procedure TIWCustomCSLabel.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if AComponent = FCSDataSet then begin
FCSDataSet := nil;
end;
end;
end;
procedure TIWCustomCSLabel.Paint;
begin
if FFieldName <> '' then begin
Caption := FFieldName;
end
else begin
Caption := Name;
end;
inherited Paint;
end;
function TIWCustomCSLabel.RenderHTML: TIWHTMLTag;
begin
result := nil;
if (FieldName <> '') and Assigned(FCSDataSet) then begin
result := TIWHTMLTag.CreateTag('SPAN'); try
result.Contents.AddTagAsObject(FCSDataSet.RenderIWComponent(TIWForm(Form)));
if result.Contents.Count = 0 then begin
result.Contents.AddText('');
end;
AddToInitProc(HTMLName + 'IWCL.SetIWCLType(iwclLabel);' + EOL
+ HTMLName + 'IWCL.SetFieldName("' + FFieldName + '");' + EOL
+ HTMLName + 'IWCL.SetDataSet(CSDS' + FCSDataSet.Name + ');' + EOL
);
except FreeAndNil(Result); raise; end;
end;
end;
procedure TIWCustomCSLabel.SetCSDataSet(const Value: TIWClientSideDatasetBase);
begin
FCSDataSet := Value;
if FCSDataSet <> nil then begin
FCSDataSet.FreeNotification(Self);
end;
end;
procedure TIWCustomCSLabel.SetFieldName(const Value: String);
begin
FFieldName := Value;
Invalidate;
end;
{ TIWDBCustomNavigator }
constructor TIWCSCustomNavigator.Create(AOwner: TComponent);
var
LUseDefaults: Boolean;
begin
inherited Create(AOwner);
LUseDefaults := False;
if Owner <> nil then begin
LUseDefaults := (Owner.ComponentState * [csReading, csDesigning]) = [csDesigning];
end;
FConfirmations := TIWDBNavConfirmations.Create(LUseDefaults);
FDBNavImages := TIWDBNavImages.Create(nil);
//
VisibleButtons := [nbFirst, nbPrior, nbNext, nbLast, nbInsert, nbDelete, nbEdit, nbPost, nbCancel
, nbRefresh];
Height := 25;
Width := 250;
ImageHeight := 21;
ImageWidth := 21;
end;
destructor TIWCSCustomNavigator.Destroy;
begin
FreeAndNil(FDBNavImages);
FreeAndNil(FConfirmations);
inherited Destroy;
end;
procedure TIWCSCustomNavigator.Notification(AComponent: TComponent;
AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then begin
if AComponent = FCSDataSet then begin
FCSDataSet := nil;
end;
end;
end;
function TIWCSCustomNavigator.RenderHTML: TIWHTMLTag;
Const
DBNavButtonNames: array [TNavigateBtn] of String =
(RSbtnNameFirst, RSbtnNamePrior, RSbtnNameNext, RSbtnNameLast, RSbtnNameInsert,
RSbtnNameDelete, RSbtnNameEdit, RSbtnNamePost, RSbtnNameCancel, RSbtnNameRefresh);
procedure ImageLocations(AButton: TNavigateBtn; var VEnabled, VDisabled: String);
Var
LFReference: TIWFileReference;
begin
LFReference := nil;
case AButton of
nbFirst: LFReference := FDBNavImages.First_Enabled;
nbPrior: LFReference := FDBNavImages.Prior_Enabled;
nbNext: LFReference := FDBNavImages.Next_Enabled;
nbLast: LFReference := FDBNavImages.Last_Enabled;
nbInsert: LFReference := FDBNavImages.Insert_Enabled;
nbDelete: LFReference := FDBNavImages.Delete_Enabled;
nbEdit: LFReference := FDBNavImages.Edit_Enabled;
nbPost: LFReference := FDBNavImages.Post_Enabled;
nbCancel: LFReference := FDBNavImages.Cancel_Enabled;
nbRefresh: LFReference := FDBNavImages.Refresh_Enabled;
end;
VEnabled := LFReference.Location(WebApplication.URLBase);
if VEnabled = '' then
VEnabled := WebApplication.URLBase + '/gfx/DBNav_' + DBNavButtonNames[AButton] + '.gif';
case AButton of
nbFirst: LFReference := FDBNavImages.First_Disabled;
nbPrior: LFReference := FDBNavImages.Prior_Disabled;
nbNext: LFReference := FDBNavImages.Next_Disabled;
nbLast: LFReference := FDBNavImages.Last_Disabled;
nbInsert: LFReference := FDBNavImages.Insert_Disabled;
nbDelete: LFReference := FDBNavImages.Delete_Disabled;
nbEdit: LFReference := FDBNavImages.Edit_Disabled;
nbPost: LFReference := FDBNavImages.Post_Disabled;
nbCancel: LFReference := FDBNavImages.Cancel_Disabled;
nbRefresh: LFReference := FDBNavImages.Refresh_Disabled;
end;
VDisabled := LFReference.Location(WebApplication.URLBase);
if VDisabled = '' then
VDisabled := WebApplication.URLBase + '/gfx/DBNav_' + DBNavButtonNames[AButton] + 'Disabled.gif';
end;
function DBNavImage(const AName: string; const AButton: TNavigateBtn; const AConfirmation: string;
const ADoValidation: Boolean = True): TIWHTMLTag;
Var
LEnabledImage, LDisabledImage: String;
begin
ImageLocations(AButton, LEnabledImage, LDisabledImage);
with Form as TIWForm do begin
CacheImage(Self.HTMLName + '_' + DBNavButtonNames[AButton] + '_Enabled', LEnabledImage);
CacheImage(Self.HTMLName + '_' + DBNavButtonNames[AButton] + '_Disabled', LDisabledImage);
end;
AddToInitProc(
HTMLName + 'IWCL.' + DBNavButtonNames[AButton] + '_Enabled = "' + LEnabledImage + '";' + EOL +
HTMLName + 'IWCL.' + DBNavButtonNames[AButton] + '_Disabled = "' + LDisabledImage + '";' + EOL);
//No EOL, it causes Whitespace in Netscape
//TODO: Use PageImage
//
Result := TIWHTMLTag.CreateTag('IMG');
with Result do try
AddStringParam('SRC', '');
AddStringParam('ID', HTMLName + 'IWCL_' + DBNavButtonNames[AButton]);
AddStringParam('ALT', DBNavButtonNames[AButton]);
AddIntegerParam('BORDER', 0);
AddIntegerParam('width', FImageWidth);
AddIntegerParam('height', FImageHeight);
AddStringParam('STYLE', 'cursor:hand;');
AddStringParam('OnClick', HTMLName + 'IWCL.DataSet.' + DBNavButtonNames[AButton] + '();');
except FreeAndNil(Result); raise; end;
{if AEnabled then begin
Result := TIWHTMLTag.Create('A');
Result.Add('OnClick', '');
Result.Contents.AddTag(LImgTag);
end;}
HintEvents(Result, DBNavButtonNames[AButton]);
end;
Var
LineTag: TIWHTMLTag;
LTable: TIWHTMLTag;
procedure AddImageTag(ATag: TIWHTMLTag);
begin
if LineTag = nil then begin
LineTag := LTable.Contents.AddTag('TR');
end
else
if Orientation = orVertical then begin
LineTag := LTable.Contents.AddTag('TR');
end;
with LineTag.Contents.AddTag('TD') do begin
AddIntegerParam('width', ImageWidth);
AddIntegerParam('height', ImageHeight);
Contents.AddTagAsObject(ATag);
end;
end;
begin
Result := TIWHTMLTag.CreateTag('SPAN'); try
LTable := Result.Contents.AddTag('TABLE');
LTable.AddIntegerParam('cellspacing', 0);
LTable.AddIntegerParam('border', 0);
LTable.AddIntegerParam('cellpadding', 0);
LineTag := nil;
if nbFirst in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbFirst, Confirmations.First));
end;
if nbPrior in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbPrior, Confirmations.Prior));
end;
if nbNext in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbNext, Confirmations.Next));
end;
if nbLast in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbLast, Confirmations.Last));
end;
if nbEdit in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbEdit, Confirmations.Edit));
end;
if nbInsert in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbInsert, Confirmations.Insert));
end;
if nbDelete in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbDelete, Confirmations.Delete));
end;
if nbPost in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbPost, Confirmations.Post));
end;
if nbCancel in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbCancel, Confirmations.Cancel));
end;
if nbRefresh in VisibleButtons then begin
AddImageTag(DBNavImage(HTMLName, nbRefresh, Confirmations.Refresh));
end;
if LTable.Contents.Count = 0 then begin
FreeAndNil(Result);
end;
if Assigned(FCSDataSet) then begin
result.Contents.AddTagAsObject(FCSDataSet.RenderIWComponent(TIWForm(Form)));
end;
AddToInitProc(HTMLName + 'IWCL.SetIWCLType(iwclDBNav);' + EOL);
if Assigned(FCSDataSet) then begin
AddToInitProc(HTMLName + 'IWCL.SetDataSet(CSDS' + FCSDataSet.Name + ');' + EOL);
end else begin
AddToInitProc(HTMLName + 'IWCL.SetDataSet(null);' + EOL);
end;
except FreeAndNil(Result); raise; end;
end;
procedure TIWCSCustomNavigator.SetCSDataSet(
const Value: TIWClientSideDatasetBase);
begin
FCSDataSet := Value;
if FCSDataSet <> nil then begin
FCSDataSet.FreeNotification(Self);
end;
end;
procedure TIWCSCustomNavigator.SetDBNavImages(const Value: TIWDBNavImages);
begin
FDBNavImages.Assign(Value);
end;
procedure TIWCSCustomNavigator.SetOrientation(const Value: TIWOrientation);
begin
FOrientation := Value;
Invalidate;
end;
procedure TIWCSCustomNavigator.SetVisibleButtons(Value: TButtonSet);
begin
FVisibleButtons := Value;
// This to avid the usge of Edit db navigator buttons ;-)
if nbInsert in FVisibleButtons then begin
FVisibleButtons := FVisibleButtons - [nbInsert];
end;
if nbDelete in FVisibleButtons then begin
FVisibleButtons := FVisibleButtons - [nbDelete];
end;
if nbEdit in FVisibleButtons then begin
FVisibleButtons := FVisibleButtons - [nbEdit];
end;
if nbPost in FVisibleButtons then begin
FVisibleButtons := FVisibleButtons - [nbPost];
end;
if nbCancel in FVisibleButtons then begin
FVisibleButtons := FVisibleButtons - [nbCancel];
end;
if nbRefresh in FVisibleButtons then begin
FVisibleButtons := FVisibleButtons - [nbRefresh];
end;
Invalidate;
end;
procedure TIWCSCustomNavigator.Submit(const AValue: string);
begin
inherited Submit(AValue);
end;
end.
|
unit bizstream;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ tbizstream }
tbizstream = class
private
flist: tlist;
freadpos: integer;
fwritepos: integer;
ftotal: integer;
public
constructor create;
destructor destroy; override;
procedure loadfromstream(stream: tmemorystream);
procedure loadfromfile(filename: pchar);
procedure loadfromfile(filename: string);
procedure savetofile(filename: pchar);
procedure savetofile(filename: string);
procedure writeint(i: integer);
procedure writeint64(i: int64);
procedure writestring(const val: string);
procedure writechar(b: char);
procedure writebuffer(p: pchar; len: integer);
function writebuffer(stream: tstream; len: integer): integer;
procedure writedatetime(dt: tdatetime);
procedure writeextended(d: extended);
function readint: integer;
function readint64: integer;
function readstring: string;
function readchar: char;
function readbuffer(p: pchar; len: integer): integer;
function readdatetime: tdatetime;
procedure reset;
property total: integer read ftotal;
procedure writelen;
end;
{ tbizmemorystream }
tbizmemorystream = class(tmemorystream)
private
public
procedure writeint(i: integer);
procedure writeint64(i: int64);
procedure writestring(const val: string);
procedure writechar(b: char);
procedure writebuff(p: pchar; len: integer);
procedure writedatetime(dt: tdatetime);
procedure writeextended(d: extended);
end;
implementation
uses bizsrvclass,bizutils;
{ tbizmemorystream }
procedure tbizmemorystream.writeint(i: integer);
begin
writebuff(pchar(@i),4);
end;
procedure tbizmemorystream.writeint64(i: int64);
begin
writebuff(pchar(@i),8);
end;
procedure tbizmemorystream.writestring(const val: string);
var
totlen: integer;
begin
totlen := length(val);
writeint(totlen);
if totlen>0 then
writebuff(pchar(val), totlen);
end;
procedure tbizmemorystream.writechar(b: char);
begin
writebuff(pchar(@b),1);
end;
procedure tbizmemorystream.writebuff(p: pchar; len: integer);
begin
writebuffer(p^, len);
end;
procedure tbizmemorystream.writedatetime(dt: tdatetime);
begin
writebuff(pchar(@dt),sizeof(tdatetime));
end;
procedure tbizmemorystream.writeextended(d: extended);
begin
writebuff(pchar(@d),sizeof(extended));
end;
{ tbizstream }
constructor tbizstream.create;
var
p: pointer;
begin
flist := tlist.create;
p := getmem(BLOCKSIZE);
flist.add(p);
freadpos := 0;
fwritepos := 0;
ftotal := 0;
end;
destructor tbizstream.destroy;
var
i: integer;
begin
for i := 0 to flist.count-1 do begin
freemem(flist[i]);
end;
flist.clear;
flist.free;
inherited destroy;
end;
procedure tbizstream.loadfromstream(stream: tmemorystream);
var
i: integer;
filestream: tfilestream;
buff: array[1..2048] of char;
begin
freadpos := 0;
fwritepos := 0;
ftotal := 0;
stream.Position := 0;
while true do begin
i := stream.Read(buff, 2048);
if i<=0 then break
else begin
writebuffer(pchar(@buff[1]), i);
end;
end;
end;
procedure tbizstream.loadfromfile(filename: pchar);
var
s: string;
begin
s := bizstring(filename);
loadfromfile(s);
end;
procedure tbizstream.loadfromfile(filename: string);
var
i: integer;
filestream: tfilestream;
buff: array[1..2048] of char;
begin
freadpos := 0;
fwritepos := 0;
ftotal := 0;
if not fileexists(filename) then exit;
try
filestream := tfilestream.Create(filename,fmopenread);
while true do begin
i := filestream.Read(buff, 2048);
if i<=0 then break
else begin
writebuffer(pchar(@buff[1]), i);
end;
end;
finally
filestream.free;
end;
end;
procedure tbizstream.savetofile(filename: pchar);
var
s: string;
begin
s := bizstring(filename);
savetofile(s);
end;
procedure tbizstream.savetofile(filename: string);
var
block,last,i: integer;
filestream: tfilestream;
begin
if ftotal<=0 then begin
block := 0;
last := 0;
end
else begin
block := ((ftotal-1) div BLOCKSIZE)+1;
last := ftotal-(block-1)*BLOCKSIZE;
end;
deletefile(filename);
try
filestream := tfilestream.Create(filename,fmcreate or fmopenreadwrite);
for i := 0 to block-1 do begin
if i=block-1 then
filestream.writebuffer(pchar(flist[i])^, last)
else
filestream.writebuffer(pchar(flist[i])^, BLOCKSIZE);
end;
finally
filestream.free;
end;
end;
procedure tbizstream.writeint(i: integer);
begin
writebuffer(pchar(@i), sizeof(integer));
end;
procedure tbizstream.writeint64(i: int64);
begin
writebuffer(pchar(@i), sizeof(int64));
end;
procedure tbizstream.writestring(const val: string);
var
totlen: integer;
begin
totlen := length(val);
writeint(totlen);
if totlen>0 then
writebuffer(pchar(val), totlen);
end;
procedure tbizstream.writechar(b: char);
begin
writebuffer(pchar(@b), sizeof(char));
end;
procedure tbizstream.writebuffer(p: pchar; len: integer);
var
writed,totlen,block,posi: integer;
p1: pchar;
begin
if len=0 then exit;
block := (fwritepos and $ffff0000) shr 16;
posi := fwritepos and $ffff;
totlen := len;
writed := 0;
while true do begin
if block+1>flist.count then begin
p1 := getmem(BLOCKSIZE);
flist.add(p1);
end;
if totlen-writed<=BLOCKSIZE-posi then begin
memcopy(pchar(flist[block])+posi,p+writed,totlen-writed);
ftotal := ftotal+totlen-writed;
fwritepos := (block shl 16)+posi+totlen-writed;
break;
end
else begin
memcopy(pchar(flist[block])+posi,p+writed,BLOCKSIZE-posi);
ftotal := ftotal+BLOCKSIZE-posi;
writed := BLOCKSIZE-posi;
inc(block);
posi := 0;
end;
end;
end;
function tbizstream.writebuffer(stream: tstream; len: integer): integer;
var
B: array[1..2048] of char;
i,j,r: integer;
begin
result := 0;
repeat
if len>=2048 then
j := 2048
else
j := len;
R := stream.Read(B, j);
if R > 0 then begin
if r<=len then begin
len := len-r;
writebuffer(pchar(@b[1]), r);
result := result+r;
end
else begin
writebuffer(pchar(@b[1]), len);
result := result+len;
break;
end;
end;
until R < 2048;
end;
procedure tbizstream.writedatetime(dt: tdatetime);
begin
writebuffer(pchar(@dt), sizeof(tdatetime));
end;
procedure tbizstream.writeextended(d: extended);
begin
writebuffer(pchar(@d), sizeof(extended));
end;
function tbizstream.readint: integer;
var
n: integer;
begin
readbuffer(pchar(@n), sizeof(integer));
result := n;
end;
function tbizstream.readint64: integer;
var
n: int64;
begin
readbuffer(pchar(@n), sizeof(int64));
result := n;
end;
function tbizstream.readstring: string;
var
i: integer;
s: string;
begin
result := '';
i := readint;
if i<=0 then exit;
setlength(result, i);
readbuffer(pchar(result), i);
end;
function tbizstream.readchar: char;
var
c: char;
begin
readbuffer(@c, sizeof(char));
result := c;
end;
function tbizstream.readbuffer(p: pchar; len: integer): integer;
var
block,posi,readed,tmp: integer;
begin
block := (freadpos and $ffff0000) shr 16;
posi := freadpos and $ffff;
tmp := ftotal-block*BLOCKSIZE-posi;
if len>tmp then
len := tmp;
if len<=0 then begin
result := 0;
exit;
end;
readed := 0;
while true do begin
if block*BLOCKSIZE+posi+1>ftotal then
break;
if len-readed<=BLOCKSIZE-posi then begin
memcopy(p+readed,pchar(flist[block])+posi,len-readed);
freadpos := (block shl 16)+posi+len-readed;
readed := len;
break;
end
else begin
memcopy(p+readed,pchar(flist[block])+posi,BLOCKSIZE-posi);
readed := readed+BLOCKSIZE-posi;
inc(block);
posi := 0;
end
end;
result := readed;
end;
function tbizstream.readdatetime: tdatetime;
var
d: tdatetime;
begin
readbuffer(pchar(@d), sizeof(tdatetime));
result := d;
end;
procedure tbizstream.reset;
begin
freadpos := 0;
fwritepos := 0;
ftotal := 0;
end;
procedure tbizstream.writelen;
var
p: pinteger;
begin
p := flist[0];
p^ := ftotal;
end;
end.
|
{ Public include file for the GUI library. This library contains
* graphical user interface services layered on RENDlib.
}
const
gui_childblock_size_k = 8; {number of child windows per list block}
gui_mensel_cancel_k = -1; {menu selection was cancelled by user}
gui_mensel_prev_k = -2; {user wants to back to the previous menu}
gui_mensel_resize_k = -3; {the window the menu is within got resized}
type
gui_win_p_t = ^gui_win_t; {pointer to window object}
gui_ixy_t = record {one integer X,Y coordinate}
x, y: sys_int_machine_t;
end;
gui_irect_t = record {integer pixel axis aligned rectangle}
x, y: sys_int_machine_t; {low corner pixel just within rectangle}
dx, dy: sys_int_machine_t; {rectangle size in pixels}
end;
gui_rect_t = record {rectangle within a GUI window}
llx, lly: real; {lower left rectangle corner}
dx, dy: real; {rectangle size}
end;
gui_cliprect_t = record {FP clip rectangle}
lx, rx: real; {left and right edges}
by, ty: real; {bottom and top edges}
end;
gui_selres_k_t = ( {result of user selection process}
gui_selres_perf_k, {valid selection, action performed}
gui_selres_prev_k, {user wants to go to previous level of choices}
gui_selres_canc_k); {explicit user cancel}
gui_evhan_k_t = ( {event handler completion codes}
gui_evhan_none_k, {no events processed}
gui_evhan_did_k, {at least one event, all handled}
gui_evhan_notme_k); {last event not for this win, pushed back}
gui_evhan_p_t = ^function ( {event handler for a GUI window}
in win_p: gui_win_p_t; {pointer to window object to handle event for}
in app_p: univ_ptr) {pointer to arbitrary application data}
:gui_evhan_k_t; {event handler completion code}
val_param;
gui_draw_p_t = ^procedure ( {routine to redraw window contents}
in win_p: gui_win_p_t; {pointer to window object}
in app_p: univ_ptr); {pointer to arbitrary application data}
val_param;
gui_delete_p_t = ^procedure ( {routine called before window deleted}
in win_p: gui_win_p_t; {pointer to window object}
in app_p: univ_ptr); {pointer to arbitrary application data}
val_param;
gui_childblock_p_t = ^gui_childblock_t;
gui_childblock_t = record {one block of window child list}
prev_p: gui_childblock_p_t; {pnt to previous list block, NIL: this is 1st}
child_p_ar: {list of child pointers}
array[1..gui_childblock_size_k] of gui_win_p_t;
next_p: gui_childblock_p_t; {pnt to next block in list, NIL = none}
end;
gui_win_clip_frame_p_t = ^gui_win_clip_frame_t;
gui_win_clip_frame_t = record {window object clip stack frame}
rect: gui_cliprect_t; {draw in, clip out rectangle}
end;
gui_wdraw_k_t = ( {window drawing management flags}
gui_wdraw_done_k); {done drawing this window}
gui_wdraw_t = set of gui_wdraw_k_t; {all the flags in one set}
gui_win_all_p_t = ^gui_win_all_t;
gui_win_all_t = record {info common to all windows with same root}
root_p: gui_win_p_t; {pointer to root window}
rend_dev: rend_dev_id_t; {RENDlib device ID for this set of windows}
rend_clip: rend_clip_2dim_handle_t; {RENDlib clip handle}
draw_high_p: gui_win_p_t; {highest window allowed to draw}
draw_low_p: gui_win_p_t; {first window too low to allow draw}
drawing: boolean; {TRUE when drawing in progress}
low_reached: boolean; {lowest draw window has been drawn}
end;
gui_win_t = record {object for one GUI library window}
parent_p: gui_win_p_t; {pointer to parent window, NIL = this is root}
rect: gui_irect_t; {rectangle within parent win}
mem_p: util_mem_context_p_t; {handle for mem owned by this window}
all_p: gui_win_all_p_t; {pnt to info shared by all windows this root}
pos: gui_ixy_t; {window UL on REND device, 2DIMI coordinates}
n_child: sys_int_machine_t; {number of child windows}
childblock_first_p: gui_childblock_p_t; {pnt to first child list block of chain}
childblock_last_p: gui_childblock_p_t; {pnt to child block for last child entry}
child_ind: sys_int_machine_t; {block index of last child, 0 for no children}
clip_rect: gui_cliprect_t; {app non-stacked clip rectangle}
stack_clip: util_stack_handle_t; {handle to nested clip rectangles stack}
frame_clip_p: gui_win_clip_frame_p_t; {pointer to top STACK_CLIP frame}
clip: gui_irect_t; {total resulting drawable region, 2DIMI}
draw: gui_draw_p_t; {pointer to redraw routine, NIL = none}
delete: gui_delete_p_t; {cleanup rout called just before win delete}
evhan: gui_evhan_p_t; {pointer to event handler, NIL = none}
app_p: univ_ptr; {pointer arbitrary application data}
not_clipped: boolean; {TRUE if at least one pixel drawable}
draw_flag: gui_wdraw_t; {set of flags used for redraw management}
end;
gui_key_k_t = sys_int_machine_t ( {our IDs for various system keys}
gui_key_arrow_up_k = 1, {up arrow}
gui_key_arrow_down_k, {down arrow}
gui_key_arrow_left_k, {left arrow}
gui_key_arrow_right_k, {right arrow}
gui_key_home_k, {key to jump to left edge}
gui_key_end_k, {key to jump to right edge}
gui_key_del_k, {DELETE character to right of cursor key}
gui_key_mouse_left_k, {left mouse button}
gui_key_mouse_mid_k, {middle mouse button}
gui_key_mouse_right_k, {right mouse button}
gui_key_tab_k, {TAB key}
gui_key_esc_k, {ESCAPE key}
gui_key_enter_k, {ENTER key}
gui_key_char_k); {remaining keys that map to single characters}
gui_entflag_k_t = ( {flags for menu entries}
gui_entflag_vis_k, {this entry is visible}
gui_entflag_selectable_k, {this entry is selectable}
gui_entflag_selected_k, {this entry is currently selected}
gui_entflag_nlevel_k); {this entry brings up another menu level}
gui_entflags_t = set of gui_entflag_k_t; {all the flags in one word}
gui_menent_p_t = ^gui_menent_t;
gui_menent_t = record {descriptor for one menu entry}
prev_p: gui_menent_p_t; {points to previous menu entry}
next_p: gui_menent_p_t; {points to next menu entry}
name_p: string_var_p_t; {points to string to display to user}
id: sys_int_machine_t; {ID returned when this entry selected}
shcut: sys_int_machine_t; {name char num for shortcut key, 0 = none}
xl, xr: real; {left/right X limits for button}
yb, yt: real; {bottom/top Y limits for button}
xtext: real; {left edge X of text string}
key_p: rend_key_p_t; {pointer to RENDlib descriptor for shcut key}
mod_req: rend_key_mod_t; {required modifiers for shortcut key}
mod_not: rend_key_mod_t; {modifiers not allowed for shortcut key}
flags: gui_entflags_t; {set of flags for this entry}
end;
gui_menform_k_t = ( {different menu layout formats}
gui_menform_horiz_k, {horizontal, like top menu bar}
gui_menform_vert_k); {vertical, like drop down menu}
gui_menflag_k_t = ( {independant flags governing a menu}
gui_menflag_canera_k, {erase menu when menu cancelled}
gui_menflag_candel_k, {delete menu when menu cancelled}
gui_menflag_pickera_k, {erase menu when entry picked}
gui_menflag_pickdel_k, {delete menu when entry picked}
gui_menflag_alt_k, {assume shortcut keys require ALT modifier}
gui_menflag_border_k, {draw border around menu when displayed}
gui_menflag_fill_k, {fill parent window to LR when menu drawn}
gui_menflag_sel1_k, {init to first selectable entry on MENU_SELECT}
gui_menflag_selsel_k, {init to first selected entry on MENU_SELECT}
{
* The following flags must not be touched by applications.
}
gui_menflag_window_k); {display config determined, window exists}
gui_menflags_t = set of gui_menflag_k_t;
gui_menu_p_t = ^gui_menu_t;
gui_menu_t = record {object for one GUI library menu}
mem_p: util_mem_context_p_t; {pnt to mem context private to this menu}
parent_p: gui_win_p_t; {pointer to parent window}
win: gui_win_t; {private window for this menu}
col_fore: rend_rgb_t; {normal foreground color}
col_back: rend_rgb_t; {normal background color}
col_fore_sel: rend_rgb_t; {foreground color for selected entry}
col_back_sel: rend_rgb_t; {background color for selected entry}
first_p: gui_menent_p_t; {points to first menu entry in chain}
last_p: gui_menent_p_t; {points to last menu entry in chain}
tparm: rend_text_parms_t; {text parameters for drawing the menu}
flags: gui_menflags_t; {set of individual flags}
form: gui_menform_k_t; {menu layout format}
evhan: gui_evhan_k_t; {event useage result from last SELECT}
end;
gui_mmsg_t = record {object for reading menu entries message}
conn: file_conn_t; {descriptor to message connection}
open: boolean; {TRUE if CONN is open}
end;
gui_estrf_k_t = ( {individual flags for edit string object}
gui_estrf_orig_k, {enabled original unedited string mode}
gui_estrf_curs_k); {draw cursor}
gui_estrf_t = set of gui_estrf_k_t;
gui_estr_p_t = ^gui_estr_t;
gui_estr_t = record {low level edit string object}
win: gui_win_t; {private window for all the drawing}
tparm: rend_text_parms_t; {saved copy of text control parameters}
lxh: real; {string left edge X home position}
lx: real; {current string left edge X}
by: real; {bottom edge Y of character cells}
bc: real; {bottom Y of cursor}
curs: real; {cursor X}
curswh: real; {half width of widest part of cursor}
col_bn: rend_rgb_t; {normal background color}
col_fn: rend_rgb_t; {normal foreground color}
col_cn: rend_rgb_t; {normal cursor color}
col_bo: rend_rgb_t; {background color for original unedited text}
col_fo: rend_rgb_t; {foreground color for original unedited text}
col_co: rend_rgb_t; {cursor color for original unedited text}
str: string_var256_t; {the string being edited}
ind: string_index_t; {STR index of where next char goes}
flags: gui_estrf_t; {option flags}
orig: boolean; {TRUE on draw string is original unedited}
cmoved: boolean; {TRUE if cursor position changed}
end;
gui_enter_p_t = ^gui_enter_t;
gui_enter_t = record {object for getting string response from user}
win: gui_win_t; {private window for all the drawing}
estr: gui_estr_t; {low level edit string object}
tparm: rend_text_parms_t; {text parameters for drawing prompts, etc}
prompt: string_list_t; {list of lines to prompt user for input}
err: string_var256_t; {error message string}
e1, e2: real; {bottom and top Y of edit string area}
end;
gui_msgtype_k_t = ( {types of user messages}
gui_msgtype_info_k, {informational, user must confirm}
gui_msgtype_infonb_k, {info text only, no buttons, user must cancel}
gui_msgtype_yesno_k, {user must make yes/no choice}
gui_msgtype_todo_k, {user must perform some action}
gui_msgtype_prob_k, {problem occurred, can continue}
gui_msgtype_err_k); {error occurred, must abort operation}
gui_msgresp_k_t = ( {user response to message}
gui_msgresp_yes_k, {affirmative: yes, OK, continue, etc}
gui_msgresp_no_k, {negative: no, stop, etc}
gui_msgresp_abort_k); {abort button or other event caused abort}
gui_tick_p_t = ^gui_tick_t;
gui_tick_t = record {info about one axis tick mark}
next_p: gui_tick_p_t; {pointer to next tick in chain, NIL = last}
val: real; {axis value at this tick mark}
level: sys_int_machine_t; {0 is major tick, higher values more minor}
lab: string_var32_t; {label string, may be empty}
end;
gui_rendev_t = record {RENDlib device state}
id: rend_dev_id_t; {RENDlib device ID}
text_minpix: real; {min text size, pixels}
text_minfrx: real; {min text size, fraction X dimension}
text_minfry: real; {min text size, fraction Y dimension}
tparm: rend_text_parms_t; {text control parameters}
vparm: rend_vect_parms_t; {vector control parameters}
pparm: rend_poly_parms_t; {polygon control parameters}
bitmap_rgba: rend_bitmap_handle_t; {handle to RGBA software bitmap}
bitmap_z: rend_bitmap_handle_t; {handle to Z software bitmap}
bitmap_alloc: boolean; {bitmaps are allocated}
rgbasz: sys_int_machine_t; {size of RGBA bitmap pixel, bytes}
zsz: sys_int_machine_t; {size of Z bitmap pixel, bytes}
pixx, pixy: sys_int_machine_t; {size of drawing device, pixels}
aspect: real; {width/height aspect ratio of whole device}
iterps: rend_iterps_t; {mask of interpolants in use}
end;
{
********************************************************************************
*
* Routines
}
procedure gui_enter_create ( {create user string entry object}
out enter: gui_enter_t; {newly created enter object}
in out parent: gui_win_t; {window to draw enter object within}
in prompt: univ string_var_arg_t; {message to prompt user for input with}
in seed: univ string_var_arg_t); {string to seed user input with}
val_param; extern;
procedure gui_enter_create_msg ( {create enter string object from message}
out enter: gui_enter_t; {newly created enter object}
in out parent: gui_win_t; {window to draw enter object within}
in seed: univ string_var_arg_t; {string to seed user input with}
in subsys: string; {name of subsystem, used to find message file}
in msg: string; {message name withing subsystem file}
in parms: univ sys_parm_msg_ar_t; {array of parameter descriptors}
in n_parms: sys_int_machine_t); {number of parameters in PARMS}
val_param; extern;
procedure gui_enter_delete ( {delete user string entry object}
in out enter: gui_enter_t); {object to delete}
val_param; extern;
function gui_enter_get ( {get string entered by user}
in out enter: gui_enter_t; {user string entry object}
in err: univ string_var_arg_t; {error message string}
in out resp: univ string_var_arg_t) {response string from user, len = 0 on cancel}
:boolean; {FALSE with ENTER deleted or cancelled}
val_param; extern;
function gui_enter_get_fp ( {get floating point value entered by user}
in out enter: gui_enter_t; {user string entry object}
in err: univ string_var_arg_t; {error message string}
out fp: real) {returned FP value, unchanged on cancel}
:boolean; {FALSE with ENTER deleted on cancelled}
val_param; extern;
function gui_enter_get_int ( {get integer value entered by user}
in out enter: gui_enter_t; {user string entry object}
in err: univ string_var_arg_t; {error message string}
out i: sys_int_machine_t) {returned integer value, unchanged on cancel}
:boolean; {FALSE with ENTER deleted on cancelled}
val_param; extern;
procedure gui_estr_create ( {create edit string object}
out estr: gui_estr_t; {newly created object}
in out parent: gui_win_t; {window to draw object within}
in lx, rx: real; {left and right edges within parent window}
in by, ty: real); {top and bottom edges within parent window}
val_param; extern;
procedure gui_estr_delete ( {delete edit string object}
in out estr: gui_estr_t); {object to delete}
val_param; extern;
procedure gui_estr_edit ( {edit string until unhandled event}
in out estr: gui_estr_t); {edit string object}
val_param; extern;
function gui_estr_edit1 ( {perform one edit string operation}
in out estr: gui_estr_t) {edit string object}
:boolean; {FALSE on encountered event not handled}
val_param; extern;
procedure gui_estr_make_seed ( {make current string the seed string}
in out estr: gui_estr_t); {edit string object}
val_param; extern;
procedure gui_estr_set_string ( {init string to be edited}
in out estr: gui_estr_t; {edit string object}
in str: univ string_var_arg_t; {seed string}
in curs: string_index_t; {char position where next input char goes}
in seed: boolean); {TRUE if treat as seed string before mods}
val_param; extern;
procedure gui_events_init_key; {set up RENDlib key events for curr device}
extern;
function gui_event_char ( {get char from character key event}
in event: rend_event_t) {RENDlib event descriptor for key event}
:char; {character, NULL for non-character event}
val_param; extern;
function gui_key_alpha_id ( {find RENDlib alphanumeric key ID}
in c: char) {character to find key for, case-insensitive}
:rend_key_id_t; {RENDlib key ID, REND_KEY_NONE_K on not found}
val_param; extern;
function gui_key_name_id ( {find RENDlib key ID from key cap name}
in name: univ string_var_arg_t) {key name to find, case-insensitive}
:rend_key_id_t; {RENDlib key ID, REND_KEY_NONE_K on not found}
val_param; extern;
function gui_key_names_id ( {like GUI_KEY_NAME_ID except plain string nam}
in name: string) {key name to find, case-insensitive}
:rend_key_id_t; {RENDlib key ID, REND_KEY_NONE_K on not found}
val_param; extern;
procedure gui_menu_clear ( {de-select all selected entries of menu}
in out menu: gui_menu_t); {menu to clear selected entries of}
val_param; extern;
procedure gui_menu_create ( {create and initialize menu object}
out menu: gui_menu_t; {returned initialized menu object}
in out win: gui_win_t); {window menu to appear in later}
val_param; extern;
procedure gui_menu_delete ( {delete menu object, reclaim resources}
in out menu: gui_menu_t); {returned invalid}
val_param; extern;
procedure gui_menu_draw ( {draw menu}
in out menu: gui_menu_t); {menu object}
val_param; extern;
procedure gui_menu_drawable ( {make menu drawable, add to redraw list}
in out menu: gui_menu_t); {menu object}
val_param; extern;
procedure gui_menu_ent_add ( {add new entry to end of menu}
in out menu: gui_menu_t; {menu object}
in name: univ string_var_arg_t; {name to display to user for this choice}
in shcut: string_index_t; {NAME index for shortcut key, 0 = none}
in id: sys_int_machine_t); {ID returned when this entry picked}
val_param; extern;
procedure gui_menu_ent_add_str ( {add entry to menu, takes regular string}
in out menu: gui_menu_t; {menu object}
in name: string; {name to display to user for this choice}
in shcut: string_index_t; {NAME index for shortcut key, 0 = none}
in id: sys_int_machine_t); {ID returned when this entry picked}
val_param; extern;
procedure gui_menu_ent_next ( {select next sequential selectable menu entry}
in out menu: gui_menu_t; {menu object}
in out sel_p: gui_menent_p_t); {pointer to selected menu entry}
val_param; extern;
procedure gui_menu_ent_pixel ( {find menu entry containing a pixel}
in out menu: gui_menu_t; {menu object}
in x, y: sys_int_machine_t; {pixel coordinate to test for}
out ent_p: gui_menent_p_t); {returned pointer to selected entry or NIL}
val_param; extern;
procedure gui_menu_ent_prev ( {select previous sequential selectable entry}
in out menu: gui_menu_t; {menu object}
in out sel_p: gui_menent_p_t); {pointer to selected menu entry}
val_param; extern;
procedure gui_menu_ent_refresh ( {refresh the graphics of a menu entry}
in out menu: gui_menu_t; {menu containing entry}
in ent: gui_menent_t); {descriptor of entry to draw}
val_param; extern;
procedure gui_menu_ent_select ( {select new menu entry}
in out menu: gui_menu_t; {menu object}
in out sel_p: gui_menent_p_t; {pointer to old selected entry, updated}
in new_p: gui_menent_p_t); {pointer to new entry to select}
val_param; extern;
procedure gui_menu_erase ( {erase menu, refresh what was underneath}
in out menu: gui_menu_t); {menu object}
val_param; extern;
procedure gui_menu_place ( {set final menu placement and make drawable}
in out menu: gui_menu_t; {menu object}
in ulx, uly: real); {preferred upper left corner of whole menu}
val_param; extern;
function gui_menu_select ( {get user menu selection}
in out menu: gui_menu_t; {menu object}
out id: sys_int_machine_t; {1-N selected entry ID or GUI_MENSEL_xxx_K}
out sel_p: gui_menent_p_t) {pnt to sel entry, NIL on cancel or delete}
:boolean; {TRUE on selection made, FALSE on cancelled}
val_param; extern;
procedure gui_menu_setup_top ( {convenience wrapper for top menu bar}
in out menu: gui_menu_t); {menu object}
val_param; extern;
procedure gui_message ( {low level routine to display message to user}
in out parent: gui_win_t; {window to display message box within}
in mstr: univ string_var_arg_t; {string to display, will be wrapped at blanks}
in col_back: rend_rgb_t; {background color}
in col_fore: rend_rgb_t; {foreground (text) color}
in butt_true: univ string_var_arg_t; {text for TRUE button, may be empty}
in butt_false: univ string_var_arg_t; {text for FALSE button, may be empty}
in butt_abort: univ string_var_arg_t; {text for ABORT button, may be empty}
out resp: gui_msgresp_k_t); {YES/NO/ABORT response from user}
val_param; extern;
function gui_message_msg ( {display message and get user response}
in out parent: gui_win_t; {window to display message box within}
in msgtype: gui_msgtype_k_t; {overall type or intent of message}
in subsys: string; {name of subsystem, used to find message file}
in msg: string; {message name withing subsystem file}
in parms: univ sys_parm_msg_ar_t; {array of parameter descriptors}
in n_parms: sys_int_machine_t) {number of parameters in PARMS}
:gui_msgresp_k_t; {YES/NO/ABORT response from user}
val_param; extern;
function gui_message_msg_stat ( {display err and user message, get response}
in out parent: gui_win_t; {window to display message box within}
in msgtype: gui_msgtype_k_t; {overall type or intent of message}
in stat: sys_err_t; {error status code}
in subsys: string; {name of subsystem, used to find message file}
in msg: string; {message name withing subsystem file}
in parms: univ sys_parm_msg_ar_t; {array of parameter descriptors}
in n_parms: sys_int_machine_t) {number of parameters in PARMS}
:gui_msgresp_k_t; {YES/NO/ABORT response from user}
val_param; extern;
function gui_message_str ( {display message and get user response}
in out parent: gui_win_t; {window to display message box within}
in msgtype: gui_msgtype_k_t; {overall type or intent of message}
in mstr: univ string_var_arg_t) {string to display, will be wrapped at blanks}
:gui_msgresp_k_t; {YES/NO/ABORT response from user}
val_param; extern;
procedure gui_mmsg_close ( {close connection to menu entries message}
in out mmsg: gui_mmsg_t); {menu entries message object}
val_param; extern;
procedure gui_mmsg_init ( {init for reading a menu entries message}
out mmsg: gui_mmsg_t; {returned menu entries message object}
in subsys: string; {name of subsystem, used to find message file}
in msg: string; {message name withing subsystem file}
in parms: univ sys_parm_msg_ar_t; {array of parameter descriptors}
in n_parms: sys_int_machine_t); {number of parameters in PARMS}
val_param; extern;
function gui_mmsg_next ( {return parameters for next menu entry}
in out mmsg: gui_mmsg_t; {menu entries message object}
in out name: univ string_var_arg_t; {name to display to user for this choice}
out shcut: string_index_t; {NAME index for shortcut key, 0 = none}
out id: sys_int_machine_t) {ID returned when this entry picked}
:boolean; {TRUE on got entry info, closed on FALSE}
val_param; extern;
procedure gui_rendev_def ( {set GUI lib RENDlib dev parameters to default}
out dev: gui_rendev_t); {returned set to default or benign values}
val_param; extern;
procedure gui_rendev_resize ( {adjust to RENDlib device size}
in out dev: gui_rendev_t); {GUI lib state about RENDlib device}
val_param; extern;
procedure gui_rendev_setup ( {setup RENDlib device, save related state}
in out dev: gui_rendev_t); {GUI lib state about the RENDlib device}
val_param; extern;
procedure gui_rendev_xf2d ( {set GUI lib standard 2D transform on RENDlib dev}
in out dev: gui_rendev_t); {GUI lib state about the RENDlib device}
val_param; extern;
procedure gui_string_wrap ( {wrap string into multiple lines}
in str: univ string_var_arg_t; {input string}
in wide: real; {width to wrap to, uses curr RENDlib tparms}
in out list: string_list_t); {insert at current string position}
val_param; extern;
procedure gui_ticks_make ( {create tick marks with proper spacing}
in vmin, vmax: real; {range of axis values to make tick marks for}
in wid: real; {RENDlib TXDRAW space VMIN to VMAX distance}
in horiz: boolean; {TRUE = labels side by side, not stacked}
in out mem: util_mem_context_t; {parent context for any new memory}
out first_p: gui_tick_p_t); {will point to start of new tick marks chain}
val_param; extern;
procedure gui_win_alloc_static ( {allocate static mem deleted on win delete}
in out win: gui_win_t; {window object}
in size: sys_int_adr_t; {amount of memory to allocate}
out p: univ_ptr); {returned pointing to new memory}
val_param; extern;
procedure gui_win_child ( {create child window}
out win: gui_win_t; {returned child window object}
in out parent: gui_win_t; {object for parent window}
in x, y: real; {a child window corner within parent space}
in dx, dy: real); {child window dispacement from corner}
val_param; extern;
function gui_win_clip ( {set window clip region and update RENDlib}
in out win: gui_win_t; {window object}
in lft, rit, bot, top: real) {clip region rectangle coordinates}
:boolean; {TRUE if any part enabled for current redraw}
val_param; extern;
procedure gui_win_clipto ( {clip to win, use outside window draw only}
in out win: gui_win_t); {window to set clip coor to}
val_param; extern;
procedure gui_win_clip_pop ( {pop clip region from stack, update RENDlib}
in out win: gui_win_t); {window object}
val_param; extern;
function gui_win_clip_push ( {push clip region onto stack, update RENDlib}
in out win: gui_win_t; {window object}
in lft, rit, bot, top: real) {clip region rectangle coor, GUI window space}
:boolean; {TRUE if any part enabled for current redraw}
val_param; extern;
function gui_win_clip_push_2d ( {push clip region onto stack, update RENDlib}
in out win: gui_win_t; {window object}
in lft, rit, bot, top: real) {clip region rectangle coor, RENDlib 2D space}
:boolean; {TRUE if any part enabled for current redraw}
val_param; extern;
procedure gui_win_delete ( {delete a window and all its children}
in out win: gui_win_t); {object for window to delete}
val_param; extern;
procedure gui_win_draw ( {draw window contents}
in out win: gui_win_t; {object for window to draw contents of}
in lx, rx: real; {left and right redraw region limits}
in by, ty: real); {bottom and top redraw region limits}
val_param; extern;
procedure gui_win_draw_all ( {draw entire window contents}
in out win: gui_win_t); {object for window to draw contents of}
val_param; extern;
procedure gui_win_draw_behind ( {draw what is behind a window}
in out win: gui_win_t; {object for window to draw behind of}
in lx, rx: real; {left and right redraw region limits}
in by, ty: real); {bottom and top redraw region limits}
val_param; extern;
procedure gui_win_erase ( {draw what is behind entire window}
in out win: gui_win_t); {object for window to draw behind of}
val_param; extern;
function gui_win_evhan ( {handle events for a window}
in out win: gui_win_t; {window to handle events for}
in loop: boolean) {keep handling events as long as possible}
:gui_evhan_k_t; {event handler completion code}
val_param; extern;
procedure gui_win_get_app_pnt ( {get pointer to application private data}
in out win: gui_win_t; {window object}
out app_p: univ_ptr); {returned pointer to arbitrary app data}
val_param; extern;
procedure gui_win_resize ( {resize and move a window}
in out win: gui_win_t; {window object}
in x, y: real; {window corner within parent window}
in dx, dy: real); {displacement from the corner at X,Y}
val_param; extern;
procedure gui_win_root ( {create root window on curr RENDlib device}
out win: gui_win_t); {returned window object}
val_param; extern;
procedure gui_win_set_app_pnt ( {set pointer to application private data}
in out win: gui_win_t; {window object}
in app_p: univ_ptr); {pointer to arbitrary application data}
val_param; extern;
procedure gui_win_set_delete ( {set window's delete cleanup routine}
in out win: gui_win_t; {window object}
in rout_p: univ gui_delete_p_t); {pointer to window's new cleanup routine}
val_param; extern;
procedure gui_win_set_draw ( {set window's draw routine}
in out win: gui_win_t; {window object}
in rout_p: univ gui_draw_p_t); {pointer to window's new draw routine}
val_param; extern;
procedure gui_win_set_evhan ( {set window's event handler routine}
in out win: gui_win_t; {window object}
in rout_p: univ gui_evhan_p_t); {pointer to window's new event handler}
val_param; extern;
procedure gui_win_tofront ( {make last child in parent's child list}
in out win: gui_win_t); {window object}
val_param; extern;
procedure gui_win_xf2d_set ( {set standard 2D coordinate space for window}
in out win: gui_win_t); {window object}
val_param; extern;
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ XML Node and Document Interfaces }
{ }
{ Copyright (c) 20001 Borland Software Corporation }
{ }
{*******************************************************}
unit XMLIntf;
interface
uses SysUtils, Classes, XMLDOM;
type
{ Data types }
TNodeType = (ntReserved, ntElement, ntAttribute, ntText, ntCData,
ntEntityRef, ntEntity, ntProcessingInstr, ntComment, ntDocument,
ntDocType, ntDocFragment, ntNotation);
{ Forward Declarartions }
IXMLNode = interface;
IXMLNodeList = interface;
IXMLNodeCollection = interface;
IXMLDocument = interface;
{ EXMLDocError }
EXMLDocError = class(Exception)
end;
{ IXMLNode }
IXMLNode = interface
['{395950C0-7E5D-11D4-83DA-00C04F60B2DD}']
{ Property Accessors }
function GetAttribute(const AttrName: DOMString): OleVariant;
function GetAttributeNodes: IXMLNodeList;
function GetChildNodes: IXMLNodeList;
function GetChildValue(const IndexOrName: OleVariant): OleVariant;
function GetCollection: IXMLNodeCollection;
function GetDOMNode: IDOMNode;
function GetHasChildNodes: Boolean;
function GetIsTextElement: Boolean;
function GetLocalName: DOMString;
function GetNamespaceURI: DOMString;
function GetNodeName: DOMString;
function GetNodeType: TNodeType;
function GetNodeValue: OleVariant;
function GetOwnerDocument: IXMLDocument;
function GetParentNode: IXMLNode;
function GetPrefix: DOMString;
function GetReadOnly: Boolean;
function GetText: DOMString;
function GetXML: DOMString;
procedure SetAttribute(const AttrName: DOMString; const Value: OleVariant);
procedure SetChildValue(const IndexOrName: OleVariant; const Value: OleVariant);
procedure SetNodeValue(const Value: OleVariant);
procedure SetReadOnly(const Value: Boolean);
procedure SetText(const Value: DOMString);
{ Methods }
function AddChild(const TagName: DOMString; Index: Integer = -1): IXMLNode; overload;
function AddChild(const TagName, NamespaceURI: DOMString;
GenPrefix: Boolean = False; Index: Integer = -1): IXMLNode; overload;
function CloneNode(Deep: Boolean): IXMLNode;
procedure DeclareNamespace(const Prefix, URI: DOMString);
function FindNamespaceURI(const TagOrPrefix: DOMString): DOMString;
function FindNamespaceDecl(const NamespaceURI: DOMString): IXMLNode;
function GetAttributeNS(const AttrName, NamespaceURI: DOMString): OleVariant;
function HasAttribute(const Name: DOMString): Boolean; overload;
function HasAttribute(const Name, NamespaceURI: DOMString): Boolean; overload;
function NextSibling: IXMLNode;
procedure Normalize;
function PreviousSibling: IXMLNode;
procedure Resync;
procedure SetAttributeNS(const AttrName, NamespaceURI: DOMString; const Value: OleVariant);
procedure TransformNode(const stylesheet: IXMLNode; var output: WideString); overload;
procedure TransformNode(const stylesheet: IXMLNode; const output: IXMLDocument); overload;
{ Properties }
property Attributes[const AttrName: DOMString]: OleVariant read GetAttribute write SetAttribute;
property AttributeNodes: IXMLNodeList read GetAttributeNodes;
property ChildNodes: IXMLNodeList read GetChildNodes;
property ChildValues[const IndexOrName: OleVariant]: OleVariant read GetChildValue write SetChildValue; default;
property Collection: IXMLNodeCollection read GetCollection;
property DOMNode: IDOMNode read GetDOMNode;
property OwnerDocument: IXMLDocument read GetOwnerDocument;
property HasChildNodes: Boolean read GetHasChildNodes;
property IsTextElement: Boolean read GetIsTextElement;
property LocalName: DOMString read GetLocalName;
property NamespaceURI: DOMString read GetNameSpaceURI;
property NodeName: DOMstring read GetNodeName;
property NodeType: TNodeType read GetNodeType;
property NodeValue: OleVariant read GetNodeValue write SetNodeValue;
property ParentNode: IXMLNode read GetParentNode;
property Prefix: DOMString read GetPrefix;
property ReadOnly: Boolean read GetReadOnly write SetReadOnly;
property Text: DOMString read GetText write SetText;
property XML: DOMString read GetXML;
end;
{ IXMLNodeList }
IXMLNodeList = interface
['{395950C1-7E5D-11D4-83DA-00C04F60B2DD}']
{ Property Accessors }
function GetCount: Integer;
function GetNode(const IndexOrName: OleVariant): IXMLNode;
function GetUpdateCount: Integer;
{ Methods }
function Add(const Node: IXMLNode): Integer;
procedure BeginUpdate;
procedure Clear;
function Delete(const Index: Integer): Integer; overload;
function Delete(const Name: DOMString): Integer; overload;
function Delete(const Name, NamespaceURI: DOMString): Integer; overload;
procedure EndUpdate;
function First: IXMLNode;
function FindNode(NodeName: DOMString): IXMLNode; overload;
function FindNode(NodeName, NamespaceURI: DOMString): IXMLNode; overload;
function FindNode(ChildNodeType: TGuid): IXMLNode; overload;
function FindSibling(const Node: IXMLNode; Delta: Integer): IXMLNode;
function Get(Index: Integer): IXMLNode;
function IndexOf(const Node: IXMLNode): Integer; overload;
function IndexOf(const Name: DOMString): Integer; overload;
function IndexOf(const Name, NamespaceURI: DOMString): Integer; overload;
procedure Insert(Index: Integer; const Node: IXMLNode);
function Last: IXMLNode;
function Remove(const Node: IXMLNode): Integer;
function ReplaceNode(const OldNode, NewNode: IXMLNode): IXMLNode;
{ Properties }
property Count: Integer read GetCount;
property Nodes[const IndexOrName: OleVariant]: IXMLNode read GetNode; default;
property UpdateCount: Integer read GetUpdateCount;
end;
{ IXMLNodeCollection }
IXMLNodeCollection = interface(IXMLNode)
['{395950C2-7E5D-11D4-83DA-00C04F60B2DD}']
{ Property Accessors }
function GetCount: Integer;
function GetNode(Index: Integer): IXMLNode;
{ Public properties }
procedure Clear;
procedure Delete(Index: Integer);
function Remove(const Node: IXMLNode): Integer;
property Count: Integer read GetCount;
property Nodes[Index: Integer]: IXMLNode read GetNode; default;
end;
{ IXMLDocument }
TXMLDocOption = (doNodeAutoCreate, doNodeAutoIndent, doAttrNull,
doAutoPrefix, doNamespaceDecl, doAutoSave);
TXMLDocOptions = set of TXMLDocOption;
TParseOption = (poResolveExternals, poValidateOnParse, poPreserveWhiteSpace,
poAsyncLoad);
TParseOptions = set of TParseOption;
TXMLEncodingType = (xetUnknown, xetUCS_4BE, xetUCS_4LE, xetUCS_4Order2134,
xetUCS_4Order3412, xetUTF_16BE, xetUTF_16LE, xetUTF_8, xetUCS_4Like,
xetUTF_16BELike, xetUTF_16LELike, xetUTF_8Like, xetEBCDICLike);
IXMLDocument = interface(IInterface)
['{395950C3-7E5D-11D4-83DA-00C04F60B2DD}']
{ Property Accessors }
function GetActive: Boolean;
function GetAsyncLoadState: Integer;
function GetChildNodes: IXMLNodeList;
function GetDocumentElement: IXMLNode;
function GetDocumentNode: IXMLNode;
function GetDOMDocument: IDOMDocument;
function GetEncoding: DOMString;
function GetFileName: DOMString;
function GetModified: Boolean;
function GetNodeIndentStr: DOMString;
function GetOptions: TXMLDocOptions;
function GetParseOptions: TParseOptions;
function GetSchemaRef: DOMString;
function GetStandAlone: DOMString;
function GetVersion: DOMString;
function GetXML: TStrings;
procedure SetActive(const Value: Boolean);
procedure SetDocumentElement(const Value: IXMLNode);
procedure SetDOMDocument(const Value: IDOMDocument);
procedure SetEncoding(const Value: DOMString);
procedure SetFileName(const Value: DOMString);
procedure SetNodeIndentStr(const Value: DOMString);
procedure SetOptions(const Value: TXMLDocOptions);
procedure SetParseOptions(const Value: TParseOptions);
procedure SetStandAlone(const Value: DOMString);
procedure SetVersion(const Value: DOMString);
procedure SetXML(const Value: TStrings);
{ Methods }
function AddChild(const TagName: DOMString): IXMLNode; overload;
function AddChild(const TagName, NamespaceURI: DOMString): IXMLNode; overload;
function CreateElement(const TagOrData, NamespaceURI: DOMString): IXMLNode;
function CreateNode(const NameOrData: DOMString;
NodeType: TNodeType = ntElement; const AddlData: DOMString = ''): IXMLNode;
function GeneratePrefix(const Node: IXMLNode): DOMString;
function GetDocBinding(const TagName: DOMString;
DocNodeClass: TClass; NamespaceURI: DOMString = ''): IXMLNode;
function IsEmptyDoc: Boolean;
procedure LoadFromFile(const AFileName: DOMString);
procedure LoadFromStream(const Stream: TStream; EncodingType:
TXMLEncodingType = xetUnknown);
procedure LoadFromXML(const XML: string); overload;
procedure LoadFromXML(const XML: DOMString); overload;
procedure Refresh;
procedure RegisterDocBinding(const TagName: DOMString;
DocNodeClass: TClass; NamespaceURI: DOMString = '');
procedure Resync;
procedure SaveToFile(const AFileName: DOMString);
procedure SaveToStream(const Stream: TStream);
procedure SaveToXML(var XML: DOMString); overload;
procedure SaveToXML(var XML: string); overload;
procedure SetOnAsyncLoad(const Value: TAsyncEventHandler);
{ Properties }
property Active: Boolean read GetActive write SetActive;
property AsyncLoadState: Integer read GetAsyncLoadState;
property ChildNodes: IXMLNodeList read GetChildNodes;
property DocumentElement: IXMLNode read GetDocumentElement write SetDocumentElement;
property DOMDocument: IDOMDocument read GetDOMDocument write SetDOMDocument;
property Encoding: DOMString read GetEncoding write SetEncoding;
property FileName: DOMString read GetFileName write SetFileName;
property Modified: Boolean read GetModified;
property Node: IXMLNode read GetDocumentNode;
property NodeIndentStr: DOMString read GetNodeIndentStr write SetNodeIndentStr;
property Options: TXMLDocOptions read GetOptions write SetOptions;
property ParseOptions: TParseOptions read GetParseOptions write SetParseOptions;
property SchemaRef: DOMString read GetSchemaRef;
property StandAlone: DOMString read GetStandAlone write SetStandAlone;
property Version: DOMString read GetVersion write SetVersion;
property XML: TStrings read GetXML write SetXML;
end;
const
NodeTypeNames: array[TNodeType] of string = { Do not localize }
('', 'Element','Attribute','Text','CDATASection', 'EntityRef','Entity',
'ProcessingInstr', 'Comment','Document','DocumentType',
'DocumentFragment','Notation');
implementation
end.
|
unit uFIBScriptForm;
interface
{$I ..\FIBPlus.inc}
uses
Windows, Messages, SysUtils, Classes,
{$IFDEF D_XE2}
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls,
Vcl.StdCtrls,Vcl.Buttons,
{$ELSE}
Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls,Buttons,
{$ENDIF}
pFIBInterfaces , RegFIBPlusEditors, uFIBEditorForm
;
type
TfrmScript = class(TFIBEditorCustomForm)
Panel1: TPanel;
btnSave: TSpeedButton;
SaveDialog1: TSaveDialog;
btnExec: TSpeedButton;
btnOpen: TSpeedButton;
OpenDialog1: TOpenDialog;
StatusBar1: TStatusBar;
procedure btnSaveClick(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
procedure btnExecClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
private
protected
iViewSQL:IFIBSQLTextEditor;
viewSQL: TWinControl;
DB:TObject;
vScripter:TObject;
iScripter:IFIBScripter;
FReadOnly:boolean;
procedure ExecProgress(Line:Integer; StatementNo: Integer);
procedure PrepareForm(ForReadOnly:boolean = false);
public
destructor Destroy; override;
procedure ChangeScript(const ACaption,s:String);
end;
TfrmScript1=class(TFrmScript);
PForm=^TfrmScript;
var
frmScript: TfrmScript;
frmScript1: TfrmScript1;
procedure ShowScript(const aCaption:string; Database:TObject; Script:TStrings;ForReadOnly:boolean = false; asSubModal:boolean =False );
procedure ShowScriptEx( const aCaption:string; Database:TObject; Script:TStrings;ForReadOnly:boolean = false;
asSubModal:boolean =False ;ClassCase:integer=0);
implementation
{$R *.DFM}
uses RTTIRoutines,TypInfo;
{var
LastTop, LastLeft, LastWidth,LastHeight:integer;
}
procedure ShowScriptEx( const aCaption:string; Database:TObject; Script:TStrings;ForReadOnly:boolean = false; asSubModal:boolean =False;
ClassCase:integer=0
);
var
Caller:TForm;
Form: TfrmScript;
begin
case ClassCase of
1: begin
Form:= TfrmScript1.Create(Application);
frmScript1:=TfrmScript1(Form);
end
else
Form:= TfrmScript.Create(Application);
frmScript:=Form
end;
Form.Caption:=aCaption;
Form.DB:=Database;
Form.FReadOnly:=ForReadOnly;
Form.PrepareForm(ForReadOnly);
if Script<>nil then
Form.iViewSQL .Lines:=Script;
if not asSubModal then
begin
{ if LastTop>-1 then
with Form do
begin
Top :=LastTop;
Left:=LastLeft;
Width :=LastWidth;
Height:=LastHeight;
end;
}
Form.ShowModal;
// frmScript.Free
end
else
begin
{ if LastTop>-1 then
with frmScript do
begin
Top :=LastTop;
Left:=LastLeft;
Width :=LastWidth;
Height:=LastHeight;
end;
}
Caller:=Screen.ActiveForm;
if fsModal in Caller.FormState then
// if (Caller.FormState=TFormState(fsVisible)) then
begin
Caller.Enabled:=False;
try
// frmScript.FormStyle:=fsStayOnTop;
Form.Show ;
Form.SetFocus;
finally
Caller.Enabled:=True
end
end;
end;
end;
procedure ShowScript(const aCaption:string;Database:TObject; Script:TStrings;ForReadOnly:boolean = false; asSubModal:boolean =False);
begin
ShowScriptEx(aCaption,Database,Script,ForReadOnly,asSubModal) ;
end;
type THackWinControl=class(TCustomControl);
{ TfrmScript }
procedure TfrmScript.PrepareForm(ForReadOnly:boolean = false);
begin
btnExec.Enabled:=Assigned(DB);
viewSQL:=TWinControl(TComponentClass(GetSQLTextEditor).Create(Self));
ObjSupports(viewSQL, IFIBSQLTextEditor, iViewSQL);
vScripter:=expScripter.Create(Self);
ObjSupports(vScripter, IFIBScripter, iScripter);
iViewSQL.ReadOnly:=FReadOnly;
if FReadOnly then
btnExec.Enabled:=False;
with THackWinControl(viewSQL) do
begin
Parent:=Self;
Font.Name:='Courier New';
Font.Size:=10;
Align:=alClient;
SendToBack;
end;
end;
procedure TfrmScript.btnSaveClick(Sender: TObject);
begin
if SaveDialog1.Execute then
iViewSQL.Lines.SaveToFile(SaveDialog1.FileName)
end;
destructor TfrmScript.Destroy;
begin
iViewSQL:=nil;
iScripter:=nil;
frmScript:=nil;
inherited;
end;
procedure TfrmScript.btnOpenClick(Sender: TObject);
begin
if OpenDialog1.Execute then
iViewSQL.Lines.LoadFromFile(OpenDialog1.FileName)
end;
procedure TfrmScript.btnExecClick(Sender: TObject);
begin
//
SetObjectProp(vScripter,'Database',DB);
AssignStringsToProp(vScripter,'Script',iViewSQL.Lines.Text);
iScripter.SetOnStatExec(ExecProgress);
iScripter.ExecuteScript();
StatusBar1.SimpleText:=''
end;
procedure TfrmScript.ExecProgress(Line, StatementNo: Integer);
begin
StatusBar1.SimpleText:='Execute '+IntToStr(StatementNo)+' statement '+
'from '+IntToStr(iScripter.StatementsCount);
Application.ProcessMessages
end;
procedure TfrmScript.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree ;
if Self = frmScript then
frmScript:=nil
end;
procedure TfrmScript.ChangeScript(const ACaption, s: String);
begin
Caption:=ACaption;
iViewSQL .Lines.Text:=s
end;
procedure TfrmScript.FormDestroy(Sender: TObject);
begin
if Self = frmScript then
frmScript:=nil
else
if Self = frmScript1 then
frmScript1:=nil
end;
initialization
end.
|
unit LoanLedger;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopup, Vcl.StdCtrls, RzLabel,
Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, Data.DB, Vcl.Grids, Vcl.DBGrids,
RzDBGrid;
type
TfrmLoanLedger = class(TfrmBasePopup)
pnlLedger: TRzPanel;
grLedger: TRzDBGrid;
RzPanel1: TRzPanel;
RzLabel1: TRzLabel;
RzPanel2: TRzPanel;
RzLabel2: TRzLabel;
RzLabel3: TRzLabel;
lblPrincipalDeficit: TRzLabel;
lblInterestDeficit: TRzLabel;
RzLabel4: TRzLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure grLedgerDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure imgCloseClick(Sender: TObject);
private
{ Private declarations }
procedure GetTotalDeficit;
public
{ Public declarations }
constructor Create(AOwner: TComponent); overload; override;
constructor Create(AOwner: TComponent; ASource: TDataSource); reintroduce; overload;
end;
implementation
{$R *.dfm}
uses
LoanData, FormsUtil;
constructor TfrmLoanLedger.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
constructor TfrmLoanLedger.Create(AOwner: TComponent; ASource: TDataSource);
begin
Create(AOwner);
grLedger.DataSource := ASource;
end;
procedure TfrmLoanLedger.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
grLedger.DataSource.DataSet.Close;
Action := caFree;
end;
procedure TfrmLoanLedger.FormCreate(Sender: TObject);
begin
inherited;
grLedger.DataSource.DataSet.Open;
// ExtendLastColumn(grLedger);
GetTotalDeficit;
end;
procedure TfrmLoanLedger.GetTotalDeficit;
var
principal, interest: currency;
begin
with grLedger.DataSource.DataSet do
begin
principal := FieldByName('principal_deficit').AsCurrency;
interest := FieldByName('interest_deficit').AsCurrency;
end;
lblPrincipalDeficit.Caption := FormatCurr('###,###,##0.00;(###,###,##0.00);-',principal);
lblInterestDeficit.Caption := FormatCurr('###,###,##0.00;(###,###,##0.00);-',interest);
end;
procedure TfrmLoanLedger.grLedgerDrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
with grLedger do
begin
if DataSource.DataSet.FieldByName('event_object').AsString = 'PAY' then
begin
Canvas.Brush.Color := clMoneyGreen;
DefaultDrawColumnCell(Rect, DataCol, Column, State);
end
else
begin
Canvas.Brush.Color := clWhite;
DefaultDrawColumnCell(Rect, DataCol, Column, State);
end
end;
end;
procedure TfrmLoanLedger.imgCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
end.
|
unit oCoverSheetParam_Web;
{
================================================================================
*
* Application: CPRS - CoverSheet
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: 2015-12-04
*
* Description: Inherited from TCoverSheetParam this parameter holds
* custom items for displaying CPRS data in the CoverSheet.
*
* Notes:
*
================================================================================
}
interface
uses
System.Classes,
System.SysUtils,
Vcl.Controls,
oCoverSheetParam,
iCoverSheetIntf;
type
TCoverSheetParam_Web = class(TCoverSheetParam, ICoverSheetParam_Web)
private
{ Private declarations }
fHomePage: string;
fShowNavigator: boolean;
function getHomePage: string;
function getShowNavigator: boolean;
procedure setHomePage(const aValue: string);
procedure setShowNavigator(const aValue: boolean);
protected
{ Protected declarations }
function NewCoverSheetControl(aOwner: TComponent): TControl; override;
public
{ Public declarations }
constructor Create(aInitStr: string = '');
end;
implementation
uses
mCoverSheetDisplayPanel_Web,
oDelimitedString;
{ TCoverSheetParam_Web }
constructor TCoverSheetParam_Web.Create(aInitStr: string = '');
begin
inherited Create;
with NewDelimitedString(aInitStr) do
try
setTitle(GetPieceAsString(2, 'Mini-Browser'));
fHomePage := GetPieceAsString(3, 'http://www.google.com');
fShowNavigator := GetPieceAsBoolean(4, False);
finally
Free;
end;
end;
function TCoverSheetParam_Web.getHomePage: string;
begin
Result := fHomePage;
end;
function TCoverSheetParam_Web.getShowNavigator: boolean;
begin
Result := fShowNavigator;
end;
procedure TCoverSheetParam_Web.setHomePage(const aValue: string);
begin
fHomePage := aValue;
end;
procedure TCoverSheetParam_Web.setShowNavigator(const aValue: boolean);
begin
fShowNavigator := aValue;
end;
function TCoverSheetParam_Web.NewCoverSheetControl(aOwner: TComponent): TControl;
begin
Result := TfraCoverSheetDisplayPanel_Web.Create(aOwner);
end;
end.
|
{*********************************************}
{ TeeChart Delphi Component Library }
{ Overlayed Bars Demo }
{ Copyright (c) 1995-1996 by David Berneda }
{ All rights reserved }
{*********************************************}
unit Uoverbar;
interface
{ This form shows 3 bar series in a overlayed layout.
Each Bar Series has a different BarWidthPercent.
The order Series are drawn is the most important thing. See below.
}
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Chart, Series, ExtCtrls, Teengine, StdCtrls, Spin,
Buttons, TeeProcs;
type
TOverBarForm = class(TForm)
Chart1: TChart;
BarSeries1: TBarSeries;
BarSeries2: TBarSeries;
BarSeries3: TBarSeries;
Panel1: TPanel;
Memo1: TMemo;
BitBtn3: TBitBtn;
Label1: TLabel;
SpinEdit1: TSpinEdit;
Label2: TLabel;
SpinEdit2: TSpinEdit;
CBPatterns: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure BarSeries2Click(Sender: TChartSeries; ValueIndex: Integer;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure BarSeries1Click(Sender: TChartSeries; ValueIndex: Integer;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure SpinEdit1Change(Sender: TObject);
procedure SpinEdit2Change(Sender: TObject);
procedure CBPatternsClick(Sender: TObject);
procedure BarSeries3Click(Sender: TChartSeries; ValueIndex: Integer;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
procedure ChangeOverBars;
end;
var
OverBarForm: TOverBarForm;
implementation
{$R *.DFM}
procedure TOverBarForm.FormCreate(Sender: TObject);
var t:Longint;
begin
{ lets fill the 3 Bar Series with some random data }
{ Series3 has the biggest values, while Series1 has the smaller values }
With BarSeries3 do
begin
Clear;
for t:=1 to 10 do Add( 100+Random(30),'', clTeeColor);
end;
With BarSeries2 do
begin
Clear;
for t:=1 to 10 do Add( 50+Random(10), '', clTeeColor);
end;
With BarSeries1 do
begin
Clear;
for t:=1 to 10 do Add( 20+Random(10), '', clTeeColor);
end;
ChangeOverBars;
end;
procedure TOverBarForm.BarSeries2Click(Sender: TChartSeries; ValueIndex: Integer;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
Showmessage('You clicked the Red Bar at point #: '+inttostr(Valueindex));
end;
procedure TOverBarForm.BarSeries1Click(Sender: TChartSeries; ValueIndex: Integer;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
Showmessage('You clicked the Green Bar at point #: '+inttostr(Valueindex));
end;
procedure TOverBarForm.ChangeOverBars;
begin { compress / expand the overlayed space between bars }
BarSeries3.BarWidthPercent:=SpinEdit1.Value;
BarSeries1.BarWidthPercent:=SpinEdit1.Value-Round(SpinEdit1.Value*55.0/100.0);
BarSeries2.BarWidthPercent:=SpinEdit1.Value-Round(SpinEdit1.Value*35.0/100.0);
end;
procedure TOverBarForm.SpinEdit1Change(Sender: TObject);
begin
ChangeOverBars;
end;
procedure TOverBarForm.SpinEdit2Change(Sender: TObject);
begin { increase / decrease the 3 Series OffsetPercent property }
{ This will make partially overlay }
BarSeries3.OffsetPercent:=SpinEdit2.Value;
BarSeries1.OffsetPercent:=SpinEdit2.Value-Round(SpinEdit2.Value*55.0/100.0);
BarSeries2.OffsetPercent:=SpinEdit2.Value-Round(SpinEdit2.Value*35.0/100.0);
end;
procedure TOverBarForm.CBPatternsClick(Sender: TObject);
begin
if CBPatterns.Checked then
begin
BarSeries1.BarBrush.Style:=bsFDiagonal;
BarSeries2.BarBrush.Style:=bsBDiagonal;
BarSeries3.BarBrush.Style:=bsDiagCross;
Chart1.BackColor:=clWhite;
end
else
begin
BarSeries1.BarBrush.Style:=bsSolid;
BarSeries2.BarBrush.Style:=bsSolid;
BarSeries3.BarBrush.Style:=bsSolid;
Chart1.BackColor:=clTeeColor;
end;
end;
procedure TOverBarForm.BarSeries3Click(Sender: TChartSeries;
ValueIndex: Integer; Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
Showmessage('You clicked the Blue Bar at point #: '+inttostr(Valueindex));
end;
end.
|
unit fRename;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fAutoSz, StdCtrls, ORFn, ORCtrls, VA508AccessibilityManager;
type
TfrmRename = class(TfrmAutoSz)
lblRename: TLabel;
txtName: TCaptionEdit;
cmdOK: TButton;
cmdCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
private
OKPressed: Boolean;
end;
function ExecuteRename(var AName: string; const APrompt: string): Boolean;
implementation
{$R *.DFM}
function ExecuteRename(var AName: string; const APrompt: string): Boolean;
var
frmRename: TfrmRename;
begin
Result := False;
frmRename := TfrmRename.Create(Application);
try
ResizeFormToFont(TForm(frmRename));
with frmRename do
begin
lblRename.Caption := APrompt;
txtName.Text := AName;
txtName.SelectAll;
ShowModal;
if OKPressed then
begin
AName := txtName.Text;
Result := True;
end;
end;
finally
frmRename.Release;
end;
end;
procedure TfrmRename.FormCreate(Sender: TObject);
begin
inherited;
OKPressed := False;
end;
procedure TfrmRename.cmdOKClick(Sender: TObject);
begin
inherited;
OKPressed := True;
Close;
end;
procedure TfrmRename.cmdCancelClick(Sender: TObject);
begin
inherited;
Close;
end;
end.
|
unit NumLabelFrame;
interface
uses
SysUtils, Classes, Controls, Forms, StdCtrls, Buttons, ItemsDef, ActnList,
IniFiles, Core;
type
TfrmNumLabelTpl = class(TFrame)
grpNumLabelProps: TGroupBox;
lbNumLabelName: TLabel;
cbbName: TComboBox;
lbValueType: TLabel;
cbbValueType: TComboBox;
lbDefaultAction: TLabel;
cbbDefaultAction: TComboBox;
lbBaseValue: TLabel;
edBaseValue: TEdit;
grpHelp: TGroupBox;
mmoHelp: TMemo;
edPrefix: TEdit;
edSuffix: TEdit;
lbPrefix: TLabel;
lbSuffix: TLabel;
btnOK: TBitBtn;
btnCancel: TBitBtn;
actlstNumLabel: TActionList;
actOK: TAction;
actCancel: TAction;
procedure actOKExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure actCancelExecute(Sender: TObject);
private
{ Private declarations }
procedure WriteItem();
public
{ Public declarations }
Form: TForm;
CurrLangNumLabel: string;
NumProject: TNumProject;
NumLabelTpl: TNumLabelTpl;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ReadItem();
procedure ChangeLanguage();
end;
var
NumLabelCreated: Boolean = False;
sBaseValueEmpty: string = 'Пустое базовое значение нумератора';
sActionNotApplicable: string = 'Основное действие не применимо к значению нумератора';
implementation
uses MainForm;
{$R *.dfm}
procedure TfrmNumLabelTpl.ChangeLanguage();
const
CR_LF = #13#10;
CR_LF2 = '^';//Chr(3);
var
s, Part: string;
begin
if not Assigned(LangFile) then Exit;
if NumLabelCreated then
begin
Part:= 'NumLabel';
Self.grpNumLabelProps.Caption:= LangFile.ReadString(Part, 'sgrpNumLabelProps', Self.grpNumLabelProps.Caption);
Self.lbNumLabelName.Caption:= LangFile.ReadString(Part, 'slbNumLabelName', Self.lbNumLabelName.Caption);
Self.lbDefaultAction.Caption:= LangFile.ReadString(Part, 'slbDefaultAction', Self.lbDefaultAction.Caption);
Self.lbPrefix.Caption:= LangFile.ReadString(Part, 'slbPrefix', Self.lbPrefix.Caption);
Self.lbBaseValue.Caption:= LangFile.ReadString(Part, 'slbBaseValue', Self.lbBaseValue.Caption);
Self.lbSuffix.Caption:= LangFile.ReadString(Part, 'slbSuffix', Self.lbSuffix.Caption);
Self.lbValueType.Caption:= LangFile.ReadString(Part, 'slbValueType', Self.lbValueType.Caption);
Self.btnOK.Caption:= LangFile.ReadString(Part, 'sbtnOk', Self.btnOK.Caption);
Self.btnCancel.Caption:= LangFile.ReadString(Part, 'sbtnCancel', Self.btnCancel.Caption);
sBaseValueEmpty:=LangFile.ReadString(sBaseValueEmpty, 'sBaseValueEmpty', sBaseValueEmpty);
sActionNotApplicable:=LangFile.ReadString(sActionNotApplicable, 'sActionNotApplicable', sActionNotApplicable);
Self.grpHelp.Caption:= LangFile.ReadString(Part, 'sgrpHelp', Self.grpHelp.Caption);
//LangFile.WriteString(Part, 'smmoHelp',mmoToStr(mmoHelp));
s:=LangFile.ReadString(Part, 'smmoHelp', Self.mmoHelp.Text);
Self.mmoHelp.Text:=StringReplace(s, CR_LF2, CR_LF, [rfReplaceAll]);
Self.Form.Caption:= MainForm.sNewNumLabelTplName;
end;
end;
constructor TfrmNumLabelTpl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//StopUpdate:=False;
//PreviewBgImage:=nil;
cbbName.Clear();
cbbName.AddItem(csNumber, nil);
cbbName.AddItem(csRow, nil);
cbbName.AddItem(csPlace, nil);
cbbName.AddItem(csPrice, nil);
cbbName.AddItem(csSerial, nil);
cbbDefaultAction.Clear();
cbbDefaultAction.AddItem('=', nil);
cbbDefaultAction.AddItem('+', nil);
cbbDefaultAction.AddItem('-', nil);
//
NumLabelCreated:= True;
ChangeLanguage;
end;
destructor TfrmNumLabelTpl.Destroy;
begin
//if Assigned(PreviewBgImage) then FreeAndNil(PreviewBgImage);
//StopUpdate:=True;
NumLabelCreated:= False;
inherited Destroy();
end;
procedure TfrmNumLabelTpl.ReadItem();
begin
if not Assigned(NumLabelTpl) then Exit;
cbbName.Text:=NumLabelTpl.Name;
cbbDefaultAction.Text:=NumLabelTpl.Action;
edBaseValue.Text:=NumLabelTpl.BaseValue;
edPrefix.Text:=NumLabelTpl.Prefix;
edSuffix.Text:=NumLabelTpl.Suffix;
end;
procedure TfrmNumLabelTpl.WriteItem();
begin
if not Assigned(NumLabelTpl) then Exit;
NumLabelTpl.Name:=cbbName.Text;
NumLabelTpl.Action:=cbbDefaultAction.Text;
NumLabelTpl.BaseValue:=edBaseValue.Text;
NumLabelTpl.Prefix:=edPrefix.Text;
NumLabelTpl.Suffix:=edSuffix.Text;
end;
procedure TfrmNumLabelTpl.actOKExecute(Sender: TObject);
var
s, ss: string;
begin
s:=Trim(edBaseValue.Text);
if Length(s)=0 then
begin
Core.ShowWarning(sBaseValueEmpty, sWarning);
Exit;
end;
if Trim(cbbDefaultAction.Text)<>'=' then
begin
ss:='0123456789';
if Pos(Copy(s, Length(s), 1), ss)=0 then
begin
Core.ShowWarning(sActionNotApplicable, sWarning);
Exit;
end;
end;
WriteItem();
if Assigned(NumLabelTpl) then
begin
NumLabelTpl.Write();
NumLabelTpl:=nil;
end;
Core.CmdQueue.AddCmd('REFRESH NUMLABEL_LIST');
if (Parent is TSomePage) then
begin
Core.CmdQueue.AddCmd('CLOSE '+IntToStr((Parent as TSomePage).PageID));
end;
if Assigned(Form) then Form.Close();
end;
procedure TfrmNumLabelTpl.actCancelExecute(Sender: TObject);
begin
NumLabelTpl:=nil;
if (Parent is TSomePage) then
begin
Core.CmdQueue.AddCmd('CLOSE '+IntToStr((Parent as TSomePage).PageID));
end;
if Assigned(Form) then Form.Close();
end;
procedure TfrmNumLabelTpl.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(Form) then Form.Release();
end;
end.
|
unit BCEditor.Editor.Search.Highlighter.Colors;
interface
uses
Classes, Graphics, BCEditor.Consts, BCEditor.Types;
type
TBCEditorSearchColors = class(TPersistent)
strict private
FBackground: TColor;
FForeground: TColor;
FOnChange: TBCEditorSearchChangeEvent;
procedure SetBackground(const Value: TColor);
procedure SetForeground(const Value: TColor);
procedure DoChange;
public
constructor Create;
procedure Assign(Source: TPersistent); override;
published
property Background: TColor read FBackground write SetBackground default clSearchHighlighter;
property Foreground: TColor read FForeground write SetForeground default clWindowText;
property OnChange: TBCEditorSearchChangeEvent read FOnChange write FOnChange;
end;
implementation
{ TBCEditorSearchColors }
constructor TBCEditorSearchColors.Create;
begin
inherited;
FBackground := clSearchHighlighter;
FForeground := clWindowText;
end;
procedure TBCEditorSearchColors.Assign(Source: TPersistent);
begin
if Source is TBCEditorSearchColors then
with Source as TBCEditorSearchColors do
begin
Self.FBackground := FBackground;
Self.FForeground := FForeground;
Self.DoChange;
end
else
inherited;
end;
procedure TBCEditorSearchColors.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(scRefresh);
end;
procedure TBCEditorSearchColors.SetBackground(const Value: TColor);
begin
if FBackground <> Value then
begin
FBackground := Value;
DoChange;
end;
end;
procedure TBCEditorSearchColors.SetForeground(const Value: TColor);
begin
if FForeground <> Value then
begin
FForeground := Value;
DoChange;
end;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name:
Author: Roman
Purpose: Базовый класс для всех трейдеров. Реализует интерфейс IStockAlerter
History:
-----------------------------------------------------------------------------}
unit FC.Trade.Alerter.Base;
{$I Compiler.inc}
{$DEFINE IGNORE_UNKNOWN_PROPERTIES}
interface
uses
Classes, Windows, Math,Contnrs, Controls, SysUtils, BaseUtils, ActnList, Forms, Properties.Obj, Properties.Definitions,
StockChart.Definitions, StockChart.Definitions.Drawing,
Serialization, FC.Definitions;
type
{ TStockAlerter }
TSCAlerterState = (isReading);
TSCAlerterStates = set of TSCAlerterState;
TStockAlerterBase = class;
TStockAlerterClass = class of TStockAlerterBase;
TLastOrderType = (lotNone,lotBuy,lotSell);
TLogRecord = class
public
DateTime: TDateTime;
Text : string;
end;
//Псевдо-интерфейс, необходимый для генерации уникального GUID
//Будем использовать его в ExternalData экспертов, чтобы отличить
//где наш эксперта, а где не наш
IStockAlerterExternalIdentifier = interface (ISCAttribute)
['{40DE82A4-840E-4AA3-A89C-78BBE85691D0}']
function GetIdentification: string;
function GetAlerterIID: TGUID;
end;
//... и собственно класс, его реализующий
TStockAlerterExternalIdentifier = class (TNameValuePersistentObjectRefCounted,IStockAlerterExternalIdentifier,ISCAttribute)
private
FAlerterIID: TGUID;
FIdentification: string;
procedure SetIdentification(const Value: string);
function GetIdentification: string;
function GetAlerterIID: TGUID;
protected
procedure OnDefineValues; override;
property Identification: string read FIdentification write SetIdentification;
property AlerterIID: TGUID read FAlerterIID write FAlerterIID;
constructor Create; virtual;
end;
TStockAlerterExternalIdentifierClass = class of TStockAlerterExternalIdentifier;
TStockBrokerEventHandler = class;
//Базовый
TStockAlerterBase = class (TNameValuePersistentObjectRefCounted,IStockAlerter,IPropertyChangeHandler)
private
FExternalIdentifiers: TInterfaceList; //of IStockAlerterExternalIdentifier
FExternalIdentifierClass: TStockAlerterExternalIdentifierClass;
FIID : TGUID;
FCategory : string;
FName : string;
FHandlers : TInterfaceList;
FLastTime : TDateTime;
FBroker : IStockBroker;
FProject : IStockProject;
FState : TSCAlerterStates;
FEnabled : boolean;
FBrokerEventHandler : TStockBrokerEventHandler;
FPropStartFrom : TPropertyTime;
FPropStopAt : TPropertyTime;
FPropBreak : TPropertySmallUint;
FPropShowMessage: TPropertyYesNo;
FPropSendMail : TPropertyYesNo;
FPropPlaySound : TPropertyYesNo;
FVisibleProperties: TPropertyList;
function GetExternalIdentifier(index: integer): IStockAlerterExternalIdentifier;
function GetEventHandler(index: integer): IStockAlerterEventHandler;
procedure CachePropertyValues;
protected
FID : TGUID;
//Сериализация (TNameValuePersistentObjectRefCounted)
procedure OnDefineValues; override;
procedure OnReadValue(const aReader: INameValueDataReader; const aName: string; var aHandled: boolean); override;
procedure OnWriteValues(const aWriter: INameValueDataWriter); override;
procedure AddMessage(const a_Message: string);
procedure FormatMessage(const aMessage: string; out aCaption,aText: string); virtual;
//Вспомогательная функция для находждения "наших" индикаторов на указанном чарте
//Если таковой не находится - мы его создаем. Параметр aIndicatorIdentification должен быть
//уникален для каждого создаваемого индикатора
//Параметр aRegister указывает, регистрировать ли созданный индикатор в трейдере (назначить ему атрибут
//ExternalId трейдера). По регистрации см. также OnAddObject
function CreateOrFindIndicator(const aChart: IStockChart; const aIID: TGUID; aIndicatorIdentification: string; aRegister: boolean=true): ISCIndicator; overload;
function CreateOrFindIndicator(const aChart: IStockChart; const aIID: TGUID; aIndicatorIdentification: string; aRegister: boolean; out aCreated: boolean): ISCIndicator; overload;
//Специальные методы-обработчики для наследников, определяющие начало и конец работы треедра
//Вызываются при инициализации трейдера брокером (см. SetBroker)
procedure OnBeginWorkSession; virtual;
procedure OnEndWorkSession; virtual;
procedure OnAddObject(const aIndicator:ISCIndicator; aIndicatorIdentification: string); virtual;
procedure OnRemoveObject(const aIndicator:ISCIndicator); virtual;
procedure OnPropertyChanged(aNotifier:TProperty); virtual;
procedure OnPropertyCreated(aNotifier:TProperty); virtual;
//Оставлено для потомков. Методы, в которых нужно создавать и удалять свои объекты
procedure OnCreateObjects; virtual;
procedure OnReleaseObjects; virtual;
procedure GetProperties(aList: TPropertyList); overload; virtual;
function GetProperties: IPropertyCollection; overload;
procedure RegisterProperties(aProperties: array of TProperty);
procedure UnRegisterProperties(aProperties: array of TProperty);
property ExternalIdentifierClass: TStockAlerterExternalIdentifierClass read FExternalIdentifierClass write FExternalIdentifierClass;
function ExternalIdentifierCount: integer;
property ExternalIdentifiers[index: integer]: IStockAlerterExternalIdentifier read GetExternalIdentifier;
//Найти наш идентификатор в указанном индикаторе. Если нет, возврашает nil;
function FindExternalIdentifier(const aIndicator:ISCIndicator; aIndicatorIdentification: string): IStockAlerterExternalIdentifier;
property State : TSCAlerterStates read FState;
property PropStartFrom : TPropertyTime read FPropStartFrom;
property PropStopAt : TPropertyTime read FPropStopAt;
property PropBreak : TPropertySmallUint read FPropBreak;
property PropShowMessage: TPropertyYesNo read FPropShowMessage;
property PropSendMail : TPropertyYesNo read FPropSendMail;
property PropPlaySound : TPropertyYesNo read FPropPlaySound;
constructor Create; virtual;
public
//from IPersistentObject
procedure ReadData(const aReader: IDataReader); override;
//from IStockAlerter
function GetCategory: string;
function GetName: string;
procedure SetCategory(const aValue: string);
procedure SetName(const aValue : string);
function GetSymbol: string;
function GetID: TGUID;
function GetBroker: IStockBroker;
procedure SetBroker(const aBroker: IStockBroker); virtual;
function GetProject: IStockProject;
procedure SetProject(const aValue : IStockProject); virtual;
function GetEnabled: boolean;
procedure SetEnabled(const aValue : boolean); virtual;
//Посчитать
procedure IStockAlerter.Update = UpdateStep1;
procedure UpdateStep1(const aTime: TDateTime); virtual;
procedure UpdateStep2(const aTime: TDateTime); virtual; abstract;
procedure Invalidate;
procedure AddEventHandler(const aHandler: IStockAlerterEventHandler);
procedure RemoveEventHandler(const aHandler: IStockAlerterEventHandler);
function ShowPropertyWindow: boolean;
function IsThis(const aAlerter: IStockAlerter): boolean;
//end of IStockAlerter
property IID: TGUID read FIID write FIID;
function EventHandlerCount: integer;
property EventHandler[index:integer]:IStockAlerterEventHandler read GetEventHandler;
procedure Dispose; virtual;
constructor CreateNaked; override;
destructor Destroy; override;
end;
TStockBrokerEventHandler = class (TInterfacedObject,IStockBrokerEventHandler)
private
FOwner: TStockAlerterBase;
public
constructor Create (aOwner: TStockAlerterBase);
destructor Destroy; override;
procedure OnStart (const aSender: IStockBroker);
procedure OnNewOrder (const aSender: IStockBroker; const aOrder: IStockOrder);
procedure OnModifyOrder(const aSender: IStockBroker; const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
procedure OnNewData (const aSender: IStockBroker; const aSymbol: string);
procedure OnNewMessage (const aSender: IStockBroker; const aMessage: IStockBrokerMessage); overload;
procedure OnNewMessage (const aSender: IStockBroker; const aOrder: IStockOrder; const aMessage: IStockBrokerMessage); overload;
end;
implementation
uses SystemService, Log, FC.Trade.OrderCollection, FC.Singletons,
StockChart.Indicators.Properties.Dialog, FC.DataUtils, FC.General.Mailer, StockChart.Obj,
FC.fmUIDataStorage,Application.Definitions;
{ TStockAlerterBase }
constructor TStockAlerterBase.CreateNaked;
begin
FState:=[isReading];
inherited;
Create;
Exclude(FState,isReading);
end;
constructor TStockAlerterBase.Create;
begin
inherited Create;
FBrokerEventHandler:=TStockBrokerEventHandler.Create(self);
IInterface(FBrokerEventHandler)._AddRef;
FExternalIdentifiers:=TInterfaceList.Create;
FHandlers:=TInterfaceList.Create;
FExternalIdentifierClass:=TStockAlerterExternalIdentifier;
CreateGUID(FID);
FLastTime:=-1;
FPropStartFrom:=TPropertyTime.Create('Time','Start From',self);
FPropStartFrom.Value:=0;
FPropStartFrom.HelpString:='You can set start time of the alerter';
FPropStopAt:=TPropertyTime.Create('Time','Stop At',self);
FPropStopAt.Value:=0;
FPropStartFrom.HelpString:='You can set stop time of the alerter';
FPropBreak:=TPropertySmallUint.Create('Time','Break In Minutes',self);
FPropBreak.Value:=5;
FPropBreak.HelpString:='The break between alerter updates';
FPropShowMessage:= TPropertyYesNo.Create('Notification','Show Baloon',self);
FPropShowMessage.Value:=true;
FPropSendMail := TPropertyYesNo.Create('Notification','Send E-Mail',self);
FPropPlaySound := TPropertyYesNo.Create('Notification','Play Sound',self);
RegisterProperties([FPropStartFrom,FPropStopAt,FPropBreak,FPropShowMessage,FPropSendMail,FPropPlaySound]);
CachePropertyValues;
StockBrokerConnectionRegistry.AddBrokerEventHandler(FBrokerEventHandler);
end;
destructor TStockAlerterBase.Destroy;
begin
FBrokerEventHandler.FOwner:=nil;
StockBrokerConnectionRegistry.RemoveBrokerEventHandler(FBrokerEventHandler);
IInterface(FBrokerEventHandler)._Release;
FBrokerEventHandler:=nil;
//FMessages:=nil;
FreeAndNil(FHandlers);
FreeAndNil(FVisibleProperties);
FreeAndNil(FExternalIdentifiers);
inherited;
end;
procedure TStockAlerterBase.Dispose;
begin
if FVisibleProperties<>nil then
FVisibleProperties.Clear;
FreeAndNil(FPropStartFrom);
FreeAndNil(FPropStopAt);
FreeAndNil(FPropBreak);
FreeAndNil(FPropShowMessage);
FreeAndNil(FPropSendMail);
FreeAndNil(FPropPlaySound);
FBroker:=nil;
FProject:=nil;
end;
function TStockAlerterBase.GetID: TGUID;
begin
result:=FID;
end;
procedure TStockAlerterBase.Invalidate;
var
i: integer;
begin
FLastTime:=-1;
for i:=0 to EventHandlerCount-1 do
EventHandler[i].OnInvalidate(self);
end;
function TStockAlerterBase.GetCategory: string;
begin
result:=FCategory;
end;
function TStockAlerterBase.GetName: string;
begin
result:=FName;
end;
procedure TStockAlerterBase.UpdateStep1(const aTime: TDateTime);
begin
if not FEnabled then
exit;
if FLastTime>=aTime then
exit;
//Не чаще указанного диапазона
if TStockDataUtils.ToMinutes(aTime-FLastTime)<FPropBreak.Value then
exit;
if ((Frac(aTime)>=FPropStartFrom.Value) and (Frac(aTime)<FPropStopAt.Value)) or
(FPropStartFrom.Value=FPropStopAt.Value) then
try
UpdateStep2(aTime);
except
on E:EAbort do;
end;
FLastTime:=aTime;
end;
procedure TStockAlerterBase.OnDefineValues;
begin
inherited;
DefValGUID('ID',FID);
DefValString('Category',FCategory);
DefValString('Name',FName);
DefValBoolean('Enabled',FEnabled);
end;
procedure TStockAlerterBase.OnWriteValues(const aWriter: INameValueDataWriter);
var
aPropList: TPropertyList;
i: integer;
begin
inherited;
aPropList:=TPropertyList.Create;
try
GetProperties(aPropList);
for i:=0 to aPropList.Count-1 do
aWriter.WriteVariant('Property:'+aPropList[i].Category+'\'+aPropList[i].Name,aPropList[i].Value);
finally
aPropList.Free;
end;
end;
procedure TStockAlerterBase.OnReadValue(const aReader: INameValueDataReader; const aName: string; var aHandled: boolean);
var
aPropList: TPropertyList;
i,j: integer;
s: string;
v: variant;
begin
inherited;
if StrIsInLeft('Property:',pchar(aName)) then
begin
aPropList:=TPropertyList.Create;
try
GetProperties(aPropList);
for i:=0 to aPropList.Count-1 do
begin
s:='Property:'+aPropList[i].Category+'\'+aPropList[i].Name;
if s=aName then
aHandled:=true;
//Устаревшие названия
if not aHandled and (aPropList[i].ObsoleteNames<>nil) then
for j:=0 to aPropList[i].ObsoleteNames.Count-1 do
begin
s:='Property:'+aPropList[i].Category+'\'+aPropList[i].ObsoleteNames[j];
if s=aName then
begin
aHandled:=true;
end
end;
//Если имя подходит - считываем
if (aHandled) then
begin
aReader.ReadVariant(v);
aPropList[i].Value:=v;
break;
end;
end;
finally
aPropList.Free;
end;
CachePropertyValues;
{$IFDEF IGNORE_UNKNOWN_PROPERTIES}
if not aHandled then
begin
aHandled:=true;
aReader.ReadVariant(v);
end;
{$ENDIF}
end
end;
procedure TStockAlerterBase.OnCreateObjects;
begin
end;
procedure TStockAlerterBase.OnReleaseObjects;
begin
end;
procedure TStockAlerterBase.AddEventHandler(const aHandler: IStockAlerterEventHandler);
begin
if FHandlers.IndexOf(aHandler)<>-1 then
raise ESCItemAlreadyExists.Create;
FHandlers.Add(aHandler);
end;
procedure TStockAlerterBase.RemoveEventHandler(const aHandler: IStockAlerterEventHandler);
begin
FHandlers.Remove(aHandler);
end;
function TStockAlerterBase.GetEnabled: boolean;
begin
result:=FEnabled;
end;
function TStockAlerterBase.GetEventHandler(index: integer): IStockAlerterEventHandler;
begin
result:=FHandlers[index] as IStockAlerterEventHandler;
end;
function TStockAlerterBase.EventHandlerCount: integer;
begin
result:=FHandlers.Count;
end;
procedure TStockAlerterBase.SetName(const aValue: string);
begin
FName:=aValue;
OnPropertyChanged(nil);
end;
procedure TStockAlerterBase.SetCategory(const aValue: string);
begin
FCategory:=aValue;
OnPropertyChanged(nil);
end;
procedure TStockAlerterBase.SetEnabled(const aValue: boolean);
begin
FEnabled:=aValue;
end;
procedure TStockAlerterBase.AddMessage(const a_Message: string);
var
aCaption,aText: string;
begin
aText:=DateTimeToStr(GetBroker.GetCurrentTime)+#9+GetSymbol+#9+self.GetName+': '+a_Message;
Log.AppendLineToFile(AppPath+'alerts.log',aText);
FormatMessage(a_Message,aCaption,aText);
if PropShowMessage.Value then
Workspace.MainFrame.ShowTrayBalloonHint(aCaption,aText,btInfo);
if PropSendMail.Value then
with TMailer.Create() do
begin
MailSafe(aCaption,aText);
Free;
end;
end;
function TStockAlerterBase.ExternalIdentifierCount: integer;
begin
result:=FExternalIdentifiers.Count;
end;
function TStockAlerterBase.FindExternalIdentifier(const aIndicator: ISCIndicator; aIndicatorIdentification: string): IStockAlerterExternalIdentifier;
var
i: integer;
begin
//Ищем, нет ли такого атриубута у индикатора уже
for i := 0 to aIndicator.GetAttributes.Count-1 do
if (Supports (aIndicator.GetAttributes.Items[i],IStockAlerterExternalIdentifier,result)) and
(IsEqualGUID(result.GetAlerterIID,FIID)) then
begin
if result.GetIdentification=aIndicatorIdentification then
exit; //Уже идентифицирован
end;
result:=nil;
end;
procedure TStockAlerterBase.FormatMessage(const aMessage: string; out aCaption, aText: string);
begin
aCaption:='Alerter "'+self.GetName+'"';
aText:=DateTimeToStr(GetBroker.GetCurrentTime)+', '+GetSymbol+#13#10+aMessage;
end;
function TStockAlerterBase.GetExternalIdentifier(index: integer): IStockAlerterExternalIdentifier;
begin
result:=FExternalIdentifiers[index] as IStockAlerterExternalIdentifier;
end;
procedure TStockAlerterBase.ReadData(const aReader: IDataReader);
begin
Include(FState,isReading);
inherited;
Exclude(FState,isReading);
end;
procedure TStockAlerterBase.OnAddObject(const aIndicator:ISCIndicator; aIndicatorIdentification: string);
var
aId : IStockAlerterExternalIdentifier;
aIdImpl: TStockAlerterExternalIdentifier;
i: integer;
begin
aIndicator.AddUsing('Alerter "'+GetName+'"');
//Ищем, не создавали ли мы раньше такой идентификатор
aId:=FindExternalIdentifier(aIndicator,aIndicatorIdentification);
//Если не нашли
if aId=nil then
begin
//Проверка. Идентификатор не должен повторяться. Поэтому если у нас такой идентификатор
//зарегистрирован, то скорее, это ошибка в наследниках - пытаются использовать один и тот же Id
for i := 0 to ExternalIdentifierCount - 1 do
begin
if ExternalIdentifiers[i].GetIdentification=aIndicatorIdentification then
raise EStockError.Create('Duplicate identification string');
end;
Assert(FExternalIdentifierClass<>nil);
aIdImpl:=FExternalIdentifierClass.Create;
aIdImpl.Identification:=aIndicatorIdentification;
aIdImpl.FAlerterIID:=FIID;
aId:=aIdImpl;
//Добавляем в коллекцию
FExternalIdentifiers.Add(aId);
//Нужно дописать свои идентификационные данные к индикатору
Assert(aId<>nil);
Assert(aId.GetIdentification=aIndicatorIdentification);
aIndicator.GetAttributes.Add(aId);
end;
end;
procedure TStockAlerterBase.OnBeginWorkSession;
begin
end;
procedure TStockAlerterBase.OnEndWorkSession;
begin
end;
procedure TStockAlerterBase.OnRemoveObject(const aIndicator:ISCIndicator);
var
i: integer;
aId : IStockAlerterExternalIdentifier;
aOurs : boolean;
begin
aIndicator.RemoveUsing('Alerter "'+GetName+'"');
aOurs:=false;
//Удаляем свои идентификационные данные
for i := aIndicator.GetAttributes.Count-1 downto 0 do
if (Supports (aIndicator.GetAttributes.Items[i],IStockAlerterExternalIdentifier,aId)) and
(IsEqualGUID(aId.GetAlerterIID,FIID)) then
begin
aIndicator.GetAttributes.Remove(aId);
aOurs:=true;
end;
if aOurs then
if GetParentStockChart(aIndicator)<>nil then
GetParentStockChart(aIndicator).DeleteIndicator(aIndicator);
end;
function TStockAlerterBase.ShowPropertyWindow: boolean;
var
aDialog: TSCIndicatorPropertiesDialog;
aPropList: TPropertyList;
begin
result:=false;
aPropList:=TPropertyList.Create;
try
GetProperties(aPropList);
aDialog:=TSCIndicatorPropertiesDialog.Create(aPropList,GetName);
try
if aDialog.ShowModal=mrOk then
result:=true;
finally
aDialog.Free;
end;
finally
aPropList.Free;
end;
end;
procedure TStockAlerterBase.GetProperties(aList: TPropertyList);
var
i: integer;
begin
if FVisibleProperties<>nil then
for i:=0 to FVisibleProperties.Count-1 do
aList.Add(FVisibleProperties[i]);
end;
procedure TStockAlerterBase.OnPropertyChanged(aNotifier: TProperty);
var
i: integer;
begin
for i:=0 to EventHandlerCount-1 do
EventHandler[i].OnPropertiesChanged(self);
CachePropertyValues;
end;
procedure TStockAlerterBase.OnPropertyCreated(aNotifier: TProperty);
begin
end;
function TStockAlerterBase.GetProperties: IPropertyCollection;
var
aCollection: TPropertyCollection;
begin
aCollection:=TPropertyCollection.Create;
GetProperties(aCollection.List);
result:=aCollection;
end;
procedure TStockAlerterBase.RegisterProperties(aProperties: array of TProperty);
var
i: integer;
begin
if Length(aProperties)=0 then
exit;
if FVisibleProperties=nil then
FVisibleProperties:=TPropertyList.Create;
for i:=0 to High(aProperties) do
begin
if FVisibleProperties.IndexOf(aProperties[i])=-1 then
FVisibleProperties.Add(aProperties[i]);
end;
end;
procedure TStockAlerterBase.UnRegisterProperties(aProperties: array of TProperty);
var
i: integer;
begin
if Length(aProperties)=0 then
exit;
if FVisibleProperties=nil then
exit;
for i:=0 to High(aProperties) do
FVisibleProperties.Remove(aProperties[i]);
end;
procedure TStockAlerterBase.CachePropertyValues;
begin
end;
procedure TStockAlerterBase.SetBroker(const aBroker: IStockBroker);
begin
if aBroker=FBroker then
exit;
//Если брокера сняли, считаем, что конец текущий работы
if (aBroker=nil) then
OnEndWorkSession;
FBroker:=aBroker;
if (FBroker<>nil) then
OnBeginWorkSession;
end;
function TStockAlerterBase.GetBroker: IStockBroker;
begin
result:=FBroker;
end;
function TStockAlerterBase.GetSymbol: string;
begin
result:=FProject.GetStockSymbol;
end;
procedure TStockAlerterBase.SetProject(const aValue: IStockProject);
begin
if GetProject=aValue then
exit;
if FProject<>nil then
OnReleaseObjects;
FProject:=aValue;
if FProject<>nil then
OnCreateObjects;
end;
function TStockAlerterBase.GetProject: IStockProject;
begin
result:=FProject;
end;
function TStockAlerterBase.IsThis(const aAlerter: IStockAlerter): boolean;
begin
result:=IsEqualGUID(aAlerter.GetID,self.GetID);
end;
function TStockAlerterBase.CreateOrFindIndicator(const aChart: IStockChart; const aIID: TGUID; aIndicatorIdentification: string; aRegister: boolean=true): ISCIndicator;
var
aRes: boolean;
begin
result:=CreateOrFindIndicator(aChart,aIID,aIndicatorIdentification,aRegister, aRes);
end;
function TStockAlerterBase.CreateOrFindIndicator(const aChart: IStockChart; const aIID: TGUID; aIndicatorIdentification: string; aRegister: boolean; out aCreated: boolean): ISCIndicator;
var
aIndicators: ISCIndicatorCollection;
aId: IStockAlerterExternalIdentifier;
i: integer;
begin
//Ищем среди уже существующих
aIndicators:=aChart.FindIndicators(aIID);
aId:=nil;
result:=nil;
for i := 0 to aIndicators.Count- 1 do
begin
aId:=FindExternalIdentifier(aIndicators.Items[i],aIndicatorIdentification);
if aId<>nil then
begin
result:=aIndicators.Items[i];
break;
end;
end;
//Итак, нашли среди существующих
if result<>nil then
begin
aCreated:=false;
end
//Если нет - тогда создаем
else begin
result:=aChart.CreateIndicator(IndicatorFactory.GetIndicatorInfo(aIID),false);
aCreated:=true;
end;
//Регистрируем индикатор
if aRegister then
OnAddObject(result,aIndicatorIdentification);
end;
{ TStockAlerterExternalIdentifier }
constructor TStockAlerterExternalIdentifier.Create;
begin
inherited Create;
end;
function TStockAlerterExternalIdentifier.GetIdentification: string;
begin
result:=FIdentification;
end;
function TStockAlerterExternalIdentifier.GetAlerterIID: TGUID;
begin
result:=FAlerterIID;
end;
procedure TStockAlerterExternalIdentifier.OnDefineValues;
begin
inherited;
DefValString('Identification',FIdentification);
end;
procedure TStockAlerterExternalIdentifier.SetIdentification(const Value: string);
begin
FIdentification := Value;
end;
{ TStockBrokerEventHandler }
constructor TStockBrokerEventHandler.Create(aOwner: TStockAlerterBase);
begin
inherited Create;
FOwner:=aOwner;
end;
destructor TStockBrokerEventHandler.Destroy;
begin
Assert(FOwner=nil);
inherited;
end;
procedure TStockBrokerEventHandler.OnModifyOrder(const aSender: IStockBroker; const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs);
begin
end;
procedure TStockBrokerEventHandler.OnNewData(const aSender: IStockBroker; const aSymbol: string);
begin
if FOwner.GetEnabled then
if AnsiSameText(FOwner.GetSymbol,aSymbol) then
begin
FOwner.SetBroker(aSender);
FOwner.UpdateStep1(aSender.GetCurrentTime);
end;
end;
procedure TStockBrokerEventHandler.OnNewMessage(const aSender: IStockBroker; const aMessage: IStockBrokerMessage);
begin
end;
procedure TStockBrokerEventHandler.OnNewMessage(const aSender: IStockBroker; const aOrder: IStockOrder; const aMessage: IStockBrokerMessage);
begin
end;
procedure TStockBrokerEventHandler.OnNewOrder(const aSender: IStockBroker; const aOrder: IStockOrder);
begin
end;
procedure TStockBrokerEventHandler.OnStart(const aSender: IStockBroker);
begin
end;
initialization
Serialization.TClassFactory.RegisterClass(TStockAlerterExternalIdentifier);
Serialization.TClassFactory.RegisterClass(TStockAlerterBase);
end.
|
unit LLCLPng;
{
LLCL - FPC/Lazarus Light LCL
based upon
LVCL - Very LIGHT VCL
----------------------------
This file is a part of the Light LCL (LLCL).
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/.
This Source Code Form is "Incompatible With Secondary Licenses",
as defined by the Mozilla Public License, v. 2.0.
Copyright (c) 2015-2016 ChrisF
Based upon the Very LIGHT VCL (LVCL):
Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info
Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr
Version 1.02:
Version 1.01:
* File creation.
* PNG to BMP conversion
}
{$IFDEF FPC}
{$define LLCL_FPC_MODESECTION}
{$I LLCLFPCInc.inc} // For mode
{$undef LLCL_FPC_MODESECTION}
{$ENDIF}
{$I LLCLOptions.inc} // Options
//------------------------------------------------------------------------------
interface
uses
SysUtils;
function PNGToBMP(pPNGData: PByteArray; PNGDataSize: cardinal; var pBMPData: PByteArray; var BMPDataSize: cardinal): boolean;
//------------------------------------------------------------------------------
implementation
uses
LLCLZlib;
{$IFDEF FPC}
{$PUSH} {$HINTS OFF}
{$ENDIF}
const
PNG_IDENT: array [0..pred(8)] of byte = ($89,$50,$4E,$47,$0D,$0A,$1A,$0A);
PNG_IHDR: array [0..pred(4)] of byte = ($49,$48,$44,$52); // 'IHDR'
PNG_CHUNKS: array [0..pred(4), 0..pred(4)] of byte = (
($49,$44,$41,$54), // 'IDAT'
($49,$45,$4E,$44), // 'IEND'
($50,$4C,$54,$45), // 'PLTE'
($74,$52,$4E,$53)); // 'tRNS'
type
TPNGInfos = record
Width: cardinal;
Height: cardinal;
BitDepth: byte;
ColourType: byte;
InterlaceMethod: byte;
BitsPerPixel: cardinal;
BytesPerPixel: cardinal;
RowSize: cardinal;
NbrPalEntries: cardinal;
Palette: array [0..pred(4*256)] of byte;
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
TranspType: byte;
Transp: array [0..pred(3)] of word;
Adam7StartPos: array [0..pred(7)+1] of cardinal; // (+1 for total length)
Adam7ColsRows: array [0..pred(7), 0..1] of cardinal;
{$endif LLCL_OPT_PNGSIMPLIFIED}
end;
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
const
ADAM7ColStart: array [0..pred(7)] of cardinal = (0, 4, 0, 2, 0, 1, 0);
ADAM7ColIncrm: array [0..pred(7)] of cardinal = (8, 8, 4, 4, 2, 2, 1);
ADAM7RowStart: array [0..pred(7)] of cardinal = (0, 0, 4, 0, 2, 0, 1);
ADAM7RowIncrm: array [0..pred(7)] of cardinal = (8, 8, 8, 4, 4, 2, 2);
{$endif LLCL_OPT_PNGSIMPLIFIED}
function PNGtoBMP_LongArrB(const Buffer: array of byte; Offset: cardinal): cardinal; forward;
function PNGtoBMP_WordArrB(const Buffer: array of byte; Offset: cardinal): word; forward;
function PNGtoBMP_SupDiv8(Value: cardinal): cardinal; forward;
function PNGtoBMP_CheckColour(ColourType, BitDepth: byte): boolean; forward;
function PNGToBMP_BitsPerPixel(ColourType, BitDepth: byte): cardinal; forward;
function PNGToBMP_KnownChunk(pChunkIdent: PByteArray): integer; forward;
function PNGtoBMP_ReverseFilter(const PNGI: TPNGInfos; pScanLines: PByteArray; pData: PByteArray): boolean; forward;
procedure PNGtoBMP_RFOneScanLine(NumScanLine, BytesPerPixel, RowSize: cardinal; FilterType: byte; pDataCur, pDataPrev, pScanLine: PByteArray); forward;
function PNGtoBMP_PaethPredictor(a, b, c: byte): byte; forward;
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
procedure PNGToBMP_Adam7Values(var PNGI: TPNGInfos); forward;
function PNGtoBMP_ReverseInterFilter(const PNGI: TPNGInfos; pScanLines: PByteArray; pData: PByteArray): boolean; forward;
function PNGtoBMP_ComplPow2(Value, Power2: cardinal): cardinal; forward;
procedure PNGtoBMP_CopyBits(pDataIn, pDataOut: pByteArray; OffBitsIn, OffBitsOut, NbrBits: cardinal); forward;
{$endif LLCL_OPT_PNGSIMPLIFIED}
function PNGtoBMP_CreateBMP(const PNGI: TPNGInfos; pData: PByteArray; var pBMPData: PByteArray; var BMPDataSize: cardinal): boolean; forward;
procedure PNGtoBMP_ArrBLongInv(var Buffer: array of byte; Offset: cardinal; Value: cardinal); forward;
procedure PNGtoBMP_ArrBWordInv(var Buffer: array of byte; Offset: cardinal; Value: word); forward;
procedure PNGtoBMP_SwapRGB(pData: PByteArray; NbrCols: cardinal; ColourType: byte); forward;
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
procedure PNGtoBMP_PaletteGrey(pPalette: PByteArray; BitDepth: byte); forward;
procedure PNGtoBMP_16to8(pData: PByteArray; NbrCols: cardinal; ColourType: byte); forward;
procedure PNGtoBMP_TrueToTrueC(pDataIn: PByteArray; pDataOut: PByteArray; const PNGI: TPNGInfos); forward;
procedure PNGtoBMP_GreyToTrueC(pData: PByteArray; NbrCols: cardinal); forward;
procedure PNGtoBMP_PalToTrueC(pData: PByteArray; const PNGI: TPNGInfos); forward;
function PNGtoBMP_LongArrBInv(Const Buffer: array of Byte; Const Offset: cardinal): cardinal; forward;
procedure PNGtoBMP_Pal2To4(pData: PByteArray; RowSize: cardinal); forward;
{$endif LLCL_OPT_PNGSIMPLIFIED}
//------------------------------------------------------------------------------
// Converts PNG file data to BMP file data
function PNGToBMP(pPNGData: PByteArray; PNGDataSize: cardinal; var pBMPData: PByteArray; var BMPDataSize: cardinal): boolean;
var PNGI: TPNGInfos; // PNG image infos
var PNGDataPos: cardinal;
var ChunkSize: cardinal;
var pIDATData: PByteArray; // IDAT chunks data, then PNG image data (after filtering + interlace processing)
var IDATDataSize, IDATDataPos: cardinal;
var pScanLines: PByteArray; // PNG scanlines data (after decompression)
var ScanLinesSize: cardinal;
var IsOK: boolean;
var i: cardinal;
begin
result := false;
pBMPData := nil;
BMPDataSize := 0;
FillChar(PNGI, SizeOf(PNGI), 0);
// Header analysis
if PNGDataSize<33 then exit;
if not CompareMem(@pPNGData^[0], @PNG_IDENT[0], SizeOf(PNG_IDENT)) then exit;
if not CompareMem(@pPNGData^[12], @PNG_IHDR[0], SizeOf(PNG_IHDR)) then exit;
PNGI.Width := PNGtoBMP_LongArrB(pPNGData^, 16);
PNGI.Height := PNGtoBMP_LongArrB(pPNGData^, 20);
if (PNGI.Width=0) or (PNGI.Height=0) then exit;
PNGI.BitDepth := pPNGData^[24];
PNGI.ColourType := pPNGData^[25];
if not PNGtoBMP_CheckColour(PNGI.ColourType, PNGI.BitDepth) then exit;
PNGI.BitsPerPixel := PNGToBMP_BitsPerPixel(PNGI.ColourType, PNGI.BitDepth);
PNGI.BytesPerPixel := PNGtoBMP_SupDiv8(PNGI.BitsPerPixel);
PNGI.RowSize := PNGtoBMP_SupDiv8(PNGI.Width * PNGI.BitsPerPixel);
PNGI.InterlaceMethod := pPNGData^[28];
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
if (pPNGData^[26]<>0) or (pPNGData^[27]<>0) or (PNGI.InterlaceMethod>1) then exit; // Compression, filter and interlace methods
{$else LLCL_OPT_PNGSIMPLIFIED}
if (pPNGData^[26]<>0) or (pPNGData^[27]<>0) or (PNGI.InterlaceMethod>0) then exit; // Compression, filter and interlace methods
{$endif LLCL_OPT_PNGSIMPLIFIED}
// Chunk CRC ignored (1): if wanted, add CRC unit in 'uses'
// clause and uncomment the next instruction
// if CRC32(0, @pPNGData^[12], 13 + 4) <> PNGtoBMP_LongArrB(pPNGData^, 12 + 13 + 4) then exit;
IDATDataSize := PNGDataSize - 33; // (enough for all chunks, so enough for IDAT chunks data only too)
GetMem(pIDATData, IDATDataSize);
IDATDataPos := 0;
// Chunks analysis
IsOK := false;
PNGDataPos := 33;
while (PNGDataPos + 12) <= PNGDataSize do
begin
ChunkSize := PNGtoBMP_LongArrB(pPNGData^, PNGDataPos);
// Chunk CRC ignored (2): if wanted, add CRC unit in 'uses'
// clause and uncomment the next instructions
// if (PNGDataPos + ChunkSize + 12 > PNGDataSize) then
// IsOk := false
// else
// isOK := (CRC32(0, @pPNGData^[PNGDataPos + 4], ChunkSize + 4) = PNGtoBMP_LongArrB(pPNGData^, PNGDataPos + ChunkSize + 8));
// if not ISOK then break;
case PNGToBMP_KnownChunk(@pPNGData^[PNGDataPos + 4]) of
0: // IDAT
begin
if (IDATDataPos + ChunkSize) > IDATDataSize then break;
Move(pPNGData^[PNGDataPos + 8], pIDATData^[IDATDataPos], ChunkSize);
inc(IDATDataPos, ChunkSize);
end;
1: // IEND
begin
IsOK := true;
break;
end;
2: // PLTE
begin
PNGI.NbrPalEntries := ChunkSize div 3;
if PNGI.NbrPalEntries>256 then break;
for i := 0 to pred(PNGI.NbrPalEntries) do
begin
// (RGB <-> BGR swap - BMP bitmap preparation)
PNGI.Palette[(i*4) ] := pPNGData^[(PNGDataPos + 8) + (i*3) + 2];
PNGI.Palette[(i*4) + 1] := pPNGData^[(PNGDataPos + 8) + (i*3) + 1];
PNGI.Palette[(i*4) + 2] := pPNGData^[(PNGDataPos + 8) + (i*3) ];
// (alpha channel = 0 by defaut, for better BMP compatibility)
end;
end;
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
3: // tRNS
begin
case PNGI.ColourType of
0: // Greyscale
begin
if ChunkSize<>2 then break;
PNGI.Transp[0] := PNGtoBMP_WordArrB(pPNGData^, PNGDataPos + 8);
PNGI.Transp[1] := PNGI.Transp[0];
PNGI.Transp[2] := PNGI.Transp[0];
PNGI.TranspType := 1;
end;
2: // Truecolour
begin
if ChunkSize<>6 then break;
for i := 0 to pred(3) do
// (No RGB <-> BGR swap - not necessary)
PNGI.Transp[i] := PNGtoBMP_WordArrB(pPNGData^, (PNGDataPos + 8) + (i*2));
PNGI.TranspType := 1;
end;
3: // Indexed-colour (Palette)
begin
if ChunkSize>PNGI.NbrPalEntries then break; // (May have less)
for i := 0 to pred(PNGI.NbrPalEntries) do
begin
if i<ChunkSize then
PNGI.Palette[(i*4) + 3] := pPNGData^[(PNGDataPos + 8) + i]
else
PNGI.Palette[(i*4) + 3] := 255;
end;
PNGI.TranspType := 2; // (Unused)
end;
else // Error
break;
end;
end;
{$endif LLCL_OPT_PNGSIMPLIFIED}
end;
inc(PNGDataPos, ChunkSize + 12); // +12 for chunk ident + chunk size + chunk crc
end;
if IDATDataPos=0 then IsOK := false;
if (PNGI.ColourType=3) and (PNGI.NbrPalEntries=0) then IsOK:= false;
if not IsOK then
begin
FreeMem(pIDATData);
exit;
end;
// Decompression (Zlib)
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
if PNGI.InterlaceMethod=0 then
ScanLinesSize := (1 + PNGI.RowSize) * PNGI.Height // +1 for the filter type byte
else
begin
PNGToBMP_Adam7Values(PNGI);
ScanLinesSize := PNGI.Adam7StartPos[7];
end;
{$else LLCL_OPT_PNGSIMPLIFIED}
ScanLinesSize := (1 + PNGI.RowSize) * PNGI.Height; // +1 for the filter type byte
{$endif LLCL_OPT_PNGSIMPLIFIED}
GetMem(pScanLines, ScanLinesSize);
IsOK := (LLCL_uncompress(PByte(pScanLines), ScanLinesSize, PByte(pIDATData), IDATDataPos) = 0); // Z_OK=0
FreeMem(pIDATData);
if not IsOK then
begin
FreeMem(pScanLines);
exit;
end;
// Scanlines processing (filtering [and interlace])
IDATDataSize := PNGI.RowSize * PNGI.Height;
GetMem(pIDATData, IDATDataSize);
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
if PNGI.InterlaceMethod=0 then // No interlace method: filtering only
IsOK := PNGtoBMP_ReverseFilter(PNGI, pScanLines, pIDATData)
else // (Always) Adam7 interlace method
begin
if PNGI.BitsPerPixel<8 then
FillChar(pIDATData^,IDATDataSize, 0); // Needed before bits copy
IsOK := PNGtoBMP_ReverseInterFilter(PNGI, pScanLines, pIDATData);
end;
{$else LLCL_OPT_PNGSIMPLIFIED}
IsOK := PNGtoBMP_ReverseFilter(PNGI, pScanLines, pIDATData);
{$endif LLCL_OPT_PNGSIMPLIFIED}
FreeMem(pScanLines);
if not IsOK then exit;
// BMP creation
IsOK := PNGtoBMP_CreateBMP(PNGI, pIDATData, pBMPData, BMPDataSize);
FreeMem(pIDATData);
if not IsOK then exit;
result := true;
end;
// Bytes to Long
function PNGtoBMP_LongArrB(const Buffer: array of byte; Offset: cardinal): cardinal;
begin
result := (Buffer[Offset] shl 24) or (Buffer[Offset+1] shl 16) or (Buffer[Offset+2] shl 8) or Buffer[Offset+3];
end;
// Bytes to Word
function PNGtoBMP_WordArrB(const Buffer: array of byte; Offset: cardinal): word;
begin
result := (Buffer[Offset] shl 8) or Buffer[Offset+1];
end;
// Div 8 superior
function PNGtoBMP_SupDiv8(Value: cardinal): cardinal;
begin
result := (Value + 7) shr 3;
end;
// Checks validity for colour parameters
function PNGtoBMP_CheckColour(ColourType, BitDepth: byte): boolean;
begin
case ColourType of
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
0: // Greyscale
result := (BitDepth in [1, 2, 4, 8, 16]);
2,4,6: // Truecolour, Greyscale + alpha, Truecolour + alpha
result := (BitDepth in [8, 16]);
3: // Indexed-colour
result := (BitDepth in [1, 2, 4, 8]);
{$else LLCL_OPT_PNGSIMPLIFIED}
2,6: // Truecolour, Truecolour + alpha
result := (BitDepth = 8);
3: // Indexed-colour
result := (BitDepth in [1, 4, 8]);
{$endif LLCL_OPT_PNGSIMPLIFIED}
else
result := false;
end;
end;
// Computes bits per pixel
function PNGToBMP_BitsPerPixel(ColourType, BitDepth: byte): cardinal;
begin
case ColourType of
2: result := 3;
4: result := 2;
6: result := 4;
else result := 1;
end;
result := result * BitDepth;
end;
// Searches for known chunks (IHDR excluded)
function PNGToBMP_KnownChunk(pChunkIdent: PByteArray): integer;
var i: integer;
begin
for i := 0 to pred(4) do
if PLongword(pChunkIdent)^=PLongword(@PNG_CHUNKS[i])^ then
begin
result := i;
exit;
end;
result := -1;
end;
// Reverses filtering (no interlace method)
function PNGtoBMP_ReverseFilter(const PNGI: TPNGInfos; pScanLines: PByteArray; pData: PByteArray): boolean;
var curpos, outpos, outprev: cardinal;
var FilterType: byte;
var i: cardinal;
begin
result := true;
curpos := 0;
outpos := 0;
outprev := 0;
for i := 0 to pred(PNGI.Height) do
begin
FilterType := pScanLines^[curpos];
if FilterType>4 then
begin
result := false;
break;
end;
inc(curpos);
PNGtoBMP_RFOneScanLine(i, PNGI.BytesPerPixel, PNGI.RowSize, FilterType, @pData^[outpos], @pData^[outprev], @pScanLines^[curpos]);
inc(curpos, PNGI.RowSize);
outprev := outpos;
inc(outpos, PNGI.RowSize);
end;
end;
// Reverses filtering for one scanline
procedure PNGtoBMP_RFOneScanLine(NumScanLine, BytesPerPixel, RowSize: cardinal; FilterType: byte; pDataCur, pDataPrev, pScanLine: PByteArray);
var i: cardinal;
begin
Move(pScanLine^, pDataCur^, RowSize);
case FilterType of
//0: // None (already done)
1: // Sub
begin
for i := BytesPerPixel to pred(RowSize) do
inc(pDataCur^[i], pDataCur^[ i - BytesPerPixel]);
end;
2: // Up
begin
if NumScanLine>0 then // (First scanline already done)
for i := 0 to pred(RowSize) do
inc(pDataCur^[i], pDataPrev^[i]);
end;
3: // Average
begin
if NumScanLine=0 then // First scanline
for i := BytesPerPixel to pred(RowSize) do
inc(pDataCur^[i], pDataCur^[i - BytesPerPixel] div 2)
else
begin
for i := 0 to pred(BytesPerPixel) do
inc(pDataCur^[i], pDataPrev^[i] div 2);
for i := BytesPerPixel to pred(RowSize) do
inc(pDataCur^[i], (pDataCur^[i - BytesPerPixel] + pDataPrev^[i]) div 2);
end;
end;
4: // Paeth
begin
if NumScanLine=0 then // First scanline
for i := BytesPerPixel to pred(RowSize) do
inc(pDataCur^[i], PNGtoBMP_PaethPredictor(pDataCur^[i - BytesPerPixel], 0, 0))
else
begin
for i := 0 to pred(BytesPerPixel) do
inc(pDataCur^[i], PNGtoBMP_PaethPredictor(0, pDataPrev^[i], 0));
for i := BytesPerPixel to pred(RowSize) do
inc(pDataCur^[i], PNGtoBMP_PaethPredictor(pDataCur^[i - BytesPerPixel], pDataPrev^[i], pDataPrev^[i - BytesPerPixel]));
end;
end;
end;
end;
// Computes Paeth predictor for filter type 4
function PNGtoBMP_PaethPredictor(a, b, c: byte): byte;
var pa, pb, pc: integer;
begin
pa := abs(b - c);
pb := abs(a - c);
pc := abs(integer(a + b - c - c));
if (pa <= pb) and (pa <= pc) then
result := a
else
if pb <= pc then
result := b
else
result := c;
end;
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
// Computes values for Adam7 interlace method
procedure PNGToBMP_Adam7Values(var PNGI: TPNGInfos);
const ADAM7LenParam: array [0..pred(7), 0..pred(4)] of cardinal =
((7,8,7,8),(3,8,7,8),(3,4,3,8),(1,4,3,4),(1,2,1,4),(0,2,1,2),(0,1,0,2));
var i: integer;
begin
PNGI.Adam7StartPos[0] := 0;
for i:= 0 to pred(7) do
begin
PNGI.Adam7StartPos[i + 1] := PNGI.Adam7StartPos[i];
PNGI.Adam7ColsRows[i, 0] := (PNGI.Width + ADAM7ColIncrm[i] - ADAM7ColStart[i] - 1) div ADAM7ColIncrm[i];
PNGI.Adam7ColsRows[i, 1] := (PNGI.Height + ADAM7RowIncrm[i] - ADAM7RowStart[i] - 1) div ADAM7RowIncrm[i];
if PNGI.Adam7ColsRows[i, 0]<>0 then
inc(PNGI.Adam7StartPos[i + 1], (1 + PNGtoBMP_SupDiv8(((PNGI.Width + ADAM7LenParam[i, 0]) div ADAM7LenParam[i, 1]) * PNGI.BitsPerPixel)) * ((PNGI.Height + ADAM7LenParam[i, 2]) div ADAM7LenParam[i, 3]));
end;
end;
// Reverses interlacing and filtering (Adam7 interlace method)
function PNGtoBMP_ReverseInterFilter(const PNGI: TPNGInfos; pScanLines: PByteArray; pData: PByteArray): boolean;
var pTMPRowLines, pTMPRowLine1, pTMPRowLine2, pTMPRowSwap: PByteArray;
var curpos, linesize, colout, addout: cardinal;
var FilterType: byte;
var i, j, k: cardinal;
begin
result := true;
GetMem(pTMPRowLines, PNGI.RowSize * 2); // for 2 data lines (current and previous)
pTmpRowLine1 := @pTMPRowLines^[0];
pTmpRowLine2 := @pTMPRowLines^[PNGI.RowSize];
addout := 0;
for i:=0 to pred(7) do
if (PNGI.Adam7ColsRows[i, 0]<>0) and (PNGI.Adam7ColsRows[i, 1]<>0) then
begin
curpos := PNGI.Adam7StartPos[i];
linesize := PNGtoBMP_SupDiv8(PNGI.Adam7ColsRows[i, 0] * PNGI.BitsPerPixel);
for j:=0 to pred(PNGI.Adam7ColsRows[i, 1]) do
begin
FilterType := pScanLines^[curpos];
if FilterType>4 then
begin
result := false;
break;
end;
inc(curpos);
PNGtoBMP_RFOneScanLine(j, PNGI.BytesPerPixel, linesize, FilterType, pTmpRowLine1, pTmpRowLine2, @pScanLines^[curpos]);
colout := ((ADAM7RowStart[i] + (j * ADAM7RowIncrm[i])) * PNGI.Width) + ADAM7ColStart[i];
if PNGI.BitsPerPixel<8 then
addout := (colout div PNGI.Width) * PNGtoBMP_ComplPow2(PNGI.Width * PNGI.BitsPerPixel, 8);
for k := 0 to pred(PNGI.Adam7ColsRows[i, 0]) do
begin
if PNGI.BitsPerPixel<8 then
PNGtoBMP_CopyBits(pTmpRowLine1, pData, k * PNGI.BitsPerPixel, addout + (colout * PNGI.BitsPerPixel), PNGI.BitsPerPixel)
else
if PNGI.BitsPerPixel=8 then // (faster for 1 byte)
pData^[colout * PNGI.BytesPerPixel] := pTmpRowLine1^[k * PNGI.BytesPerPixel]
else
Move(pTmpRowLine1^[k * PNGI.BytesPerPixel], pData^[colout * PNGI.BytesPerPixel], PNGI.BytesPerPixel);
inc(colout, ADAM7ColIncrm[i]);
end;
inc(curpos, linesize);
pTMPRowSwap := pTMPRowLine1;
pTMPRowLine1 := pTMPRowLine2;
pTMPRowLine2 := pTMPRowSwap;
end;
end;
FreeMem(pTMPRowLines);
end;
// Complement for a power of 2
function PNGtoBMP_ComplPow2(Value, Power2: cardinal): cardinal;
begin
result := Value and (Power2 - 1);
if result <>0 then result := Power2 - result;
end;
// Copies bit per bit
procedure PNGtoBMP_CopyBits(pDataIn, pDataOut: pByteArray; OffBitsIn, OffBitsOut, NbrBits: cardinal);
var posIn, posOut: cardinal;
var i: cardinal;
var b: byte;
begin
posIn := OffBitsIn; posOut := OffBitsOut;
for i := 0 to pred(NbrBits) do
begin
b := (pDataIn^[posIn shr 3] shr (7 - (posIn and 7))) and 1;
if b<>0 then // (faster if nul)
pDataOut^[posOut shr 3] := pDataOut^[posOut shr 3] or (b shl (7 - (posOut and 7)));
inc(posIn); inc(posOut);
end;
end;
{$endif LLCL_OPT_PNGSIMPLIFIED}
// Creates BMP
function PNGtoBMP_CreateBMP(const PNGI: TPNGInfos; pData: PByteArray; var pBMPData: PByteArray; var BMPDataSize: cardinal): boolean;
const
BMPHEADER_LEN = 14;
BMPDIBHEADER_LEN = 40; // (BITMAPINFOHEADER)
BMPRESOLUTION_DEFAULT = $0B12; // Default horizontal/vertical physical resolution
var pIn, pOut: PByteArray;
var BaseSize, RowSize, NewRowSize, NewBitsPerPixel, NewNbrPalEntries: cardinal;
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
var TransformPal, TranspToProcess: boolean;
{$endif LLCL_OPT_PNGSIMPLIFIED}
var i: cardinal;
begin
result := true;
NewBitsPerPixel := PNGI.BitsPerPixel;
RowSize := PNGI.RowSize;
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
if PNGI.BitDepth=16 then // Not supported by BMP
begin
if PNGI.ColourType in [0, 2, 6] then NewBitsPerPixel := PNGToBMP_BitsPerPixel(PNGI.ColourType, 8); // (not for ColourType 4, because (*2/2)=1)
RowSize := PNGtoBMP_SupDiv8(PNGI.Width * NewBitsPerPixel);
end
else
begin
if (PNGI.ColourType in [0, 3]) and (PNGI.BitDepth=2) then NewBitsPerPixel := 4; // See hereafter (2 bits per pixel in palette)
if (PNGI.ColourType=4) and (PNGI.BitDepth=8) then NewBitsPerPixel := 32; // Transformed in truecolour+alpha
end;
{$endif LLCL_OPT_PNGSIMPLIFIED}
NewRowSize := (((PNGI.Width * NewBitsPerPixel) + 31) div 32) * 4;
NewNbrPalEntries := 0;
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
TransformPal := false;
TranspToProcess := false;
case PNGI.ColourType of
0: // Greyscale
begin
NewNbrPalEntries := 1 shl PNGI.BitDepth;
if PNGI.BitDepth=16 then
if PNGI.TranspType=1 then
begin
NewNbrPalEntries := 0;
TranspToProcess := true;
end
else
NewNbrPalEntries := 1 shl 8; // BMP doesn't support 16 bits per pixel in palette
end;
2: // Truecolour
begin
if PNGI.TranspType=1 then
TranspToProcess := true;
end;
3: // Indexed-colour (Palette)
begin
NewNbrPalEntries := 1 shl PNGI.BitDepth;
end;
end;
BaseSize := BMPHEADER_LEN + BMPDIBHEADER_LEN;
if NewNbrPalEntries>0 then
begin
if PNGI.BitDepth=2 then NewNbrPalEntries := 1 shl 4; // BMP doesn't support 2 bits per pixel in palette
if PNGI.ColourType=0 then // Greyscale
TransformPal := (PNGI.TranspType=1)
else // Indexed-colour (Palette)
TransformPal := (PNGI.TranspType<>0);
if not TransformPal then
BaseSize := BMPHEADER_LEN + BMPDIBHEADER_LEN + (NewNbrPalEntries * 4);
end;
if TranspToProcess or TransformPal then
begin
NewBitsPerPixel := 32;
NewRowSize := PNGI.Width * 4;
end;
{$else LLCL_OPT_PNGSIMPLIFIED}
if PNGI.ColourType=3 then // Indexed-colour (Palette)
NewNbrPalEntries := 1 shl PNGI.BitDepth;
BaseSize := BMPHEADER_LEN + BMPDIBHEADER_LEN + (NewNbrPalEntries * 4);
{$endif LLCL_OPT_PNGSIMPLIFIED}
BMPDataSize := BaseSize + (NewRowSize * PNGI.Height);
GetMem(pBMPData, BMPDataSize);
FillChar(pBMPData^, BaseSize, 0);
// Header
PNGtoBMP_ArrBWordInv(pBMPData^, 0, $4D42); // 'BM' inversed
PNGtoBMP_ArrBLongInv(pBMPData^, 2, BMPDataSize);
PNGtoBMP_ArrBLongInv(pBMPData^, 10, BaseSize);
// DIB Header
PNGtoBMP_ArrBLongInv(pBMPData^, BMPHEADER_LEN + 00, BMPDIBHEADER_LEN);
PNGtoBMP_ArrBLongInv(pBMPData^, BMPHEADER_LEN + 04, PNGI.Width);
PNGtoBMP_ArrBLongInv(pBMPData^, BMPHEADER_LEN + 08, PNGI.Height);
PNGtoBMP_ArrBWordInv(pBMPData^, BMPHEADER_LEN + 12, 1); // Plane
PNGtoBMP_ArrBWordInv(pBMPData^, BMPHEADER_LEN + 14, NewBitsPerPixel);
PNGtoBMP_ArrBLongInv(pBMPData^, BMPHEADER_LEN + 24, BMPRESOLUTION_DEFAULT);
PNGtoBMP_ArrBLongInv(pBMPData^, BMPHEADER_LEN + 28, BMPRESOLUTION_DEFAULT);
// Palette (if present)
if NewNbrPalEntries>0 then
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
begin
if PNGI.ColourType=0 then // Greyscale
PNGtoBMP_PaletteGrey(@PNGI.Palette, PNGI.BitDepth);
if not TransformPal then
Move(PNGI.Palette, pBMPData^[BMPHEADER_LEN + BMPDIBHEADER_LEN], NewNbrPalEntries * 4);
end;
{$else LLCL_OPT_PNGSIMPLIFIED}
Move(PNGI.Palette, pBMPData^[BMPHEADER_LEN + BMPDIBHEADER_LEN], NewNbrPalEntries * 4);
{$endif LLCL_OPT_PNGSIMPLIFIED}
// Bitmap data
pIn := @pData^[pred(PNGI.Height) * PNGI.RowSize];
pOut := @pBMPData^[BaseSize];
for i := 0 to pred(PNGI.Height) do
begin
PNGtoBMP_ArrBLongInv(pOut^, NewRowSize-4, 0); // Clears BMP padded byte(s)
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
if TranspToProcess then // Greyscale 16 bits and truecolour with tRNS chunk
PNGtoBMP_TrueToTrueC(pIn, pOut, PNGI)
else
begin
// Before
if PNGI.BitDepth=16 then // 16 bits per channel (not supported by BMP)
PNGtoBMP_16to8(pIn, PNGI.Width, PNGI.ColourType);
// Data move
Move(pIn^, pOut^, RowSize); // (Not PNGI.rowsize)
// After
if PNGI.ColourType in [2, 6] then // Truecolour, truecolour + alpha
PNGtoBMP_SwapRGB(pOut, PNGI.Width, PNGI.ColourType)
else
if PNGI.ColourType=4 then // Greyscale + alpha
PNGtoBMP_GreyToTrueC(pOut, PNGI.Width)
else
if (PNGI.ColourType in [0, 3]) then // Greyscale (-> indexed colour) and indexed colour with 4 colours
if TransformPal then
PNGtoBMP_PalToTrueC(pOut, PNGI)
else
if PNGI.BitDepth=2 then
PNGtoBMP_Pal2To4(pOut, PNGI.RowSize);
end;
{$else LCL_OPT_PNGSIMPLIFIED}
// Data move
Move(pIn^, pOut^, RowSize); // (Not PNGI.rowsize)
// After
if PNGI.ColourType in [2, 6] then // Truecolour, truecolour + alpha
PNGtoBMP_SwapRGB(pOut, PNGI.Width, PNGI.ColourType);
{$endif LLCL_OPT_PNGSIMPLIFIED}
dec(pByte(pIn), PNGI.RowSize);
inc(pByte(pOut), NewRowSize);
end;
end;
// Long to Bytes inversed
procedure PNGtoBMP_ArrBLongInv(var Buffer: array of byte; Offset: cardinal; Value: cardinal);
begin
PLongword(@Buffer[Offset])^ := Value;
end;
// Word to Bytes inversed
procedure PNGtoBMP_ArrBWordInv(var Buffer: array of byte; Offset: cardinal; Value: word);
begin
PWord(@Buffer[Offset])^ := Value;
end;
// Colour Swap RGB <-> BGR
procedure PNGtoBMP_SwapRGB(pData: PByteArray; NbrCols: cardinal; ColourType: byte);
var pTmpData: PByteArray;
var i, bpc: cardinal;
var b: byte;
begin
pTmpData := pData;
if ColourType=2 then bpc := 3 else bpc := 4; // Truecolour or truecolour+alpha
for i := 0 to pred(NbrCols) do
begin
b := pTmpData^[0];
pTmpData^[0] := pTmpData^[2];
pTmpData^[2] := b;
inc(pByte(pTmpData), bpc);
end;
end;
{$ifndef LLCL_OPT_PNGSIMPLIFIED}
// Creates palette for greyscale
procedure PNGtoBMP_PaletteGrey(pPalette: PByteArray; BitDepth: byte);
var bd: cardinal;
var i: cardinal;
var b1, b2: byte;
begin
// Notes: eventual transparency (tRNS chunk) processed in PNGtoBMP_PalToTrueC
// greyscale with BitDepth=16 and tRNS chunk processed in PNGtoBMP_TrueToTrueC
if BitDepth>8 then
bd := 256 // 16 bits -> 8 bits per channel
else
bd := 1 shl BitDepth;
case BitDepth of
1: b1 := $FF;
2: b1 := $55;
4: b1 := $11;
else b1 := $01;
end;
b2 := $00;
for i:=0 to pred(bd) do
begin
PNGtoBMP_ArrBLongInv(pPalette^, i * 4, (b2 shl 16) + (b2 shl 8) + b2);
inc(b2, b1);
end;
end;
// Reduces 16 bits to 8 bits (channels, alpha)
procedure PNGtoBMP_16to8(pData: PByteArray; NbrCols: cardinal; ColourType: byte);
var pIn, pOut: PByteArray;
var i, NbrTimes: cardinal;
begin
// Note: for greyscale and truecolour, if tRNS chunk present, processed in PNGtoBMP_TrueToTrueC
pIn := pData;
pOut := pData;
case ColourType of
2: NbrTimes := 3; // Truecolour
4: NbrTimes := 2; // Greyscale + alpha
6: NbrTimes := 4; // Truecolour + alpha
else NbrTimes := 1; // Greyscale
end;
NbrTimes := NbrTimes * NbrCols;
for i := 0 to pred(NbrTimes) do
begin
pOut^[0] := pIn^[0]; // Only MSB
inc(pByte(pIn), 2);
inc(pByte(pOut));
end;
end;
// Truecolour (with tRNS chunk) to truecolour + alpha (8 bits)
procedure PNGtoBMP_TrueToTrueC(pDataIn: PByteArray; pDataOut: PByteArray; const PNGI: TPNGInfos);
var pIn, pOut: PByteArray;
var PixelColour: cardinal;
var i: cardinal;
var w1, w2, w3: cardinal;
begin
// Note: includes also greyscale with BitDepth=16 and tRNS chunk
pIn := @pDataIn^[pred(PNGI.Width) * PNGI.BytesPerPixel];
pOut := @pDataOut^[pred(PNGI.Width) * 4];
for i := 0 to pred(PNGI.Width) do
begin
if PNGI.ColourType=0 then // Greyscale (only with BitDepth=16 and tRNS chunk)
begin
w1 := PNGtoBMP_WordArrB(pIn^, 0);
w2 := w1; w3 := w1;
dec(pByte(pIn), 2);
end
else // Truecolour (BitDepth=8 or 16)
if PNGI.BitDepth=8 then
begin
w1 := pIn^[2];
w2 := pIn^[1];
w3 := pIn^[0];
dec(pByte(pIn), 3);
end
else
begin
w1 := PNGtoBMP_WordArrB(pIn^, 4);
w2 := PNGtoBMP_WordArrB(pIn^, 2);
w3 := PNGtoBMP_WordArrB(pIn^, 0);
dec(pByte(pIn), 6);
end;
if PNGI.BitDepth=16 then
PixelColour := ((w3 shr 8) shl 16) + ((w2 shr 8) shl 8) + (w1 shr 8)
else
PixelColour := (w3 shl 16) + (w2 shl 8) + w1;
if PNGI.TranspType=1 then
if (w1<>PNGI.Transp[0]) or (w2<>PNGI.Transp[1]) or (w3<>PNGI.Transp[2]) then
PixelColour := PixelColour or $FF000000;
PNGtoBMP_ArrBLongInv(pOut^, 0, PixelColour);
dec(pByte(pOut), 4);
end;
end;
// Greyscale + alpha to truecolour + alpha (8 bits)
procedure PNGtoBMP_GreyToTrueC(pData: PByteArray; NbrCols: cardinal);
var pIn, pOut: PByteArray;
var i: cardinal;
var b: byte;
begin
pIn := @pData^[pred(NbrCols) * 2];
pOut := @pData^[pred(NbrCols) * 4];
for i := 0 to pred(NbrCols) do
begin
b := pIn^[0];
PNGtoBMP_ArrBLongInv(pOut^, 0, (pIn^[1] shl 24) + (b shl 16) + (b shl 8) + b);
dec(pByte(pIn), 2);
dec(pByte(pOut), 4);
end;
end;
// Palette (with tRNS chunk) to truecolour + alpha (8 bits)
procedure PNGtoBMP_PalToTrueC(pData: PByteArray; const PNGI: TPNGInfos);
var pIn, pOut: PByteArray;
var PixelBits, NbrPixels, Mask, PixelIndex: byte;
var PixelColour, ColourTransp: cardinal;
var i, j: cardinal;
begin
// Note: greyscale (-> palette) with BitDepth=16 and tRNS chunk processed in PNGtoBMP_TrueToTrueC
pIn := @pData^[pred(PNGI.RowSize)];
pOut := @pData^[pred(PNGI.Width) * 4];
if PNGI.BitDepth<8 then
begin
Mask := Pred(1 shl PNGI.BitDepth);
PixelBits := pIn^[0];
NbrPixels := 8 div PNGI.BitDepth;
// Skip padding bits, if present
j := PNGtoBMP_ComplPow2(PNGI.Width * PNGI.BitsPerPixel, 8);
if j>0 then
for i:=0 to pred(j div PNGI.BitDepth) do
begin
PixelBits := PixelBits shr PNGI.BitDepth;
dec(NbrPixels);
end;
end
else
begin
Mask := 0; PixelBits := 0; NbrPixels := 0; // (to avoid compilation warning)
end;
if PNGI.ColourType=0 then // Greyscale
ColourTransp := (PNGI.Transp[0] and $FF)
else // Palette
ColourTransp := ((PNGI.Transp[0] and $FF) shl 16) + ((PNGI.Transp[1] and $FF) shl 8) + (PNGI.Transp[2] and $FF);
for i := 0 to pred(PNGI.Width) do
begin
if PNGI.BitDepth<8 then
begin
PixelIndex := PixelBits and Mask;
PixelBits := PixelBits shr PNGI.BitDepth;
dec(NbrPixels);
end
else
PixelIndex := pIn^[0];
PixelColour := PNGtoBMP_LongArrBInv(PNGI.Palette, PixelIndex * 4);
if PNGI.TranspType=1 then
if ((PNGI.ColourType=0) and (PixelIndex<>ColourTransp)) or ((PNGI.ColourType=3) and (PixelColour<>ColourTransp)) then
PixelColour := PixelColour or $FF000000;
PNGtoBMP_ArrBLongInv(pOut^, 0, PixelColour);
if (PNGI.BitDepth=8) or (NbrPixels=0) then
begin
dec(pByte(pIn), 1);
if PNGI.BitDepth<8 then
begin
PixelBits := pIn^[0];
NbrPixels := 8 div PNGI.BitDepth;
end;
end;
dec(pByte(pOut), 4);
end;
end;
// Bytes to Long inversed
function PNGtoBMP_LongArrBInv(Const Buffer: array of Byte; Const Offset: cardinal): cardinal;
begin
result := PLongword(@Buffer[Offset])^;
end;
// Palette 2 bits per colour to 4 bits
procedure PNGtoBMP_Pal2To4(pData: PByteArray; RowSize: cardinal);
var pIn, pOut: PByteArray;
var i: cardinal;
var b: byte;
begin
pIn := @pData^[pred(RowSize)];
pOut := @pData^[pred(RowSize) * 2];
for i := 0 to pred(RowSize) do
begin
b := pIn^[0];
PNGtoBMP_ArrBWordInv(pOut^, 0, ((b and $0C) shl 10) + ((b and $03) shl 8) + ((b and $C0) shr 2) + ((b and $30) shr 4)); // (Probably another faster way)
dec(pByte(pIn));
dec(pByte(pOut), 2);
end;
end;
{$endif LLCL_OPT_PNGSIMPLIFIED}
{$IFDEF FPC}
{$POP}
{$ENDIF}
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.WinHelpViewer;
{ ************************************************************************ }
{ }
{ This unit implements a help viewer for WinHelp (on Windows) or }
{ HyperHelp (a WinHelp emulator) on Linux. The design goal is for this }
{ unit to be indistinguishable from other viewers as far as the IDE help }
{ manager can determine --- there should be no special casing. }
{ }
{ Because neither WinHelp nor HyperHelp support direct querying without }
{ displaying results, it is necessary for the WinHelp viewer to maintain }
{ a topic list itself. In the case of the built-in IDE help viewer, this }
{ list is drawn out of the .ALS file, and the analysis of the list is }
{ delegated to an implementation of IWinHelpTester. The code for this }
{ is not publically available, and individual applications wishing to }
{ support this functionality must implement IWinHelpTester themselves. }
{ Absent an implementation of IWinHelpTester, the WinHelpViewer will }
{ *always* assume that the query should succeed and WinHelp can be asked }
{ to provide help (in a Windows application; the opposite is true in a }
{ Linux application). Any application supporting multiple help viewers is }
{ encouraged to implement IWinHelpTester to get around this. }
{ }
{ Much of the code in this file was ripped from existing systems which }
{ have been redirected through this system; some of the obscurity is }
{ built-in, and significant portions of the code reflect necessities }
{ imposed by interactions with ancient WinHelp systems. }
{ }
{ This file is part of the Visual Component Library on Windows, and is }
{ linked into the VCL package. On Linux, it is provided as an example }
{ and may be used *in applications* as desired. This file does not work }
{ when linked into a package on Linux (because the unit is already used }
{ by the IDE), and will not interact with HyperHelp without an associated }
{ implementation of the function WinHelp. NOTE: winhelp.so is provided by }
{ Borland for use of the IDE only and is *not* redistributable in any }
{ fashion. Developers of applications wishing to use HyperHelp *must* }
{ licence HyperHelp seperately from Bristol Technologies. }
{ }
{ ************************************************************************ }
interface
uses
{$IF DEFINED(CLR)}
System.Security.Permissions,
{$IFEND}
System.Classes;
{ Because WinHelp is uncooperative about responding to queries along the
lines of 'do you support this', the WinHelp viewer in essence needs to
hack a response to that. This interface is a hook by which user applications
can override the WinHelp viewer's default hack answer. }
type
IWinHelpTester = interface(IInterface)
['{B0FC9354-5F0E-11D3-A3B9-00C04F79AD3A}']
function CanShowALink(const ALink, FileName: String): Boolean;
function CanShowTopic(const Topic, FileName: String): Boolean;
function CanShowContext(const Context: Integer;
const FileName: String): Boolean;
function GetHelpStrings(const ALink: String): TStringList;
[FileIOPermission(SecurityAction.Demand, Unrestricted=True)]
function GetHelpPath : String;
[FileIOPermission(SecurityAction.Demand, Unrestricted=True)]
function GetDefaultHelpFile: String;
end;
{ Naming variables which can be set externally, probably by the implementation
of WinHelpTester. }
var
WinHelpTester : IWinHelpTester;
{ The Viewer Name is the name used by the Help Manager when it
needs to display a UI element to allow the program's user to
select a viewer by name. }
ViewerName : String;
{$IFDEF LINUX}
{ HyperHelp requires that you specify the name of the window, and requires
in which it will display help information, as well. }
HyperHelpWindowName : String;
{$ENDIF}
{ =========================================================================== }
implementation
uses
{$IF DEFINED(CLR)}
System.Text, System.Threading,
{$IFEND}
{$IF DEFINED(LINUX)}
Libc,
{$ELSE}
Winapi.Windows,
{$IFEND}
Vcl.Consts, System.HelpIntfs, System.SysUtils;
{$IFDEF LINUX}
{ forward calls to WinHelp on to the HyperHelp implementation }
const
winhelpmodulename = 'winhelp.so';
function WinHelp(HWND: LongInt; HelpFile: PChar; Command: LongInt;
Data: LongWord): Boolean; cdecl;
external winhelpmodulename name 'WinHelp';
{$ENDIF}
type
{$IF DEFINED(CLR)}
TWinHelpFinder = class
private
HelpTitle: string;
HelpWnd: HWnd;
DialogWnd: HWnd;
FoundMainWindow: Boolean;
FoundDialog: Boolean;
public
function WindowEnumerationTester(wnd: HWnd; Info: LParam): Bool;
function DialogEnumerationTester(wnd: HWnd; Info: LParam): Bool;
end;
{$IFEND}
{$IF DEFINED(MSWINDOWS)}
TWinHelpFinder = record
HelpTitle: PChar;
HelpWnd: HWnd;
DialogWnd: HWnd;
FoundMainWindow: Boolean;
FoundDialog: Boolean;
end;
{$IFEND}
{$IF DEFINED(LINUX)}
TWinHelpFinder = record
HelpTitle: PChar;
HelpWnd: Longint;
DialogWnd: Longint;
FoundMainWindow: Boolean;
FoundDialog: Boolean;
end;
{$IFEND}
TWHCommandType = (twhContext, twhCommand, twhContents, twhQuit);
{ TWinHelpViewer.
TWinHelpViewer implements the interfaces supported by WinHelp ---
ICustomHelpViewer (required of all Help Viewers),
IExtendedHelpViewer (Topic and Context),
ISpecialWinHelpViewer (Winhelp-specific messages }
TWinHelpViewer = class(TInterfacedObject, ICustomHelpViewer, IExtendedHelpViewer, ISpecialWinHelpViewer)
private
FViewerID: Integer;
FLastCommandType: TWHCommandType;
FLastCommand: String;
FLastContext: Integer;
function IsNewQuery(QueryType: TWHCommandType; Command: String; Context: Integer): Boolean;
function MakeWinHelpHappy: Boolean;
function IsBusyWindow(WndInfo: TWinHelpFinder): Boolean;
function CouldBeUnstableWindow(WndInfo: TWinHelpFinder): Boolean;
procedure RestartWinHelp;
{$IF DEFINED(CLR)}
strict protected
procedure Finalize; override;
{$IFEND}
public
FHelpManager: IHelpManager;
constructor Create;
destructor Destroy; override;
function HelpFile(const Name: String) : String;
procedure InternalShutDown;
{ ICustomHelpViewer }
function GetViewerName : String;
function UnderstandsKeyword(const HelpString: String): Integer;
function GetHelpStrings(const HelpString: String): TStringList;
function CanShowTableOfContents: Boolean;
procedure ShowTableOfContents;
procedure ShowHelp(const HelpString: String);
procedure NotifyID(const ViewerID: Integer);
procedure SoftShutDown;
procedure ShutDown;
{ IExtendedHelpViewer }
function UnderstandsTopic(const Topic: String): Boolean;
procedure DisplayTopic(const Topic: String);
function UnderstandsContext(const ContextID: Integer;
const HelpFileName: String): Boolean;
procedure DisplayHelpByContext(const ContextID: Integer;
const HelpFileName: String);
{ ISpecialWinHelpViewer }
function CallWinHelp(Handle: THandle; const HelpFileName: String;
Command: Word; Data: NativeUInt) : Boolean;
property ViewerID : Integer read FViewerID;
property HelpManager : IHelpManager read FHelpManager write FHelpManager;
end;
{ global instance of TWinHelpViewer which HelpIntfs can talk to. }
var
HelpViewer: TWinHelpViewer;
HelpViewerIntf: ICustomHelpViewer;
{----------------------------------------------------------------------------}
{ TWinHelpVIewer }
{ internal function used to ensure that the Help File variable
is something meaningful. Order of checking is:
(a) if the parameter is nil, then ask the Help Manager what it thinks.
(b) if the value is stil nil, then ask the Help Tester for the default.
(c) if this is Linux, then build a full path name, because
HyperHelp doesn't understand it if you don't. }
[FileIOPermission(SecurityAction.Demand, Unrestricted=True)]
function TWinHelpViewer.HelpFile(const Name: String): String;
var
FileName : String;
begin
Result := '';
if (Name = '') and Assigned(FHelpManager) then
FileName := HelpManager.GetHelpFile
else FileName := Name;
if FileName = '' then
if Assigned(WinHelpTester) then
FileName := WinHelpTester.GetDefaultHelpFile;
if Assigned(WinHelpTester) then
FileName := WinHelpTester.GetHelpPath + PathDelim + FileName;
Result := FileName;
end;
{ InternalShut Down is called from unit finalization if the unit is exiting
and the Help Manager needs to be informed. }
procedure TWinHelpViewer.InternalShutDown;
begin
SoftShutDown;
if Assigned(FHelpManager) then
begin
HelpManager.Release(ViewerID);
HelpManager := nil;
end;
end;
{ Finalize frees any resources if the WinHelpViewer gets garbage collected
without being explicitly freed }
{$IF DEFINED(CLR)}
procedure TWinHelpViewer.Finalize;
begin
InternalShutDown;
end;
{$IFEND}
{---------------------------------------------------------------------------}
{ TWinHelpViewer - ICustomHelpViewer }
{ GetViewerName returns a string that the Help Manager can use to identify
this Viewer in a UI element asking users to choose among Viewers. }
function TWinHelpViewer.GetViewerName: String;
begin
Result := ViewerName;
end;
{ UnderstandsKeyword is a querying function that the Help Manager calls to
determine if the Viewer provide helps on a particular keyword string. }
function TWinHelpViewer.UnderstandsKeyword(const HelpString: String): Integer;
var
CanShowHelp : Boolean;
begin
{ if there's a WinHelp Tester, then ask it if the keyword is supported. }
if Assigned(WinHelpTester) then
begin
CanShowHelp := WinHelpTester.CanShowALink(HelpString, HelpFile(''));
if CanShowHelp then
Result := 1
else
Result := 0;
end
{ if there is no Tester, then use operating-system specific assumptions:
under Windows, assume that it's supported; under Linux, assume that it
isn't. }
else
begin
{$IF DEFINED(CLR) OR DEFINED(MSWINDOWS)}
Result := 1;
{$IFEND}
{$IF DEFINED(LINUX)}
Result := 0;
{$IFEND}
end;
end;
{ GetHelpStrings is used by the Help Manager to display a list of keyword
matches from which an application's user can select one. It assumes
that the String List is properly allocated, so this function should
never return nil. }
function TWinHelpViewer.GetHelpStrings(const HelpString: String): TStringList;
begin
{ ask the Tester, if there is one. }
if Assigned(WinHelpTester) then
Result := WinHelpTester.GetHelpStrings(HelpString)
else
begin
{ otherwise, use operating-system specific assumptions:
(1) under Windows, return a list with just the string, signifying support;
(2) under Linux, return an empty list. }
Result := TStringList.Create;
{$IF NOT DEFINED(LINUX)}
Result.Add(GetViewerName + ': ' + HelpString);
{$IFEND}
end;
end;
{ CanShowTableOfContents is a querying function that the Help Manager
calls to determine if the Viewer supports tables of contents. WinHelp
and HyperHelp both do. }
function TWinHelpViewer.CanShowTableOfContents: Boolean;
begin
Result := True;
end;
{ ShowTableOfContents is a command function that the Help Manager uses
to direct the Viewer to display a table of contents. It is never
called without being preceded by a call to CanShowTableOfContents. }
procedure TWinHelpViewer.ShowTableOfContents;
var
FileName : String;
begin
if MakeWinHelpHappy then
begin
FLastCommandType := twhContents;
FileName := HelpFile(HelpManager.GetHelpFile);
if FileName <> '' then
WinHelp(HelpManager.GetHandle, FileName, HELP_CONTENTS, 0);
end;
end;
{ ShowHelp is the function that the Help Manager calls to request that
a Help Viewer display help for a given keyword. For WinHelp, this is
done via a complex WinHelp macro. }
{$IF DEFINED(CLR) OR DEFINED(MSWINDOWS)}
procedure TWinHelpViewer.ShowHelp(const HelpString: String);
const
Macro = 'IE(AL("%s",4),"AL(\"%0:s\",3)","JK(\"%1:s\",\"%0:s\")")';
var
HelpCmd : String;
FileName: String;
begin
if HelpString = '' then
raise EHelpSystemException.CreateRes({$IFNDEF CLR}@{$ENDIF}SNoKeyword);
HelpCmd := Format(Macro, [HelpString, HelpFile('')]);
if (MakeWinHelpHappy) then
begin
FileName := HelpFile('');
if (IsNewQuery(twhCommand, HelpCmd, 0)) and (FileName <> '') then
begin
FLastCommandType := twhCommand;
FLastCommand := HelpCmd;
{$IF DEFINED(CLR)}
WinHelp(HelpManager.GetHandle, FileName, HELP_COMMAND, HelpCmd);
{$ELSE}
WinHelp(HelpManager.GetHandle, PChar(FileName), HELP_COMMAND,
UIntPtr(PChar(HelpCmd)));
{$IFEND}
end;
end;
end;
{$IFEND}
{$IF DEFINED(LINUX)}
procedure TWinHelpViewer.ShowHelp(const HelpString: String);
const
Macro = 'AL(%0s,3,,%1s)';
var
HelpCmd : String;
FileName: String;
begin
HelpCmd := Format(Macro, [HelpString, HyperHelpWindowName]);
FileName := HelpFile('');
if (IsNewQuery(twhCommand, HelpCmd, 0)) and (FileName <> '') then
begin
FLastCommandType := twhCommand;
FLastCommand := HelpCmd;
WinHelp(HelpManager.GetHandle, PChar(FileName), HELP_COMMAND,
UIntPtr(Pchar(HelpCmd)));
end;
end;
{$IFEND}
{ NotifyID is called by the Help Manager after a successful registration
to provide the Help Viewer with a cookie which uniquely identifies the
Viewer to the Manager, and can be used in communications between the two. }
procedure TWinHelpViewer.NotifyID(const ViewerID: Integer);
begin
FViewerID := ViewerID;
end;
{ SoftShutDown is called by the help manager to ask the viewer to
terminate any externally spawned subsystem without shutting itself down. }
procedure TWinHelpViewer.SoftShutDown;
begin
FLastCommandType := twhQuit;
WinHelp(0, '', HELP_QUIT, 0);
end;
procedure TWinHelpViewer.ShutDown;
begin
SoftShutDown;
if Assigned(FHelpManager) then
HelpManager := nil;
if Assigned(WinHelpTester) then
WinHelpTester := nil;
end;
{-----------------------------------------------------------------------------}
{ TWinHelpViewer --- IExtendedHelpViewer }
{ UnderstandsTopic is called by the Help Manager to ask if the Viewer
is capable of displaying a topic-based help query for a given topic.
Its default behavior, like all default behaviors in this file, is
opposite for Windows than it is for linux. }
function TWinHelpViewer.UnderstandsTopic(const Topic: String): Boolean;
begin
{ after setting the defaults, if there's a Tester, ask it. }
if Assigned(WinHelpTester) then
Result := WinHelpTester.CanShowTopic(Topic, HelpFile(''))
else
Result := True; //there is no tester, assume it understands
end;
{ DisplayTopic is called by the Help Manager if a Help Viewer claims
in its response to UnderstandsTopic to be able to provide Topic-based
help for a particular keyword. }
procedure TWinHelpViewer.DisplayTopic(const Topic: String);
var
{$IF DEFINED(CLR)}
HelpCommand: string;
{$ELSE}
HelpCommand: array[0..255] of Char;
{$IFEND}
FileName: String;
begin
{ note that because HelpCommand is of a fixed-size, ridiculously long
topic strings will result in errors from WinHelp/HyperHelp. }
{$IF DEFINED(CLR)}
HelpCommand := Format('JumpID("","%s")', [Topic]);
{$ELSE}
StrLFmt(HelpCommand, Length(HelpCommand) -1, 'JumpID("","%s")', [Topic]);
{$IFEND}
FileName := HelpFile('');
if MakeWinHelpHappy then
begin
if (IsNewQuery(twhCommand, HelpCommand, 0)) and (FileName <> '') then
begin
FLastCommandType := twhCommand;
FLastCommand := HelpCommand;
{$IF DEFINED(CLR)}
WinHelp(HelpManager.GetHandle, FileName, HELP_COMMAND, HelpCommand);
{$ELSE}
WinHelp(HelpManager.GetHandle, PChar(FileName), HELP_COMMAND,
UIntPtr(@HelpCommand));
{$IFEND}
end;
end;
end;
{ UnderstandsContext is a querying function called by the Help Manager
to determine if an Extended Help Viewer is capable of providing
help for a particular context-ID. Like all querying functions in
this file, the default behavior is opposite --- YES for windows,
NO for linux --- and the Tester is asked, if available. }
function TWinHelpViewer.UnderstandsContext(const ContextID: Integer;
const HelpFileName: String): Boolean;
begin
{$IF NOT DEFINED(LINUX)}
Result := True;
{$ELSE}
Result := False;
{$IFEND}
if Assigned(WinHelpTester) then
Result := WinHelpTester.CanShowContext(ContextID, HelpFile(HelpFileName));
end;
{ DisplayHelpByContext is used by the Help Manager to request that a
Help Viewer display help for a particular Context-ID. It is only
invoked after a successful call to CanShowContext. }
procedure TWinHelpViewer.DisplayHelpByContext(const ContextID: Integer;
const HelpFileName: String);
var
FileName: String;
begin
FileName := HelpFile(HelpFileName);
if MakeWinHelpHappy then
begin
if IsNewQuery(twhContext, '', ContextID) and (FileName <> '') then
begin
FLastCommandType := twhContext;
FLastContext := ContextID;
WinHelp(HelpManager.GetHandle, FileName, HELP_CONTEXT, ContextID);
end;
end;
end;
{----------------------------------------------------------------------------}
{ TWinHelpViewer --- ISpecialWinHelpViewer }
{ CallWinHelp is called by the Help Manager when it recieves WinHelp-style
help requests from external systems and is not able to deconstruct them
into something meaningful for non-winhelp specific viewers. These
get forwarded on to WinHelp in *all* circumstances. HyperHelp may
not support some of these functions, and will issue an error complaint
in that case. }
function TWinHelpViewer.CallWinHelp(Handle: THandle; const HelpFileName: String;
Command: Word; Data: NativeUInt) : Boolean;
var
Calling : Boolean;
begin
Result := False;
if MakeWinHelpHappy then
begin
if (Command = 258 { HELP_COMMAND }) or
(Command = 261 { HELP_PARTIALKEY}) or
(Command = 513 { HELP_MULTIKEY}) or
(Command = 10 { HELP_CONTEXTMENU}) or
(Command = 8 { HELP_CONTEXTPOPUP}) or
(Command = 1 { HELP_CONTEXT }) or
(Command = 257 { HELP_KEY}) then
Calling := IsNewQuery(twhCommand, IntToStr(Command), 0)
else
Calling := True;
if Calling then
begin
FLastCommandType := twhCommand;
FLastCommand := IntToStr(Command);
Result := WinHelp(Handle, HelpFile(HelpFileName), Command, Data);
end;
end;
end;
{----------------------------------------------------------------------------}
{ TWinHelpViewer internal support methods }
{ These functions may only be invoked from code intended to run under Windows.}
{$IF DEFINED(CLR)}
function TWinHelpFinder.WindowEnumerationTester(wnd: HWnd; Info: LParam): Bool;
var
Buf: StringBuilder;
begin
Buf := StringBuilder.Create(256);
GetClassName(wnd, Buf, Buf.Capacity);
if SameText(Buf.ToString, 'MS_WINHELP') then
begin
HelpWnd := Wnd;
FoundMainWindow := True;
end;
Result := not FoundMainWindow;
end;
function TWinHelpFinder.DialogEnumerationTester(wnd: HWnd; Info: LParam): Bool;
var
Buf: StringBuilder;
begin
Buf := StringBuilder.Create(256);
GetClassName(wnd, Buf, Buf.Capacity);
if SameStr(Buf.ToString, '#32770') then
begin
FoundDialog := True;
DialogWnd := Wnd;
end;
Result := not FoundDialog;
end;
function FindWinHelp: TWinHelpFinder;
begin
Result := TWinHelpFinder.Create;
Result.FoundMainWindow := False;
Result.FoundDialog := False;
Result.HelpWnd := 0;
EnumWindows(@Result.WindowEnumerationTester, 0);
end;
{$IFEND}
{$IF NOT DEFINED(CLR)}
{$IFDEF MSWINDOWS}
{ These functions will not work with HyperHelp, because HyperHelp does not
run under the WINE subsystem. These functions may only be invoked from code
intended to run under Windows.}
function WindowEnumerationTester(wnd: HWnd; var Info: TWinHelpFinder): Bool; stdcall;
var
Buf: array [Byte] of Char;
begin
GetClassName(wnd, Buf, Length(Buf));
if (StrIComp(Buf, 'MS_WINHELP') = 0) then
begin
Info.HelpWnd := Wnd;
Info.FoundMainWindow := True;
end;
Result := not Info.FoundMainWindow;
end;
function DialogEnumerationTester(wnd: HWnd; var Info: TWinHelpFinder): Bool; stdcall;
var
Buf: Array [Byte] of Char;
begin
GetClassName(wnd, Buf, Length(Buf));
if (StrComp(Buf, '#32770') = 0) then
begin
Info.FoundDialog := True;
Info.DialogWnd := Wnd;
end;
Result := not Info.FoundDialog;
end;
{$ENDIF}
function FindWinHelp: TWinHelpFinder;
begin
{$IFDEF MSWINDOWS}
Result.FoundMainWindow := False;
Result.FoundDialog := False;
Result.HelpWnd := 0;
EnumWindows(@WindowEnumerationTester, LPARAM(@Result));
{$ENDIF}
end;
{$IFEND}
function TWinHelpViewer.IsNewQuery(QueryType: TWHCommandType; Command: String; Context: Integer): Boolean;
var
WndHelpFinder : TWinHelpFinder;
begin
Result := True;
WndHelpFinder := FindWinHelp;
if WndHelpFinder.FoundMainWindow and (QueryType = FLastCommandType) then
case QueryType of
twhCommand:
Result := (CompareStr(Command, FLastCommand) <> 0);
twhContext:
Result := Context <> FLastContext;
end;
end;
{ Note --- the following two methods will work in Linux but is semantically
devoid of meaningless. If you find yourself tempted to use them, please
reconsider, and be sure that the TWinHelpFinder you pass is meaningful.}
function TWinHelpViewer.IsBusyWindow(WndInfo: TWinHelpFinder): Boolean;
begin
Result := False;{
if (WndInfo.HelpWnd <> 0) and (not IsWindowVisible(WndInfo.HelpWnd)) then
Result := true;}
end;
function TWinHelpViewer.CouldBeUnstableWindow(WndInfo: TWinHelpFinder): Boolean;
begin
Result := (not WndInfo.FoundDialog);
{ also check here for version number. }
end;
function TWinHelpViewer.MakeWinHelpHappy: Boolean;
{$IF NOT DEFINED(LINUX)}
var
WndInfo: TWinHelpFinder;
{$IFEND}
begin
{$IF NOT DEFINED(LINUX)}
Result := False;
{ first pretend we're in C. }
{ if winhelp is up, see if it has a dialog loaded. }
WndInfo := FindWinHelp;
if WndInfo.FoundMainWindow then
{$IF DEFINED(CLR)}
EnumThreadWindows(GetWindowThreadProcessId(WndInfo.HelpWnd, nil),
@WndInfo.DialogEnumerationTester, 0);
{$ELSE}
EnumThreadWindows(GetWindowThreadProcessId(WndInfo.HelpWnd, nil),
@DialogEnumerationTester, LPARAM(@WndInfo));
{$IFEND}
{ if the window is busy, silently fail the help request rather
than harassing WinHelp into failure. }
if IsBusyWindow(WndInfo) then
Exit;
if CouldBeUnstableWindow(WndInfo) then RestartWinHelp;
{$IFEND}
Result := True;
end;
procedure TWinHelpViewer.RestartWinHelp;
{$IF NOT DEFINED(LINUX)}
var
StartTime: LongWord;
FileName : String;
{$IFEND}
begin
{ WinHelp has an annoying property where if it has an open dialog
and you send it a new macro, it crashes. In addition, certain older
versions of WinHelp exhibit similar instabilities at other times.
This function sends a HELP_QUIT message to winhelp and then waits
for long enough for the message to be processed and WinHelp to go away.
WinHelp can then be restarted with a new macro. }
{$IF NOT DEFINED(LINUX)}
SoftShutDown;
StartTime := GetTickCount;
repeat
//Application.ProcessMessages;
Sleep(0);
until ((GetTickCount - StartTime) > 1000);
FileName := HelpFile('');
if FileName <> '' then
WinHelp(HelpManager.GetHandle, FileName, HELP_FORCEFILE, 0);
{$IFEND}
{$IFDEF LINUX}
{ The above code has not been tested with HyperHelp under Linux. It is
possible that the identical code will work, but it is not guaranteed
at this time. }
{$ENDIF}
end;
{============================================================================}
constructor TWinHelpViewer.Create;
begin
inherited Create;
HelpViewerIntf := Self;
end;
destructor TWinHelpViewer.Destroy;
begin
HelpViewer := nil;
inherited Destroy;
end;
initialization
HelpViewer := TWinHelpViewer.Create;
System.HelpIntfs.RegisterViewer(HelpViewerIntf, HelpViewer.FHelpManager);
{$IF NOT DEFINED(CLR)}
finalization
if Assigned(HelpViewer.FHelpManager) then
HelpViewer.InternalShutDown;
HelpViewerIntf := nil;
WinHelpTester := nil;
{$IFEND}
end.
|
unit UDMCadContador;
interface
uses
SysUtils, Classes, FMTBcd, DB, DBClient, Provider, SqlExpr;
type
TDMCadContador = class(TDataModule)
sdsContador: TSQLDataSet;
dspContador: TDataSetProvider;
cdsContador: TClientDataSet;
dsContador: TDataSource;
sdsContadorID: TIntegerField;
sdsContadorNOME: TStringField;
cdsContadorID: TIntegerField;
cdsContadorNOME: TStringField;
sdsContadorPESSOA: TStringField;
sdsContadorCPF: TStringField;
cdsContadorPESSOA: TStringField;
cdsContadorCPF: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure dspContadorUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError;
UpdateKind: TUpdateKind; var Response: TResolverResponse);
private
{ Private declarations }
public
{ Public declarations }
vMsgErro : String;
ctCommand : String;
procedure prc_Localizar(ID : Integer); //-1 = Inclusão
procedure prc_Inserir;
procedure prc_Gravar;
procedure prc_Excluir;
end;
var
DMCadContador: TDMCadContador;
implementation
uses DmdDatabase, uUtilPadrao, Variants;
{$R *.dfm}
{ TDMCadPais }
procedure TDMCadContador.prc_Inserir;
var
vAux : Integer;
begin
if not cdsContador.Active then
prc_Localizar(-1);
vAux := dmDatabase.ProximaSequencia('CONTADOR',0);
cdsContador.Insert;
cdsContadorID.AsInteger := vAux;
end;
procedure TDMCadContador.prc_Excluir;
begin
if not(cdsContador.Active) or (cdsContador.IsEmpty) then
exit;
cdsContador.Delete;
cdsContador.ApplyUpdates(0);
end;
procedure TDMCadContador.prc_Gravar;
var
vTipo_Aux : array[1..5] of Integer;
i : Integer;
begin
vMsgErro := '';
if trim(cdsContadorNOME.AsString) = '' then
vMsgErro := '*** Nome não informado!';
if (trim(cdsContadorCPF.AsString) = '') then
vMsgErro := '*** CPF não informado!';
if vMsgErro <> '' then
exit;
cdsContador.Post;
cdsContador.ApplyUpdates(0);
end;
procedure TDMCadContador.prc_Localizar(ID: Integer);
begin
cdsContador.Close;
sdsContador.CommandText := ctCommand;
if ID <> 0 then
sdsContador.CommandText := sdsContador.CommandText + ' WHERE ID = ' + IntToStr(ID);
cdsContador.Open;
end;
procedure TDMCadContador.DataModuleCreate(Sender: TObject);
begin
ctCommand := sdsContador.CommandText;
end;
procedure TDMCadContador.dspContadorUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
dmDatabase.prc_UpdateError(DataSet.Name,UpdateKind,E);
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Math.Delta.Intf;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes,
{$ELSE}
Classes,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf,
ADAPT.Collections.Intf,
ADAPT.Math.Common.Intf;
{$I ADAPT_RTTI.inc}
type
{ Exception Types }
EADMathDeltaException = class(EADMathException);
EADMathDeltaPolatorException = class(EADMathDeltaException);
EADMathDeltaPolatorInsufficientDataPoints = class(EADMathDeltaPolatorException);
/// <summary><c>Common Interface for Delta Extrapolator and Interpolator Interfaces.</c></summary>
IADDeltaPolator<T> = interface(IADInterface)
// Getters
/// <returns><c>The Minimum number of Absolute Data Points required for the Extrapolator/Interpolator to work.</c></returns>
function GetMinimumKnownValues: Integer;
// Setters
/// <summary><c>Defines the Minimum number of Absolute Data Points required for the Extrapolator/Interpolator to work.</c></summary>
procedure SetMinimumKnownValues(const AMinimumKnownValues: Integer);
// Properties
/// <summary><c>Defines the Minimum number of Absolute Data Points required for the Extrapolator/Interpolator to work.</c></summary>
/// <returns><c>The Minimum number of Absolute Data Points required for the Extrapolator/Interpolator to work.</c></returns>
property MinimumKnownValues: Integer read GetMinimumKnownValues write SetMinimumKnownValues;
end;
/// <summary><c>Provides an algorithmic solution for calculating values beyond the range of fixed data points.</c></summary>
IADDeltaExtrapolator<T> = interface(IADDeltaPolator<T>)
/// <summary><c>Takes a Map of existing data points, calculates a rate of change, then returns the calculated value for the given Key Data Point.</c></summary>
/// <returns><c>The Calculated Value for the given Delta Point.</c></returns>
function Extrapolate(const AMap: IADMapReader<ADFloat, T>; const ADelta: ADFloat): T;
end;
/// <summary><c>Provides an algorithmic solution for calculating values between fixed data points.</c></summary>
IADDeltaInterpolator<T> = interface(IADDeltaPolator<T>)
/// <summary><c>Takes a Map of existing data points, calculates a rate of change, then returns the calculated value for the given Key Data Point.</c></summary>
/// <returns><c>The Calculated Value for the given Delta Point.</c></returns>
function Interpolate(const AMap: IADMapReader<ADFloat, T>; const ANearestNeighbour: Integer; const ADelta: ADFloat): T;
end;
/// <summary><c>Stores n Values to enable calculations based on historical Values.</c></summary>
/// <remarks>
/// <para><c>Uses an IADDeltaInterpolator to calculate values between given data points.</c></para>
/// <para><c>Uses an IADDeltaExtrapolator to calculate values beyond given data points.</c></para>
/// <para><c>Provides Read-Only Access.</c></para>
/// </remarks>
IADDeltaValueReader<T> = interface(IADInterface)
// Getters
/// <returns><c>The Extrapolator being used to calculate Values beyond the range of the Absolute Values given.</c></returns>
function GetExtrapolator: IADDeltaExtrapolator<T>;
/// <returns><c>The Interpolator being used to calculate Values between the range of the Absolute Values given.</c></returns>
function GetInterpolator: IADDeltaInterpolator<T>;
/// <returns><c>The Value at the given Delta (Reference Time).</c></returns>
function GetValueAt(const ADelta: ADFloat): T;
/// <returns><c>The Value for the CURRENT Delta (Reference Time).</c></returns>
function GetValueNow: T;
// Properties
/// <returns><c>The Extrapolator being used to calculate Values beyond the range of the Absolute Values given.</c></returns>
property Extrapolator: IADDeltaExtrapolator<T> read GetExtrapolator;
/// <returns><c>The Interpolator being used to calculate Values between the range of the Absolute Values given.</c></returns>
property Interpolator: IADDeltaInterpolator<T> read GetInterpolator;
/// <returns><c>The Value at the given Delta (Reference Time).</c></returns>
property ValueAt[const ADelta: ADFloat]: T read GetValueAt; default;
/// <returns><c>The Value for the CURRENT Delta (Reference Time).</c></returns>
property ValueNow: T read GetValueNow;
end;
/// <summary><c>Stores n Values to enable calculations based on historical Values.</c></summary>
/// <remarks>
/// <para><c>Use IADDeltaValueReader for Read-Only Access.</c></para>
/// <para><c>Call .Reader to return an IADDeltaValueReader reference to this Delta Value Object.</c></para>
/// <para><c>Uses an IADDeltaInterpolator to calculate values between given data points.</c></para>
/// <para><c>Uses an IADDeltaExtrapolator to calculate values beyond given data points.</c></para>
/// <para><c>Provides Read/Write Access.</c></para>
/// </remarks>
IADDeltaValue<T> = interface(IADDeltaValueReader<T>)
// Getters
/// <returns><c>A Read-Only Interface for this Delta Value Object.</c></returns>
function GetReader: IADDeltaValueReader<T>;
// Setters
/// <summary><c>Defines the Extrapolator to use when calculating Values beyond the range of the Absolute Values given.</c></summary>
procedure SetExtrapolator(const AExtrapolator: IADDeltaExtrapolator<T>);
/// <summary><c>Defines the Interpolator to use when calculating Values between the range of the Absolute Values given.</c></summary>
procedure SetInterpolator(const AInterpolator: IADDeltaInterpolator<T>);
/// <summary><c>Defines a Known Value for a specific Delta (Reference Time).</c></summary>
procedure SetValueAt(const ADelta: ADFloat; const AValue: T);
/// <summary><c>Defines a Known Value for the CURRENT Delta (Reference Time).</c></summary>
procedure SetValueNow(const AValue: T);
// Properties
/// <summary><c>Defines the Extrapolator to use when calculating Values beyond the range of the Absolute Values given.</c></summary>
/// <returns><c>The Extrapolator being used to calculate Values beyond the range of the Absolute Values given.</c></returns>
property Extrapolator: IADDeltaExtrapolator<T> read GetExtrapolator write SetExtrapolator;
/// <summary><c>Defines the Interpolator to use when calculating Values between the range of the Absolute Values given.</c></summary>
/// <returns><c>The Interpolator being used to calculate Values between the range of the Absolute Values given.</c></returns>
property Interpolator: IADDeltaInterpolator<T> read GetInterpolator write SetInterpolator;
/// <summary><c>Defines a Known Value for a specific Delta (Reference Time).</c></summary>
/// <returns><c>The Value at the given Delta (Reference Time).</c></returns>
property ValueAt[const ADelta: ADFloat]: T read GetValueAt write SetValueAt; default;
/// <summary><c>Defines a Known Value for the CURRENT Delta (Reference Time).</c></summary>
/// <returns><c>The Value for the CURRENT Delta (Reference Time).</c></returns>
property ValueNow: T read GetValueNow write SetValueNow;
end;
implementation
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the GNU General Public 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.gnu.org/copyleft/gpl.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Initial Developer of the Original Code is Michael Elsdörfer.
All Rights Reserved.
$Id$
You may retrieve the latest version of this file at the Corporeal
Website, located at http://www.elsdoerfer.info/corporeal
Known Issues:
-----------------------------------------------------------------------------}
unit PasswordGeneratorFormUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, CheckLst, Mask, JvExMask, JvSpin,
ExtCtrls, JvComponentBase, JvBalloonHint, gnugettext;
type
TPasswordGeneratorForm = class(TForm)
CharSpacesList: TCheckListBox;
PasswordLengthEdit: TJvSpinEdit;
TntLabel1: TLabel;
Bevel1: TBevel;
Button2: TButton;
Button1: TButton;
JvBalloonHint: TJvBalloonHint;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
function GetDrawSet: string;
function GetRequestedLength: Integer;
public
property DrawSet: string read GetDrawSet;
property RequestedLength: Integer read GetRequestedLength;
end;
var
PasswordGeneratorForm: TPasswordGeneratorForm;
implementation
uses
Utilities, VistaCompat;
{$R *.dfm}
{ TPasswordGeneratorForm }
procedure TPasswordGeneratorForm.Button1Click(Sender: TObject);
var
I, SelectedCount: Integer;
begin
SelectedCount := 0;
for I := 0 to CharSpacesList.Count - 1 do
if CharSpacesList.Checked[I] then
Inc(SelectedCount);
if SelectedCount > 0 then
ModalResult := mrOk
else
JvBalloonHint.ActivateHint(CharSpacesList,
'You''ll need to select at least one charset.', ikError, 'Error');
end;
procedure TPasswordGeneratorForm.FormCreate(Sender: TObject);
var
I: Integer;
begin
// Localize
TranslateComponent(Self);
// use font setting of os (mainly intended for new vista font)
SetDesktopIconFonts(Self.Font);
// per default, check the first three items
for I := 0 to 2 do
CharSpacesList.Checked[I] := True;
end;
function TPasswordGeneratorForm.GetDrawSet: string;
const
// As in CharSpacesList.strings
CharSpaces: array[0..7] of string = (
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmuopqrstufwxyz',
'0123456789',
'_',
'-',
' ',
'!§$%&/"''#*+~',
'()[]{}'
);
var
I: Integer;
begin
for I := 0 to CharSpacesList.Count - 1 do
if CharSpacesList.Checked[I] then
Result := Result + CharSpaces[I];
end;
function TPasswordGeneratorForm.GetRequestedLength: Integer;
begin
Result := PasswordLengthEdit.AsInteger;
end;
end.
|
unit testxblasunit;
interface
uses Math, Sysutils, Ap, xblas;
function TestXBlas(Silent : Boolean):Boolean;
function testxblasunit_test_silent():Boolean;
function testxblasunit_test():Boolean;
implementation
const
XChunk = 1048576;
XChunkCount = 4;
function TestXBlas(Silent : Boolean):Boolean;
var
ApproxErrors : Boolean;
ExactnessErrors : Boolean;
WasErrors : Boolean;
ApproxThreshold : Double;
MaxN : AlglibInteger;
PassCount : AlglibInteger;
N : AlglibInteger;
I : AlglibInteger;
Pass : AlglibInteger;
RV1 : Double;
RV2 : Double;
RV2Err : Double;
CV1 : Complex;
CV2 : Complex;
CV2Err : Double;
CV2ErrX : Double;
CV2ErrY : Double;
RX : TReal1DArray;
RY : TReal1DArray;
CX : TComplex1DArray;
CY : TComplex1DArray;
Temp : TReal1DArray;
B : Double;
S : Double;
i_ : AlglibInteger;
begin
ApproxErrors := False;
ExactnessErrors := False;
WasErrors := False;
ApproxThreshold := 1000*MachineEpsilon;
MaxN := 1000;
PassCount := 10;
//
// tests:
// 1. ability to calculate dot product
// 2. higher precision
//
N:=1;
while N<=MaxN do
begin
Pass:=1;
while Pass<=PassCount do
begin
//
// ability to approximately calculate real dot product
//
SetLength(RX, N);
SetLength(RY, N);
SetLength(Temp, N);
I:=0;
while I<=N-1 do
begin
if AP_FP_Greater(RandomReal,0.2) then
begin
RX[I] := 2*RandomReal-1;
end
else
begin
RX[I] := 0;
end;
if AP_FP_Greater(RandomReal,0.2) then
begin
RY[I] := 2*RandomReal-1;
end
else
begin
RY[I] := 0;
end;
Inc(I);
end;
RV1 := APVDotProduct(@RX[0], 0, N-1, @RY[0], 0, N-1);
XDot(RX, RY, N, Temp, RV2, RV2Err);
ApproxErrors := ApproxErrors or AP_FP_Greater(AbsReal(RV1-RV2),ApproxThreshold);
//
// ability to approximately calculate complex dot product
//
SetLength(CX, N);
SetLength(CY, N);
SetLength(Temp, 2*N);
I:=0;
while I<=N-1 do
begin
if AP_FP_Greater(RandomReal,0.2) then
begin
CX[I].X := 2*RandomReal-1;
CX[I].Y := 2*RandomReal-1;
end
else
begin
CX[I] := C_Complex(0);
end;
if AP_FP_Greater(RandomReal,0.2) then
begin
CY[I].X := 2*RandomReal-1;
CY[I].Y := 2*RandomReal-1;
end
else
begin
CY[I] := C_Complex(0);
end;
Inc(I);
end;
CV1 := C_Complex(0.0);
for i_ := 0 to N-1 do
begin
CV1 := C_Add(CV1,C_Mul(CX[i_],CY[i_]));
end;
XCDot(CX, CY, N, Temp, CV2, CV2Err);
ApproxErrors := ApproxErrors or AP_FP_Greater(AbsComplex(C_Sub(CV1,CV2)),ApproxThreshold);
Inc(Pass);
end;
Inc(N);
end;
//
// test of precision: real
//
N := 50000;
SetLength(RX, N);
SetLength(RY, N);
SetLength(Temp, N);
Pass:=0;
while Pass<=PassCount-1 do
begin
Assert(N mod 2=0);
//
// First test: X + X + ... + X - X - X - ... - X = 1*X
//
S := Exp(Max(Pass, 50));
if (Pass=PassCount-1) and (Pass>1) then
begin
S := MaxRealNumber;
end;
RY[0] := (2*RandomReal-1)*S*Sqrt(2*RandomReal);
I:=1;
while I<=N-1 do
begin
RY[I] := RY[0];
Inc(I);
end;
I:=0;
while I<=N div 2-1 do
begin
RX[I] := 1;
Inc(I);
end;
I:=N div 2;
while I<=N-2 do
begin
RX[I] := -1;
Inc(I);
end;
RX[N-1] := 0;
XDot(RX, RY, N, Temp, RV2, RV2Err);
ExactnessErrors := ExactnessErrors or AP_FP_Less(RV2Err,0);
ExactnessErrors := ExactnessErrors or AP_FP_Greater(RV2Err,4*MachineEpsilon*AbsReal(RY[0]));
ExactnessErrors := ExactnessErrors or AP_FP_Greater(AbsReal(RV2-RY[0]),RV2Err);
//
// First test: X + X + ... + X = N*X
//
S := Exp(Max(Pass, 50));
if (Pass=PassCount-1) and (Pass>1) then
begin
S := MaxRealNumber;
end;
RY[0] := (2*RandomReal-1)*S*Sqrt(2*RandomReal);
I:=1;
while I<=N-1 do
begin
RY[I] := RY[0];
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
RX[I] := 1;
Inc(I);
end;
XDot(RX, RY, N, Temp, RV2, RV2Err);
ExactnessErrors := ExactnessErrors or AP_FP_Less(RV2Err,0);
ExactnessErrors := ExactnessErrors or AP_FP_Greater(RV2Err,4*MachineEpsilon*AbsReal(RY[0])*N);
ExactnessErrors := ExactnessErrors or AP_FP_Greater(AbsReal(RV2-N*RY[0]),RV2Err);
Inc(Pass);
end;
//
// test of precision: complex
//
N := 50000;
SetLength(CX, N);
SetLength(CY, N);
SetLength(Temp, 2*N);
Pass:=0;
while Pass<=PassCount-1 do
begin
Assert(N mod 2=0);
//
// First test: X + X + ... + X - X - X - ... - X = 1*X
//
S := Exp(Max(Pass, 50));
if (Pass=PassCount-1) and (Pass>1) then
begin
S := MaxRealNumber;
end;
CY[0].X := (2*RandomReal-1)*S*Sqrt(2*RandomReal);
CY[0].Y := (2*RandomReal-1)*S*Sqrt(2*RandomReal);
I:=1;
while I<=N-1 do
begin
CY[I] := CY[0];
Inc(I);
end;
I:=0;
while I<=N div 2-1 do
begin
CX[I] := C_Complex(1);
Inc(I);
end;
I:=N div 2;
while I<=N-2 do
begin
CX[I] := C_Complex(-1);
Inc(I);
end;
CX[N-1] := C_Complex(0);
XCDot(CX, CY, N, Temp, CV2, CV2Err);
ExactnessErrors := ExactnessErrors or AP_FP_Less(CV2Err,0);
ExactnessErrors := ExactnessErrors or AP_FP_Greater(CV2Err,4*MachineEpsilon*AbsComplex(CY[0]));
ExactnessErrors := ExactnessErrors or AP_FP_Greater(AbsComplex(C_Sub(CV2,CY[0])),CV2Err);
//
// First test: X + X + ... + X = N*X
//
S := Exp(Max(Pass, 50));
if (Pass=PassCount-1) and (Pass>1) then
begin
S := MaxRealNumber;
end;
CY[0] := C_Complex((2*RandomReal-1)*S*Sqrt(2*RandomReal));
I:=1;
while I<=N-1 do
begin
CY[I] := CY[0];
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
CX[I] := C_Complex(1);
Inc(I);
end;
XCDot(CX, CY, N, Temp, CV2, CV2Err);
ExactnessErrors := ExactnessErrors or AP_FP_Less(CV2Err,0);
ExactnessErrors := ExactnessErrors or AP_FP_Greater(CV2Err,4*MachineEpsilon*AbsComplex(CY[0])*N);
ExactnessErrors := ExactnessErrors or AP_FP_Greater(AbsComplex(C_Sub(CV2,C_MulR(CY[0],N))),CV2Err);
Inc(Pass);
end;
//
// report
//
WasErrors := ApproxErrors or ExactnessErrors;
if not Silent then
begin
Write(Format('TESTING XBLAS'#13#10'',[]));
Write(Format('APPROX.TESTS: ',[]));
if ApproxErrors then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
Write(Format('EXACT TESTS: ',[]));
if ExactnessErrors then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
if WasErrors then
begin
Write(Format('TEST FAILED'#13#10'',[]));
end
else
begin
Write(Format('TEST PASSED'#13#10'',[]));
end;
Write(Format(''#13#10''#13#10'',[]));
end;
//
// end
//
Result := not WasErrors;
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testxblasunit_test_silent():Boolean;
begin
Result := TestXBlas(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testxblasunit_test():Boolean;
begin
Result := TestXBlas(False);
end;
end. |
unit ExpenseData;
interface
uses
System.SysUtils, System.Classes, Data.DB, Data.Win.ADODB, ExpenseDataMethodsIntf,
Generics.Collections, AccountTitle, Expense;
type
TdmExpense = class(TDataModule, IExpenseDataMethods)
dstExpenseTitles: TADODataSet;
dscExpenseTitles: TDataSource;
dstExpense: TADODataSet;
dscExpense: TDataSource;
dstLedger: TADODataSet;
dscLedger: TDataSource;
dstLedgerposting_id: TStringField;
dstLedgerloc_prefix: TStringField;
dstLedgerref_posting_id: TStringField;
dstLedgerdebit_amt: TBCDField;
dstLedgercredit_amt: TBCDField;
dstLedgerevent_object: TStringField;
dstLedgerpk_event_object: TStringField;
dstLedgercase_type: TStringField;
dstLedgerpost_date: TDateTimeField;
dstLedgervalue_date: TDateTimeField;
dstLedgerstatus_code: TStringField;
dstLedgertitle: TStringField;
dstVoucher: TADODataSet;
dscVoucher: TDataSource;
procedure DataModuleCreate(Sender: TObject);
procedure dstLedgerCalcFields(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
procedure Add;
procedure Save(AExpense: TExpense);
function GetAccountTitles: TObjectList<TAccountTitle>;
end;
var
dmExpense: TdmExpense;
implementation
uses
AppData, DBUtil;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TdmExpense }
procedure TdmExpense.Add;
begin
dstExpense.Append;
end;
procedure TdmExpense.DataModuleCreate(Sender: TObject);
begin
dstExpense.Open;
dstLedger.Open;
end;
procedure TdmExpense.dstLedgerCalcFields(DataSet: TDataSet);
begin
with DataSet do
begin
if FieldByName('case_type').AsString = 'CSH' then
FieldByName('title').AsString := 'Cash'
else if FieldByName('case_type').AsString = 'CHK' then
FieldByName('title').AsString := 'Check'
else if FieldByName('case_type').AsString = 'EXP' then
FieldByName('title').AsString := 'Expense'
else
FieldByName('title').AsString := 'Accounts payable';
end;
end;
function TdmExpense.GetAccountTitles: TObjectList<TAccountTitle>;
var
LTitle: TAccountTitle;
list: TObjectList<TAccountTitle>;
begin
with dstExpenseTitles do
begin
list := TObjectList<TAccountTitle>.Create;
try
Open;
while not Eof do
begin
LTitle := TAccountTitle.Create;
LTitle.Code := FieldByName('acct_title_code').AsString;
LTitle.Name := FieldByName('acct_title_name').AsString;
LTitle.CostType := TCostTypes(FieldByName('cost_type').AsInteger);
list.Add(LTitle);
Next;
end;
finally
Close;
end;
end;
Result := list;
end;
procedure TdmExpense.Save(AExpense: TExpense);
begin
{with dstExpense do
begin
if State = dsInsert then
FieldByName('expense_id').AsString := GetExpenseId;
Post;
end; }
with dstLedger do
begin
Open;
// debit
Append;
FieldByName('case_type').AsString := 'EXP';
FieldByName('debit_amt').AsCurrency := AExpense.Amount;
Post;
// credit cash
if AExpense.Cash > 0 then
begin
Append;
FieldByName('case_type').AsString := 'CSH';
FieldByName('credit_amt').AsCurrency := AExpense.Cash;
Post;
end;
// credit check
if AExpense.Cash > 0 then
begin
Append;
FieldByName('case_type').AsString := 'CHK';
FieldByName('credit_amt').AsCurrency := AExpense.Check;
Post;
end;
// credit accounts payable
if (AExpense.Amount - AExpense.Cash - AExpense.Check) > 0 then
begin
Append;
FieldByName('case_type').AsString := 'ACP';
FieldByName('credit_amt').AsCurrency := AExpense.Amount - AExpense.Cash - AExpense.Check;
Post;
end;
Refresh;
end;
end;
end.
|
{$mode objfpc}{$H+}{$J-}
program is_as;
uses
SysUtils;
type
TMyClass = class
procedure MyMethod;
end;
TMyClassDescendant = class(TMyClass)
procedure MyMethodInDescendant;
end;
procedure TMyClass.MyMethod;
begin
WriteLn('MyMethod');
end;
procedure TMyClassDescendant.MyMethodInDescendant;
begin
WriteLn('MyMethodInDescendant');
end;
var
Descendant: TMyClassDescendant;
C: TMyClass;
begin
Descendant := TMyClassDescendant.Create;
try
Descendant.MyMethod;
Descendant.MyMethodInDescendant;
{ Descendant има цялата функционалност, която се очаква от
TMyClass, така че това присвояване е OK }
C := Descendant;
C.MyMethod;
{ Това не може да сработи, тъй като TMyClass не дефинира този метод }
//C.MyMethodInDescendant;
if C is TMyClassDescendant then
(C as TMyClassDescendant).MyMethodInDescendant;
finally
FreeAndNil(Descendant);
end;
end.
|
unit WasmSample_Finalize;
interface
uses
System.SysUtils, System.Classes
, Wasm
{$ifndef USE_WASMER}
, Wasmtime
{$else}
, Wasmer
{$ifend}
;
// wasm_instance_set_host_info_with_finalizer is not implemented!
function FinalizeSample_Clike() : Boolean;
implementation
const iterations = 100000;
var live_count : Integer = 0;
procedure finalize(data : Pointer); cdecl;
begin
var i := NativeInt(data);
if (i mod (iterations div 10)) = 0 then
begin
writeln('Finalizing #'+IntToStr(i)+'...');
end;
Dec(live_count);
end;
function run_in_store(const store : TOwnStore) : Boolean;
begin
result := true;
// Load binary.
writeln('Loading binary...');
var binary := TWasmByteVec.NewEmpty;
{$ifdef USE_WASMFILE}
binary.Unwrap.LoadFromFile('finalize.wasm');
{$else}
var wat :=
'(module'+
' (func (export "f"))'+
' (func (export "g"))'+
' (func (export "h"))'+
')';
binary.Unwrap.Wat2Wasm(wat);
{$ifend}
// Compile.
writeln('Compiling module...');
var module := TWasmModule.New(+store, +binary);
if module.IsNone then
begin
writeln('> Error compiling module!');
exit(false);
end;
// Instantiate.
Writeln('Instantiating module...');
for var i := 0 to iterations do
begin
if (i mod (iterations div 10) = 0) then writeln(IntToStr(i));
var imports := TWasmExternVec.Create([]);
var instance := TWasm.instance_new(+store, +module, @imports, nil);
if instance = nil then
begin
writeln('> Error instantiating module '+IntToStr(i)+'!');
exit(false);
end;
var data := Pointer(i);
TWasm.instance_set_host_info_with_finalizer(instance, data, finalize); // not implemented
TWasm.instance_delete(instance);
Inc(live_count);
end;
end;
function FinalizeSample_Clike() : Boolean;
begin
// Initialize.
writeln('Initializing...');
begin
var engine := TWasmEngine.New();
writeln('Live count '+IntToStr(live_count));
writeln('Creating store 1...');
begin
var store1 := TWasmStore.New(+engine);
writeln('Running in store 1...');
run_in_store(store1);
writeln('Live count '+IntToStr(live_count));
writeln('Creating store 2...');
begin
var store2 := TWasmStore.New(+engine);
writeln('Running in store 2...');
run_in_store(store2);
writeln('Live count '+IntToStr(live_count));
writeln('Deleting store 2...');
end;
writeln('Live count '+IntToStr(live_count));
writeln('Running in store 1...');
run_in_store(store1);
writeln('Live count '+IntToStr(live_count));
writeln('Deleting store 1...');
end;
writeln('Live count '+IntToStr(live_count));
assert(live_count = 0);
// Shut down.
writeln('Shutting down...');
end;
// All done.
writeln('Done.');
result := true;
end;
end.
|
unit Optimizer.Defrag;
interface
uses
SysUtils,
OS.EnvironmentVariable, Optimizer.Template, Global.LanguageString,
OS.ProcessOpener, Registry.Helper;
type
TDefragOptimizer = class(TOptimizationUnit)
public
function IsOptional: Boolean; override;
function IsCompatible: Boolean; override;
function IsApplied: Boolean; override;
function GetName: String; override;
procedure Apply; override;
procedure Undo; override;
end;
implementation
function TDefragOptimizer.IsOptional: Boolean;
begin
exit(false);
end;
function TDefragOptimizer.IsCompatible: Boolean;
begin
exit(IsBelowWindows8);
end;
function TDefragOptimizer.IsApplied: Boolean;
begin
if not IsBelowWindows8 then
exit(false);
result :=
not
((NSTRegistry.GetRegStr(NSTRegistry.LegacyPathToNew('LM',
'SOFTWARE\Microsoft\Dfrg\BootOptimizeFunction', 'Enable')) <> 'N')
and
(NSTRegistry.GetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SOFTWARE\Microsoft\Windows\CurrentVersion\OptimalLayout',
'EnableAutoLayout')) <> 0));
end;
function TDefragOptimizer.GetName: String;
begin
exit(CapOptDfrg[CurrLang]);
end;
procedure TDefragOptimizer.Apply;
begin
NSTRegistry.SetRegStr(NSTRegistry.LegacyPathToNew(
'LM', 'SOFTWARE\Microsoft\Dfrg\BootOptimizeFunction',
'Enable'), 'N');
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SOFTWARE\Microsoft\Windows\CurrentVersion' +
'\OptimalLayout', 'EnableAutoLayout'), 0);
end;
procedure TDefragOptimizer.Undo;
begin
NSTRegistry.SetRegStr(NSTRegistry.LegacyPathToNew(
'LM', 'SOFTWARE\Microsoft\Dfrg\BootOptimizeFunction', 'Enable'), 'Y');
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SOFTWARE\Microsoft\Windows\CurrentVersion' +
'\OptimalLayout', 'EnableAutoLayout'), 1);
end;
end.
|
unit Providers.DataSet.Serialize.Constants;
interface
const
FIELD_TYPE_NOT_FOUND = 'Cannot find type for field "%s"';
DATASET_ACTIVATED = 'The DataSet can not be active.';
PREDEFINED_FIELDS = 'The DataSet can not have predefined fields';
DATASET_HAS_NO_DEFINED_FIELDS = 'DataSet has no defined fields';
JSON_NOT_DIFINED = 'JSON not defined';
SIZE_NOT_DEFINED_FOR_FIELD = 'Size not defined for field "%s".';
TO_CONVERT_STRUCTURE_ONLY_JSON_ARRAY_ALLOWED = 'To convert a structure only JSONArray is allowed';
OBJECT_STATE = 'object_state';
INVALID_FIELD_COUNT = '[%s] Invalid field count';
implementation
end.
|
unit MainGame;
interface
{Процедура инциализации сцены игры }
procedure InitMainGame();
{Процедура отлова нажатия клавиш сцене игры }
procedure HandleInputInMainGame();
{Процедура обновления логики в сцене игры }
procedure UpdateMainGame(dt : integer);
{Процедура отрисовки ввода сцены игры }
procedure RenderMainGame();
{Процедура очистки данных сцены игры }
procedure DisposeMainGame();
implementation
uses
GraphABC, GlobalVars, Renderer, UIAssets;
const
SpawnDelay = 1000; //Задержка спавна монстров
ToUp = 1; //Направление вверх
ToRight = 2; //Направление вправо
ToDown = 3; //Направление вниз
ToLeft = 4; //Направление влево
type
{Запись физического объекта, который взаимодействует с другими физическими объектами }
Collider = record
_x : integer;
_y : integer;
_w : integer;
_h : integer;
_offsetX : integer;
_offsetY : integer;
Pooled : boolean;
ColId : word;
end;
{Запись координат объекта }
Transform = record
_x : integer;
_y : integer;
end;
{Запись игрока }
Player = record
_col : Collider;
_pos : Transform;
_sprite : word = 1;
Speed : word;
Up : word;
Left : word;
Down : word;
Right : word;
Place : word;
PlayerId : byte;
PlayerScore : integer;
BombCount : byte;
Respawn : integer;
IsDead : boolean;
Immortal : integer;
IsImmortal : boolean;
Name : string;
end;
{Запись врага }
Enemy = record
_col : Collider;
_pos : Transform;
_sprite : word;
Speed : word;
Respawn : integer;
IsDead : boolean;
EnemyType : byte;
Direction : byte;
LastChange : integer;
NeedChange : boolean;
CurPosInArray : Transform;
NewPosInArray : Transform;
end;
{Запись бомбы }
Bomb = record
_col : Collider;
_pos : Transform;
_sprite : word = 2;
Time : integer;
Pooled : boolean;
PlayerId : byte;
IsAddable : boolean;
end;
{Запись неломаемого блока }
Iron = record
_col : Collider;
_pos : Transform;
_sprite : word = 3;
end;
{Запись ломаемого блока }
Brick = record
_col : Collider;
_pos : Transform;
_sprite : word = 4;
Pooled : boolean;
end;
{Запись огня}
Fire = record
_pos : Transform;
_sprite : word = 6;
Time : integer;
Pooled : boolean;
PlayerId : byte;
end;
{Запись состояния сцены игры }
GameState = record
Players : array[1..MaxPlayers] of Player;
Map : array[1..20, 1..20] of integer;
MapX : word;
MapY : word;
ColliderMap : array[1..255] of Collider;
ColCount : word;
IronMap : array[1..255] of Iron;
IronCount : word;
BrickMap : array[1..255] of Brick;
BrickCount : word;
BombMap : array[1..63] of Bomb;
BombCount : word;
FireMap : array[1..255] of Fire;
FireCount : word;
SpawnPoints : array[1..8] of Transform;
SpawnCount : word;
SpawnEnemies : array[1..4] of Transform;
SpawnCountEnemy : word;
Enemies : array[1..6] of Enemy;
CurrentMap : string;
end;
var
GameplayState : GameState; //Сцена игры
MainTime : longint; //Оставшиеся время игры
SpawnCooldown : longint; //Время смерти монстров
IsPause : boolean; //Поставлена пауза или нет
Options : array[1..2] of string; //Кнопки в паузе
CurrentOp : byte; //Текущая кнопка
{Процедура уменьшения времени игры }
{Параметры: dt - время между кадрами }
procedure Countdown(dt : integer);
begin
MainTime := MainTime - dt;
end;
{Процедура уменьшения времени взрыва бомбы }
{Параметры: dt - время между кадрами }
procedure Bombdown(dt : integer);
begin
for var i:=1 to GameplayState.BombCount do
begin
if (GameplayState.BombMap[i].Pooled) then
begin
GameplayState.BombMap[i].Time := GameplayState.BombMap[i].Time - dt;
end;
end;
end;
{Процедура уменьшения существования огня }
{Параметры: dt - время между кадрами }
procedure Firedown(dt : integer);
begin
for var i:=1 to GameplayState.FireCount do
begin
if (GameplayState.FireMap[i].Pooled) then
begin
GameplayState.FireMap[i].Time := GameplayState.FireMap[i].Time - dt;
end;
end;
end;
{Процедура уменьшения времени спавнка игрока }
{Параметры: dt - время между кадрами }
procedure Respawndown(dt : integer);
begin
for var i:=1 to MaxPlayers do
begin
if (GameplayState.Players[i].IsDead) then
begin
GameplayState.Players[i].Respawn := GameplayState.Players[i].Respawn - dt;
end;
end;
end;
{Процедура уменьшения времени щита игрока }
{Параметры: dt - время между кадрами }
procedure Immortaldown(dt : integer);
begin
for var i:=1 to MaxPlayers do
begin
if (GameplayState.Players[i].IsImmortal) then
begin
GameplayState.Players[i].Immortal := GameplayState.Players[i].Immortal - dt;
if (GameplayState.Players[i].Immortal <= 0) then
GameplayState.Players[i].IsImmortal := false;
end;
end;
end;
{Процедура проверки сталковения двух коллайдеров (Алгоритм AABB) }
{Параметры: first, second - физические объекты }
function IsCollide(first, second : Collider) : boolean;
begin
if ((first.Pooled = false) or (second.Pooled = false)) then
begin
IsCollide := false;
end
else
begin
if (((first._x + first._w + first._offsetX) <= (second._x + second._offsetX))
or ((first._x + first._offsetX) >= (second._x + second._w + second._offsetX))) then
begin
IsCollide := false;
end
else
if (((first._y + first._h + first._offsetY) <= (second._y + second._offsetY))
or ((first._y + first._offsetY) >= (second._y + second._h + + second._offsetY))) then
begin
IsCollide := false;
end
else
begin
IsCollide := true;
end;
end;
end;
{Функция создания физического объекта }
{Параметры: x, y - позиция, offsetX, offsetY - смещение, }
{ w, h - ширина, высота, isPooled - активный или нет }
function CreateCollider(x, y, offsetX, offsetY, h, w : integer; isPooled : boolean) : Collider;
begin
var temp : Collider;
temp._x := x;
temp._y := y;
temp._offsetX := offsetX;
temp._offsetY := offsetY;
temp._h := h;
temp._w := w;
temp.Pooled := isPooled;
Inc(GameplayState.colCount);
temp.ColId := GameplayState.colCount;
GameplayState.ColliderMap[GameplayState.colCount] := temp;
CreateCollider := temp;
end;
{Функция попытки убить игрока }
{Параметры: _player - игрок }
function TryKillPlayer(var _player : Player) : boolean;
begin
TryKillPlayer := false;
if (not _player.IsImmortal) then
begin
_player.Respawn := 2000;
_player.IsDead := true;
TryKillPlayer := true;
end;
end;
{Функция проверки столкновений с врагами }
{Параметры: _player - физический объект игрока }
function CheckCollisionWithEnemy(_player : Collider) : boolean;
begin
CheckCollisionWithEnemy := false;
for var i:=1 to 6 do
begin
if (IsCollide(_player, GameplayState.Enemies[i]._col)) then
begin
CheckCollisionWithEnemy := true;
exit;
end;
end;
end;
{Функция проверки столкновений с блоками }
{Параметры: entity - физический объект игрока }
function CheckCollision(entity : Collider) : boolean;
begin
CheckCollision:=false;
for var i:=1 to GameplayState.ColCount do
begin
if (IsCollide(entity, GameplayState.ColliderMap[i])) then
begin
CheckCollision:=true;
exit;
end;
end;
end;
{Функция проверки существует бомба на данный позиции или нет }
{Параметры: _bomb - добавляемая бомба }
function ContainsBomb(_bomb : Bomb) : boolean;
begin
ContainsBomb := false;
for var i := 1 to GameplayState.BombCount do
begin
if ((_bomb._pos._x = GameplayState.BombMap[i]._pos._x) and
(_bomb._pos._y = GameplayState.BombMap[i]._pos._y) and
GameplayState.BombMap[i].Pooled = true) then
begin
ContainsBomb := true;
exit;
end;
end;
end;
{Функция получения свободного индекса бомбы в массиве }
function GetFirstPooledBomb() : word;
begin
for var i:=1 to GameplayState.BombCount do
begin
if (GameplayState.BombMap[i].Pooled = false) then
begin
GetFirstPooledBomb := i;
exit;
end;
if (i = GameplayState.BombCount) then
begin
GetFirstPooledBomb := i + 1;
GameplayState.BombCount := GameplayState.BombCount + 1;
exit;
end;
end;
if (GameplayState.BombCount = 0) then
begin
GameplayState.BombCount := GameplayState.BombCount + 1;
GetFirstPooledBomb := 1;
end;
end;
{Процедура создания бомбы }
{Параметры: x, y - позиция, playerId - номер игрока }
{ byPlayer - бомба игрока или нет, time - время взрыва }
procedure CreateBomb(x, y : integer; playerId : word; byPlayer : boolean; time : integer);
begin
var _x := (x + 32) div 64 * 64;
var _y := (y + 32) div 64 * 64;
var temp : Bomb;
temp._pos._x := _x;
temp._pos._y := _y;
temp._col._h := 64;
temp._col._w := 64;
temp._col._x := _x;
temp._col._y := _y;
temp.Pooled := true;
temp.IsAddable := byPlayer;
temp.Time := time;
temp.PlayerId := playerId;
if (not ContainsBomb(temp)) then
begin
Dec(GameplayState.Players[playerId].BombCount);
var index := GetFirstPooledBomb();
GameplayState.BombMap[index] := temp;
end;
end;
{Процедура управления игроком }
{Параметры: movablePlayer - управляемый игрок, dt - время между кадрами }
procedure MovePlayer(var movablePlayer : Player; dt : integer);
begin
if (not movablePlayer.IsDead) then
begin
var newCol : Collider;
newCol := movablePlayer._col;
if (inputKeys[movablePlayer.Up]) then
begin
newCol._y := newCol._y - round(movablePlayer.Speed * dt / 1000);
end
else if (inputKeys[movablePlayer.Left]) then
begin
newCol._x := newCol._x - round(movablePlayer.Speed * dt / 1000);
end
else if (inputKeys[movablePlayer.Down]) then
begin
newCol._y := newCol._y + round(movablePlayer.Speed * dt / 1000);
end
else if (inputKeys[movablePlayer.Right]) then
begin
newCol._x := newCol._x + round(movablePlayer.Speed * dt / 1000);
end;
if (not CheckCollision(newCol)) then
begin
movablePlayer._col := newCol;
movablePlayer._pos._x := newCol._x;
movablePlayer._pos._y := newCol._y;
end;
if (inputKeys[movablePlayer.Place]) then
begin
if (movablePlayer.BombCount > 0) then
begin
CreateBomb(movablePlayer._pos._x, movablePlayer._pos._y, movablePlayer.PlayerId, true, 3000);
end;
end;
if ((CheckCollisionWithEnemy(movablePlayer._col))) then
begin
if (TryKillPlayer(movablePlayer)) then
begin
movablePlayer.PlayerScore := movablePlayer.PlayerScore - 3;
end;
end;
end;
end;
{Функция получения свободного индекса огня в массиве }
function GetFirstPooledFire() : word;
begin
for var i:=1 to GameplayState.FireCount do
begin
if (GameplayState.FireMap[i].Pooled = false) then
begin
GetFirstPooledFire := i;
exit;
end;
if (i = GameplayState.FireCount) then
begin
GetFirstPooledFire := i + 1;
GameplayState.FireCount := GameplayState.FireCount + 1;
exit;
end;
end;
if (GameplayState.FireCount = 0) then
begin
GameplayState.FireCount := GameplayState.FireCount + 1;
GetFirstPooledFire := 1;
end;
end;
{Фукнция создания огня }
{Параметры: x, y - позиция, nx, ny - смещение огня }
{ playerId - номер игрока }
function CreateFire(x, y, nx, ny : integer; playerId : word) : Fire;
begin
var _x := x div 64;
var _y := y div 64;
var _fire : Fire;
_fire._pos._x := (_x + nx) * 64;
_fire._pos._y := (_y + ny) * 64;
_fire.PlayerId := playerId;
_fire.Pooled := true;
_fire.Time := 300;
var _index := GetFirstPooledFire();
GameplayState.FireMap[_index] := _fire;
CreateFire := _fire;
end;
{Фукнция взрыва клетки }
{Параметры: _fire - огонь на клетке }
function BlowUpCell(_fire : Fire) : boolean;
begin
var _x := _fire._pos._x div 64 + 1;
var _y := _fire._pos._y div 64 + 1;
BlowUpCell := false;
for var i:=1 to 6 do
begin
if ((((GameplayState.Enemies[i]._pos._x + 32) div 64 + 1) = _x) and (((GameplayState.Enemies[i]._pos._y + 32) div 64 + 1) = _y)) then
begin
if (not GameplayState.Enemies[i].IsDead) then
begin
BlowUpCell := true;
GameplayState.Players[_fire.PlayerId].PlayerScore := GameplayState.Players[_fire.PlayerId].PlayerScore + 3;
GameplayState.Enemies[i].IsDead := true;
GameplayState.Enemies[i].Respawn := 3000;
GameplayState.Enemies[i]._col.Pooled := false;
if (GameplayState.Enemies[i].EnemyType = BlowupEnemy) then
begin
CreateBomb(GameplayState.Enemies[i]._pos._x, GameplayState.Enemies[i]._pos._y, _fire.PlayerId, false, 20);
end;
end;
end;
end;
if (GameplayState.Map[_y, _x] = 1) then
begin
BlowUpCell := true;
exit;
end
else
if (GameplayState.Map[_y, _x] = 2) then
begin
GameplayState.Map[_y, _x] := 0;
for var i:=1 to GameplayState.BrickCount do
begin
if ((GameplayState.BrickMap[i]._pos._x = _fire._pos._x) and
(GameplayState.BrickMap[i]._pos._y = _fire._pos._y) and
GameplayState.BrickMap[i].Pooled) then
begin
BlowUpCell := true;
GameplayState.ColliderMap[GameplayState.BrickMap[i]._col.ColId].Pooled := false;
GameplayState.BrickMap[i].Pooled := false;
GameplayState.Players[_fire.PlayerId].PlayerScore := GameplayState.Players[_fire.PlayerId].PlayerScore + 1;
exit;
end;
end;
end;
for var i:=1 to MaxPlayers do
begin
if ((((GameplayState.Players[i]._pos._x + 32) div 64 + 1) = _x) and
(((GameplayState.Players[i]._pos._y + 32) div 64 + 1) = _y) and
not GameplayState.Players[i].IsDead) then
begin
BlowUpCell := true;
if (TryKillPlayer(GameplayState.Players[i])) then
begin
if (_fire.PlayerId <> GameplayState.Players[i].PlayerId) then
begin
GameplayState.Players[_fire.PlayerId].PlayerScore := GameplayState.Players[_fire.PlayerId].PlayerScore + 10;
end;
GameplayState.Players[i].PlayerScore := GameplayState.Players[i].PlayerScore - 3;
end;
end;
end;
end;
{Процедура взрыва бомбы }
{Параметры: _bomb - бомба, waveSize - длина волны взрыва }
procedure ExplodeBomb(_bomb : Bomb; waveSize : word);
begin
var center := CreateFire(_bomb._pos._x, _bomb._pos._y, 0, 0, _bomb.PlayerId);
if (not BlowUpCell(center)) then
begin
//To Up
for var i:=1 to waveSize do
begin
var temp := CreateFire(_bomb._pos._x, _bomb._pos._y, 0, -i, _bomb.PlayerId);
if (BlowUpCell(temp)) then
begin
break;
end;
end;
//To Down
for var i:=1 to waveSize do
begin
var temp := CreateFire(_bomb._pos._x, _bomb._pos._y, 0, i, _bomb.PlayerId);
if (BlowUpCell(temp)) then
begin
break;
end;
end;
//To Left
for var i:=1 to waveSize do
begin
var temp := CreateFire(_bomb._pos._x, _bomb._pos._y, -i, 0, _bomb.PlayerId);
if (BlowUpCell(temp)) then
begin
break;
end;
end;
//To Right
for var i:=1 to waveSize do
begin
var temp := CreateFire(_bomb._pos._x, _bomb._pos._y, i, 0, _bomb.PlayerId);
if (BlowUpCell(temp)) then
begin
break;
end;
end;
end;
end;
{Процедура обновления огня }
{Параметры: dt - время между кадрами }
procedure UpdateFire(dt : integer);
begin
for var i:=1 to GameplayState.FireCount do
begin
if ((GameplayState.FireMap[i].Time <= 0) and (GameplayState.FireMap[i].Pooled)) then
begin
GameplayState.FireMap[i].Pooled := false;
end;
end;
end;
{Процедура обновления бомб }
{Параметры: dt - время между кадрами }
procedure UpdateBomb(dt : integer);
begin
for var i:=1 to GameplayState.BombCount do
begin
if ((GameplayState.BombMap[i].Time <= 0) and (GameplayState.BombMap[i].Pooled)) then
begin
if (i = GameplayState.BombCount) then
begin
GameplayState.BombCount := GameplayState.BombCount - 1;
end
else
begin
GameplayState.BombMap[i].Pooled := false;
end;
Inc(GameplayState.Players[GameplayState.BombMap[i].PlayerId].BombCount);
if (GameplayState.Players[GameplayState.BombMap[i].PlayerId].BombCount > 3) then
GameplayState.Players[GameplayState.BombMap[i].PlayerId].BombCount := 3;
if (GameplayState.BombMap[i].IsAddable) then
begin
ExplodeBomb(GameplayState.BombMap[i], 2);
end
else
begin
ExplodeBomb(GameplayState.BombMap[i], 1);
end;
end;
end;
end;
{Функция проверки, свободно на клетке или нет }
{Параметры: x, y - координаты в двумерном массиве }
function IsEmpty(x, y : integer) : boolean;
begin
if (x > 0) and (x < 16) and (y > 0) and (y < 12) then
begin
if ((GameplayState.Map[y, x] = 1) or (GameplayState.Map[y, x] = 2)) then
begin
IsEmpty := false;
end
else
begin
IsEmpty := true;
end;
end;
end;
{Функция проверки, свободно в определенном направлении для монстра }
{Параметры: _enemy - враг, dir - направление }
function IsEmptyForEnemy(_enemy : Enemy; dir : integer) : boolean;
begin
IsEmptyForEnemy := true;
case Dir of
ToUp:
begin
if (not IsEmpty(_enemy.CurPosInArray._x, _enemy.CurPosInArray._y - 1)) then
IsEmptyForEnemy := false;
end;
ToDown:
begin
if (not IsEmpty(_enemy.CurPosInArray._x, _enemy.CurPosInArray._y + 1)) then
IsEmptyForEnemy := false;
end;
ToRight:
begin
if (not IsEmpty(_enemy.CurPosInArray._x + 1, _enemy.CurPosInArray._y)) then
IsEmptyForEnemy := false;
end;
ToLeft:
begin
if (not IsEmpty(_enemy.CurPosInArray._x - 1, _enemy.CurPosInArray._y)) then
IsEmptyForEnemy := false;
end;
end;
end;
{Функция проверки, мертвы ли другие игроки или нет }
{Параметры: playerId - номер спавнящегося игрока }
function AreOtherDead(playerId : integer) : boolean;
var
deadCount : integer;
begin
deadCount := 0;
for var i:=1 to MaxPlayers do
begin
if (GameplayState.Players[i].PlayerId <> playerId) then
begin
if (GameplayState.Players[i].IsDead) then
Inc(deadCount);
end;
end;
if (deadCount = (MaxPlayers - 1)) then
AreOtherDead := true
else
AreOtherDead := false;
end;
{Процедура получения самой опасной координаты }
{Параметры: x, y - координаты точки, playerId - номер игрока }
procedure GetDangerousPoint(var x, y : integer; playerId : integer);
var
n : integer;
begin
x := 0;
y := 0;
n := 0;
for var i:=1 to MaxPlayers do
begin
if (GameplayState.Players[i].PlayerId <> playerId) then
begin
if (not GameplayState.Players[i].IsDead) then
begin
Inc(n);
x += GameplayState.Players[i]._pos._x;
y += GameplayState.Players[i]._pos._y;
end;
end;
end;
for var i:=1 to 6 do
begin
if (not GameplayState.Enemies[i].IsDead) then
begin
Inc(n);
x += GameplayState.Enemies[i]._pos._x;
y += GameplayState.Enemies[i]._pos._y;
end;
end;
x := Round(x / n);
y := Round(y / n);
end;
{Процедура спавна игрока }
{Параметры: _player - спавнящийся игрок }
procedure SpawnPlayer(var _player : Player);
begin
var trans, dang : Transform;
if (AreOtherDead(_player.PlayerId)) then
begin
trans := GameplayState.SpawnPoints[Random(1, GameplayState.SpawnCount)];
end
else
begin
GetDangerousPoint(dang._x, dang._y, _player.PlayerId);
var max := sqrt(sqr(dang._x - GameplayState.SpawnPoints[1]._x) +
sqr(dang._y - GameplayState.SpawnPoints[1]._y));
var id := 1;
for var i:=2 to GameplayState.SpawnCount do
begin
if (max < sqrt(sqr(dang._x - GameplayState.SpawnPoints[i]._x) +
sqr(dang._y - GameplayState.SpawnPoints[i]._y))) then
begin
max := sqrt(sqr(dang._x - GameplayState.SpawnPoints[i]._x) +
sqr(dang._y - GameplayState.SpawnPoints[i]._y));
id := i;
end;
end;
trans := GameplayState.SpawnPoints[id];
end;
_player._pos._x := trans._x;
_player._pos._y := trans._y;
_player._col._x := trans._x;
_player._col._y := trans._y;
_player._col.Pooled := true;
_player.IsDead := false;
_player.Respawn := 0;
_player.IsImmortal := true;
_player.Immortal := 1500;
end;
{Процедура спавна врага }
{Параметры: x, y - координаты }
procedure SpawnEnemy(var _enemy : Enemy; x, y:integer);
begin
with _enemy do
begin
_col._x := x;
_col._y := y;
_col._h := 32;
_col._w := 32;
_col._offsetX := 16;
_col._offsetY := 16;
_col.Pooled := true;
_pos._x := x;
_pos._y := y;
NewPosInArray._x := x div 64 + 1;
NewPosInArray._y := y div 64 + 1;
IsDead := false;
NeedChange := true;
EnemyType := Random(1, 3);
if (EnemyType = FastEnemy) then
begin
Speed := 150;
_sprite := 6;
end
else
if (EnemyType = SlowEnemy) then
begin
Speed := 125;
_sprite := 7;
end
else
if (EnemyType = BlowupEnemy) then
begin
Speed := 125;
_sprite := 8;
end;
Respawn := 0;
CurPosInArray._x := x div 64 + 1;
CurPosInArray._y := y div 64 + 1;
Direction := Random(1, 4);
end;
end;
{Процедура попытки смены направления движения врага }
{Параметры: _enemy - враг }
procedure TryToChangeDir(var _enemy : Enemy);
begin
if ((_enemy.Direction = ToRight) or (_enemy.Direction = ToLeft)) then
begin
if (IsEmptyForEnemy(_enemy, ToUp) and IsEmptyForEnemy(_enemy, ToDown)) then
begin
var dir := Random(1, 2);
if (dir = 1) then
begin
_enemy.Direction := ToUp;
end
else
begin
_enemy.Direction := ToDown;
end;
end
else
if (IsEmptyForEnemy(_enemy, ToUp)) then
begin
_enemy.Direction := ToUp;
end
else
if (IsEmptyForEnemy(_enemy, ToDown)) then
begin
_enemy.Direction := ToDown;
end;
end
else
begin
if (IsEmptyForEnemy(_enemy, ToLeft) and IsEmptyForEnemy(_enemy, ToRight)) then
begin
var dir := Random(1, 2);
if (dir = 1) then
begin
_enemy.Direction := ToLeft;
end
else
begin
_enemy.Direction := ToRight;
end;
end
else
if (IsEmptyForEnemy(_enemy, ToLeft)) then
begin
_enemy.Direction := ToLeft;
end
else
if (IsEmptyForEnemy(_enemy, ToRight)) then
begin
_enemy.Direction := ToRight;
end;
end;
end;
{Функция получения координат в двумерном массиве врага }
{Параметры: _enemy - враг }
function GetCurPosInArr(var _enemy : Enemy) : Transform;
begin
var trans : Transform;
if (((_enemy._pos._x + 58) div 64 + 1) <> _enemy.NewPosInArray._x) and ((_enemy._pos._x div 64 + 1) <> _enemy.NewPosInArray._x) then
begin
_enemy.NewPosInArray._x := _enemy._pos._x div 64 + 1;
end;
if (((_enemy._pos._y + 58) div 64 + 1) <> _enemy.NewPosInArray._y) and ((_enemy._pos._y div 64 + 1) <> _enemy.NewPosInArray._y)then
begin
_enemy.NewPosInArray._y := _enemy._pos._y div 64 + 1;
end;
trans._x := _enemy.NewPosInArray._x;
trans._y := _enemy.NewPosInArray._y;
GetCurPosInArr := trans;
end;
{Функция проверки координаты врага на новые координаты }
{Параметры: _enemy - враг }
function CheckEnemyPosition(var _enemy : Enemy) : boolean;
begin
var x := _enemy.CurPosInArray._x;
var y := _enemy.CurPosInArray._y;
var newPos := GetCurPosInArr(_enemy);
if ((x <> newPos._x) or (y <> newPos._y)) then
begin
CheckEnemyPosition := true;
_enemy.CurPosInArray._x := newPos._x;
_enemy.CurPosInArray._y := newPos._y;
end
else
begin
CheckEnemyPosition := false;
end;
end;
{Процедура обновления респавна игроков }
{Параметры: dt - время между кадрами }
procedure UpdateRespawn(dt : integer);
begin
for var i:=1 to MaxPlayers do
begin
if ((GameplayState.Players[i].Respawn <= 0) and (GameplayState.Players[i].IsDead)) then
begin
SpawnPlayer(GameplayState.Players[i]);
end;
end;
end;
{Процедура обновления респавна врагов }
{Параметры: dt - время между кадрами }
procedure UpdateRespawnEnemies(dt : integer);
begin
for var i:=1 to 6 do
begin
if ((GameplayState.Enemies[i].Respawn > 0) and (GameplayState.Enemies[i].IsDead)) then
begin
GameplayState.Enemies[i].Respawn := GameplayState.Enemies[i].Respawn - dt;
end
else
begin
if (Milliseconds() - SpawnCooldown > SpawnDelay) then
begin
if (GameplayState.Enemies[i].IsDead) then
begin
SpawnCooldown := Milliseconds();
var trans : Transform;
trans := GameplayState.SpawnEnemies[Random(1, GameplayState.SpawnCountEnemy)];
SpawnEnemy(GameplayState.Enemies[i], trans._x, trans._y);
end;
end;
end;
end;
end;
{Процедура обновления врагов }
{Параметры: dt - время между кадрами }
procedure UpdateEnemy(dt : integer);
begin
for var i:=1 to 6 do
begin
if (not GameplayState.Enemies[i].IsDead) then
begin
GetCurPosInArr(GameplayState.Enemies[i]);
if (GameplayState.Enemies[i].NeedChange) then
begin
TryToChangeDir(GameplayState.Enemies[i]);
GameplayState.Enemies[i].NeedChange := false;
end
else
begin
if (IsEmptyForEnemy(GameplayState.Enemies[i], GameplayState.Enemies[i].Direction)) then
begin
case GameplayState.Enemies[i].Direction of
ToUp :
begin
GameplayState.Enemies[i]._pos._y := GameplayState.Enemies[i]._pos._y - round(GameplayState.Enemies[i].Speed * dt / 1000);
GameplayState.Enemies[i]._col._y := GameplayState.Enemies[i]._pos._y;
end;
ToDown :
begin
GameplayState.Enemies[i]._pos._y := GameplayState.Enemies[i]._pos._y + round(GameplayState.Enemies[i].Speed * dt / 1000);
GameplayState.Enemies[i]._col._y := GameplayState.Enemies[i]._pos._y;
end;
ToRight :
begin
GameplayState.Enemies[i]._pos._x := GameplayState.Enemies[i]._pos._x + round(GameplayState.Enemies[i].Speed * dt / 1000);
GameplayState.Enemies[i]._col._x := GameplayState.Enemies[i]._pos._x;
end;
ToLeft :
begin
GameplayState.Enemies[i]._pos._x := GameplayState.Enemies[i]._pos._x - round(GameplayState.Enemies[i].Speed * dt / 1000);
GameplayState.Enemies[i]._col._x := GameplayState.Enemies[i]._pos._x;
end;
end;
end
else
begin
case GameplayState.Enemies[i].Direction of
ToUp :
begin
GameplayState.Enemies[i].Direction := ToDown;
end;
ToDown :
begin
GameplayState.Enemies[i].Direction := ToUp;
end;
ToRight :
begin
GameplayState.Enemies[i].Direction := ToLeft;
end;
ToLeft :
begin
GameplayState.Enemies[i].Direction := ToRight;
end;
end;
end;
end;
GameplayState.Enemies[i].NeedChange := CheckEnemyPosition(GameplayState.Enemies[i]);
end;
end;
end;
{Процедура рисования врагов }
procedure RenderEnemies();
begin
for var i:=1 to 6 do
begin
if (not GameplayState.Enemies[i].IsDead) then
begin
RenderEnemy(GameplayState.Enemies[i]._pos._x, GameplayState.Enemies[i]._pos._y, 0, TopOffset, GameplayState.Enemies[i].EnemyType);
end;
end;
end;
{Процедура рисования земли }
procedure RenderGround();
begin
RenderGrass(0, 0, 0, TopOffset);
end;
{Процедура рисования неломаемых блоков }
procedure RenderIrons();
begin
for var i:=1 to GameplayState.IronCount do
begin
RenderIron(GameplayState.IronMap[i]._pos._x, GameplayState.IronMap[i]._pos._y, 0, TopOffset);
end;
end;
{Процедура рисования ломаемых блоков }
procedure RenderBricks();
begin
for var i:=1 to GameplayState.BrickCount do
begin
if (GameplayState.BrickMap[i].Pooled) then
begin
RenderBrick(GameplayState.BrickMap[i]._pos._x, GameplayState.BrickMap[i]._pos._y, 0, TopOffset);
end;
end;
end;
{Процедура рисования бомб }
procedure RenderBombs();
begin
for var i:=1 to GameplayState.BombCount do
begin
if (GameplayState.BombMap[i].Pooled) then
begin
RenderBomb(GameplayState.BombMap[i]._pos._x, GameplayState.BombMap[i]._pos._y, 0, TopOffset);
end;
end;
end;
{Процедура рисования огня }
procedure RenderFires();
begin
for var i:=1 to GameplayState.FireCount do
begin
if (GameplayState.FireMap[i].Pooled) then
begin
RenderFire(GameplayState.FireMap[i]._pos._x, GameplayState.FireMap[i]._pos._y, 0, TopOffset);
end;
end;
end;
{Процедура рисования игроков }
procedure RenderPlayers();
begin
for var i:=1 to MaxPlayers do
begin
if (not GameplayState.Players[i].IsDead) then
begin
RenderPlayer(GameplayState.Players[i]._pos._x, GameplayState.Players[i]._pos._y, 0, TopOffset, GameplayState.Players[i].PlayerId, GameplayState.Players[i].Name);
if (GameplayState.Players[i].IsImmortal) then
begin
RenderShield(GameplayState.Players[i]._pos._x, GameplayState.Players[i]._pos._y, 0, TopOffset);
end;
end;
end;
end;
{Процедура рисования порталов врага }
procedure RenderPortals();
begin
for var i:=1 to GameplayState.SpawnCountEnemy do
begin
RenderEnemySpawner(GameplayState.SpawnEnemies[i]._x, GameplayState.SpawnEnemies[i]._y, 0, TopOffset);
end;
end;
{Процедура загрузки карты }
{Параметры: filename - название карты }
procedure LoadMap(filename : string);
begin
var textFile : Text;
var rows, columns : integer;
rows := 0;
columns := 0;
Assign(textFile, 'maps/' + filename);
Reset(textFile);
while (not Eof(textFile)) do
begin
rows := rows + 1;
var line : string;
Readln(textFile, line);
columns := 0;
for var i:=1 to Length(line) do
begin
GameplayState.Map[rows, i] := Ord(line[i]) - 48;
columns := columns + 1;
end;
end;
GameplayState.MapY := rows;
GameplayState.MapX := columns;
Close(textFile);
end;
{Процедура заполения массивов блоков и порталов }
procedure FillMap();
begin
for var rows:=1 to GameplayState.MapY do
begin
for var columns:=1 to GameplayState.MapX do
begin
case (GameplayState.Map[rows, columns]) of
5:
begin
if (GameplayState.SpawnCount + 1 < 8) then
begin
GameplayState.SpawnCount := GameplayState.SpawnCount + 1;
var temp : Transform;
temp._x := (columns - 1) * 64;
temp._y := (rows - 1) * 64;
GameplayState.SpawnPoints[GameplayState.SpawnCount] := temp;
end;
end;
4:
begin
if (GameplayState.SpawnCountEnemy + 1 < 4) then
begin
GameplayState.SpawnCountEnemy := GameplayState.SpawnCountEnemy + 1;
var temp : Transform;
temp._x := (columns - 1) * 64;
temp._y := (rows - 1) * 64;
GameplayState.SpawnEnemies[GameplayState.SpawnCountEnemy] := temp;
end;
end;
1:
begin
var temp := CreateCollider((columns - 1) * 64, (rows - 1) * 64, 0, 0, 64, 64, true);
var _iron : Iron;
_iron._col := GameplayState.ColliderMap[GameplayState.colCount];
_iron._pos._x := temp._x;
_iron._pos._y := temp._y;
GameplayState.IronCount := GameplayState.IronCount + 1;
GameplayState.IronMap[GameplayState.IronCount] := _iron;
end;
2:
begin
var temp := CreateCollider((columns - 1) * 64, (rows - 1) * 64, 0, 0, 64, 64, true);
var _brick : Brick;
_brick._col := GameplayState.ColliderMap[GameplayState.colCount];
_brick._pos._x := temp._x;
_brick._pos._y := temp._y;
_brick.Pooled := true;
GameplayState.BrickCount := GameplayState.BrickCount + 1;
GameplayState.BrickMap[GameplayState.BrickCount] := _brick;
end;
end;
end;
end;
end;
procedure InitMainGame();
begin
with GameplayState do
begin
for var i:=1 to MaxPlayers do
begin
Players[i]._pos._x := 0;
Players[i]._pos._y := 0;
Players[i]._col := CreateCollider(0, 0, 16, 6, 52, 32, false);
Players[i].PlayerId := i;
Players[i].IsDead := true;
Players[i].Respawn := 0;
Players[i].BombCount := 3;
Players[i].Name := PlayerNames[i];
Players[i].Speed := 125;
Players[i].PlayerScore := 0;
if (i = 1) then
begin
Players[i].Down := VK_S;
Players[i].Up := VK_W;
Players[i].Left := VK_A;
Players[i].Right := VK_D;
Players[i].Place := VK_G;
end;
if (i = 2) then
begin
Players[i].Down := VK_DOWN;
Players[i].Up := VK_UP;
Players[i].Left := VK_LEFT;
Players[i].Right := VK_RIGHT;
Players[i].Place := VK_L;
end;
end;
//Map
CurrentMap := _CurrentMap;
LoadMap(CurrentMap + '.txt');
ColCount := 0;
BombCount := 0;
BrickCount := 0;
FireCount := 0;
IronCount := 0;
for var i:=1 to 6 do
begin
Enemies[i].LastChange := 0;
Enemies[i]._col.Pooled := true;
Enemies[i].IsDead := true;
end;
end;
FillMap();
MainTime := 120000;
IsPause := false;
Options[1] := 'Продолжить';
Options[2] := 'Выйти';
CurrentOp := 1;
end;
procedure HandleInputInMainGame;
begin
if (inputKeys[VK_O]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
MainTime := MainTime - 2000;
end;
end;
if (inputKeys[VK_ESCAPE]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
if (not IsPause) then
begin
IsPause := true;
CurrentOp := 1;
end
else
begin
IsPause := false;
end;
end;
end;
if (IsPause) then
begin
if (inputKeys[VK_DOWN] or inputKeys[VK_S]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
if (CurrentOp + 1 > 2) then
begin
CurrentOp := 1;
end
else
begin
CurrentOp := CurrentOp + 1;
end;
end;
end;
if (inputKeys[VK_UP] or inputKeys[VK_W]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
if (CurrentOp - 1 < 1) then
begin
CurrentOp := 2;
end
else
begin
CurrentOp := CurrentOp - 1;
end;
end;
end;
if (inputKeys[VK_ENTER]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
if (CurrentOp = 2) then
begin
ChangeState(MenuState);
end
else
if (CurrentOp = 1) then
begin
IsPause := false;
end;
end;
end;
end;
end;
procedure UpdateMainGame;
begin
HandleInputInMainGame();
if (not IsPause) then
begin
for var i:=1 to MaxPlayers do
begin
MovePlayer(GameplayState.Players[i], dt);
end;
UpdateEnemy(dt);
Countdown(dt);
Bombdown(dt);
Firedown(dt);
Respawndown(dt);
Immortaldown(dt);
UpdateBomb(dt);
UpdateFire(dt);
UpdateRespawn(dt);
UpdateRespawnEnemies(dt);
end;
if ((MainTime < 0)) then
begin
for var i:=1 to MaxPlayers do
begin
PlayerScores[i] := GameplayState.Players[i].PlayerScore;
end;
ChangeState(EndHighState);
end;
end;
procedure RenderMainGame;
begin
Window.Clear();
SetBrushStyle(bsSolid);
RenderGround();
RenderPortals();
RenderIrons();
RenderBricks();
RenderBombs();
RenderEnemies();
RenderPlayers();
SetBrushStyle(bsSolid);
RenderFires();
SetFontSize(14);
SetBrushStyle(bsSolid);
SetBrushColor(clWhite);
//UI
var TimeString := (MainTime div 1000) div 60 + ':' + (MainTime div 1000) mod 60;
TextOut(WindowWidth div 2 - 96, 8, 'Осталось времени');
TextOut(WindowWidth div 2 - 32, 32, TimeString);
TextOut(16, 26, GameplayState.Players[1].Name + ' Score: ' + GameplayState.Players[1].PlayerScore);
for var i:=1 to GameplayState.Players[1].BombCount do
begin
RenderBombIcon(224 + 28 * i, 20, 0, 0);
end;
for var i:= 1 to GameplayState.Players[2].BombCount do
begin
RenderBombIcon(WindowWidth - 274 - 28 * i, 20, 0, 0);
end;
TextOut(WindowWidth - 256, 26, GameplayState.Players[2].Name + ' Score: ' + GameplayState.Players[2].PlayerScore);
//Pause
if (IsPause) then
begin
SetBrushStyle(bsSolid);
SetBrushColor(ARGB(50, 0, 0, 0));
FillRectangle(0, 0, 960, 768);
PauseBack.Draw(Window.Width div 2 - 128, Window.Height div 2 - 96);
SetFontSize(26);
SetFontColor(clWhite);
DrawTextCentered(Window.Width div 2, Window.Height div 2 - 54, 'Пауза');
SetFontSize(20);
for var i := 1 to 2 do
begin
if (CurrentOp = i) then
begin
DrawChooseLine(Window.Width div 2 - 125, Window.Height div 2 - 74 + 50 * i, 251, 40);
end;
DrawTextCentered(Window.Width div 2, Window.Height div 2 - 54 + 50 * i, Options[i]);
end;
SetFontColor(clBlack);
end;
end;
procedure DisposeMainGame;
begin
MainTime := 120000;
for var i:=1 to GameplayState.ColCount do
begin
GameplayState.ColliderMap[i].Pooled := false;
end;
for var i:=1 to GameplayState.BombCount do
begin
GameplayState.BombMap[i].Pooled := false;
end;
for var i:=1 to GameplayState.BrickCount do
begin
GameplayState.BrickMap[i].Pooled := false;
end;
for var i:=1 to GameplayState.FireCount do
begin
GameplayState.FireMap[i].Pooled := false;
end;
GameplayState.ColCount := 0;
GameplayState.BombCount := 0;
GameplayState.BrickCount := 0;
GameplayState.FireCount := 0;
GameplayState.IronCount := 0;
GameplayState.SpawnCount := 0;
GameplayState.SpawnCountEnemy := 0;
end;
begin
end. |
unit caTypes;
{$INCLUDE ca.inc}
interface
uses
// Standard Delphi units
Classes,
Controls;
type
//---------------------------------------------------------------------------
// Array types
//---------------------------------------------------------------------------
TcaWordBoolArray = array[Boolean] of Word;
TcaIntBoolArray = array[Boolean] of Integer;
TcaDoubleBoolArray = array[Boolean] of Double;
TcaMouseMessageArray = array[Low(TMouseButton)..High(TMouseButton)] of Word;
//---------------------------------------------------------------------------
// Dynamic array definitions
//---------------------------------------------------------------------------
TcaPointerArray = array of Pointer;
TcaPointerArray2 = array of array of Pointer;
TcaObjectArray = array of TObject;
TcaObjectArray2 = array of array of TObject;
TcaIntegerArray = array of Integer;
TcaIntegerArray2 = array of array of Integer;
TcaDoubleArray = array of Double;
TcaDoubleArray2 = array of array of Double;
TcaExtendedArray = array of Extended;
TcaExtendedArray2 = array of array of Extended;
TcaStringArray = array of String;
TcaStringArray2 = array of array of String;
//---------------------------------------------------------------------------
// ShortString types
//---------------------------------------------------------------------------
String10 = String[10];
String20 = String[20];
String30 = String[30];
String40 = String[40];
String50 = String[50];
String60 = String[60];
String70 = String[70];
String80 = String[80];
String90 = String[90];
String100 = String[100];
String110 = String[110];
String120 = String[120];
String130 = String[130];
String140 = String[140];
String150 = String[150];
String160 = String[160];
String170 = String[170];
String180 = String[180];
String190 = String[190];
String200 = String[200];
String210 = String[210];
String220 = String[220];
String230 = String[230];
String240 = String[240];
String250 = String[250];
//---------------------------------------------------------------------------
// GUID support
//---------------------------------------------------------------------------
TcaUniqueID = string[32];
//---------------------------------------------------------------------------
// Time types
//---------------------------------------------------------------------------
TcaTimePoint = packed record
Year: Word;
Month: Word;
Day: Word;
Hour: Word;
Min: Word;
Sec: Word;
MSec: Word;
end;
//---------------------------------------------------------------------------
// Enumerated types and sets
//---------------------------------------------------------------------------
TcaArrayStringsAlignment = (saLeft, saRight, saPreZero);
TcaButtonLayout = (laGlyphLeftCentered, laGlyphLeft, laGlyphRight, laGlyphTop, laGlyphBottom, laTextLeft, laTextRight);
TcaButtonState = (bsUp, bsDisabled, bsDown, bsExclusive);
TcaButtonStyle = (bsDefault, bsThin, bsFlat, bsNoEdge);
TcaCompareResult = (crFirstGreater, crSecondGreater, crEqual, crUndefined);
TcaFrameStyle = (fsLowered, fsRaised, fsLoweredPanel, fsRaisedPanel, fsLine);
TcaNumGlyphs = 1..2;
TcaSide = (sdLeft, sdTop, sdRight, sdBottom);
TcaSides = set of TcaSide;
TcaSortDirection = (sdAscending, sdDescending, sdNone, sdUndefined);
TcaTextStyle = (tsNormal, tsRaised, tsLowered);
TcaMenuState = (meBig, meSmall);
TcaSizeBarBtnPosition = (spTop, spCenter, spBottom);
TcaSizeBarKind = (sbHorizontal, sbVertical);
TcaSizeBarState = (bsBig, bsSmall);
TcaSizeBarArrows = (baLeftRight, baRightLeft, baUpDown, baDownUp);
TcaArrowType = (atLeft, atRight, atUp, atDown);
TcaLetterCase = (caLower, caUpper, caAny);
TcaXMLTagType = (ttStart, ttEnd, ttEmpty, ttText);
TcaMsgDialogResponse = (mgNone, mgAbort, mgYes, mgOk, mgRetry, mgNo, mgCancel, mgIgnore, mgAll);
TcaCellType = (ctNil, ctObject, ctInteger, ctInt64, ctSingle, ctDouble,
ctExtended, ctString, ctMemo, ctBoolean, ctDateTime, ctFormula);
TcaCellTypes = set of TcaCellType;
TcaChartAxisType = (caLeft, caRight, caTop, caBottom);
TcaOperatorPrecedence = (opHigher, opLower, opSameLeftAssoc, opSameRightAssoc);
TcaTrigUnits = (tuDegrees, tuRadians);
TcaColorColumn = (ccColor, ccName, ccHue, ccSaturation, ccValue, ccIntensity, ccLightness, ccYic);
TcaNodeCheckState = (csFullyUnChecked, csSemiChecked, csFullyChecked);
TcaNodeMatchAction = (maCheck, maClear);
TcaNodeMatchMode = (mmMatch, mmLevel, mmAll);
TcaNumberType = (ntInteger, ntFloat);
TcaCaptionMode = (cmText, cmNumber);
TcaByteSet = set of Byte;
TcaMathOperation = (moAdd, moDivide, moMultiply, moSubtract);
TcaMessageDialogResponse = (drFirst, drSecond, drThird, drUndefined);
TcaWinVersion = (wvUnknown, wvWin95, wvWin98, wvWinNT, wvWin2K, wvWinXP);
TcaOperator = (opEqual, opLessThan, opGreaterThan, opNotEqual, opGreaterThanOrEqual, opLessThanOrEqual, opUnspecified);
TcaShowWindow = (swHide, swMaximize, swMinimize, swRestore, swShow, swShowDefault, swShowMaximized,
swShowMinimized, swShowMinNoActive, swShowNA, swShowNoActivate, swShowNormal);
TcaConjunction = (coAnd, coOr);
implementation
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC SQL command generator }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.SQLGenerator;
interface
uses
System.Classes, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.Phys.Intf;
type
TFDPhysCommandPart = (cpSELECT, cpFROM, cpWHERE, cpORDERBY, cpVALUES, cpSET,
cpRETURNING);
TFDPhysCommandGenerator = class(TInterfacedObject, IFDPhysCommandGenerator)
private
FColumn: TFDDatSColumn;
FTabAlias: String;
FUpdateRowOptions: TFDUpdateRowOptions;
FFillRowOptions: TFDPhysFillRowOptions;
FGenOptions: TFDPhysCommandGeneratorOptions;
FMappingHandler: IFDPhysMappingHandler;
FLastColumn: TFDDatSColumn;
FLastColumnAttrs: TFDDataAttributes;
FLastColumnOptions: TFDDataOptions;
FLastColumnObjName: String;
FLastColumnAliasName: String;
FSQLOrderByPos: Integer;
FCommandText: String;
constructor Create; overload;
function NormalizeName(const AName: String; ASubObj, AForceNoQuote,
AForceQuote: Boolean): String;
function GenerateInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String;
function GenerateIdentityInsert(const ATable, AStmt: String;
ARequest: TFDUpdateRequest): String;
function ColumnIdentityAssigned(ARow: TFDDatSRow;
AColumn: TFDDatSColumn; AAlready: Boolean): Boolean;
function GetNestedRow(ARow: TFDDatSRow; AColIndex: Integer): TFDDatSRow;
function GetStoredProcODBCCall(const ACatalog, ASchema, APackage, AProc: String;
AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
protected
FTable: TFDDatSTable;
FRow: TFDDatSRow;
FParams: TFDParams;
FConnMeta: IFDPhysConnectionMetadata;
FCommand: IFDPhysCommand;
FOptions: IFDStanOptions;
FCommandKind: TFDPhysCommandKind;
FCommandPart: TFDPhysCommandPart;
FFlags: TFDPhysCommandGeneratorFlags;
function GetSelectList(AAllowIdentityExp, AFlatFieldList: Boolean;
out ANeedFrom: Boolean): String;
function GetFrom: String;
function GetWhere(AInInsert, ARequired, ANotNull: Boolean): String;
function GetColumn(const AParentField: String; ARowIndex: Integer;
AColumn: TFDDatSColumn): String;
function ColumnChanged(ARow: TFDDatSRow; AColumn: TFDDatSColumn): Boolean;
function ColumnGenerator(AColumn: TFDDatSColumn): String;
function ColumnInKey(AColumn: TFDDatSColumn): Boolean;
function ColumnSearchable(AColumn: TFDDatSColumn): Boolean;
function ColumnStorable(AColumn: TFDDatSColumn): Boolean;
function ColumnReqRefresh(ARequest: TFDUpdateRequest;
AColumn: TFDDatSColumn): Boolean;
function ColumnIsHBLOB(AColumn: TFDDatSColumn): Boolean;
function AddColumnParam(AColumn: TFDDatSColumn; AValueAge: Integer;
AType: TParamType): String;
function ColumnUpdatable(AColumn: TFDDatSColumn; AInInsert: Boolean): Boolean;
function NormalizeColName(const AName: String): String;
function NormalizeTabName(const AName: String): String;
procedure GetColumnAttributes(AColumn: TFDDatSColumn;
var AAttrs: TFDDataAttributes; var AOptions: TFDDataOptions;
var AObjName, AAliasName: String);
function BRK: String;
function IND: String;
function GetReturning(ARequest: TFDUpdateRequest; AWithInto: Boolean): String;
function GetColumnDim(ASize, APrec, AScale, ADefSize, ADefPrec, ADefScale: Integer): String;
// IFDPhysCommandGenerator
// private
function GetFillRowOptions: TFDPhysFillRowOptions;
function GetGenOptions: TFDPhysCommandGeneratorOptions;
function GetFlags: TFDPhysCommandGeneratorFlags;
function GetParams: TFDParams;
function GetRow: TFDDatSRow;
function GetTable: TFDDatSTable;
function GetUpdateRowOptions: TFDUpdateRowOptions;
procedure SetParams(const AValue: TFDParams);
procedure SetRow(const AValue: TFDDatSRow);
procedure SetTable(const AValue: TFDDatSTable);
procedure SetUpdateRowOptions(const AValue: TFDUpdateRowOptions);
function GetCol: TFDDatSColumn;
procedure SetCol(const AValue: TFDDatSColumn);
procedure SetFillRowOptions(const AValue: TFDPhysFillRowOptions);
procedure SetGenOptions(const AValue: TFDPhysCommandGeneratorOptions);
function GetCommandKind: TFDPhysCommandKind;
function GetSQLOrderByPos: Integer;
function GetOptions: IFDStanOptions;
procedure SetOptions(const AValue: IFDStanOptions);
function GetMappingHandler: IFDPhysMappingHandler;
procedure SetMappingHandler(const AValue: IFDPhysMappingHandler);
// public
function GenerateSelect(ARequired: Boolean): String; virtual;
function GenerateInsert: String;
function GenerateMerge(AAction: TFDPhysMergeAction): String;
function GenerateUpdateHBlobs: String;
function GenerateUpdate: String;
function GenerateDelete: String;
function GenerateDeleteAll(ANoUndo: Boolean): String;
function GenerateLock: String;
function GenerateUnLock: String;
function GenerateSavepoint(const AName: String): String;
function GenerateRollbackToSavepoint(const AName: String): String;
function GenerateCommitSavepoint(const AName: String): String;
function GenerateFetchGenerators: String;
function GenerateReadGenerator(const AName, AAlias: String;
ANextValue, AFullSelect: Boolean): String;
function GenerateCall(const AName: String): String;
function GenerateEval(const AExpr: String): String;
function GeneratePing: String;
function GenerateSelectTable(ATableParams: TFDPhysTableParams): String;
function GenerateStoredProcParams(const ACatalog, ASchema, APackage, AProc: String;
AOverload: Word): String;
function GenerateStoredProcCall(const ACatalog, ASchema, APackage, AProc: String;
AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
function GenerateSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String;
function GenerateLimitSelect(ASkip, ARows: Integer; AOneMore: Boolean;
var AOptions: TFDPhysLimitOptions): String;
function GenerateCountSelect: String;
function GenerateRowId(out AAlias: String): String;
function GenerateCreateTable(AParts: TFDPhysCreateTableParts): TStrings;
function GenerateDropTable(AParts: TFDPhysCreateTableParts): TStrings;
// overridable
function GetSubColumn(const AParentField, ASubField: String): String; virtual;
function GetRowConstructor(const AValues: String; ARowCol: TFDDatSColumn): String; virtual;
function GetCastColumn(const AValue: String; ACol: TFDDatSColumn): String; virtual;
function GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String; virtual;
function GetIdentityInsert(const ATable, AStmt: String;
ARequest: TFDUpdateRequest): String; virtual;
function GetIdentity(ASessionScope: Boolean): String; virtual;
function GetRowId(var AAlias: String): String; virtual;
function GetSingleRowTable: String; virtual;
function GetPessimisticLock: String; virtual;
function GetPessimisticUnLock: String; virtual;
function GetTruncate: String; virtual;
function GetSavepoint(const AName: String): String; virtual;
function GetRollbackToSavepoint(const AName: String): String; virtual;
function GetCommitSavepoint(const AName: String): String; virtual;
function GetReadGenerator(const AName, AAlias: String;
ANextValue, AFullSelect: Boolean): String; virtual;
function GetCall(const AName: String): String; virtual;
function GetPing: String; virtual;
function GetStoredProcParams(const ACatalog, ASchema, APackage,
AProc: String; AOverload: Word): String; virtual;
function GetStoredProcCall(const ACatalog, ASchema, APackage, AProc: String;
AOverload: Word; ASPUsage: TFDPhysCommandKind): String; virtual;
function GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String; virtual;
function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer;
var AOptions: TFDPhysLimitOptions): String; virtual;
function GetCountSelect(const ASQL: String): String; virtual;
function GetColumnType(AColumn: TFDDatSColumn): String; virtual;
function GetColumnDef(AColumn: TFDDatSColumn): String; virtual;
function GetCreateTable(const ATab, ACols: String): String; virtual;
function GetCreateGenerator(const AName: String): String; virtual;
function GetDropGenerator(const AName: String): String; virtual;
function GetCreateIdentityTrigger: String; virtual;
function GetCreatePrimaryKey(const ACols: String): String; virtual;
function GetCreateIndex(const AName, ACols: String; AUnique: Boolean): String; virtual;
function GetInsert(const AOption: String): String; virtual;
function GetUpdate: String; virtual;
function GetMerge(AAction: TFDPhysMergeAction): String; virtual;
public
constructor Create(const ACommand: IFDPhysCommand); overload;
constructor Create(const AConnection: IFDPhysConnection); overload;
end;
implementation
uses
System.Variants, Data.FmtBCD, System.SysUtils,
FireDAC.Stan.Consts, FireDAC.Stan.Error, FireDAC.Stan.Util;
{-------------------------------------------------------------------------------}
{ TFDPhysCommandGenerator }
{-------------------------------------------------------------------------------}
constructor TFDPhysCommandGenerator.Create;
begin
inherited Create;
FTabAlias := C_FD_CmdGenAlias;
FFillRowOptions := [foBlobs, foDetails, foData, foAfterIns, foAfterUpd,
foUpdatable, foClear];
FGenOptions := [goBeautify];
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysCommandGenerator.Create(const ACommand: IFDPhysCommand);
begin
ASSERT((ACommand <> nil) and (ACommand.Connection <> nil));
Create;
ACommand.Connection.CreateMetadata(FConnMeta);
FCommand := ACommand;
FOptions := ACommand.Options;
FCommandKind := ACommand.CommandKind;
FCommandText := ACommand.SQLText;
FSQLOrderByPos := ACommand.SQLOrderByPos;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysCommandGenerator.Create(const AConnection: IFDPhysConnection);
begin
ASSERT(AConnection <> nil);
Create;
AConnection.CreateMetadata(FConnMeta);
FCommand := nil;
FOptions := AConnection.Options;
FCommandKind := skUnknown;
FCommandText := '';
FSQLOrderByPos := 0;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetFillRowOptions: TFDPhysFillRowOptions;
begin
Result := FFillRowOptions;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetGenOptions: TFDPhysCommandGeneratorOptions;
begin
Result := FGenOptions;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetFlags: TFDPhysCommandGeneratorFlags;
begin
Result := FFlags;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetParams: TFDParams;
begin
Result := FParams;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetRow: TFDDatSRow;
begin
Result := FRow;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetTable: TFDDatSTable;
begin
Result := FTable;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCol: TFDDatSColumn;
begin
Result := FColumn;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetUpdateRowOptions: TFDUpdateRowOptions;
begin
Result := FUpdateRowOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandGenerator.SetCol(const AValue: TFDDatSColumn);
begin
FColumn := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandGenerator.SetParams(const AValue: TFDParams);
begin
FParams := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandGenerator.SetRow(const AValue: TFDDatSRow);
begin
FRow := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandGenerator.SetTable(const AValue: TFDDatSTable);
begin
FTable := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandGenerator.SetUpdateRowOptions(const AValue: TFDUpdateRowOptions);
begin
FUpdateRowOptions := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandGenerator.SetFillRowOptions(const AValue: TFDPhysFillRowOptions);
begin
FFillRowOptions := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandGenerator.SetGenOptions(const AValue: TFDPhysCommandGeneratorOptions);
begin
FGenOptions := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCommandKind: TFDPhysCommandKind;
begin
Result := FCommandKind;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetSQLOrderByPos: Integer;
begin
Result := FSQLOrderByPos;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetOptions: IFDStanOptions;
begin
Result := FOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandGenerator.SetOptions(const AValue: IFDStanOptions);
begin
FOptions := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetMappingHandler: IFDPhysMappingHandler;
begin
Result := FMappingHandler;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandGenerator.SetMappingHandler(const AValue: IFDPhysMappingHandler);
begin
FMappingHandler := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.BRK: String;
begin
if goBeautify in FGenOptions then
Result := C_FD_EOL
else
Result := ' ';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.IND: String;
begin
if goBeautify in FGenOptions then
Result := ' '
else
Result := ' ';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.NormalizeName(const AName: String; ASubObj,
AForceNoQuote, AForceQuote: Boolean): String;
var
rName: TFDPhysParsedName;
eEncOpts: TFDPhysEncodeOptions;
eDecOpts: TFDPhysDecodeOptions;
begin
eDecOpts := [];
if ASubObj then
Include(eDecOpts, doSubObj);
if not FOptions.FormatOptions.QuoteIdentifiers then
Include(eDecOpts, doNormalize);
if AForceNoQuote then
Include(eDecOpts, doUnquote);
FConnMeta.DecodeObjName(AName, rName, FCommand, eDecOpts);
eEncOpts := [];
if not AForceNoQuote and (AForceQuote or FOptions.FormatOptions.QuoteIdentifiers) then
Include(eEncOpts, eoQuote);
if goBeautify in FGenOptions then
Include(eEncOpts, eoBeautify);
Result := FConnMeta.EncodeObjName(rName, FCommand, eEncOpts);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.NormalizeColName(const AName: String): String;
begin
Result := NormalizeName(AName, True, goForceNoQuoteCol in FGenOptions,
goForceQuoteCol in FGenOptions);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.NormalizeTabName(const AName: String): String;
begin
Result := NormalizeName(AName, False, goForceNoQuoteTab in FGenOptions,
goForceQuoteTab in FGenOptions);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetSubColumn(const AParentField,
ASubField: String): String;
begin
Result := AParentField + '.' + ASubField;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetRowConstructor(const AValues: String;
ARowCol: TFDDatSColumn): String;
begin
Result := NormalizeColName(ARowCol.SourceDataTypeName) + '(' + AValues + ')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCastColumn(const AValue: String;
ACol: TFDDatSColumn): String;
begin
Result := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetColumn(const AParentField: String;
ARowIndex: Integer; AColumn: TFDDatSColumn): String;
var
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
sName, sAlias: String;
ePrevGenOpts: TFDPhysCommandGeneratorOptions;
begin
if ARowIndex >= 0 then
Result := AParentField + '[' + IntToStr(ARowIndex) + ']'
else begin
sName := '';
sAlias := '';
eOpts := [];
eAttrs := [];
GetColumnAttributes(AColumn, eAttrs, eOpts, sName, sAlias);
ePrevGenOpts := FGenOptions;
if [caInternal, caROWID] * eAttrs = [caInternal, caROWID] then
Include(FGenOptions, goForceNoQuoteCol);
Result := NormalizeColName(sName);
FGenOptions := ePrevGenOpts;
if AParentField <> '' then
Result := GetSubColumn(AParentField, Result);
if (AParentField = '') and (FTabAlias <> '') then
Result := FTabAlias + '.' + Result;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetNestedRow(ARow: TFDDatSRow; AColIndex: Integer): TFDDatSRow;
begin
if ARow = nil then
Result := nil
else
Result := ARow.NestedRow[AColIndex];
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetFrom: String;
var
iTmp: Integer;
sTmp: String;
oTmp: TFDDatSTable;
rName: TFDPhysMappingName;
begin
FCommandPart := cpFROM;
if FTable = nil then
rName := TFDPhysMappingName.Create(0, nkDefault)
else
rName := TFDPhysMappingName.Create(FTable, nkObj);
iTmp := 0;
sTmp := '';
oTmp := nil;
Result := '';
if (GetMappingHandler = nil) or
(GetMappingHandler.MapRecordSet(rName, iTmp, sTmp, sTmp, Result, oTmp) = mrDefault) then
Result := FTable.ActualOriginName;
Result := NormalizeTabName(Result);
if Result = '' then
FDException(Self, [S_FD_LPhys], er_FD_AccUpdateTabUndefined, []);
if FTabAlias <> '' then
Result := Result + ' ' + FTabAlias;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysCommandGenerator.GetColumnAttributes(AColumn: TFDDatSColumn;
var AAttrs: TFDDataAttributes; var AOptions: TFDDataOptions;
var AObjName, AAliasName: String);
var
eMapResult: TFDPhysMappingResult;
iTmp: Integer;
sTmp, sAliasName, sUpdateName: String;
oTmp: TFDDatSColumn;
begin
if FLastColumn = AColumn then begin
AAttrs := FLastColumnAttrs;
AOptions := FLastColumnOptions;
AObjName := FLastColumnObjName;
AAliasName := FLastColumnAliasName;
Exit;
end;
// Do not map column, if it is nested. At moment TFDRdbmsDataSet creates a
// TFDTableAdapter, which always return mrNotMapped for columns of a sub-table.
if (GetMappingHandler = nil) or (AColumn.ColumnList.ParentRowRefCol <> -1) then
eMapResult := mrDefault
else begin
iTmp := 0;
sTmp := '';
sAliasName := '';
sUpdateName := '';
oTmp := nil;
eMapResult := GetMappingHandler.MapRecordSetColumn(
TFDPhysMappingName.Create(AColumn.Table, nkObj),
TFDPhysMappingName.Create(AColumn.Name, nkDatS),
iTmp, sAliasName, sTmp, sUpdateName, oTmp);
end;
case eMapResult of
mrDefault:
begin
AOptions := AColumn.ActualOptions;
AAttrs := AColumn.ActualAttributes;
AObjName := AColumn.ActualOriginColName;
AAliasName := AColumn.Name;
end;
mrMapped:
begin
AOptions := AColumn.ActualOptions;
AAttrs := AColumn.ActualAttributes;
AObjName := sUpdateName;
AAliasName := sAliasName;
end;
else
AOptions := [];
AAttrs := [];
AObjName := '';
AAliasName := '';
end;
FLastColumn := AColumn;
FLastColumnAttrs := AAttrs;
FLastColumnOptions := AOptions;
FLastColumnObjName := AObjName;
if CompareText(AObjName, AAliasName) = 0 then
AAliasName := '';
FLastColumnAliasName := AAliasName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.ColumnStorable(AColumn: TFDDatSColumn): Boolean;
var
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
sName, sAlias: String;
begin
sName := '';
sAlias := '';
eAttrs := [];
eOpts := [];
GetColumnAttributes(AColumn, eAttrs, eOpts, sName, sAlias);
Result :=
not (caUnnamed in eAttrs) and (sName <> '') and
not ((caCalculated in eAttrs) and (AColumn.SourceID <= 0)) and
not ((caInternal in eAttrs) and not (caROWID in eAttrs)) and
((caBase in eAttrs) or (gfInlineView in FFlags) or FOptions.UpdateOptions.UpdateNonBaseFields);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.ColumnReqRefresh(ARequest: TFDUpdateRequest;
AColumn: TFDDatSColumn): Boolean;
var
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
eRefreshMode: TFDRefreshMode;
sName, sAlias: String;
begin
sName := '';
sAlias := '';
eAttrs := [];
eOpts := [];
eRefreshMode := FOptions.UpdateOptions.RefreshMode;
GetColumnAttributes(AColumn, eAttrs, eOpts, sName, sAlias);
case ARequest of
arInsert:
Result := (eRefreshMode = rmAll) or (eRefreshMode = rmOnDemand) and (
(coAfterInsChanged in eOpts) or
(caDefault in eAttrs) and ((FRow = nil) or VarIsNull(FRow.GetData(AColumn, rvCurrent))) or
([caAutoInc, caCalculated, caDefault, caROWID, caRowVersion, caVolatile] * eAttrs <> [])
);
arUpdate:
Result := (eRefreshMode = rmAll) or (eRefreshMode = rmOnDemand) and (
(coAfterUpdChanged in eOpts) or
([caCalculated, caRowVersion, caVolatile] * eAttrs <> [])
);
arFetchRow:
Result :=
(foAfterIns in FFillRowOptions) and
// following protects from [SELECT IncFld FROM MyTab WHERE IncFld IS NULL]
not ((caAutoInc in eAttrs) and (coInKey in eOpts) and (GetIdentity(False) = '')) and
((eRefreshMode = rmAll) or (eRefreshMode = rmOnDemand) and (
(coAfterInsChanged in eOpts) or
(caDefault in eAttrs) and ((FRow = nil) or VarIsNull(FRow.GetData(AColumn, rvCurrent))) or
([caAutoInc, caCalculated, caROWID, caRowVersion, caVolatile] * eAttrs <> [])
)) or
(foAfterUpd in FFillRowOptions) and
((eRefreshMode = rmAll) or (eRefreshMode = rmOnDemand) and (
(coAfterUpdChanged in eOpts) or
([caCalculated, caRowVersion, caVolatile] * eAttrs <> [])
));
else
Result := False;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.ColumnSearchable(AColumn: TFDDatSColumn): Boolean;
var
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
sName, sAlias: String;
begin
sName := '';
sAlias := '';
eAttrs := [];
eOpts := [];
GetColumnAttributes(AColumn, eAttrs, eOpts, sName, sAlias);
Result := ColumnStorable(AColumn) and (caSearchable in eAttrs) and
(eOpts * [coInWhere, coInKey] <> []);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.ColumnUpdatable(AColumn: TFDDatSColumn;
AInInsert: Boolean): Boolean;
var
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
sName, sAlias: String;
begin
sName := '';
sAlias := '';
eAttrs := [];
eOpts := [];
GetColumnAttributes(AColumn, eAttrs, eOpts, sName, sAlias);
Result := ColumnStorable(AColumn) and (coInUpdate in eOpts) and
([caInternal, caCalculated] * eAttrs = []) and (
not (caReadOnly in eAttrs) or
not FOptions.UpdateOptions.CheckReadOnly and not (caAutoInc in eAttrs) or
(caAutoInc in eAttrs) and AInInsert and
(not FConnMeta.IdentitySupported or FConnMeta.IdentityInsertSupported)
);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.ColumnChanged(ARow: TFDDatSRow;
AColumn: TFDDatSColumn): Boolean;
var
i: Integer;
oCol: TFDDatSColumn;
begin
if ARow = nil then
Result := True
else if AColumn.DataType = dtArrayRef then begin
ARow := ARow.NestedRow[AColumn.Index];
Result := False;
for i := 0 to ARow.Table.Columns.Count - 1 do begin
oCol := ARow.Table.Columns[i];
if (oCol.DataType <> dtParentRowRef) and ColumnChanged(ARow, oCol) then begin
Result := True;
Break;
end;
end;
end
else
Result := not ARow.CompareColumnVersions(AColumn.Index, rvCurrent, rvOriginal);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.ColumnGenerator(AColumn: TFDDatSColumn): String;
begin
Result := AColumn.ActualGenerator;
if (Result = '') and (FOptions <> nil) then
Result := FOptions.UpdateOptions.GeneratorName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.ColumnIdentityAssigned(ARow: TFDDatSRow;
AColumn: TFDDatSColumn; AAlready: Boolean): Boolean;
var
V1, V2: Variant;
begin
if not AAlready and
(FOptions.UpdateOptions.FetchGeneratorsPoint <> gpNone) and
FConnMeta.GeneratorSupported and (ColumnGenerator(AColumn) <> '') then
Result := True
else if (ARow <> nil) and ColumnChanged(ARow, AColumn) then begin
V1 := ARow.GetData(AColumn, rvCurrent);
V2 := AColumn.ColumnList.CurrValues[AColumn.Index];
Result := VarIsNull(V1) or (VarIsNull(V2) or (V2 = 0)) or not (
(AColumn.DataType in C_FD_NumUnsignedTypes) and
(V1 > 0) and (V2 > 0) and (V1 >= V2) or
(AColumn.DataType in (C_FD_NumTypes - C_FD_NumUnsignedTypes)) and
(V1 < 0) and (V2 < 0) and (V1 >= V2));
end
else
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.ColumnInKey(AColumn: TFDDatSColumn): Boolean;
var
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
sName, sAlias: String;
begin
sName := '';
sAlias := '';
eAttrs := [];
eOpts := [];
GetColumnAttributes(AColumn, eAttrs, eOpts, sName, sAlias);
Result := coInKey in eOpts;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.AddColumnParam(AColumn: TFDDatSColumn;
AValueAge: Integer; AType: TParamType): String;
const
C_ValAge: array[-1 .. 1] of String = ('OLD_', '', 'NEW_');
var
oParam: TFDParam;
iSize: LongWord;
i, iPrecision, iScale: Integer;
eType: TFieldType;
sName: String;
lBeautify: Boolean;
function GetColumnPath(AColumn: TFDDatSColumn): String;
var
oCol: TFDDatSColumn;
begin
oCol := AColumn.ParentColumn;
if oCol <> nil then
Result := GetColumnPath(oCol)
else
Result := 'P';
Result := Result + '$_' + IntToStr(AColumn.Index);
end;
begin
lBeautify := (goBeautify in FGenOptions) and
((FTable = nil) or not (ctParentRef in FTable.Columns.HasThings));
if goNoVersion in FGenOptions then
AValueAge := 0;
if lBeautify then
Result := C_ValAge[AValueAge] + AColumn.Name
else
Result := C_ValAge[AValueAge] + GetColumnPath(AColumn);
if FParams <> nil then begin
// Unique parameter name is required for Oracle:
// INSERT INTO tab (id) VALUES (:NEW_ID) RETURNING id INTO :NEW_ID$#1
// If :NEW_ID will be used twice, then Oracle connection fails.
// For details see TFDQACompQRYTsHolder.TestInsertSequence.
i := 0;
sName := Result;
while FParams.FindParam(Result) <> nil do begin
Inc(i);
Result := Format('%s$#%d', [sName, i]);
end;
oParam := TFDParam(FParams.Add);
oParam.Position := FParams.Count;
FOptions.FormatOptions.ColumnDef2FieldDef(AColumn.DataType,
AColumn.Size, AColumn.Precision, AColumn.Scale,
AColumn.Attributes, eType, iSize, iPrecision, iScale);
oParam.Name := Result;
oParam.ParamType := AType;
oParam.DataType := eType;
oParam.FDDataType := AColumn.DataType;
oParam.Precision := iPrecision;
oParam.NumericScale := iScale;
oParam.Size := iSize;
end;
if lBeautify then begin
sName := NormalizeColName(Result);
if (FConnMeta.Kind = TFDRDBMSKinds.SQLite) and SameText(sName, Result) then
Result := ':' + Result
else
Result := ':' + sName
end
else
case FConnMeta.PositionedParamMark of
prQMark: Result := '?';
prNumber: Result := ':' + IntToStr(FParams.Count - 1);
prName: Result := ':' + Result;
prDollar: Result := '$' + IntToStr(FParams.Count);
prQNumber: Result := '?' + IntToStr(FParams.Count);
end;
Result := GetCastColumn(Result, AColumn);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.ColumnIsHBLOB(AColumn: TFDDatSColumn): Boolean;
begin
Result := AColumn.DataType in [dtHBlob, dtHBFile, dtHMemo, dtWideHMemo];
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetSelectList(AAllowIdentityExp, AFlatFieldList: Boolean;
out ANeedFrom: Boolean): String;
var
iLockMode: TFDLockMode;
iTotalLen: Integer;
procedure ProcessDataTableFields(ATable: TFDDatSTable;
const AParentField: String; var S: String);
var
i: Integer;
sField, sName, sAlias: String;
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
oCol: TFDDatSColumn;
lIdentity: Boolean;
begin
for i := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns[i];
sName := '';
sAlias := '';
eAttrs := [];
eOpts := [];
GetColumnAttributes(oCol, eAttrs, eOpts, sName, sAlias);
if AFlatFieldList and (oCol.DataType = dtRowRef) then
ProcessDataTableFields(oCol.NestedTable, GetColumn(AParentField, -1, oCol), S)
else if ColumnStorable(oCol) and (
(
(caBlobData in oCol.Attributes) and (foBlobs in FFillRowOptions) or
(oCol.DataType in [dtRowSetRef, dtCursorRef]) and (foDetails in FFillRowOptions) or
(foData in FFillRowOptions)
) and (
not (foUpdatable in FFillRowOptions) or (
ColumnUpdatable(oCol, False) or
(iLockMode = lmPessimistic) and ColumnIsHBLOB(oCol)
)
) and (
([foAfterIns, foAfterUpd] * FFillRowOptions = []) or
// used to generate generic FetchRow SQL
([foAfterIns, foAfterUpd] * FFillRowOptions = [foAfterIns, foAfterUpd]) or
ColumnReqRefresh(arFetchRow, oCol)
)
) then begin
sField := '';
lIdentity := False;
case oCol.DataType of
dtBlob, dtMemo, dtHBlob, dtHBFile, dtHMemo, dtWideHMemo:
if foBlobs in FFillRowOptions then begin
sField := GetColumn(AParentField, -1, oCol);
ANeedFrom := True;
end;
dtRowSetRef, dtCursorRef:
if foDetails in FFillRowOptions then begin
sField := GetColumn(AParentField, -1, oCol);
ANeedFrom := True;
end;
else
if AAllowIdentityExp and (foAfterIns in FFillRowOptions) and
(caAutoInc in eAttrs) and (GetIdentity(False) <> '') then begin
if not (foNoIdentity in FFillRowOptions) then begin
sField := GetIdentity(False);
if sAlias = '' then
sAlias := sName;
lIdentity := True;
end;
end
else begin
sField := GetColumn(AParentField, -1, oCol);
ANeedFrom := True;
end;
end;
if sField <> '' then begin
if S <> '' then
S := S + ', ';
if (goBeautify in FGenOptions) and (Length(S) - iTotalLen >= C_FD_CmdGenRight) then begin
iTotalLen := Length(S);
S := S + BRK + ' ';
end;
S := S + sField;
if sAlias <> '' then
S := S + ' AS ' + NormalizeColName(sAlias);
if lIdentity and not FConnMeta.IdentityInWhere then
Exit;
end;
end;
end;
end;
begin
FCommandPart := cpSELECT;
iLockMode := FOptions.UpdateOptions.LockMode;
Result := '';
ANeedFrom := False;
iTotalLen := 0;
if FColumn <> nil then begin
if not AFlatFieldList and (FColumn.DataType = dtRowRef) then
ProcessDataTableFields(FColumn.NestedTable, GetColumn('', -1, FColumn), Result)
else
Result := GetColumn('', -1, FColumn);
end
else
ProcessDataTableFields(FTable, '', Result);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetWhere(AInInsert, ARequired, ANotNull: Boolean): String;
var
eUpdMode: TUpdateMode;
eRowVersion: TFDDatSRowVersion;
iTotalLen, iValueAge: Integer;
procedure ProcessDataTableFields(ATable: TFDDatSTable; ARow: TFDDatSRow;
const AParentField: String; var S: String);
var
i: Integer;
oCol: TFDDatSColumn;
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
sName, sAlias: String;
begin
for i := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns[i];
sName := '';
sAlias := '';
eAttrs := [];
eOpts := [];
GetColumnAttributes(oCol, eAttrs, eOpts, sName, sAlias);
if oCol.DataType = dtRowRef then
ProcessDataTableFields(oCol.NestedTable, GetNestedRow(ARow, i),
GetColumn(AParentField, -1, oCol), S)
else if ColumnSearchable(oCol) and
((eUpdMode = upWhereAll) or
(eUpdMode = upWhereChanged) and (ColumnChanged(ARow, oCol) or ColumnInKey(oCol)) or
(eUpdMode = upWhereKeyOnly) and ColumnInKey(oCol)) and
not (AInInsert and ([caROWID, caRowVersion] * eAttrs <> [])) and
not (AInInsert and (coAfterInsChanged in eOpts) and
not ((caAutoInc in eAttrs) and ((GetIdentity(False) <> '') or
ColumnIdentityAssigned(ARow, oCol, True)))) and
(not ANotNull or (ARow <> nil) and not VarIsNull(ARow.GetData(i, eRowVersion))) and
not (AInInsert and (caDefault in eAttrs) and VarIsNull(ARow.GetData(i, eRowVersion))) then begin
if S <> '' then
S := S + ' AND ';
if (goBeautify in FGenOptions) and (Length(S) - iTotalLen >= C_FD_CmdGenRight) then begin
iTotalLen := Length(S);
S := S + BRK + ' ';
end;
if AInInsert and
(caAutoInc in eAttrs) and (GetIdentity(False) <> '') and
not ColumnIdentityAssigned(ARow, oCol, True) then begin
if not FConnMeta.IdentityInWhere then begin
S := '';
Exit;
end;
S := S + GetColumn(AParentField, -1, oCol) + ' = ' + GetIdentity(False);
end
else if (ARow <> nil) and VarIsNull(ARow.GetData(i, eRowVersion)) then
S := S + GetColumn(AParentField, -1, oCol) + ' IS NULL'
else
S := S + GetColumn(AParentField, -1, oCol) + ' = ' + AddColumnParam(oCol,
iValueAge, ptInput);
end;
end;
end;
begin
FCommandPart := cpWHERE;
Result := '';
if AInInsert then begin
eRowVersion := rvCurrent;
iValueAge := 1;
eUpdMode := upWhereKeyOnly;
end
// used to generate generic FetchRow SQL
else if [foAfterIns, foAfterUpd] * FFillRowOptions = [foAfterIns, foAfterUpd] then begin
eRowVersion := rvCurrent;
iValueAge := 0;
eUpdMode := upWhereKeyOnly;
end
else if [foAfterIns, foAfterUpd] * FFillRowOptions = [foAfterUpd] then begin
eRowVersion := rvCurrent;
iValueAge := 1;
eUpdMode := FOptions.UpdateOptions.UpdateMode;
end
else begin
eRowVersion := rvOriginal;
iValueAge := -1;
eUpdMode := FOptions.UpdateOptions.UpdateMode;
end;
iTotalLen := 0;
ProcessDataTableFields(FTable, FRow, '', Result);
if (Result = '') and (eUpdMode = upWhereKeyOnly) then begin
eUpdMode := upWhereAll;
ProcessDataTableFields(FTable, FRow, '', Result);
end;
if (Result = '') and ARequired then
FDException(Self, [S_FD_LPhys], er_FD_AccWhereIsEmpty, []);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String;
var
prevFillOpts: TFDPhysFillRowOptions;
begin
prevFillOpts := FFillRowOptions;
Include(FFillRowOptions, foData);
if ARequest = arInsert then
Include(FFillRowOptions, foAfterIns)
else if ARequest = arUpdate then
Include(FFillRowOptions, foAfterUpd);
try
Result := GetInlineRefresh(AStmt, ARequest);
finally
FFillRowOptions := prevFillOpts;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateIdentityInsert(
const ATable, AStmt: String; ARequest: TFDUpdateRequest): String;
begin
Result := GetIdentityInsert(ATable, AStmt, ARequest);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetUpdate: String;
var
lUpdChngFields: Boolean;
iTotalLen: Integer;
procedure ProcessDataTableFields(ATable: TFDDatSTable; ARow: TFDDatSRow;
const AParentField: String; ARowIndex: Integer; var S: String);
var
i, j: Integer;
oCol: TFDDatSColumn;
lFldChng: Boolean;
oRows: TFDDatSNestedRowList;
begin
for i := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns[i];
if ColumnUpdatable(oCol, False) then
if oCol.DataType = dtRowRef then
ProcessDataTableFields(oCol.NestedTable, GetNestedRow(ARow, i),
GetColumn(AParentField, ARowIndex, oCol), -1, S)
else if oCol.DataType = dtRowSetRef then begin
oRows := ARow.NestedRows[oCol.Index];
for j := 0 to oRows.Count - 1 do
ProcessDataTableFields(oCol.NestedTable, oRows[j],
GetColumn(AParentField, ARowIndex, oCol), j, S)
end
else begin
lFldChng := not lUpdChngFields or ColumnChanged(ARow, oCol);
if lFldChng then begin
if S <> '' then
S := S + ', ';
if (goBeautify in FGenOptions) and (Length(S) - iTotalLen >= C_FD_CmdGenRight) then begin
iTotalLen := Length(S);
S := S + BRK + ' ';
end;
S := S + GetColumn(AParentField, ARowIndex, oCol) + ' = ';
if FConnMeta.InsertHBlobMode = hmSetAfterReturning then
case oCol.DataType of
dtHBlob:
begin
Include(FFlags, gfHasHBlob);
S := S + 'EMPTY_BLOB()';
end;
dtHBFile:
begin
Include(FFlags, gfHasHBlob);
S := S + 'BFILENAME(''' + oCol.SourceDirectory + ''', ''' +
VarToStr(ARow.GetData(i, rvCurrent)) + ''')';
end;
dtHMemo,
dtWideHMemo:
begin
Include(FFlags, gfHasHBlob);
S := S + 'EMPTY_CLOB()';
end;
else
S := S + AddColumnParam(oCol, 1, ptInput);
end
else begin
if ColumnIsHBLOB(oCol) then
Include(FFlags, gfHasHBlob);
S := S + AddColumnParam(oCol, 1, ptInput);
end;
end;
end;
end;
end;
begin
Result := '';
lUpdChngFields := FOptions.UpdateOptions.UpdateChangedFields;
iTotalLen := 0;
FCommandPart := cpSET;
ProcessDataTableFields(FTable, FRow, '', -1, Result);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateUpdate: String;
begin
FTabAlias := '';
FFlags := [];
FCommandKind := skUnknown;
Result := GetUpdate();
if Result <> '' then begin
Result := 'UPDATE ' + GetFrom + BRK + 'SET ' + Result + BRK + 'WHERE ' +
GetWhere(False, True, False);
if FConnMeta.InlineRefresh then
Result := GenerateInlineRefresh(Result, arUpdate);
end;
if FCommandKind = skUnknown then
FCommandKind := skUpdate;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetInsert(const AOption: String): String;
var
s1, s2, s3, s4: String;
lUpdChngFields: Boolean;
iTotalLen: Integer;
procedure ProcessDataTableFields(ATable: TFDDatSTable; ARow: TFDDatSRow;
const AParentField: String; var AFieldList, AValueList, AFirstField: String;
AForceAddField: Boolean);
var
i: Integer;
oCol: TFDDatSColumn;
lFldChng: Boolean;
sName, sAlias, s1, s2, s3, sReserveFirst: String;
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
begin
sReserveFirst := '';
for i := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns[i];
sName := '';
sAlias := '';
eAttrs := [];
eOpts := [];
GetColumnAttributes(oCol, eAttrs, eOpts, sName, sAlias);
if ColumnUpdatable(oCol, True) then begin
if oCol.DataType = dtRowRef then begin
s1 := '';
s2 := '';
ProcessDataTableFields(oCol.NestedTable, GetNestedRow(ARow, i),
GetColumn(AParentField, -1, oCol), s1, s2, AFirstField, True);
if AFieldList <> '' then begin
AFieldList := AFieldList + ', ';
AValueList := AValueList + ', ';
end;
AFieldList := AFieldList + GetColumn(AParentField, -1, oCol);
AValueList := AValueList + GetRowConstructor(s2, oCol);
end
else begin
lFldChng := AForceAddField or
not lUpdChngFields or
(caAutoInc in eAttrs) and ColumnIdentityAssigned(ARow, oCol, False) or
not (caAutoInc in eAttrs) and ColumnChanged(ARow, oCol) or
ColumnIsHBLOB(oCol);
if lFldChng then begin
if AFieldList <> '' then begin
AFieldList := AFieldList + ', ';
AValueList := AValueList + ', ';
if (goBeautify in FGenOptions) and (
(Length(AFieldList) - iTotalLen >= C_FD_CmdGenRight) or
(Length(AValueList) - iTotalLen >= C_FD_CmdGenRight)
) then begin
iTotalLen := Length(AFieldList);
if iTotalLen < Length(AValueList) then
iTotalLen := Length(AValueList);
AFieldList := AFieldList + BRK + ' ';
AValueList := AValueList + BRK + ' ';
end;
end;
if FConnMeta.InsertHBlobMode = hmSetAfterReturning then
case oCol.DataType of
dtHBlob:
begin
Include(FFlags, gfHasHBlob);
s3 := 'EMPTY_BLOB()';
end;
dtHBFile:
begin
Include(FFlags, gfHasHBlob);
s3 := 'BFILENAME(''' + oCol.SourceDirectory + ''', ''' +
VarToStr(ARow.GetData(i, rvCurrent)) + ''')';
end;
dtHMemo,
dtWideHMemo:
begin
Include(FFlags, gfHasHBlob);
s3 := 'EMPTY_CLOB()';
end;
else
s3 := AddColumnParam(oCol, 1, ptInput);
end
else begin
if ColumnIsHBLOB(oCol) then
Include(FFlags, gfHasHBlob);
if oCol.DataType = dtHBFile then
s3 := 'BFILENAME(''' + oCol.SourceDirectory + ''', ''' +
VarToStr(ARow.GetData(i, rvCurrent)) + ''')'
else
s3 := AddColumnParam(oCol, 1, ptInput);
end;
AFieldList := AFieldList + GetColumn(AParentField, -1, oCol);
AValueList := AValueList + s3;
end;
if caAutoInc in eAttrs then
if FConnMeta.GeneratorSupported and (ColumnGenerator(oCol) <> '') then begin
if (FOptions.UpdateOptions.FetchGeneratorsPoint <> gpNone) and
not ColumnIdentityAssigned(ARow, oCol, True) then
Include(FFlags, gfFetchGenerator);
end
else begin
if lFldChng then
Include(FFlags, gfIdentityInsert);
end;
if (AFirstField = '') and (coAllowNull in eOpts) then begin
if not (caDefault in eAttrs) then
AFirstField := GetColumn(AParentField, -1, oCol)
else if sReserveFirst = '' then
sReserveFirst := GetColumn(AParentField, -1, oCol);
end;
end;
end;
end;
if AFirstField = '' then
AFirstField := sReserveFirst;
end;
begin
s1 := '';
s2 := '';
s3 := '';
if AOption = '' then
s4 := ''
else
s4 := AOption + ' ';
lUpdChngFields := FOptions.UpdateOptions.UpdateChangedFields;
iTotalLen := 0;
FCommandPart := cpVALUES;
ProcessDataTableFields(FTable, FRow, '', s1, s2, s3, False);
if s1 = '' then
case FConnMeta.DefValuesSupported of
dvNone: Result := Result + '(' + s3 + ') ' + s4 + 'VALUES (NULL)';
dvDefVals: Result := Result + s4 + 'DEFAULT VALUES';
dvDef: Result := Result + '(' + s3 + ') ' + s4 + 'VALUES (DEFAULT)';
end
else
Result := Result + '(' + s1 + ')' + BRK + s4 + 'VALUES (' + s2 + ')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateInsert: String;
var
sFrom: String;
begin
FTabAlias := '';
FFlags := [];
FCommandKind := skUnknown;
sFrom := GetFrom;
Result := 'INSERT INTO ' + sFrom + BRK + GetInsert('');
if FConnMeta.InlineRefresh or
(gfHasHBlob in FFlags) and (FConnMeta.InsertHBlobMode = hmSetAfterReturning) then
Result := GenerateInlineRefresh(Result, arInsert);
if (gfIdentityInsert in FFlags) and
FConnMeta.IdentitySupported and FConnMeta.IdentityInsertSupported then
Result := GenerateIdentityInsert(sFrom, Result, arInsert);
if FCommandKind = skUnknown then
FCommandKind := skInsert;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetMerge(AAction: TFDPhysMergeAction): String;
function GetMatched: String;
begin
Result := 'WHEN MATCHED THEN UPDATE SET ' + GetUpdate();
end;
function GetNotMatched: String;
begin
Result := 'WHEN NOT MATCHED THEN INSERT ' + GetInsert('');
end;
var
sUsing: String;
begin
if (GetSingleRowTable() = '') or
(FConnMeta.SelectOptions * [soWithoutFrom, soInlineView] = [soWithoutFrom, soInlineView]) then
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
sUsing := GetSingleRowTable();
if sUsing = '' then
sUsing := '(SELECT 1 AS X) AS U';
Result := 'MERGE INTO ' + GetFrom + BRK + 'USING ' + sUsing +
' ON (' + GetWhere(False, True, False) + ')' + BRK;
case AAction of
maInsertUpdate: Result := Result + GetNotMatched() + BRK + GetMatched();
maInsertIgnore: Result := Result + GetNotMatched();
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateMerge(AAction: TFDPhysMergeAction): String;
begin
FTabAlias := '';
FFlags := [];
FCommandKind := skUnknown;
if FTable.PrimaryKey = '' then
FDException(Self, [S_FD_LPhys], er_FD_DPDestNoKeyFields, []);
Result := GetMerge(AAction);
if FCommandKind = skUnknown then
FCommandKind := skMerge;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateUpdateHBlobs: String;
var
iTotalLen: Integer;
procedure ProcessBlobFields(ATable: TFDDatSTable; ARow: TFDDatSRow;
const AParentField: String; var S: String);
var
i: Integer;
oCol: TFDDatSColumn;
begin
for i := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns[i];
if ColumnUpdatable(oCol, False) then
if oCol.DataType = dtRowRef then
ProcessBlobFields(oCol.NestedTable, GetNestedRow(ARow, i),
GetColumn(AParentField, -1, oCol), S)
else if ColumnIsHBLOB(oCol) and ColumnChanged(ARow, oCol) then begin
if S <> '' then
S := S + ', ';
if (goBeautify in FGenOptions) and (Length(S) - iTotalLen >= C_FD_CmdGenRight) then begin
iTotalLen := Length(S);
S := S + BRK + ' ';
end;
S := S + GetColumn(AParentField, -1, oCol) + ' = ' +
AddColumnParam(oCol, 1, ptInput);
end;
end;
end;
begin
Result := '';
FTabAlias := '';
iTotalLen := 0;
FCommandPart := cpSET;
ProcessBlobFields(FTable, FRow, '', Result);
if Result <> '' then
Result := 'UPDATE ' + GetFrom + BRK + 'SET ' + Result + BRK + 'WHERE ' +
GetWhere(True, True, False);
FCommandKind := skUpdate;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateDelete: String;
begin
FTabAlias := '';
Result := 'DELETE FROM ' + GetFrom + BRK + 'WHERE ' + GetWhere(False, True, False);
FCommandKind := skDelete;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateDeleteAll(ANoUndo: Boolean): String;
begin
FTabAlias := '';
if ANoUndo and FConnMeta.TruncateSupported then
Result := GetTruncate
else begin
Result := 'DELETE FROM ' + GetFrom;
FCommandKind := skDelete;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateLock: String;
var
sList: String;
lNeedFrom: Boolean;
begin
FCommandKind := skSelect;
if FOptions.UpdateOptions.LockMode = lmPessimistic then
Result := GetPessimisticLock;
if Result = '' then begin
lNeedFrom := False;
sList := GetSelectList(False, False, lNeedFrom);
if sList <> '' then begin
Result := 'SELECT ' + sList;
if lNeedFrom then
Result := Result + BRK + 'FROM ' + GetFrom + BRK + 'WHERE ' +
GetWhere(False, True, False)
else if GetSingleRowTable <> '' then
Result := Result + ' FROM ' + GetSingleRowTable;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateUnLock: String;
begin
Result := '';
FCommandKind := skUnknown;
if FOptions.UpdateOptions.LockMode = lmPessimistic then
Result := GetPessimisticUnLock;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateSelect(ARequired: Boolean): String;
var
sList, sWhere, sView: String;
lNeedFrom: Boolean;
function IsQueryComplex(): Boolean;
var
i: Integer;
begin
Result := False;
if FTable <> nil then
for i := 0 to FTable.Columns.Count - 1 do
if not (caBase in FTable.Columns[i].ActualAttributes) then begin
Result := True;
Exit;
end;
end;
begin
if ([foAfterIns, foAfterUpd] * FFillRowOptions = []) and
(FCommandText <> '') and (FColumn = nil) and
(soInlineView in FConnMeta.SelectOptions) and
(not FConnMeta.ColumnOriginProvided or IsQueryComplex()) then
Include(FFlags, gfInlineView)
else
Exclude(FFlags, gfInlineView);
lNeedFrom := False;
sList := GetSelectList(soWithoutFrom in FConnMeta.SelectOptions, False, lNeedFrom);
if sList <> '' then begin
FCommandKind := skSelect;
Result := 'SELECT ' + sList;
if lNeedFrom then begin
sWhere := GetWhere([foAfterIns, foAfterUpd] * FFillRowOptions = [foAfterIns],
ARequired, foUnkRec in FFillRowOptions);
if sWhere = '' then
Result := ''
else begin
Result := Result + BRK + 'FROM ';
if gfInlineView in FFlags then begin
if FSQLOrderByPos > 0 then
sView := Copy(FCommandText, 1, FSQLOrderByPos - 1)
else
sView := FCommandText;
Result := Result + '(' + BRK + sView + BRK + ') ' + FTabAlias;
end
else
Result := Result + GetFrom;
Result := Result + BRK + 'WHERE ' + sWhere;
end;
end
else if GetSingleRowTable <> '' then
Result := Result + ' FROM ' + GetSingleRowTable;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateSavepoint(const AName: String): String;
begin
FCommandKind := skOther;
Result := GetSavepoint(AName);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateRollbackToSavepoint(const AName: String): String;
begin
FCommandKind := skOther;
Result := GetRollbackToSavepoint(AName);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateCommitSavepoint(const AName: String): String;
begin
FCommandKind := skOther;
Result := GetCommitSavepoint(AName);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateFetchGenerators: String;
procedure ProcessAutoGenFields(ATable: TFDDatSTable; ARow: TFDDatSRow;
const AParentField: String; var S: String);
var
i: Integer;
oCol: TFDDatSColumn;
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
sName, sAlias, sGen: String;
begin
for i := 0 to ATable.Columns.Count - 1 do begin
oCol := ATable.Columns[i];
if ColumnUpdatable(oCol, False) then
if oCol.DataType = dtRowRef then
ProcessAutoGenFields(oCol.NestedTable, GetNestedRow(ARow, i),
GetColumn(AParentField, -1, oCol), S)
else begin
sName := '';
sAlias := '';
eAttrs := [];
eOpts := [];
GetColumnAttributes(oCol, eAttrs, eOpts, sName, sAlias);
if (caAutoInc in eAttrs) and (ColumnGenerator(oCol) <> '') then begin
if S <> '' then
S := S + ', ';
sGen := ColumnGenerator(oCol);
if sAlias = '' then
sAlias := sName;
S := S + GetReadGenerator(sGen, NormalizeColName(sAlias), True, False);
end;
end;
end;
end;
begin
Result := '';
if not FConnMeta.GeneratorSupported then
Exit;
ProcessAutoGenFields(FTable, FRow, '', Result);
if Result <> '' then begin
Result := 'SELECT ' + Result;
if GetSingleRowTable <> '' then
Result := Result + BRK + 'FROM ' + GetSingleRowTable;
end;
FCommandKind := skSelect;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateReadGenerator(const AName, AAlias: String;
ANextValue, AFullSelect: Boolean): String;
begin
FCommandKind := skSelect;
Result := GetReadGenerator(AName, AAlias, ANextValue, AFullSelect);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateCall(const AName: String): String;
begin
FCommandKind := skExecute;
Result := GetCall(AName);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateEval(const AExpr: String): String;
begin
Result := 'SELECT ' + AExpr + ' AS V';
if not (soWithoutFrom in FConnMeta.SelectOptions) then
Result := Result + ' FROM ' + GetSingleRowTable;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GeneratePing: String;
begin
FCommandKind := skSelect;
Result := GetPing;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateSelectTable(ATableParams: TFDPhysTableParams): String;
var
rName: TFDPhysParsedName;
sDescFields: String;
sNocaseFields: String;
sMastNullFields: String;
i1: Integer;
i2: Integer;
iFld: Integer;
il: Integer;
sField: String;
sMasterField: String;
sTabAlias: String;
sColAlias: String;
lAsc: Boolean;
sSQLSelect, sSQLPostSelect: String;
iSQLPostSelect: Integer;
sSQLFrom: String;
sSQLWhere: String;
sSQLOrderBy: String;
sSQLLimit: String;
sSQLField: String;
asKeys: array of String;
asSQLKeys: array of String;
sLocateField: String;
sLocateParam: String;
sIndexFields: String;
oCol: TFDDatSColumn;
sRowId, sRowIdAlias: String;
{-----------------------------------------------------------------------------}
function ParamName(const AName: String): String;
begin
Result := NormalizeColName(AName);
end;
{-----------------------------------------------------------------------------}
function EncloseBrackets(const AString: String): String;
begin
if AString <> '' then
Result := '(' + AString + ')'
else
Result := '';
end;
{-----------------------------------------------------------------------------}
procedure AddWhere(const ACond: String);
begin
if ACond = '' then
Exit;
if sSQLWhere <> '' then
sSQLWhere := sSQLWhere + ' AND' + BRK;
sSQLWhere := sSQLWhere + EncloseBrackets(ACond);
end;
{-----------------------------------------------------------------------------}
procedure AddOrderBy(const AFieldName: String; AAscending: Boolean);
begin
if AFieldName = '' then
Exit;
if sSQLOrderBy <> '' then
sSQLOrderBy := sSQLOrderBy + ', ';
sSQLOrderBy := sSQLOrderBy + AFieldName;
if AAscending then
sSQLOrderBy := sSQLOrderBy + ' ASC'
else
sSQLOrderBy := sSQLOrderBy + ' DESC'
end;
{-----------------------------------------------------------------------------}
function GetRange(const AFieldName, ASQLFieldName: String; AFieldNo: Integer): String;
const
C_JOIN: array [Boolean] of String = (' OR ', ' AND ');
var
vStartKeyValue: Variant;
vEndKeyValue: Variant;
lEQ, lAnd: Boolean;
w1, w2: String;
begin
Result := '';
if Assigned(ATableParams.FRangeStartRow) and (AFieldNo <= ATableParams.FRangeStartFieldCount) then
vStartKeyValue := ATableParams.FRangeStartRow.GetData(AFieldName, rvDefault)
else
vStartKeyValue := Unassigned;
if Assigned(ATableParams.FRangeEndRow) and (AFieldNo <= ATableParams.FRangeEndFieldCount) then
vEndKeyValue := ATableParams.FRangeEndRow.GetData(AFieldName, rvDefault)
else
vEndKeyValue := Unassigned;
// no range borders set - exit
if VarIsEmpty(vStartKeyValue) and VarIsEmpty(vEndKeyValue) then
Exit
// both range borders are set
else if not VarIsEmpty(vStartKeyValue) and not VarIsEmpty(vEndKeyValue) then begin
lAnd := True;
lEQ := False;
if not ATableParams.FRangeStartExclusive and not ATableParams.FRangeEndExclusive then
try
lEQ := vStartKeyValue = vEndKeyValue;
except
// silent
end;
// both borders are equal
if lEQ then
if VarIsNull(vStartKeyValue) then
Result := ASQLFieldName + ' IS NULL'
else
Result := ASQLFieldName + ' = :' + ParamName(C_FD_CmdGenRangeStart + AFieldName)
// borders are different
else begin
// starting border is exclusive
if ATableParams.FRangeStartExclusive then
if VarIsNull(vStartKeyValue) then
if nlAscLast in ATableParams.FNullLocation then
w1 := '0 = 1'
else
w1 := ASQLFieldName + ' IS NOT NULL'
else
w1 := ASQLFieldName + ' > :' + ParamName(C_FD_CmdGenRangeStart + AFieldName)
// starting border is inclusive
else
if VarIsNull(vStartKeyValue) then begin
w1 := ASQLFieldName + ' IS NULL';
lAnd := nlAscLast in ATableParams.FNullLocation;
end
else
w1 := ASQLFieldName + ' >= :' + ParamName(C_FD_CmdGenRangeStart + AFieldName);
// ending border is exclusive
if ATableParams.FRangeEndExclusive then
if VarIsNull(vEndKeyValue) then
if nlAscFirst in ATableParams.FNullLocation then
w2 := '0 = 1'
else
w2 := ASQLFieldName + ' IS NOT NULL'
else
w2 := ASQLFieldName + ' < :' + ParamName(C_FD_CmdGenRangeFinish + AFieldName)
// ending border is inclusive
else
if VarIsNull(vEndKeyValue) then begin
w2 := ASQLFieldName + ' IS NULL';
lAnd := nlAscFirst in ATableParams.FNullLocation;
end
else
w2 := ASQLFieldName + ' <= :' + ParamName(C_FD_CmdGenRangeFinish + AFieldName);
Result := w1 + C_JOIN[lAnd] + w2;
end;
end
// starting border is not set
else if VarIsEmpty(vStartKeyValue) and not VarIsEmpty(vEndKeyValue) then begin
if VarIsNull(vEndKeyValue) then
if nlAscFirst in ATableParams.FNullLocation then
Result := ASQLFieldName + ' IS NULL'
else
Exit
// exclude border
else if ATableParams.FRangeEndExclusive then
Result := ASQLFieldName + ' < :' + ParamName(C_FD_CmdGenRangeFinish + AFieldName)
// include border
else
Result := ASQLFieldName + ' <= :' + ParamName(C_FD_CmdGenRangeFinish + AFieldName);
// NULL's are possible
if (nlAscFirst in ATableParams.FNullLocation) and
(caAllowNull in ATableParams.FRangeEndRow.Table.Columns.ColumnByName(AFieldName).ActualAttributes) then
Result := Result + C_JOIN[False] + ASQLFieldName + ' IS NULL';
end
// ending border is not set
else if not VarIsEmpty(vStartKeyValue) and VarIsEmpty(vEndKeyValue) then begin
if VarIsNull(vStartKeyValue) then
if nlAscLast in ATableParams.FNullLocation then
Result := ASQLFieldName + ' IS NULL'
else
Exit
// exclude border
else if ATableParams.FRangeStartExclusive then
Result := ASQLFieldName + ' > :' + ParamName(C_FD_CmdGenRangeStart + AFieldName)
// include border
else
Result := ASQLFieldName + ' >= :' + ParamName(C_FD_CmdGenRangeStart + AFieldName);
// NULL's are possible
if (nlAscLast in ATableParams.FNullLocation) and
(caAllowNull in ATableParams.FRangeStartRow.Table.Columns.ColumnByName(AFieldName).ActualAttributes) then
Result := Result + C_JOIN[False] + ASQLFieldName + ' IS NULL';
end;
end;
{-----------------------------------------------------------------------------}
// When "down":
// (f1 > :p1) or
// (f1 = :p1) and (f2 > :p2) or
// (f1 = :p1) and (f2 = :p2) and (f3 > :p3)
function GetWindow(const AKeys, ASQLKeys: array of String; ADown, AInclude: Boolean): String;
var
sKey, sSQLKey: String;
sKeyItem, sCond: String;
oCol: TFDDatSColumn;
nKeys, iKeyCount, i: Integer;
lIsNull, lIncluded, lDown: Boolean;
begin
Result := '';
lIncluded := False;
nKeys := Length(AKeys);
if (ATableParams.FKeyFieldCount > 0) and (ATableParams.FKeyFieldCount < nKeys) then
nKeys := ATableParams.FKeyFieldCount;
for iKeyCount := nKeys - 1 downto 0 do begin
sKeyItem := '';
for i := 0 to iKeyCount do begin
sKey := AKeys[i];
sSQLKey := ASQLKeys[i];
oCol := FRow.Table.Columns.ColumnByName(sKey);
lIsNull := VarIsNull(FRow.GetData(oCol.Index, rvDefault));
lDown := ADown xor FDFieldInFieldNames(sDescFields, sKey);
if sKeyItem <> '' then
sKeyItem := sKeyItem + ' AND ';
if i < iKeyCount then
if lIsNull then
sKeyItem := sKeyItem + sSQLKey + ' IS NULL'
else
sKeyItem := sKeyItem + EncloseBrackets(sSQLKey + ' = :' +
ParamName(C_FD_CmdGenWindow + sKey))
else begin
if lIsNull then
if AInclude and not lIncluded then begin
sKeyItem := sKeyItem + sSQLKey + ' IS NULL';
lIncluded := True;
end
else if (caAllowNull in oCol.Attributes) and (
lDown and (nlAscFirst in ATableParams.FNullLocation) or
not lDown and (nlAscLast in ATableParams.FNullLocation)) then
sKeyItem := sKeyItem + sSQLKey + ' IS NOT NULL'
else begin
sKeyItem := '';
lIncluded := False;
Break;
end
else begin
if AInclude and not lIncluded then begin
if lDown then
sCond := ' >= '
else
sCond := ' <= ';
lIncluded := True;
end
else
if lDown then
sCond := ' > '
else
sCond := ' < ';
sCond := sSQLKey + sCond + ':' + ParamName(C_FD_CmdGenWindow + sKey);
if (caAllowNull in oCol.Attributes) and (
lDown and (nlAscLast in ATableParams.FNullLocation) or
not lDown and (nlAscFirst in ATableParams.FNullLocation)) then
sCond := sCond + ' OR ' + sSQLKey + ' IS NULL';
sKeyItem := sKeyItem + EncloseBrackets(sCond);
end;
end;
end;
if sKeyItem <> '' then begin
if Result <> '' then
Result := Result + ' OR ';
Result := Result + EncloseBrackets(sKeyItem);
end;
end;
if Result = '' then
Result := '(0 = 1)';
end;
{-----------------------------------------------------------------------------}
function GetWindowUp(const AKeys, ASQLKeys: array of String; AInclude: Boolean = False): String;
begin
Result := GetWindow(AKeys, ASQLKeys, False, AInclude);
end;
{-----------------------------------------------------------------------------}
function GetWindowDown(const AKeys, ASQLKeys: array of String; AInclude: Boolean = False): String;
begin
Result := GetWindow(AKeys, ASQLKeys, True, AInclude);
end;
{-----------------------------------------------------------------------------}
function BuildFilter(const AFlt: String): String;
begin
Result := AFlt;
end;
begin
if FTabAlias <> '' then
sTabAlias := FTabAlias + '.'
else
sTabAlias := '';
Result := '';
sSQLWhere := '';
sSQLOrderBy := '';
sSQLSelect := '';
sSQLPostSelect := '';
iSQLPostSelect := 0;
// Build SELECT list
if not (ATableParams.FTableCommand in [tcGetRecNo, tcGetRowCount]) then begin
if ATableParams.FSelectFields = '' then
sSQLSelect := sTabAlias + '*'
else begin
i1 := 1;
while i1 <= Length(ATableParams.FSelectFields) do begin
sField := FDExtractFieldName(ATableParams.FSelectFields, i1);
sSQLField := NormalizeColName(sField);
if sSQLSelect <> '' then
sSQLSelect := sSQLSelect + ', ';
sSQLSelect := sSQLSelect + sTabAlias + sSQLField;
end;
end;
// Add Unique Row Identifier, depending on a DBMS
if not ATableParams.FReadOnly then begin
sRowId := GenerateRowId(sRowIdAlias);
if sRowId <> '' then
sSQLSelect := sSQLSelect + ', ' + sTabAlias + sRowId + ' AS ' + C_FD_SysColumnPrefix + sRowIdAlias;
end;
end
else
sSQLSelect := 'COUNT(*)';
// Build FROM
rName.FCatalog := ATableParams.FCatalog;
rName.FSchema := ATableParams.FSchema;
rName.FObject := ATableParams.FTable;
sSQLFrom := FConnMeta.EncodeObjName(rName, FCommand, [eoBeautify]);
if FTabAlias <> '' then
sSQLFrom := sSQLFrom + ' ' + FTabAlias;
// merge primary key fields when IndexFields does not contain them
sIndexFields := FDMergeFieldNames(ATableParams.FIndexFields, ATableParams.FPrimaryKeyFields);
// Do all tasks in one loop
if sIndexFields <> '' then begin
sDescFields := ';' + UpperCase(ATableParams.FDescFields) + ';';
sNocaseFields := ';' + UpperCase(ATableParams.FNoCaseFields) + ';';
sMastNullFields := ';' + UpperCase(ATableParams.FMasterNullFields) + ';';
i1 := 1;
i2 := 1;
iFld := 1;
while i1 <= Length(sIndexFields) do begin
sField := FDExtractFieldName(sIndexFields, i1);
sSQLField := sTabAlias + NormalizeColName(sField);
// Build master / detail WHERE part
if i2 <= Length(ATableParams.FMasterFields) then begin
sMasterField := FDExtractFieldName(ATableParams.FMasterFields, i2);
if Pos(';' + UpperCase(sMasterField) + ';', sMastNullFields) <> 0 then
AddWhere(sSQLField + ' IS NULL')
else
AddWhere(sSQLField + ' = :' + ParamName(sMasterField));
end
// Build range WHERE part
else if ATableParams.FRanged then
AddWhere(GetRange(sField, sSQLField, iFld));
// Build FindKey WHERE part
if ATableParams.FTableCommand = tcFindKey then
if VarIsNull(FRow.GetData(sField, rvDefault)) then begin
if iFld <= ATableParams.FKeyFieldCount then
AddWhere(sSQLField + ' IS NULL');
end
else
AddWhere(sSQLField + ' = :' + ParamName(C_FD_CmdGenWindow + sField));
// Build ORDER BY
// Note, when table has record with every index fields is null,
// then window works correctly only when all sort orders are ASC
// No need for ORDER BY in case of GetRecNo or GetRowCount
if not (ATableParams.FTableCommand in [tcGetRecNo, tcGetRowCount]) then begin
// When window command is Eof, PageUp or LocateBackward, then ORDER BY is inverted
lAsc := Pos(';' + UpperCase(sField) + ';', sDescFields) = 0;
if (ATableParams.FTableCommand in [tcPageUp, tcEof]) or
((ATableParams.FTableCommand = tcLocate) and ATableParams.FLocateBackward) then
lAsc := not lAsc;
if (Pos(';' + UpperCase(sField) + ';', sNocaseFields) <> 0) {and
(ATableParams.FRow.Table.Columns.ColumnByName(sField).DataType in C_FD_CharTypes)} then
// Interbase, {UCASE(col)} in ORDER BY gives "Token unknown UPPER"
if FConnMeta.Kind = TFDRDBMSKinds.Interbase then begin
Inc(iSQLPostSelect);
sColAlias := C_FD_SysColumnPrefix + IntToStr(iSQLPostSelect);
sSQLPostSelect := sSQLPostSelect + ', {FN UCASE(' + sSQLField + ')} AS ' + sColAlias;
AddOrderBy(sColAlias, lAsc);
end
else
AddOrderBy('{FN UCASE(' + sSQLField + ')}', lAsc)
else
AddOrderBy(sSQLField, lAsc);
end;
// collect key fields
il := Length(asKeys);
SetLength(asKeys, il + 1);
SetLength(asSQLKeys, il + 1);
asKeys[il] := sField;
asSQLKeys[il] := sSQLField;
Inc(iFld);
end;
// Build key tree for window (if needed)
case ATableParams.FTableCommand of
tcPageUp:
AddWhere(GetWindowUp(asKeys, asSQLKeys));
tcPageDown:
AddWhere(GetWindowDown(asKeys, asSQLKeys));
tcFindNearest:
AddWhere(GetWindowDown(asKeys, asSQLKeys, not ATableParams.FExclusive));
tcLocate:
if ATableParams.FLocateFromCurrent then
if ATableParams.FLocateBackward then
AddWhere(GetWindowUp(asKeys, asSQLKeys))
else
AddWhere(GetWindowDown(asKeys, asSQLKeys));
tcGetRecNo:
AddWhere(GetWindowUp(asKeys, asSQLKeys, True));
end;
end
else if ATableParams.FRecordCount > 0 then
// expression index is not supported
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
// Build filter
if ATableParams.FFiltered then
// Currently just insert filter expression into WHERE
AddWhere(BuildFilter(ATableParams.FFilter));
// Build locate WHERE part
if ATableParams.FTableCommand = tcLocate then begin
if ATableParams.FLocateExpression = '' then begin
i1 := 1;
while i1 <= Length(ATableParams.FLocateFields) do begin
sField := FDExtractFieldName(ATableParams.FLocateFields, i1);
sSQLField := sTabAlias + NormalizeColName(sField);
oCol := ATableParams.FLocateRow.Table.Columns.ColumnByName(sField);
// NULL handling
if VarIsNull(ATableParams.FLocateRow.GetData(oCol.Index, rvDefault)) then begin
sLocateField := sSQLField;
AddWhere(sLocateField + ' IS NULL');
end
// not NULL handling
else begin
// use UCASE for the case-insensitive compare
if ATableParams.FLocateIgnoreCase and (oCol.DataType in C_FD_CharTypes) then begin
sLocateField := '{FN UCASE(' + sSQLField + ')}';
sLocateParam := '{FN UCASE('+ ':' + ParamName(C_FD_CmdGenLocate + sField) + ')}';
end
else begin
sLocateField := sSQLField;
sLocateParam := ':' + ParamName(C_FD_CmdGenLocate + sField);
end;
// use LIKE for partial compare
if ATableParams.FLocatePartial and (oCol.DataType in C_FD_CharTypes) then begin
// Firebird, VC(N) LIKE MASK(N+1) gives "string right truncation"
if FConnMeta.Kind in [TFDRDBMSKinds.Interbase, TFDRDBMSKinds.Firebird] then
sLocateField := '{FN CONVERT(' + sLocateField + ', VARCHAR(250))}';
AddWhere(sLocateField + ' LIKE ' + sLocateParam);
end
else
AddWhere(sLocateField + ' = ' + sLocateParam);
end;
end;
// lxoFromCurrent option has been attached in window section
end
else
AddWhere(ATableParams.FLocateExpression);
end;
// Build CurrentRecord WHERE part
if ATableParams.FTableCommand = tcCurrentRecord then begin
i1 := 1;
while i1 <= Length(ATableParams.FPrimaryKeyFields) do begin
sField := FDExtractFieldName(ATableParams.FPrimaryKeyFields, i1);
sSQLField := sTabAlias + NormalizeColName(sField);
if not VarIsNull(FRow.GetData(sField, rvDefault)) then
AddWhere(sSQLField + ' = :' + ParamName(C_FD_CmdGenWindow + sField));
end;
end;
// Add custom WHERE
if ATableParams.FCustomWhere <> '' then
AddWhere(ATableParams.FCustomWhere);
// Do not use {LIMIT} when ODBC / dbExp bridge or DBMS does not support {LIMIT}
if (loRows in FConnMeta.LimitOptions) and
not (FConnMeta.Kind in [TFDRDBMSKinds.Unknown, TFDRDBMSKinds.Other]) and
(ATableParams.FRecordCount > 0) then
// It is recommended to set {LIMIT}
if ATableParams.FTableCommand = tcSetRecNo then
// {LIMIT} works from zero
sSQLLimit := Format('{LIMIT(%d,1)}', [ATableParams.FRecordNumber - 1])
else
sSQLLimit := Format('{LIMIT(%d)}', [ATableParams.FRecordCount]);
// Final SQL Text
Result := 'SELECT ' + sSQLSelect + sSQLPostSelect + BRK + 'FROM ' + sSQLFrom;
if sSQLWhere <> '' then
Result := Result + BRK + 'WHERE ' + sSQLWhere;
if sSQLOrderBy <> '' then
Result := Result + BRK + 'ORDER BY ' + sSQLOrderBy;
if sSQLLimit <> '' then
Result := Result + BRK + sSQLLimit;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateStoredProcParams(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word): String;
begin
FParams.Clear;
Result := GetStoredProcParams(ACatalog, ASchema, APackage, AProc, AOverload);
if (Result <> '') and (FCommandKind = skUnknown) then
FCommandKind := skStoredProc;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateStoredProcCall(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
begin
if CompareText(FCommand.Connection.Driver.BaseDriverID, S_FD_ODBCId) = 0 then
Result := GetStoredProcODBCCall(ACatalog, ASchema, APackage, AProc, AOverload, ASPUsage)
else
Result := GetStoredProcCall(ACatalog, ASchema, APackage, AProc, AOverload, ASPUsage);
if (FCommandKind = skStoredProc) and
(ASPUsage in [skStoredProcWithCrs, skStoredProcNoCrs]) then
FCommandKind := ASPUsage;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String;
begin
FCommandKind := skUnknown;
Result := GetSelectMetaInfo(AKind, ACatalog, ASchema, ABaseObject, AObject,
AWildcard, AObjectScopes, ATableKinds, AOverload);
if (Result <> '') and (FCommandKind = skUnknown) then
FCommandKind := skSelect;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateLimitSelect(ASkip, ARows: Integer;
AOneMore: Boolean; var AOptions: TFDPhysLimitOptions): String;
var
iAfter: Integer;
begin
if ((ARows >= 0) or (ASkip >= 0)) and (FCommandKind in [skUnknown, skSelect]) and
(FDStartsWithKW(FCommandText, 'SELECT', iAfter) or
FDStartsWithKW(FCommandText, 'WITH', iAfter)) then begin
if AOneMore and (ARows >= 0) then
Inc(ARows);
if ASkip < 0 then
ASkip := 0;
if ARows < 0 then
ARows := MAXINT - ASkip;
Result := GetLimitSelect(FCommandText, ASkip, ARows, AOptions);
// ORDER BY cannot be striped anymore, because user asked for TOP N rows
// using currently specified ORDER BY order
FSQLOrderByPos := 0;
end
else
Result := FCommandText;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateCountSelect: String;
begin
if FSQLOrderByPos <> 0 then begin
Result := Copy(FCommandText, 1, FSQLOrderByPos - 1);
FSQLOrderByPos := 0;
end
else
Result := FCommandText;
FCommandKind := skSelect;
Result := GetCountSelect(Result);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateRowId(out AAlias: String): String;
begin
AAlias := '';
Result := GetRowId(AAlias);
if (AAlias = '') and (Result <> '') then
AAlias := Result;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateCreateTable(AParts: TFDPhysCreateTableParts): TStrings;
var
oCols: TFDDatSColumnList;
i: Integer;
oCol: TFDDatSColumn;
sDef, sCols, sGen, sKey: String;
oNames: TFDStringList;
oView: TFDDatSView;
oSort: TFDDatSMechSort;
rName: TFDPhysParsedName;
sFrom: String;
begin
FCommandKind := skCreate;
FFlags := [];
FTabAlias := '';
oCols := FTable.Columns;
oNames := TFDStringList.Create(dupIgnore, True, False);
Result := TFDStringList.Create;
try
try
sFrom := GetFrom;
// Create table
if tpTable in AParts then begin
sCols := '';
for i := 0 to oCols.Count - 1 do begin
oCol := oCols[i];
if ColumnStorable(oCol) then begin
sDef := GetColumnDef(oCol);
if sDef <> '' then begin
if sCols <> '' then
sCols := sCols + ',' + BRK;
sCols := sCols + IND + sDef;
end;
end;
end;
if sCols = '' then
Exit;
Result.Add(GetCreateTable(sFrom, sCols));
end;
// Create sequence / generator / trigger
if FConnMeta.GeneratorSupported then begin
if (not (tpTable in AParts) or (gfCreateIdentityGenerator in FFlags)) and
(tpGenerators in AParts) then
for i := 0 to oCols.Count - 1 do begin
oCol := oCols[i];
if ColumnStorable(oCol) and (caAutoInc in oCol.ActualAttributes) then begin
sGen := ColumnGenerator(oCol);
if sGen = '' then begin
FConnMeta.DecodeObjName(sFrom, rName, nil, [doUnquote]);
rName.FObject := 'GEN_' + rName.FObject;
sGen := FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]);
end;
if (sGen <> '') and (oNames.IndexOf(sGen) = -1) then begin
oNames.Add(sGen);
Result.Add(GetCreateGenerator(sGen));
end;
end;
end;
if (not (tpTable in AParts) or (gfCreateIdentityTrigger in FFlags)) and
(tpTriggers in AParts) then
Result.Add(GetCreateIdentityTrigger);
end;
oNames.Clear;
// Primary key
if tpPrimaryKey in AParts then begin
sKey := FTable.PrimaryKey;
if sKey = '' then
for i := 0 to oCols.Count - 1 do begin
oCol := oCols[i];
if ColumnStorable(oCol) and (coInKey in oCol.ActualOptions) then begin
if sKey <> '' then
sKey := sKey + ';';
sKey := sKey + oCol.Name;
end;
end;
if (sKey <> '') and (oNames.IndexOf(sKey) = -1) then begin
oNames.Add(sKey);
if not (ctNoAlterTableConstraint in FConnMeta.CreateTableOptions) then
Result.Add(GetCreatePrimaryKey(sKey));
end;
end;
// Indexes
if tpIndexes in AParts then begin
for i := 0 to FTable.Views.Count - 1 do begin
oView := FTable.Views[i];
if oView.Creator = vcDataSetIndex then begin
oSort := TFDDatSMechSort(oView.GetMechanismByClass(TFDDatSMechSort, mkSort));
if oSort = nil then
sKey := ''
else
sKey := oSort.Columns;
if (sKey <> '') and (oNames.IndexOf(sKey) = -1) then begin
oNames.Add(sKey);
Result.Add(GetCreateIndex(oView.Name, sKey, soUnique in oSort.SortOptions));
end;
end;
end;
end;
except
FDFree(Result);
raise;
end;
finally
FDFree(oNames);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GenerateDropTable(AParts: TFDPhysCreateTableParts): TStrings;
var
oCols: TFDDatSColumnList;
i: Integer;
oCol: TFDDatSColumn;
sGen: String;
oNames: TFDStringList;
rName: TFDPhysParsedName;
sFrom: String;
begin
FCommandKind := skDrop;
FFlags := [];
FTabAlias := '';
oCols := FTable.Columns;
oNames := TFDStringList.Create(dupIgnore, True, False);
Result := TFDStringList.Create;
try
try
sFrom := GetFrom;
// Drop table
if tpTable in AParts then
Result.Add('DROP TABLE ' + sFrom);
// Drop sequence / generator
if FConnMeta.GeneratorSupported and (tpGenerators in AParts) then
for i := 0 to oCols.Count - 1 do begin
oCol := oCols[i];
if ColumnStorable(oCol) and (caAutoInc in oCol.ActualAttributes) then begin
sGen := ColumnGenerator(oCol);
if sGen = '' then begin
FConnMeta.DecodeObjName(sFrom, rName, nil, [doUnquote]);
rName.FObject := 'GEN_' + rName.FObject;
sGen := FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]);
end;
if (sGen <> '') and (oNames.IndexOf(sGen) = -1) then begin
oNames.Add(sGen);
Result.Add(GetDropGenerator(sGen));
end;
end;
end;
except
FDFree(Result);
raise;
end;
finally
FDFree(oNames);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetReturning(ARequest: TFDUpdateRequest;
AWithInto: Boolean): String;
var
s1, s2: String;
i: Integer;
oCols: TFDDatSColumnList;
oCol: TFDDatSColumn;
lRefresh, lPutBlob: Boolean;
eParType: TParamType;
begin
FCommandPart := cpRETURNING;
s1 := '';
s2 := '';
oCols := FTable.Columns;
for i := 0 to oCols.Count - 1 do begin
oCol := oCols[i];
if ColumnStorable(oCol) then begin
lRefresh := ColumnReqRefresh(ARequest, oCol);
lPutBlob := (FConnMeta.InsertHBlobMode = hmSetAfterReturning) and
ColumnIsHBLOB(oCol) and ColumnChanged(FRow, oCol) and (oCol.DataType <> dtHBFile);
if lRefresh or lPutBlob then begin
if s1 <> '' then begin
s1 := s1 + ', ';
if AWithInto then
s2 := s2 + ', ';
end;
s1 := s1 + GetColumn('', -1, oCol);
if AWithInto then begin
// if Insert then
// after exec put
// else if Update then
// if Set then
// after exec put
// else if Refr then
// after exec get
// else
// after exec get
if lPutBlob then
eParType := ptInput
else if lRefresh then
eParType := ptOutput
else
eParType := ptUnknown;
s2 := s2 + AddColumnParam(oCol, 1, eParType);
end;
end;
end;
end;
if s1 <> '' then begin
Result := BRK + 'RETURNING ' + s1;
if AWithInto then
Result := Result + ' INTO ' + s2;
end
else
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String;
begin
// overridden by MSSQL, Oracle, DB2, IB descendant classes
Result := AStmt;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetIdentityInsert(const ATable, AStmt: String;
ARequest: TFDUpdateRequest): String;
begin
// overridden by MSSQL descendant class
Result := AStmt;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetIdentity(ASessionScope: Boolean): String;
begin
// overridden by MSSQL, MySQL, ADS descendant classes
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetRowId(var AAlias: String): String;
begin
// overridden by Oracle, ADS, SQLite, Informix, Interbase, Firebird
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetSingleRowTable: String;
begin
// overridden by Oracle, ADS, IB, DB2 descendant classes
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetPessimisticLock: String;
begin
// overridden by Oracle, MSSQL, MySQL, IB descendant classes
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetPessimisticUnLock: String;
begin
// overridden by ADS descendant classes
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetTruncate: String;
begin
// overridden by Teradata descendant classes
Result := 'TRUNCATE TABLE ' + GetFrom;
FCommandKind := skOther;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetRollbackToSavepoint(const AName: String): String;
begin
// overridden by Oracle, MSSQL, MySQL, IB, PGSQL, SQLite descendant classes
Result := '';
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCommitSavepoint(const AName: String): String;
begin
// overridden by DB2, IB, SQLite descendant classes
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetSavepoint(const AName: String): String;
begin
// overridden by Oracle, MSSQL, MySQL, IB, PGSQL, SQLite descendant classes
Result := '';
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetReadGenerator(const AName, AAlias: String;
ANextValue, AFullSelect: Boolean): String;
var
sIdent: String;
begin
if ANextValue or (AName <> '') then
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
FCommandPart := cpSELECT;
sIdent := GetIdentity(True);
if sIdent <> '' then begin
Result := sIdent;
if AAlias <> '' then
Result := Result + ' AS ' + AAlias;
if AFullSelect then begin
Result := 'SELECT ' + Result;
if GetSingleRowTable <> '' then begin
FCommandPart := cpFROM;
Result := Result + ' FROM ' + GetSingleRowTable;
end;
end;
end
else
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCall(const AName: String): String;
begin
// overridden by all descendant classes
Result := '';
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetPing: String;
begin
Result := 'SELECT 1';
if not (soWithoutFrom in FConnMeta.SelectOptions) then
if GetSingleRowTable <> '' then
Result := Result + ' FROM ' + GetSingleRowTable
else
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetStoredProcParams(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word): String;
const
ResultParam = 'Result';
var
oView: TFDDatSView;
i, j, iPosDelta: Integer;
oPar: TFDParam;
V: Variant;
iDestDataType: TFieldType;
iSrcSize, iDestSize: LongWord;
iSrcPrec, iSrcScale, iDestPrec, iDestScale: Integer;
eSrcFDDataType, eDestFDDataType: TFDDataType;
iSrcAttrs: TFDDataAttributes;
lHasCursors, lMayHaveCursor, lUnifyParams: Boolean;
oRow: TFDDatSRow;
oFmt: TFDFormatOptions;
begin
oFmt := FOptions.FormatOptions;
oView := FConnMeta.GetProcArgs(ACatalog, ASchema, APackage, AProc, '', AOverload);
try
lHasCursors := False;
lMayHaveCursor := False;
iPosDelta := 0;
lUnifyParams := FOptions.ResourceOptions.UnifyParams;
for i := 0 to oView.Rows.Count - 1 do begin
oRow := oView.Rows[i];
oPar := FParams.Add;
V := oRow.GetData(7, rvDefault);
if not VarIsNull(V) then
oPar.Position := V - iPosDelta
else
oPar.Position := 0;
V := oRow.GetData(8, rvDefault);
if not VarIsNull(V) then
oPar.ParamType := V;
V := oRow.GetData(6, rvDefault);
if VarIsNull(V) then
oPar.Name := ResultParam
else
oPar.Name := V;
if lUnifyParams then
if (oPar.Position = 1) and (oPar.ParamType = ptResult) and
(oPar.Name = '@RETURN_VALUE') then begin
FDFree(oPar);
iPosDelta := 1;
Continue;
end
else if Copy(oPar.Name, 1, 1) = '@' then
oPar.Name := Copy(oPar.Name, 2, MAXINT);
V := oRow.GetData(9, rvDefault);
if not VarIsNull(V) then
eSrcFDDataType := TFDDataType(Integer(V))
else
eSrcFDDataType := dtUnknown;
V := oRow.GetData(11, rvDefault);
if not VarIsNull(V) then begin
j := Integer(V);
iSrcAttrs := TFDDataAttributes(Pointer(@j)^);
end
else
iSrcAttrs := [];
V := oRow.GetData(14, rvDefault);
if not VarIsNull(V) then
iSrcSize := V
else
iSrcSize := 0;
V := oRow.GetData(12, rvDefault);
if not VarIsNull(V) then
iSrcPrec := V
else
iSrcPrec := 0;
V := oRow.GetData(13, rvDefault);
if not VarIsNull(V) then
iSrcScale := V
else
iSrcScale := 0;
eDestFDDataType := dtUnknown;
iDestDataType := ftUnknown;
iDestSize := 0;
iDestPrec := 0;
oFmt.ResolveDataType(oPar.Name, oPar.DataTypeName, eSrcFDDataType, iSrcSize,
iSrcPrec, iSrcScale, eDestFDDataType, iSrcSize, True);
oFmt.ColumnDef2FieldDef(eDestFDDataType, iSrcSize, iSrcPrec, iSrcScale,
iSrcAttrs, iDestDataType, iDestSize, iDestPrec, iDestScale);
oPar.DataType := iDestDataType;
if eDestFDDataType = dtWideHMemo then
oPar.FDDataType := eDestFDDataType;
oPar.Size := iDestSize;
oPar.Precision := iDestPrec;
oPar.NumericScale := iDestScale;
if oPar.DataType in ObjectFieldTypes then
oPar.DataTypeName := VarToStr(oRow.GetData(10, rvDefault));
lHasCursors := lHasCursors or (iDestDataType in [ftCursor, ftDataSet]) and
(oPar.ParamType <> ptInput);
lMayHaveCursor := lMayHaveCursor or ((oPar.ParamType = ptOutput) and
(FConnMeta.Kind in [TFDRDBMSKinds.Interbase, TFDRDBMSKinds.Firebird,
TFDRDBMSKinds.Advantage, TFDRDBMSKinds.PostgreSQL]));
end;
if lHasCursors then
FCommandKind := skStoredProcWithCrs
else if not lMayHaveCursor then
FCommandKind := skStoredProcNoCrs;
finally
FDClearMetaView(oView, FOptions.FetchOptions);
end;
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetStoredProcODBCCall(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
var
i: Integer;
oParam: TFDParam;
rName: TFDPhysParsedName;
lWasParam: Boolean;
begin
// overridden by Oracle, MySQL, IB, PGSQL descendant classes
Result := '{';
for i := 0 to FParams.Count - 1 do
if FParams[i].ParamType = ptResult then begin
Result := Result + '? = ';
Break;
end;
Result := Result + 'CALL ';
if FConnMeta.Kind = TFDRDBMSKinds.Informix then begin
// Informix supports {CALL name(...)}, where name does not include catalog /
// schema and name is not quoted. Otherwise "syntax error" is returned.
rName.FObject := AProc;
Result := Result + FConnMeta.EncodeObjName(rName, FCommand, [eoNormalize]);
end
else begin
rName.FCatalog := ACatalog;
rName.FSchema := ASchema;
rName.FBaseObject := APackage;
rName.FObject := AProc;
rName.OverInd := AOverload;
Result := Result + FConnMeta.EncodeObjName(rName, FCommand, [eoQuote, eoNormalize]);
end;
lWasParam := False;
for i := 0 to FParams.Count - 1 do begin
oParam := FParams[i];
if oParam.ParamType <> ptResult then begin
if lWasParam then
Result := Result + ', '
else begin
Result := Result + '(';
lWasParam := True;
end;
if oParam.ArrayType = atTable then
Result := Result + '{RESULTSET ' + IntToStr(oParam.ArraySize) + ', ' + oParam.SQLName + '}'
else
Result := Result + '?';
end;
end;
if lWasParam then
Result := Result + ')'
else if FConnMeta.Kind in [TFDRDBMSKinds.Informix, TFDRDBMSKinds.Teradata] then
// Informix, Teradata require trailing () in contrast to other DBs.
Result := Result + '()';
Result := Result + '}';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetStoredProcCall(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
begin
Result := GetStoredProcODBCCall(ACatalog, ASchema, APackage, AProc, AOverload, ASPUsage);
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String;
var
lWasWhere: Boolean;
eParts: TFDPhysNameParts;
procedure AddWhere(const ACond: String; const AParam: String = '');
var
oParam: TFDParam;
begin
if lWasWhere then
Result := Result + ' AND ' + ACond
else begin
Result := Result + ' WHERE ' + ACond;
lWasWhere := True;
end;
if AParam <> '' then begin
case FConnMeta.NamedParamMark of
prQMark: Result := Result + '?';
prName: Result := Result + ':' + AParam;
prNumber: Result := Result + ':' + IntToStr(GetParams.Count + 1);
prDollar: Result := Result + '$' + IntToStr(GetParams.Count + 1);
prQNumber: Result := Result + '?' + IntToStr(GetParams.Count + 1);
end;
oParam := GetParams.Add;
oParam.Name := AParam;
oParam.DataType := ftString;
oParam.Size := 70;
end;
end;
function FK_EncodeRule(const ARuleField: String): String;
begin
Result :=
'CASE' +
' WHEN ' + ARuleField + ' = ''CASCADE'' THEN ' + IntToStr(Integer(ckCascade)) +
' WHEN ' + ARuleField + ' = ''SET NULL'' THEN ' + IntToStr(Integer(ckSetNull)) +
' WHEN ' + ARuleField + ' = ''RESTRICT'' THEN ' + IntToStr(Integer(ckRestrict)) +
' WHEN ' + ARuleField + ' = ''SET DEFAULT'' THEN ' + IntToStr(Integer(ckSetDefault)) +
' ELSE ' + IntToStr(Integer(ckNone)) +
' END';
end;
function GetFK_TABLE_CATALOG: String;
begin
if FConnMeta.Kind <> TFDRDBMSKinds.MySQL then
Result := 'B.TABLE_CATALOG'
else
Result := 'B.TABLE_SCHEMA';
end;
function GetFK_TABLE_SCHEMA: String;
begin
if FConnMeta.Kind <> TFDRDBMSKinds.MySQL then
Result := 'B.TABLE_SCHEMA'
else
Result := '''''';
end;
function GetFK_PKEY_CONSTRAINT_CATALOG: String;
begin
if FConnMeta.Kind <> TFDRDBMSKinds.MySQL then
Result := 'C.TABLE_CATALOG'
else
Result := 'C.TABLE_SCHEMA';
end;
function GetFK_PKEY_CONSTRAINT_SCHEMA: String;
begin
if FConnMeta.Kind <> TFDRDBMSKinds.MySQL then
Result := 'C.TABLE_SCHEMA'
else
Result := '''''';
end;
function GetFK_REFERENCED_COLUMN: String;
begin
if FConnMeta.Kind <> TFDRDBMSKinds.MySQL then
Result := 'E.COLUMN_NAME'
else
Result := 'D.REFERENCED_COLUMN_NAME';
end;
begin
// overridden by descendant classes
Result := '';
eParts := FConnMeta.NameParts;
case AKind of
mkForeignKeys:
begin
Result := 'SELECT 0 AS RECNO, ' +
GetFK_TABLE_CATALOG + ' AS CATALOG_NAME, ' +
GetFK_TABLE_SCHEMA + ' AS SCHEMA_NAME, ' +
'B.TABLE_NAME, ' +
'A.CONSTRAINT_NAME AS FKEY_NAME, ' +
GetFK_PKEY_CONSTRAINT_CATALOG + ' AS PKEY_CATALOG_NAME, ' +
GetFK_PKEY_CONSTRAINT_SCHEMA + ' AS PKEY_SCHEMA_NAME, ' +
'C.TABLE_NAME AS PKEY_TABLE_NAME, ' +
FK_EncodeRule('A.DELETE_RULE') + ' AS DELETE_RULE, ' +
FK_EncodeRule('A.UPDATE_RULE') + ' AS UPDATE_RULE ' +
'FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS A ' +
'INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS B ON';
if FConnMeta.Kind = TFDRDBMSKinds.MySQL then
Result := Result + ' B.TABLE_NAME = A.TABLE_NAME AND';
Result := Result + ' B.CONSTRAINT_NAME = A.CONSTRAINT_NAME';
if npCatalog in eParts then
Result := Result + ' AND B.CONSTRAINT_CATALOG = A.CONSTRAINT_CATALOG';
if npSchema in eParts then
Result := Result + ' AND B.CONSTRAINT_SCHEMA = A.CONSTRAINT_SCHEMA';
Result := Result + ' INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C ON';
if FConnMeta.Kind = TFDRDBMSKinds.MySQL then
Result := Result + ' C.TABLE_NAME = A.REFERENCED_TABLE_NAME AND';
Result := Result + ' C.CONSTRAINT_NAME = ';
if FConnMeta.Kind = TFDRDBMSKinds.MySQL then
Result := Result + 'CONCAT(A.UNIQUE_CONSTRAINT_NAME, '''')'
else
Result := Result + 'A.UNIQUE_CONSTRAINT_NAME';
if npCatalog in eParts then
Result := Result + ' AND C.CONSTRAINT_CATALOG = A.UNIQUE_CONSTRAINT_CATALOG';
if npSchema in eParts then
Result := Result + ' AND C.CONSTRAINT_SCHEMA = A.UNIQUE_CONSTRAINT_SCHEMA';
if (ACatalog <> '') and (npCatalog in eParts) then
AddWhere(GetFK_TABLE_CATALOG + ' = ', 'CAT');
if (ASchema <> '') and (npSchema in eParts) then
AddWhere(GetFK_TABLE_SCHEMA + ' = ', 'SCH');
AddWhere('B.TABLE_NAME = ', 'OBJ');
if AWildcard <> '' then
AddWhere('A.CONSTRAINT_NAME LIKE ', 'WIL');
Result := Result + ' ORDER BY 4, 5';
end;
mkForeignKeyFields:
begin
Result := 'SELECT 0 AS RECNO, ' +
GetFK_TABLE_CATALOG + ' AS CATALOG_NAME, ' +
GetFK_TABLE_SCHEMA + ' AS SCHEMA_NAME, ' +
'B.TABLE_NAME, ' +
'A.CONSTRAINT_NAME AS FKEY_NAME, ' +
'D.COLUMN_NAME, ' +
GetFK_REFERENCED_COLUMN + ' AS PKEY_COLUMN_NAME, ' +
'D.ORDINAL_POSITION AS COLUMN_POSITION ' +
'FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS A ' +
'INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS B ON';
if FConnMeta.Kind = TFDRDBMSKinds.MySQL then
Result := Result + ' B.TABLE_NAME = A.TABLE_NAME AND';
Result := Result + ' B.CONSTRAINT_NAME = A.CONSTRAINT_NAME';
if npCatalog in eParts then
Result := Result + ' AND B.CONSTRAINT_CATALOG = A.CONSTRAINT_CATALOG';
if npSchema in eParts then
Result := Result + ' AND B.CONSTRAINT_SCHEMA = A.CONSTRAINT_SCHEMA';
Result := Result + ' INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C ON';
if FConnMeta.Kind = TFDRDBMSKinds.MySQL then
Result := Result + ' C.TABLE_NAME = A.REFERENCED_TABLE_NAME AND';
Result := Result + ' C.CONSTRAINT_NAME = ';
if FConnMeta.Kind = TFDRDBMSKinds.MySQL then
Result := Result + 'CONCAT(A.UNIQUE_CONSTRAINT_NAME, '''')'
else
Result := Result + 'A.UNIQUE_CONSTRAINT_NAME';
if npCatalog in eParts then
Result := Result + ' AND C.CONSTRAINT_CATALOG = A.UNIQUE_CONSTRAINT_CATALOG';
if npSchema in eParts then
Result := Result + ' AND C.CONSTRAINT_SCHEMA = A.UNIQUE_CONSTRAINT_SCHEMA';
Result := Result + ' INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE D ON';
if FConnMeta.Kind = TFDRDBMSKinds.MySQL then
Result := Result + ' D.TABLE_NAME = A.TABLE_NAME AND';
Result := Result + ' D.CONSTRAINT_NAME = A.CONSTRAINT_NAME';
if npCatalog in eParts then
Result := Result + ' AND D.CONSTRAINT_CATALOG = A.CONSTRAINT_CATALOG';
if npSchema in eParts then
Result := Result + ' AND D.CONSTRAINT_SCHEMA = A.CONSTRAINT_SCHEMA';
if FConnMeta.Kind <> TFDRDBMSKinds.MySQL then begin
Result := Result + ' INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE E ON';
Result := Result + ' E.CONSTRAINT_NAME = A.UNIQUE_CONSTRAINT_NAME';
if npCatalog in eParts then
Result := Result + ' AND E.CONSTRAINT_CATALOG = A.UNIQUE_CONSTRAINT_CATALOG';
if npSchema in eParts then
Result := Result + ' AND E.CONSTRAINT_SCHEMA = A.UNIQUE_CONSTRAINT_SCHEMA';
end;
if (ACatalog <> '') and (npCatalog in eParts) then
AddWhere(GetFK_TABLE_CATALOG + ' = ', 'CAT');
if (ASchema <> '') and (npSchema in eParts) then
AddWhere(GetFK_TABLE_SCHEMA + ' = ', 'SCH');
AddWhere('B.TABLE_NAME = ', 'BAS');
AddWhere('A.CONSTRAINT_NAME = ', 'OBJ');
if AWildcard <> '' then
AddWhere('D.COLUMN_NAME LIKE ', 'WIL');
Result := Result + ' ORDER BY 8';
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetLimitSelect(const ASQL: String;
ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String;
var
s: String;
iAfter: Integer;
begin
AOptions := [loRows];
// overridden by descendant classes
if (ASkip + ARows <> MAXINT) and
FDStartsWithKW(ASQL, 'SELECT', iAfter) and
not FDStartsWithKW(ASQL, 'SELECT TOP', iAfter) then begin
if (ARows = 0) and (FConnMeta.Kind in [TFDRDBMSKinds.MSAccess, TFDRDBMSKinds.SQLAnywhere]) then
Result := 'SELECT * FROM (' + BRK + ASQL + BRK + ') A' + BRK + 'WHERE 0 = 1'
else begin
Result := 'SELECT TOP ';
if GetSQLOrderByPos > 0 then begin
s := UpperCase(ASQL);
if FDHasKW(s, 'UNION') or FDHasKW(s, 'MINUS') or FDHasKW(s, 'INTERSECT') or
FDHasKW(s, 'EXCEPT') then
Result := Result + IntToStr(ASkip + ARows) + ' * FROM (' + BRK +
Copy(ASQL, 1, GetSQLOrderByPos - 1) + BRK + ') A' + BRK +
Copy(ASQL, GetSQLOrderByPos, MAXINT)
else if FDStartsWithKW(ASQL, 'SELECT DISTINCT', iAfter) then
Result := 'SELECT DISTINCT TOP ' + IntToStr(ASkip + ARows) +
Copy(ASQL, iAfter, MAXINT)
else
Result := Result + IntToStr(ASkip + ARows) + Copy(ASQL, iAfter, MAXINT);
end
else if FConnMeta.Kind in [TFDRDBMSKinds.MSSQL, TFDRDBMSKinds.SQLAnywhere, TFDRDBMSKinds.Advantage] then begin
// SQL Server, SQL Anywhere and Advantage does not support subqueries
// with unaliased expressions in SELECT list. So, try to avoid
// SELECT * FROM (<original query>)
s := UpperCase(ASQL);
if FDHasKW(s, 'UNION') or FDHasKW(s, 'MINUS') or FDHasKW(s, 'INTERSECT') or
FDHasKW(s, 'EXCEPT') then
Result := Result + IntToStr(ASkip + ARows) + ' * FROM (' + BRK +
ASQL + BRK + ') A'
else if FDStartsWithKW(ASQL, 'SELECT DISTINCT', iAfter) then
Result := 'SELECT DISTINCT TOP ' + IntToStr(ASkip + ARows) +
Copy(ASQL, iAfter, MAXINT)
else
Result := Result + IntToStr(ASkip + ARows) + Copy(ASQL, iAfter, MAXINT);
end
else
Result := Result + IntToStr(ASkip + ARows) + ' * FROM (' + BRK +
ASQL + BRK + ') A';
end;
end
else begin
Result := ASQL;
AOptions := [];
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCountSelect(const ASQL: String): String;
begin
Result := 'SELECT COUNT(*) FROM (' + BRK + ASQL + BRK + ') A';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetColumnDim(ASize, APrec, AScale, ADefSize, ADefPrec, ADefScale: Integer): String;
begin
Result := '';
if ASize > 0 then
Result := IntToStr(ASize)
else if ADefSize > 0 then
Result := IntToStr(ADefSize)
else begin
if APrec > 0 then
Result := IntToStr(APrec)
else if ADefPrec > 0 then
Result := IntToStr(ADefPrec);
if (AScale > 0) or (ADefScale > 0) then begin
if Result = '' then
Result := '*';
Result := Result + ', ';
if AScale > 0 then
Result := Result + IntToStr(AScale)
else if ADefPrec > 0 then
Result := Result + IntToStr(ADefScale);
end;
end;
if Result <> '' then
Result := '(' + Result + ')';
end;
{-------------------------------------------------------------------------------}
// http://savage.net.au/SQL/sql-2003-2.bnf.html#data type
function TFDPhysCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String;
begin
// SQL 2003 data types
case AColumn.DataType of
dtBoolean:
Result := 'BOOLEAN';
dtSByte,
dtByte,
dtInt16,
dtUInt16:
Result := 'SMALLINT';
dtInt32,
dtUInt32:
Result := 'INTEGER';
dtInt64,
dtUInt64:
Result := 'BIGINT';
dtSingle:
Result := 'REAL';
dtDouble,
dtExtended:
Result := 'FLOAT';
dtCurrency:
Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1, 18, 4);
dtBCD,
dtFmtBCD:
Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1,
FOptions.FormatOptions.MaxBcdPrecision, 0);
dtDateTimeStamp,
dtDateTime:
Result := 'TIMESTAMP';
dtTime:
Result := 'TIME';
dtDate:
Result := 'DATE';
dtTimeIntervalYM:
Result := 'INTERVAL YEAR TO MONTH';
dtTimeIntervalFull,
dtTimeIntervalDS:
Result := 'INTERVAL DAY TO SECOND';
dtAnsiString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'CHAR'
else
Result := 'VARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtWideString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'NCHAR'
else
Result := 'NVARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtByteString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'BINARY'
else
Result := 'VARBINARY';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtGUID:
Result := 'CHAR(38)';
dtBlob,
dtHBlob,
dtHBFile:
Result := 'BLOB';
dtMemo,
dtHMemo:
Result := 'CLOB';
dtWideMemo,
dtWideHMemo,
dtXML:
Result := 'NCLOB';
dtUnknown,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef,
dtParentRowRef,
dtObject:
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetColumnDef(AColumn: TFDDatSColumn): String;
var
sType: String;
eAttrs: TFDDataAttributes;
eOpts: TFDDataOptions;
procedure AddDefault;
begin
if (AColumn.Expression <> '') and not (caExpr in eAttrs) then
Result := Result + ' DEFAULT ' + AColumn.Expression;
end;
procedure AddNotNull;
begin
if not (caAllowNull in eAttrs) or (coInKey in eOpts) then
Result := Result + ' NOT NULL';
end;
begin
sType := GetColumnType(AColumn);
if sType = '' then
if goSkipUnsupTypes in FGenOptions then begin
Result := '';
Exit;
end
else
FDException(Self, [S_FD_LPhys], er_FD_AccUnsupColumnType,
[AColumn.Name, C_FD_DataTypeNames[AColumn.DataType]]);
Result := GetColumn('', -1, AColumn) + ' ' + sType;
eAttrs := AColumn.ActualAttributes;
eOpts := AColumn.ActualOptions;
if ctDefaultFirst in FConnMeta.CreateTableOptions then begin
AddDefault;
AddNotNull;
end
else begin
AddNotNull;
AddDefault;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCreateTable(const ATab, ACols: String): String;
begin
// overridden by Teradata descendant classes
Result := 'CREATE TABLE ' + ATab + ' (' + BRK + ACols + BRK + ')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCreateGenerator(const AName: String): String;
begin
// overridden by Oracle, IB descendant classes
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetDropGenerator(const AName: String): String;
begin
// overridden by Oracle, IB descendant classes
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCreateIdentityTrigger: String;
begin
// overridden by Oracle, IB descendant classes
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCreatePrimaryKey(const ACols: String): String;
var
sTab: String;
rName: TFDPhysParsedName;
i: Integer;
begin
sTab := GetFrom;
FConnMeta.DecodeObjName(sTab, rName, nil, [doUnquote]);
rName.FObject := 'PK_' + rName.FObject;
Result := 'ALTER TABLE ' + sTab + ' ADD CONSTRAINT ' +
FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]) + ' PRIMARY KEY (';
i := 1;
while i <= Length(ACols) do begin
if i <> 1 then
Result := Result + ', ';
Result := Result + GetColumn('', -1, FTable.Columns.ColumnByName(FDExtractFieldName(ACols, i)));
end;
Result := Result + ')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysCommandGenerator.GetCreateIndex(const AName, ACols: String; AUnique: Boolean): String;
var
sTab, sInd: String;
rName: TFDPhysParsedName;
i: Integer;
begin
sTab := GetFrom;
if (AName = '') or (CompareText(Copy(AName, 1, 4), 'View') = 0) then begin
FConnMeta.DecodeObjName(sTab, rName, nil, [doUnquote]);
rName.FObject := 'I_' + rName.FObject;
sInd := FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]);
end
else
sInd := AName;
Result := 'CREATE ';
if AUnique then
Result := Result + 'UNIQUE ';
Result := Result + 'INDEX ' + sInd + ' ON ' + sTab + ' (';
i := 1;
while i <= Length(ACols) do begin
if i <> 1 then
Result := Result + ', ';
Result := Result + GetColumn('', -1, FTable.Columns.ColumnByName(FDExtractFieldName(ACols, i)));
end;
Result := Result + ')';
end;
end.
|
unit OS.Codesign;
interface
uses Windows;
type
PCCERT_CONTEXT = Pointer;
HCRYPTPROV_LEGACY = Pointer;
PFN_CRYPT_GET_SIGNER_CERTIFICATE = Pointer;
CRYPT_VERIFY_MESSAGE_PARA = record
cbSize: DWORD;
dwMsgAndCertEncodingType: DWORD;
hCryptProv: HCRYPTPROV_LEGACY;
pfnGetSignerCertificate: PFN_CRYPT_GET_SIGNER_CERTIFICATE;
pvGetArg: Pointer;
end;
TCertificateContext = record
Context: PCCERT_CONTEXT;
IsContextValid: Boolean;
end;
const
PKCS_7_ASN_ENCODING = $00010000;
X509_ASN_ENCODING = $00000001;
CERT_SECTION_TYPE_ANY = $FF;
function ImageEnumerateCertificates(FileHandle: THandle; TypeFilter: WORD;
out CertificateCount: DWORD; Indicies: PDWORD; IndexCount: Integer): BOOL;
stdcall; external 'Imagehlp.dll';
function ImageGetCertificateHeader(FileHandle: THandle;
CertificateIndex: Integer; var CertificateHeader: TWinCertificate): BOOL;
stdcall; external 'Imagehlp.dll';
function ImageGetCertificateData(FileHandle: THandle;
CertificateIndex: Integer; Certificate: PWinCertificate;
var RequiredLength: DWORD): BOOL; stdcall; external 'Imagehlp.dll';
function CryptVerifyMessageSignature(
const pVerifyPara: CRYPT_VERIFY_MESSAGE_PARA;
dwSignerIndex: DWORD; pbSignedBlob: PByte; cbSignedBlob: DWORD;
pbDecoded: PBYTE; pcbDecoded: PDWORD; ppSignerCert: PCCERT_CONTEXT): BOOL;
stdcall; external 'Crypt32.dll';
function CertGetNameStringW(pCertContext: PCCERT_CONTEXT; dwType: DWORD;
dwFlags: DWORD; pvTypePara: Pointer; pszNameString: PChar;
cchNameString: DWORD): DWORD; stdcall; external 'Crypt32.dll';
function CertFreeCertificateContext(pCertContext: PCCERT_CONTEXT): BOOL;
stdcall; external 'Crypt32.dll';
implementation
end.
|
unit string_segment;
interface
implementation
type Integer = Int32;
function Pos(const SubStr, Str: string; Offset: Int32): Int32;
var
I, LIterCnt, L, J: Int32;
begin
L := Length(SubStr);
LIterCnt := Length(Str) - L - Offset;
if (Offset >= 0) and (LIterCnt >= 0) and (L > 0) then
begin
for I := 0 to LIterCnt do
begin
J := 0;
while (J >= 0) and (J < L) do
begin
if Str[Offset + I + J] = SubStr[J] then
Inc(J)
else
J := -1;
end;
if J >= L then
Exit(Offset + I);
end;
end;
Result := -1;
end;
function StringSegCount(const Str: string; const Separator: string = ','): Integer;
var
SPos, StrLen: integer;
begin
SPos := -1;
Result := 0;
StrLen := Length(Str);
repeat
Inc(Result);
Inc(SPos);
SPos := Pos(separator, Str, SPos);
until (SPos = -1) or (SPos >= StrLen);
end;
function StringSegment(const Str: string; Idx: Integer; const Separator: string = ','): string;
var
SPos, NPos, StrLen: integer;
begin
Result := '';
SPos := -1;
StrLen := Length(Str);
repeat
Dec(Idx);
Inc(SPos);
NPos := Pos(Separator, Str, SPos);
if Idx <= 0 then begin
if NPos = -1 then
NPos := StrLen;
Result := Copy(Str, SPos, NPos - SPos);
Exit;
end;
SPos := NPos;
until (SPos = -1) or (SPos >= StrLen);
end;
var
Res: string;
Str: string;
procedure Test;
begin
Str := '111,222,,5';
Res := StringSegment(Str, 0);
Assert(Res = '111');
Res := StringSegment(Str, 1);
Assert(Res = '111');
Res := StringSegment(Str, 2);
Assert(Res = '222');
Res := StringSegment(Str, 3);
Assert(Res = '');
Res := StringSegment(Str, 4);
Assert(Res = '5');
Res := StringSegment(Str, 6);
Assert(Res = '');
end;
initialization
Test();
finalization
end. |
unit uDXFImport;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons, uObjectDXFDrawing,
uObjectPanel, uObjectDrawing;
type
TfDxfImport = class(TForm)
pnlTop: TPanel;
btnPanelShape: TBitBtn;
btnHoles: TBitBtn;
btnPockets: TBitBtn;
shpSeparator: TShape;
btnBrowse: TBitBtn;
shp1: TShape;
lbThickness: TLabel;
comHrubka: TComboBox;
comHrubkaValue: TComboBox;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure btnBrowseClick(Sender: TObject);
procedure comHrubkaChange(Sender: TObject);
procedure FormMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
procedure FormMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
private
{ Private declarations }
_dxfFileName: string;
_dxf: TDXFDrawing;
_drawing: TDrawingObject;
public
{ Public declarations }
property dxfFileName: string read _dxfFileName write _dxfFileName;
property DXF: TDXFDrawing read _dxf write _dxf;
procedure DrawStatic;
procedure DrawDynamic;
procedure LoadDXF;
end;
var
fDxfImport: TfDxfImport;
implementation
{$R *.dfm}
uses uConfig, uMain, uPanelSett, uTranslate, uDebug, uMyTypes;
procedure TfDxfImport.FormCreate(Sender: TObject);
var
tmp: string;
begin
try
tmp := 'creating drawing';
_drawing := TDrawingObject.Create(Self.Canvas);
except
messagebox(0, PChar('DXF import OnCreate error in operation: ' + tmp), 'Error', MB_OK);
ModalResult := mrAbort;
end;
fMain.Log('DXF import: Drawing canvas created');
comHrubka.Items := fPanelSett.comHrubka.Items;
comHrubkaValue.Items := fPanelSett.comHrubkaValue.Items;
TransObj(Self);
end;
procedure TfDxfImport.FormMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
if fMain.ViewReverseWheel.Checked then
_drawing.SetZoom(1.1, ScreenToClient(mouse.CursorPos).X, ScreenToClient(mouse.CursorPos).Y)
else
_drawing.SetZoom(0.9, ScreenToClient(mouse.CursorPos).X, ScreenToClient(mouse.CursorPos).Y);
_dxf.Draw(_drawing);
end;
procedure TfDxfImport.FormMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
if fMain.ViewReverseWheel.Checked then
_drawing.SetZoom(0.9, ScreenToClient(mouse.CursorPos).X, ScreenToClient(mouse.CursorPos).Y)
else
_drawing.SetZoom(1.1, ScreenToClient(mouse.CursorPos).X, ScreenToClient(mouse.CursorPos).Y);
_dxf.Draw(_drawing);
end;
procedure TfDxfImport.FormActivate(Sender: TObject);
begin
fMain.Log('DXF import: FormActivate');
LoadDXF;
end;
procedure TfDxfImport.FormPaint(Sender: TObject);
var
i: Integer;
begin
//fDebug.LogMessage('FORM PAINT()');
_drawing.Init(farbaBgndTmavy);
_drawing.Text(8, pnlTop.Height+8, _dxfFileName, farbaBgndSvetly, 13);
_drawing.CanvasHeight := ClientHeight - pnlTop.Height;
_dxf.Draw(_drawing);
_drawing.FlipToFront;
end;
procedure TfDxfImport.FormShow(Sender: TObject);
begin
fMain.Log('DXF import: FormShow');
end;
procedure TfDxfImport.btnBrowseClick(Sender: TObject);
begin
fMain.OpenDialog.InitialDir := ExtractFilePath(Self.dxfFileName);
if fMain.OpenDialog.Execute then begin
_dxfFileName := fMain.OpenDialog.FileName;
Self.LoadDXF;
Self.Paint;
end;
end;
procedure TfDxfImport.comHrubkaChange(Sender: TObject);
begin
comHrubkaValue.ItemIndex := comHrubka.ItemIndex;
end;
procedure TfDxfImport.DrawDynamic;
begin
end;
procedure TfDxfImport.DrawStatic;
begin
end;
procedure TfDxfImport.LoadDXF;
begin
if Assigned(_dxf) then _dxf.Free;
_dxf := TDXFDrawing.Create;
_dxf.LoadFromFile(_dxfFileName);
_drawing.CanvasHeight := ClientHeight - pnlTop.Height;
_drawing.ZoomAll( _dxf.BoundingBox, ClientWidth, (ClientHeight - pnlTop.Height), 0, pnlTop.Height );
fMain.Log('BOUNDING RECT: ' + MyRectToStr(_dxf.BoundingBox));
end;
end.
|
unit xProtocolBase;
interface
uses System.Types, xTypes, xConsts, System.Classes, xFunction, xVCL_FMX,
system.SysUtils;
type
/// <summary>
/// 设备通信协议
/// </summary>
TProtocolBase = class
private
FOnRevData: TEnventPack;
FOnSendData: TSendPack;
FOnLog: TSendRevPack;
FOrderTimeOut: Cardinal;
FOnError: TGetStrProc;
FIsReplay: Boolean;
FOnGetOrderObject: TOrderObject;
protected
FIsStop : Boolean; // 是否停止运行
FOrderType : Integer; // 命令类型
FDev : TObject; // 命令对象
FRevDataLen : Integer; // 接收数据长度
FRvdPacks : TBytes; // 接收数据包
FReplySate : Integer; // 数据接收状态
/// <summary>
/// 发送接收
/// </summary>
procedure CommSenRev( aPacks : TBytes; bSend : Boolean; sParam1, sParam2 : string );
/// <summary>
/// 发送之前函数
/// </summary>
procedure BeforeSend; virtual;
/// <summary>
/// 发送之后函数
/// </summary>
procedure AfterSend; virtual;
/// <summary>
/// 接收之前函数
/// </summary>
procedure BeforeRev; virtual;
/// <summary>
/// 接收之后函数
/// </summary>
procedure AfterRev; virtual;
/// <summary>
/// 检查是否有反馈
/// </summary>
/// <returns></returns>
function IsReplied : Boolean;
/// <summary>
/// 是否需要返回数据
/// </summary>
property IsReplay : Boolean read FIsReplay write FIsReplay;
/// <summary>
/// 生成数据包
/// </summary>
function CreatePacks: TBytes; virtual;
/// <summary>
/// 解析接收到的数据包
/// </summary>
procedure ParseData(RvdPack : TBytes); virtual;
/// <summary>
/// 检查接收的数据包是否合法
/// </summary>
function CheckData(RvdPack : TBytes): Boolean; virtual;
/// <summary>
/// 通讯错误
/// </summary>
procedure ProtocolError( sError : string );
/// <summary>
/// 命令超时
/// </summary>
procedure OrderOutTime; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
/// <summary>
/// 接收数据包
/// </summary>
procedure ReceivedData(aPacks: TBytes; sParam1, sParam2 : string); virtual;
/// <summary>
/// 发送数据包
/// </summary>
function SendData(nOrderType: Integer; ADev: TObject; sParam1, sParam2 : string) : Boolean; virtual;
/// <summary>
/// 退出
/// </summary>
procedure SetExit;
public
/// <summary>
/// 命令超时时间
/// </summary>
property OrderTimeOut : Cardinal read FOrderTimeOut write FOrderTimeOut;
/// <summary>
/// 发送数据包事件
/// </summary>
property OnSendData: TSendPack read FOnSendData write FOnSendData;
/// <summary>
/// 接收数据包事件
/// </summary>
property OnRevData: TEnventPack read FOnRevData write FOnRevData;
/// <summary>
/// 通讯记录
/// </summary>
property OnLog : TSendRevPack read FOnLog write FOnLog;
/// <summary>
/// 错误事件
/// </summary>
property OnError: TGetStrProc read FOnError write FOnError;
/// <summary>
/// 根据命令获取对象(设备发送软件应答的命令 必须赋值这个事件)
/// </summary>
property OnGetOrderObject : TOrderObject read FOnGetOrderObject write FOnGetOrderObject;
end;
implementation
procedure TProtocolBase.AfterRev;
begin
// nothing
// WaitForSeconds(20);
end;
procedure TProtocolBase.AfterSend;
begin
// nothing
end;
procedure TProtocolBase.BeforeRev;
begin
// nothing
end;
procedure TProtocolBase.BeforeSend;
begin
FRevDataLen := 0;
FReplySate := C_REPLY_NORESPONSE;
SetLength(FRvdPacks, 0);
end;
function TProtocolBase.CheckData(RvdPack: TBytes): Boolean;
begin
Result := False;
// nothing
end;
procedure TProtocolBase.CommSenRev(aPacks: TBytes; bSend: Boolean; sParam1, sParam2 : string);
begin
if Length(aPacks) > 0 then
begin
if Assigned(FOnLog) then
FOnLog( aPacks, bSend);
if bSend then
begin
if Assigned(FOnSendData) then
FOnSendData(aPacks, sParam1, sParam2);
end
else
begin
if Assigned(FOnRevData) then
FOnRevData(aPacks, sParam1, sParam2);
end;
end;
end;
constructor TProtocolBase.Create;
begin
FOrderTimeOut := 1500;
FIsReplay := True;
end;
function TProtocolBase.CreatePacks: TBytes;
begin
// nothing
end;
destructor TProtocolBase.Destroy;
begin
inherited;
end;
function TProtocolBase.IsReplied: Boolean;
var
nTick : Cardinal;
begin
nTick := TThread.GetTickCount;
repeat
Sleep(3);
MyProcessMessages;
until ( FReplySate > C_REPLY_NORESPONSE ) or
( TThread.GetTickCount - nTick > FOrderTimeOut );
if FReplySate > C_REPLY_NORESPONSE then
Result := True
else
Result := False;
if not Result then
OrderOutTime;
end;
procedure TProtocolBase.OrderOutTime;
begin
end;
procedure TProtocolBase.ParseData(RvdPack: TBytes);
begin
FReplySate := C_REPLY_CORRECT;
// nothing
end;
procedure TProtocolBase.ProtocolError(sError: string);
begin
if Assigned(FOnError) then
FOnError(sError);
end;
procedure TProtocolBase.ReceivedData(aPacks: TBytes; sParam1, sParam2 : string);
begin
BeforeRev;
ParseData(aPacks);
CommSenRev(aPacks, False, sParam1, sParam2);
AfterRev;
end;
function TProtocolBase.SendData(nOrderType: Integer; ADev: TObject; sParam1, sParam2 : string): Boolean;
begin
FOrderType := nOrderType;
FDev := ADev;
BeforeSend;
CommSenRev(CreatePacks, True, sParam1, sParam2);
AfterSend;
if FIsReplay then
Result := IsReplied
else
Result := True;
end;
procedure TProtocolBase.SetExit;
begin
FIsStop := True;
end;
end.
|
unit SIP_Script;
interface
uses Contnrs,SIP_Action,Classes;
type
TSIPScript=class(TPersistent)
private
FObjects:TObjectList;
FScriptID: Integer;
function GetAction(Index: Integer): TSIPAction;
procedure SetName(const Value: String);
procedure ReadData(Reader: TReader);
procedure WriteData(Writer: TWriter);
function GetText: String;
procedure SetText(const Value: String);
procedure SetScriptID(const Value: Integer);
public
FName:String;
procedure AddAction(OpCode:TSIPOperation;Operands:String);
procedure AddActionString(Action:String);
property Action[Index: Integer]:TSIPAction read GetAction;
constructor Create;
destructor Destroy;override;
function Count:Integer;
procedure DefineProperties(Filer: TFiler); override;
procedure Delete(Index:Integer);
property Text:String read GetText write SetText;
function IsGroup:Boolean;
function IsDTMF:Boolean;
procedure Move(Index1,Index2:Integer);
function LastPlayAction:TSIPAction;
published
property Description:String read FName write SetName;
property ScriptID:Integer read FScriptID write SetScriptID;
end;
TSIPScriptComponent=class(TComponent)
private
FScript: TSIPScript;
published
property Script:TSIPScript read FScript write FScript;
end;
implementation
uses SysUtils, Util;
{ TSIPScript }
procedure TSIPScript.AddAction(OpCode: TSIPOperation; Operands: String);
var A:TSIPAction;
begin
A:=TSIPAction.Create;
A.OpCode:=OpCode;
A.Operands:=Operands;
FObjects.Add(A);
end;
procedure TSIPScript.AddActionString(Action: String);
var A:TSIPAction;
begin
A:=TSIPAction.Create;
A.Action:=Action;
FObjects.Add(A);
end;
function TSIPScript.Count: Integer;
begin
Result:=FObjects.Count;
end;
constructor TSIPScript.Create;
begin
FObjects:=TObjectList.Create;
end;
procedure TSIPScript.DefineProperties(Filer: TFiler);
begin
Filer.DefineProperty('Actions', ReadData, WriteData, true);
end;
procedure TSIPScript.Delete(Index: Integer);
begin
FObjects.Delete(Index);
end;
destructor TSIPScript.Destroy;
begin
FreeAndNil(FObjects);
inherited;
end;
function TSIPScript.GetAction(Index: Integer): TSIPAction;
begin
Result:=FObjects.Items[Index] as TSIPAction;
end;
function TSIPScript.GetText: String;
var C:TSIPScriptComponent;
begin
C:=TSIPScriptComponent.Create(nil);
try
C.Script:=Self;
Result:=ComponentToString(C);
finally
C.Free;
end;
end;
function TSIPScript.IsDTMF: Boolean;
var
I: Integer;
begin
Result:=False;
for I := 0 to FObjects.Count - 1 do
if (Action[I].OpCode = OP_DTMF) then
begin
Result:=True;
Break;
end;
end;
function TSIPScript.IsGroup: Boolean;
var
I: Integer;
begin
Result:=False;
for I := 0 to FObjects.Count - 1 do
if ((Action[I].OpCode in [OP_RING]) and SameText(Action[I].Operand[1],'group'))
or ((Action[I].OpCode in [OP_SMS,OP_Mail]) and SameText(Action[I].Operand[2],'group')) then
begin
Result:=True;
Break;
end;
end;
function TSIPScript.LastPlayAction: TSIPAction;
var I:Integer;
Ring:Boolean;
begin
Result:=nil;
Ring:=False;
for I := 0 to FObjects.Count - 1 do
if not Ring and (Action[I].OpCode in [OP_RING]) then Ring:=True else
if Ring and (Action[I].OpCode in [OP_PLAY]) then Result:=Action[I];
end;
procedure TSIPScript.ReadData(Reader: TReader);
begin
Reader.ReadListBegin;
FObjects.Clear;
while not Reader.EndOfList do AddActionString(Reader.ReadString);
Reader.ReadListEnd;
end;
procedure TSIPScript.SetName(const Value: String);
begin
FName := Value;
end;
procedure TSIPScript.SetScriptID(const Value: Integer);
begin
FScriptID := Value;
end;
procedure TSIPScript.SetText(const Value: String);
var S:TSIPScriptComponent;
begin
if Value='' then
begin
FObjects.Clear;
Exit;
end;
S:=TSIPScriptComponent.Create(nil);
S.Script:=Self;
try
StringToComponent(Value,S);
finally
S.Free;
end;
end;
procedure TSIPScript.Move(Index1, Index2: Integer);
begin
if (Index1>=0) and (Index1<FObjects.Count) and (Index2>=0) and (Index2<FObjects.Count) then
FObjects.Move(Index1,Index2);
end;
procedure TSIPScript.WriteData(Writer: TWriter);
var
I: Integer;
begin
Writer.WriteListBegin;
for I := 0 to Count - 1 do Writer.WriteString(Action[I].Action);
Writer.WriteListEnd;
end;
end.
|
unit fODLabOthCollSamp;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ORCtrls, StdCtrls, ORFn, fBase508Form, VA508AccessibilityManager;
type
TfrmODLabOthCollSamp = class(TfrmBase508Form)
pnlBase: TORAutoPanel;
cboOtherCollSamp: TORComboBox;
cmdOK: TButton;
cmdCancel: TButton;
procedure cmdCancelClick(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
procedure cboOtherCollSampDblClick(Sender: TObject);
private
FOtherCollSamp: string;
end;
function SelectOtherCollSample(FontSize: Integer; Skip: integer; CollSampList: TList): string ;
implementation
{$R *.DFM}
uses fODLab, rODLab;
const
TX_NOCOLLSAMP_TEXT = 'Select a collection sample or press Cancel.';
TX_NOCOLLSAMP_CAP = 'Missing Collection Sample';
function SelectOtherCollSample(FontSize: Integer; Skip: integer; CollSampList: TList): string ;
{ displays collection sample select form for lab and returns a record of the selection }
var
frmODLabOthCollSamp: TfrmODLabOthCollSamp;
W, H, i: Integer;
x: string;
begin
frmODLabOthCollSamp := TfrmODLabOthCollSamp.Create(Application);
try
with frmODLabOthCollSamp do
begin
Font.Size := FontSize;
W := ClientWidth;
H := ClientHeight;
ResizeToFont(FontSize, W, H);
ClientWidth := W; pnlBase.Width := W;
ClientHeight := H; pnlBase.Height := H;
with CollSampList do for i := Skip to Count-1 do with TCollSamp(Items[i]) do
begin
x := IntToStr(CollSampID) + '^' + CollSampName;
if Length(TubeColor) <> 0 then x := x + ' (' + TubeColor + ')';
cboOtherCollSamp.Items.Add(x) ;
end;
ShowModal;
Result := FOtherCollSamp;
end;
finally
frmODLabOthCollSamp.Release;
end;
end;
procedure TfrmODLabOthCollSamp.cmdCancelClick(Sender: TObject);
begin
FOtherCollSamp := '-1' ;
Close;
end;
procedure TfrmODLabOthCollSamp.cmdOKClick(Sender: TObject);
begin
if cboOtherCollSamp.ItemIEN = 0 then
begin
InfoBox(TX_NOCOLLSAMP_TEXT, TX_NOCOLLSAMP_CAP, MB_OK or MB_ICONWARNING);
Exit;
end;
if cboOtherCollSamp.ItemIEN > 0 then
FOtherCollSamp := cboOtherCollSamp.Items[cboOtherCollSamp.ItemIndex]
else
FOtherCollSamp := '-1' ;
Close;
end;
procedure TfrmODLabOthCollSamp.cboOtherCollSampDblClick(Sender: TObject);
begin
cmdOKClick(Self);
end;
end.
|
unit Classe_TributacaoPIS;
interface
uses Classes, Dialogs, SysUtils, IniFiles,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
FireDAC.Stan.Intf, FireDAC.Stan.Option;
type
TPIS = class
private
FCumulativo : Boolean;
FAliquota : Real;
function getFCumulativo: Boolean;
procedure setFCumulativo(const Value: Boolean);
function getFAliquota: Real;
procedure setFAliquota(const Value: Real);
public
property Cumulativo : Boolean read getFCumulativo write setFCumulativo;
property Aliquota : Real read getFAliquota write setFAliquota;
end;
implementation
{ TPIS }
function TPIS.getFAliquota: Real;
begin
result := self.FAliquota;
end;
function TPIS.getFCumulativo: Boolean;
begin
result := self.FCumulativo;
end;
procedure TPIS.setFAliquota(const Value: Real);
begin
FAliquota := Value;
end;
procedure TPIS.setFCumulativo(const Value: Boolean);
begin
FCumulativo := Value;
end;
end.
|
unit NtUtils.Access;
interface
uses
Winapi.WinNt, NtUtils.Exceptions;
function FormatAccess(Access: TAccessMask; MaskType: PAccessMaskType): String;
function FormatAccessPrefixed(Access: TAccessMask; MaskType: PAccessMaskType)
: String;
implementation
uses
DelphiUtils.Strings, System.SysUtils;
function MapFlagRefs(Value: Cardinal; MaskType: PAccessMaskType): String;
var
Strings: array of String;
i, Count: Integer;
begin
SetLength(Strings, MaskType.Count);
Count := 0;
for i := 0 to MaskType.Count - 1 do
if Contains(Value, MaskType.Mapping{$R-}[i]{$R+}.Value) then
begin
Strings[Count] := String(MaskType.Mapping{$R-}[i]{$R+}.Name);
Inc(Count);
end;
SetLength(Strings, Count);
if Count = 0 then
Result := ''
else
Result := String.Join(', ', Strings);
end;
procedure ExcludeFlags(var Value: Cardinal; MaskType: PAccessMaskType);
var
i: Integer;
begin
for i := 0 to MaskType.Count - 1 do
Value := Value and not MaskType.Mapping{$R-}[i]{$R+}.Value;
end;
procedure ConcatFlags(var Result: String; NewFlags: String);
begin
if (Result <> '') and (NewFlags <> '') then
Result := Result + ', ' + NewFlags
else if NewFlags <> '' then
Result := NewFlags;
end;
function FormatAccess(Access: TAccessMask; MaskType: PAccessMaskType): String;
var
i: Integer;
begin
if Access = 0 then
Exit('No access');
Result := '';
if not Assigned(MaskType) then
MaskType := @NonSpecificAccessType;
// Map and exclude full access
if Contains(Access, MaskType.FullAccess) then
begin
Result := 'Full access';
Access := Access and not MaskType.FullAccess;
if Access = 0 then
Exit;
end;
// Map and exclude type-specific access
ConcatFlags(Result, MapFlagRefs(Access, MaskType));
ExcludeFlags(Access, MaskType);
if Access = 0 then
Exit;
// Map and exclude standard, generic, and other access rights
ConcatFlags(Result, MapFlagRefs(Access, @NonSpecificAccessType));
ExcludeFlags(Access, @NonSpecificAccessType);
if Access = 0 then
Exit;
// Map unknown and reserved bits as hex values
for i := 0 to 31 do
if Contains(Access, 1 shl i) then
ConcatFlags(Result, IntToHexEx(1 shl i, 6));
end;
function FormatAccessPrefixed(Access: TAccessMask; MaskType: PAccessMaskType)
: String;
begin
Result := IntToHexEx(Access, 6) + ' (' + FormatAccess(Access, MaskType) + ')';
end;
end.
|
unit Main;
interface //#################################################################### ■
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.StdCtrls, FMX.Edit, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo,
LUX;
type
TForm1 = class(TForm)
Memo1: TMemo;
Edit1: TEdit;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
GroupBox1: TGroupBox;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ private 宣言 }
_Array :TArray<Word>;
_ArrayN :Integer;
_ArrayW :Integer;
_ArrayH :Integer;
_Pattern :TArray<Word>;
_PatternN :Integer;
///// メソッド
procedure MakeArray( const ArrayW_,ArrayH_:Integer );
procedure ShowArray;
procedure MakePattern( const PatternN_:Integer );
procedure ShowPattern;
procedure HidePattern( const HideN_:Integer );
procedure ShowMatch;
public
{ public 宣言 }
_SearchBM :TSearchBM<Word>;
_MatchI :Integer;
end;
var
Form1: TForm1;
implementation //############################################################### ■
{$R *.fmx}
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
/////////////////////////////////////////////////////////////////////// メソッド
procedure TForm1.MakeArray( const ArrayW_,ArrayH_:Integer );
var
I :Integer;
begin
_ArrayW := ArrayW_;
_ArrayH := ArrayH_;
_ArrayN := _ArrayH * _ArrayW;
SetLength( _Array, _ArrayN );
for I := 0 to _ArrayN-1 do _Array[ I ] := Random( Word.MaxValue+1 );
end;
procedure TForm1.ShowArray;
var
X, Y, I :Integer;
S :String;
begin
with Memo1.Lines do
begin
Clear;
for Y := 0 to _ArrayH-1 do
begin
I := _ArrayW * Y;
S := _Array[ I ].ToHexString( 4{文字} );
for X := 1 to _ArrayW-1 do
begin
S := S + ' ' + _Array[ I+X ].ToHexString( 4{文字} );
end;
Add( S );
end;
end;
end;
//------------------------------------------------------------------------------
procedure TForm1.MakePattern( const PatternN_:Integer );
var
I :Integer;
begin
_PatternN := PatternN_;
SetLength( _Pattern, _PatternN );
for I := 0 to _PatternN-1 do _Pattern[ I ] := Random( Word.MaxValue+1 );
end;
procedure TForm1.ShowPattern;
var
S :String;
I :Integer;
begin
S := _Pattern[ 0 ].ToHexString( 4{文字} );
for I := 1 to _PatternN-1 do
begin
S := S + ' ' + _Pattern[ I ].ToHexString( 4{文字} );
end;
Edit1.Text := S;
end;
procedure TForm1.HidePattern( const HideN_:Integer );
var
N, I0, I :Integer;
begin
for N := 1 to HideN_ do
begin
I0 := Random( _ArrayN - _PatternN );
for I := 0 to _PatternN-1 do _Array[ I0 + I ] := _Pattern[ I ];
end;
end;
//------------------------------------------------------------------------------
procedure TForm1.ShowMatch;
//・・・・・・・・・・・・・・・・・・・・・・・・
function CellI( const I_:Integer ) :Integer;
var
X, Y :Integer;
begin
X := I_ mod _ArrayW;
Y := I_ div _ArrayW;
Result := ( 4{文字} * _ArrayW + _ArrayW-1 + 2{改行} ) * Y + 5{文字+空白} * X;
end;
//・・・・・・・・・・・・・・・・・・・・・・・・
begin
with Memo1 do
begin
if _MatchI < 0 then
begin
SelStart := 0;
SelLength := 0;
end
else
begin
SelStart := CellI( _MatchI );
SelLength := CellI( _MatchI + _PatternN-1 ) + 4{文字} - CellI( _MatchI );
end;
SetFocus;
Caret.Hide;
end;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
procedure TForm1.FormCreate(Sender: TObject);
begin
_SearchBM := TSearchbm<Word>.Create;
Button1Click( Sender );
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
_SearchBM.Free;
end;
//------------------------------------------------------------------------------
procedure TForm1.Button1Click(Sender: TObject);
begin
MakeArray( 16{列}, 32{行} );
MakePattern( 1 + Random( 8 ) );
ShowPattern;
_SearchBM.Pattern := _Pattern;
HidePattern( 8 ); // Pattern を Array の様々な場所へ上書きする(隠す)
ShowArray;
_MatchI := _SearchBM.Match( _Array );
ShowMatch;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
_MatchI := _SearchBM.Match( _Array, _MatchI + 1 );
ShowMatch;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
_MatchI := _SearchBM.Match( _MatchI + 1, _ArrayN,
function( const I_:Integer ) :Word
begin
Result := _Array[ I_ ];
end );
ShowMatch;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
_MatchI := _SearchBM.Match( _MatchI + 1, _ArrayN,
procedure( const HeadI_:Integer; const Buffer_:TArray<Word> )
begin
Move( _Array[ HeadI_ ], Buffer_[0], SizeOf( Word ) * _PatternN );
end );
ShowMatch;
end;
end. //######################################################################### ■
|
unit cls_TUsers;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TUsers = class
private
{ Private declarations }
userName : string ;
password : string ;
userType : string ;
public
{ Public declarations }
Constructor Create (pUserName, pPassword, pUserType : string );
Function GetUserName : string ;
Function GetPassword : string ;
Function GetUserType : string ;
Function CheckValidPassword : Boolean ;
end;
implementation
{ TUsers }
function TUsers.CheckValidPassword: Boolean;
begin
ado.Close;
ado.SQL.Text := 'SELECT ';
ado.Open ;
{ado.SQL.Text := 'SELECT COUNT(*) as [batsmanCount] FROM Batsman;';
ado.ExecSQL;
ado.Open;
NoOfBatsman := ado.FieldByName('batsmanCount').AsInteger;}
end;
constructor TUsers.Create(pUserName, pPassword, pUserType: string);
begin
pUserName := pUserType ;
pPassword := userName ;
pUserType := userType ;
end;
function TUsers.GetPassword: string;
begin
Result := password ;
end;
function TUsers.GetUserName: string;
begin
Result := userName ;
end;
function TUsers.GetUserType: string;
begin
Result := userType ;
end;
end.
|
unit NsLibSSH2SFTP;
interface
uses
Forms, Windows, Messages, SysUtils, Classes, WinSock, libssh2, libssh2_sftp,
NsLibSSH2Session, NsLibSSH2Const;
type
TFTPThread = class(TThread)
private
FOwnerHandle: HWND;
FFTPSession: PLIBSSH2_SFTP;
FFTPHandle: PLIBSSH2_SFTP_HANDLE;
FSrcFile: AnsiString;
FDestFile: AnsiString;
// Property getters/setters
function GetOwnerHandle: HWND;
procedure SetOwnerHandle(Value: HWND);
function GetFTPSession: PLIBSSH2_SFTP;
procedure SetFTPSession(Value: PLIBSSH2_SFTP);
function GetSrcFile: AnsiString;
procedure SetSrcFile(Value: AnsiString);
function GetDestFile: AnsiString;
procedure SetDestFile(Value: AnsiString);
property OwnerHandle: HWND read GetOwnerHandle write SetOwnerHandle;
property FTPSession: PLIBSSH2_SFTP read GetFTPSession write SetFTPSession;
property SrcFile: AnsiString read GetSrcFile write SetSrcFile;
property DestFile: AnsiString read GetDestFile write SetDestFile;
public
procedure StartExchange(const SourceFile, DestinationFile: string);
end;
type
TFTPGetter = class(TFTPThread)
public
procedure Execute; override;
property OwnerHandle;
property FTPSession;
property SrcFile;
property DestFile;
end;
type
TFTPPutter = class(TFTPThread)
public
procedure Execute; override;
property OwnerHandle;
property FTPSession;
property SrcFile;
property DestFile;
end;
type
TNsLibSSH2SFTP = class(TComponent)
private
FSession: TNsLibSSH2Session;
FFTPSession: PLIBSSH2_SFTP;
FFTPHandle: PLIBSSH2_SFTP_HANDLE;
FGetter: TFTPGetter;
FPutter: TFTPPutter;
FOpened: Boolean;
FStatus: string;
FGetInProgress: Boolean;
FPutInProgress: Boolean;
//Events
FAfterCreate: TNotifyEvent;
FBeforeDestroy: TNotifyEvent;
FBeforeOpen: TNotifyEvent;
FAfterOpen: TNotifyEvent;
FBeforeClose: TNotifyEvent;
FAfterClose: TNotifyEvent;
FBeforeGet: TNotifyEvent;
FAfterGet: TNotifyEvent;
FBeforePut: TNotifyEvent;
FAfterPut: TNotifyEvent;
procedure GetterEnd(Sender: TObject);
procedure PutterEnd(Sender: TObject);
// Property getters/setters
function GetSession: TNsLibSSH2Session;
procedure SetSession(Value: TNsLibSSH2Session);
function GetOpened: Boolean;
function GetStatus: string;
function GetGetInProgress: Boolean;
function GetPutInProgress: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Open: Boolean;
procedure Close;
procedure GetFile(const SourceFile, DestinationFile: AnsiString);
procedure PutFile(const SourceFile, DestinationFile: AnsiString);
published
property AfterCreate: TNotifyEvent read FAfterCreate write FAfterCreate;
property BeforeDestroy: TNotifyEvent read FBeforeDestroy write
FBeforeDestroy;
property BeforeOpen: TNotifyEvent read FBeforeOpen write FBeforeOpen;
property AfterOpen: TNotifyEvent read FAfterOpen write FAfterOpen;
property BeforeClose: TNotifyEvent read FBeforeClose write FBeforeClose;
property AfterClose: TNotifyEvent read FAfterClose write FAfterClose;
property BeforeGet: TNotifyEvent read FBeforeGet write FBeforeGet;
property AfterGet: TNotifyEvent read FAfterGet write FAfterGet;
property BeforePut: TNotifyEvent read FBeforePut write FBeforePut;
property AfterPut: TNotifyEvent read FAfterPut write FAfterPut;
property Session: TNsLibSSH2Session read GetSession write SetSession;
property Opened: Boolean read GetOpened;
property Status: string read GetStatus;
property GetInProgress: Boolean read GetGetInProgress;
property PutInProgress: Boolean read GetPutInProgress;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NeferSky', [TNsLibSSH2SFTP]);
end;
//---------------------------------------------------------------------------
{ TNsLibSSH2SFTP }
// Public
constructor TNsLibSSH2SFTP.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSession := nil;
FFTPSession := nil;
FFTPHandle := nil;
FGetInProgress := False;
FPutInProgress := False;
FPutter := nil;
FOpened := False;
FStatus := ST_DISCONNECTED;
if Assigned(AfterCreate) then
AfterCreate(Self);
end;
//---------------------------------------------------------------------------
destructor TNsLibSSH2SFTP.Destroy;
begin
if Assigned(BeforeDestroy) then
BeforeDestroy(Self);
if Opened then
Close;
inherited Destroy;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2SFTP.Open: Boolean;
var
SafeCounter: Integer;
begin
if Assigned(BeforeOpen) then
BeforeOpen(Self);
Result := False;
if FSession = nil then
begin
FStatus := ER_SESSION_UNAVAILABLE;
Exit;
end;
// Unclear why the channel is not created by the first time,
// that's why i have to make several attempts.
// I use the SafeCounter to prevent an infinite loop.
SafeCounter := 0;
repeat
Inc(SafeCounter);
FFTPSession := libssh2_sftp_init(FSession.Session);
// Just waiting. It's a kind of magic.
Sleep(1000);
until (FFTPSession <> nil) or (SafeCounter > MAX_CONNECTION_ATTEMPTS);
if (FFTPSession = nil) then
begin
FStatus := ER_FTP_OPEN;
Exit;
end;
FStatus := ST_CONNECTED;
FOpened := True;
Result := Opened;
if Assigned(AfterOpen) then
AfterOpen(Self);
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2SFTP.Close;
begin
if Assigned(BeforeClose) then
BeforeClose(Self);
if FFTPSession <> nil then
begin
libssh2_sftp_shutdown(FFTPSession);
FFTPSession := nil;
end;
FStatus := ST_DISCONNECTED;
FOpened := False;
if Assigned(AfterClose) then
AfterClose(Self);
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2SFTP.GetFile(const SourceFile, DestinationFile: string);
var
DestinationDir: string;
begin
if Assigned(BeforeGet) then
BeforeGet(Self);
if GetInProgress then
Exit;
DestinationDir := ExtractFilePath(DestinationFile);
if not DirectoryExists(DestinationDir) then
raise Exception.Create(ER_DEST_NOT_EXISTS);
FGetInProgress := True;
FGetter := TFTPGetter.Create(True);
FGetter.OnTerminate := GetterEnd;
FGetter.FTPSession := FFTPSession;
FGetter.StartExchange(SourceFile, DestinationFile);
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2SFTP.PutFile(const SourceFile, DestinationFile: string);
begin
if Assigned(BeforePut) then
BeforePut(Self);
if PutInProgress then
Exit;
FPutInProgress := True;
FPutter := TFTPPutter.Create(True);
FPutter.OnTerminate := PutterEnd;
FPutter.FTPSession := FFTPSession;
FPutter.StartExchange(SourceFile, DestinationFile);
end;
//---------------------------------------------------------------------------
// Private
procedure TNsLibSSH2SFTP.GetterEnd(Sender: TObject);
begin
FGetInProgress := False;
if Assigned(AfterGet) then
AfterGet(Self);
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2SFTP.PutterEnd(Sender: TObject);
begin
FPutInProgress := False;
if Assigned(AfterPut) then
AfterPut(Self);
end;
//---------------------------------------------------------------------------
function TNsLibSSH2SFTP.GetGetInProgress: Boolean;
begin
Result := FGetInProgress;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2SFTP.GetOpened: Boolean;
begin
Result := FOpened;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2SFTP.GetPutInProgress: Boolean;
begin
Result := FPutInProgress;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2SFTP.GetSession: TNsLibSSH2Session;
begin
Result := FSession;
end;
//---------------------------------------------------------------------------
function TNsLibSSH2SFTP.GetStatus: string;
begin
Result := FStatus;
end;
//---------------------------------------------------------------------------
procedure TNsLibSSH2SFTP.SetSession(Value: TNsLibSSH2Session);
begin
if FSession <> Value then
FSession := Value;
end;
//---------------------------------------------------------------------------
{ TFTPGetter }
procedure TFTPGetter.Execute;
var
Buffer: array[1..1024] of Char;
BytesReaded: Integer;
TargetFile: file;
SafeCounter: Integer;
begin
// Unclear why the channel is not created by the first time,
// that's why i have to make several attempts.
// I use the SafeCounter to prevent an infinite loop.
SafeCounter := 0;
repeat
Inc(SafeCounter);
FFTPHandle := libssh2_sftp_open(FFTPSession, PAnsiChar(FSrcFile),
LIBSSH2_FXF_READ, 0);
// Just waiting. It's a kind of magic.
Sleep(1000);
until (FFTPHandle <> nil) or (SafeCounter > MAX_CONNECTION_ATTEMPTS);
if (FFTPHandle = nil) then
Terminate;
AssignFile(TargetFile, FDestFile);
ReWrite(TargetFile, 1);
repeat
begin
FillChar(Buffer, SizeOf(Buffer), #0);
SafeCounter := 0;
repeat
Inc(SafeCounter);
BytesReaded := libssh2_sftp_read(FFTPHandle, @Buffer, SizeOf(Buffer));
// Just waiting. It's a kind of magic.
if BytesReaded < 0 then
Sleep(100);
until (BytesReaded <> LIBSSH2_ERROR_EAGAIN) or (SafeCounter >
MAX_CONNECTION_ATTEMPTS);
if (BytesReaded > 0) then
BlockWrite(TargetFile, Buffer, BytesReaded)
else
Break;
end;
until Terminated;
CloseFile(TargetFile);
libssh2_sftp_close(FFTPHandle);
FFTPHandle := nil;
end;
//---------------------------------------------------------------------------
{ TFTPPutter }
procedure TFTPPutter.Execute;
var
Buffer: array[1..1024] of Char;
BytesReaded, BytesWritten: Integer;
TargetFile: file;
SafeCounter: Integer;
procedure AnalyseSendingResult;
begin
if BytesWritten < BytesReaded then
begin
if (BytesWritten <> LIBSSH2_ERROR_EAGAIN) then
BytesReaded := BytesReaded - BytesWritten
else
begin
Inc(SafeCounter);
Sleep(100);
end;
end;
end;
begin
// Unclear why the channel is not created by the first time,
// that's why i have to make several attempts.
// I use the SafeCounter to prevent an infinite loop.
SafeCounter := 0;
repeat
Inc(SafeCounter);
FFTPHandle := libssh2_sftp_open(FFTPSession, PAnsiChar(FDestFile),
(LIBSSH2_FXF_WRITE or LIBSSH2_FXF_CREAT or LIBSSH2_FXF_TRUNC),
(LIBSSH2_SFTP_S_IRUSR or LIBSSH2_SFTP_S_IWUSR or LIBSSH2_SFTP_S_IRGRP or
LIBSSH2_SFTP_S_IROTH));
// Just waiting. It's a kind of magic.
Sleep(1000);
until (FFTPHandle <> nil) or (SafeCounter > MAX_CONNECTION_ATTEMPTS);
if (FFTPHandle = nil) then
Terminate;
AssignFile(TargetFile, FSrcFile);
ReSet(TargetFile, 1);
BytesReaded := 0;
repeat
begin
FillChar(Buffer, SizeOf(Buffer), #0);
BlockRead(TargetFile, Buffer, SizeOf(Buffer), BytesReaded);
if (BytesReaded > 0) then
begin
SafeCounter := 1;
repeat
BytesWritten := libssh2_sftp_write(FFTPHandle, @Buffer, BytesReaded);
AnalyseSendingResult;
until (BytesWritten = BytesReaded) or (SafeCounter >
MAX_CONNECTION_ATTEMPTS);
end;
end;
until (BytesReaded < 1) or Terminated;
CloseFile(TargetFile);
libssh2_sftp_close(FFTPHandle);
end;
//---------------------------------------------------------------------------
{ TFTPThread }
procedure TFTPThread.StartExchange(const SourceFile, DestinationFile: string);
begin
SrcFile := SourceFile;
DestFile := DestinationFile;
Resume;
end;
//---------------------------------------------------------------------------
function TFTPThread.GetDestFile: AnsiString;
begin
Result := FDestFile;
end;
//---------------------------------------------------------------------------
function TFTPThread.GetFTPSession: PLIBSSH2_SFTP;
begin
Result := FFTPSession;
end;
//---------------------------------------------------------------------------
function TFTPThread.GetOwnerHandle: HWND;
begin
Result := FOwnerHandle;
end;
//---------------------------------------------------------------------------
function TFTPThread.GetSrcFile: AnsiString;
begin
Result := FSrcFile;
end;
//---------------------------------------------------------------------------
procedure TFTPThread.SetDestFile(Value: AnsiString);
begin
if FDestFile <> Value then
FDestFile := Value;
end;
//---------------------------------------------------------------------------
procedure TFTPThread.SetFTPSession(Value: PLIBSSH2_SFTP);
begin
if FFTPSession <> Value then
FFTPSession := Value;
end;
//---------------------------------------------------------------------------
procedure TFTPThread.SetOwnerHandle(Value: HWND);
begin
if FOwnerHandle <> Value then
FOwnerHandle := Value;
end;
//---------------------------------------------------------------------------
procedure TFTPThread.SetSrcFile(Value: AnsiString);
begin
if FSrcFile <> Value then
FSrcFile := Value;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC SQLite metadata }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.SQLiteMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator;
type
TFDPhysSQLiteBrand = (sbSQLite, sbBDB);
IFDPhysSQLiteConnectionMetadata = interface (IUnknown)
['{91D454A4-327D-4ED2-8EF5-3F77BFB5B619}']
// private
function GetBrand: TFDPhysSQLiteBrand;
// public
property Brand: TFDPhysSQLiteBrand read GetBrand;
end;
TFDPhysSQLiteMetadata = class (TFDPhysConnectionMetadata, IFDPhysSQLiteConnectionMetadata)
private
FBrand: TFDPhysSQLiteBrand;
FColumnOriginProvided: Boolean;
protected
// IFDPhysConnectionMetadata
function GetKind: TFDRDBMSKind; override;
function GetTxSavepoints: Boolean; override;
function GetEventSupported: Boolean; override;
function GetEventKinds: String; override;
function GetParamNameMaxLength: Integer; override;
function GetNameParts: TFDPhysNameParts; override;
function GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; override;
function GetNameQuotedCaseSensParts: TFDPhysNameParts; override;
function GetNameQuotedCaseSens(const AName: String; APart: TFDPhysNamePart): Boolean; override;
function GetNameCaseSensParts: TFDPhysNameParts; override;
function GetNameDefLowCaseParts: TFDPhysNameParts; override;
function GetIdentityInsertSupported: Boolean; override;
function GetNamedParamMark: TFDPhysParamMark; override;
function GetPositionedParamMark: TFDPhysParamMark; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function GetAsyncAbortSupported: Boolean; override;
function GetArrayExecMode: TFDPhysArrayExecMode; override;
function GetLimitOptions: TFDPhysLimitOptions; override;
function GetDefValuesSupported: TFDPhysDefaultValues; override;
function GetColumnOriginProvided: Boolean; override;
function GetInlineRefresh: Boolean; override;
function GetTruncateSupported: Boolean; override;
function GetCreateTableOptions: TFDPhysCreateTableOptions; override;
function InternalEscapeBoolean(const AStr: String): String; override;
function InternalEscapeDate(const AStr: String): String; override;
function InternalEscapeDateTime(const AStr: String): String; override;
function InternalEscapeFloat(const AStr: String): String; override;
function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override;
function InternalEscapeTime(const AStr: String): String; override;
function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
// IFDPhysSQLiteConnectionMetadata
function GetBrand: TFDPhysSQLiteBrand;
public
constructor Create(const AConnection: TFDPhysConnection;
ABrand: TFDPhysSQLiteBrand; AServerVersion, AClientVersion: TFDVersion;
AIsUnicode, AColumnOriginProvided: Boolean);
end;
TFDPhysSQLiteCommandGenerator = class(TFDPhysCommandGenerator)
protected
function GetIdentity(ASessionScope: Boolean): String; override;
function GetRowId(var AAlias: String): String; override;
function GetReadGenerator(const AName, AAlias: String;
ANextValue, AFullSelect: Boolean): String; override;
function GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String; override;
function GetCommitSavepoint(const AName: String): String; override;
function GetRollbackToSavepoint(const AName: String): String; override;
function GetSavepoint(const AName: String): String; override;
function GetCall(const AName: String): String; override;
function GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String; override;
function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer;
var AOptions: TFDPhysLimitOptions): String; override;
function GetColumnType(AColumn: TFDDatSColumn): String; override;
function GetMerge(AAction: TFDPhysMergeAction): String; override;
end;
implementation
uses
System.SysUtils,
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Error;
{-------------------------------------------------------------------------------}
{ TFDPhysSQLiteMetadata }
{-------------------------------------------------------------------------------}
constructor TFDPhysSQLiteMetadata.Create(const AConnection: TFDPhysConnection;
ABrand: TFDPhysSQLiteBrand; AServerVersion, AClientVersion: TFDVersion;
AIsUnicode, AColumnOriginProvided: Boolean);
begin
inherited Create(AConnection, AServerVersion, AClientVersion, AIsUnicode);
FBrand := ABrand;
FColumnOriginProvided := AColumnOriginProvided;
FKeywords.CommaText :=
'ABORT,ADD,AFTER,ALL,ALTER,ANALYZE,AND,AS,ASC,ATTACH,AUTOINCREMENT,BEFORE,' +
'BEGIN,BETWEEN,BY,CASCADE,CASE,CAST,CHECK,COLLATE,COLUMN,COMMIT,CONFLICT,' +
'CONSTRAINT,CREATE,CROSS,CURRENT_DATE,CURRENT_TIME,CURRENT_TIMESTAMP,DATABASE,' +
'DEFAULT,DEFERRABLE,DEFERRED,DELETE,DESC,DETACH,DISTINCT,DROP,EACH,ELSE,END,' +
'ESCAPE,EXCEPT,EXCLUSIVE,EXISTS,EXPLAIN,FAIL,FOR,FOREIGN,FROM,FULL,GLOB,GROUP,' +
'HAVING,IF,IGNORE,IMMEDIATE,IN,INDEX,INITIALLY,INNER,INSERT,INSTEAD,INTERSECT,' +
'INTO,IS,ISNULL,JOIN,KEY,LEFT,LIKE,LIMIT,MATCH,NATURAL,NOT,NOTNULL,NULL,OF,' +
'OFFSET,ON,OR,ORDER,OUTER,PLAN,PRAGMA,PRIMARY,QUERY,RAISE,REFERENCES,REGEXP,' +
'REINDEX,RENAME,REPLACE,RESTRICT,RIGHT,ROLLBACK,ROW,SELECT,SET,TABLE,TEMP,' +
'TEMPORARY,THEN,TO,TRANSACTION,TRIGGER,UNION,UNIQUE,UPDATE,USING,VACUUM,' +
'VALUES,VIEW,VIRTUAL,WHEN,WHERE';
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.SQLite;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetNameCaseSensParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetParamNameMaxLength: Integer;
begin
Result := MAXINT;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetNameParts: TFDPhysNameParts;
begin
Result := [npCatalog, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel;
ASide: TFDPhysNameQuoteSide): Char;
begin
Result := ' ';
case AQuote of
ncDefault:
Result := '"';
ncSecond:
if ASide = nsLeft then
Result := '['
else
Result := ']';
ncThird:
Result := '`';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetNameQuotedCaseSens(const AName: String;
APart: TFDPhysNamePart): Boolean;
var
i: Integer;
begin
Result := False;
for i := 1 to Length(AName) do
if not FDInSet(AName[i], ['a' .. 'z', 'A' .. 'Z', '0' .. '9',
'_', '$', '#', '"', '[', ']', '`']) then begin
Result := True;
Break;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetNamedParamMark: TFDPhysParamMark;
begin
Result := prName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetPositionedParamMark: TFDPhysParamMark;
begin
Result := prQNumber;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetTxSavepoints: Boolean;
begin
Result := GetServerVersion >= svSQLite030608;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetEventSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetEventKinds: String;
begin
Result := S_FD_EventKind_SQLite_Events;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetTruncateSupported: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetInlineRefresh: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
Result := [soWithoutFrom, soInlineView];
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysSQLiteMetadata.GetAsyncAbortSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
Result := dvDefVals;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetColumnOriginProvided: Boolean;
begin
Result := FColumnOriginProvided;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetIdentityInsertSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetArrayExecMode: TFDPhysArrayExecMode;
begin
if GetServerVersion >= svSQLite030711 then
Result := aeOnErrorUndoAll
else
Result := aeUpToFirstError;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetLimitOptions: TFDPhysLimitOptions;
begin
Result := [loSkip, loRows];
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetCreateTableOptions: TFDPhysCreateTableOptions;
begin
Result := [ctDefaultFirst, ctNoAlterTableConstraint];
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.GetBrand: TFDPhysSQLiteBrand;
begin
Result := FBrand;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.InternalEscapeBoolean(const AStr: String): String;
begin
if CompareText(AStr, S_FD_True) = 0 then
Result := '1'
else
Result := '0';
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.InternalEscapeDate(const AStr: String): String;
begin
Result := AnsiQuotedStr(AStr, '''');
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
Result := AnsiQuotedStr(AStr, '''');
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.InternalEscapeTime(const AStr: String): String;
begin
Result := AnsiQuotedStr(AStr, '''');
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.InternalEscapeFloat(const AStr: String): String;
begin
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS REAL)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String;
var
sName, A1, A2, A3: String;
i: Integer;
function AddArgs: string;
begin
Result := '(';
if Length(ASeq.FArgs) > 0 then
Result := Result + AddEscapeSequenceArgs(ASeq);
Result := Result + ')';
end;
function Unquote(const AValue: String): String;
begin
Result := Trim(AValue);
if Result[1] = '''' then
Result := Copy(Result, 2, Length(Result) - 2);
end;
begin
sName := ASeq.FName;
if Length(ASeq.FArgs) >= 1 then begin
A1 := ASeq.FArgs[0];
if Length(ASeq.FArgs) >= 2 then begin
A2 := ASeq.FArgs[1];
if Length(ASeq.FArgs) >= 3 then
A3 := ASeq.FArgs[2];
end;
end;
case ASeq.FFunc of
// numeric
efRANDOM:
begin
Result := '(ABS(RANDOM()) / 9223372036854775807)';
if Length(ASeq.FArgs) = 1 then
Result := '(' + Result + ' * (' + A1 + '))';
end;
efDEGREES,
efRADIANS,
efTRUNCATE,
efLOG,
efROUND,
efABS,
efACOS,
efASIN,
efATAN,
efATAN2,
efCEILING,
efCOS,
efCOT,
efEXP,
efFLOOR,
efLOG10,
efMOD,
efPI,
efPOWER,
efSIGN,
efSIN,
efSQRT,
efTAN: Result := sName + AddArgs;
// character
efBIT_LENGTH: Result := '(OCTET_LENGTH(' + A1 + ') * 8)';
efASCII,
efCHAR,
efCONCAT,
efLCASE,
efLENGTH,
efLOCATE,
efPOSITION,
efLTRIM,
efREPEAT,
efRTRIM,
efSPACE,
efUCASE,
efCHAR_LENGTH,
efOCTET_LENGTH,
efREPLACE,
efSUBSTRING: Result := sName + AddArgs;
// See comment in FireDAC.Phys.SQLiteWrapper, TSQLiteExpressionFunction.Create
efINSERT,
efLEFT,
efRIGHT: Result := sName + '_' + AddArgs;
// system
efCATALOG: Result := '''MAIN''';
efSCHEMA: Result := '''''';
efIFNULL: Result := 'CASE WHEN ' + A1 + ' IS NULL THEN ' + A2 + ' ELSE ' + A1 + ' END';
efIF: Result := 'CASE WHEN ' + A1 + ' THEN ' + A2 + ' ELSE ' + A3 + ' END';
efDECODE:
begin
Result := 'CASE ' + ASeq.FArgs[0];
i := 1;
while i < Length(ASeq.FArgs) - 1 do begin
Result := Result + ' WHEN ' + ASeq.FArgs[i] + ' THEN ' + ASeq.FArgs[i + 1];
Inc(i, 2);
end;
if i = Length(ASeq.FArgs) - 1 then
Result := Result + ' ELSE ' + ASeq.FArgs[i];
Result := Result + ' END';
end;
// convert
efCONVERT:
begin
A2 := UpperCase(Trim(A2));
if A2 = 'DATE' then
Result := 'DATE(' + A1 + ')'
else if A2 = 'TIME' then
Result := 'TIME(' + A1 + ')'
else if (A2 = 'DATETIME') or (A2 = 'TIMESTAMP') then
Result := 'DATETIME(' + A1 + ')'
else
Result := 'CAST(' + A1 + ' AS ' + A2 + ')';
end;
// date and time
efCURDATE: Result := 'DATE(''NOW'')';
efCURTIME: Result := 'TIME(''NOW'')';
efNOW: Result := 'DATETIME(''NOW'')';
efDAYNAME:
begin
Result := 'CASE STRFTIME(''%w'', ' + A1 + ')';
for i := 1 to 7 do
Result := Result + ' WHEN ''' + IntToStr(i mod 7) + ''' THEN ''' +
AnsiUpperCase(FormatSettings.LongDayNames[i mod 7 + 1]) + '''';
Result := Result + ' END';
end;
efDAYOFMONTH: Result := 'CAST(STRFTIME(''%d'', ' + A1 + ') AS INT)';
efDAYOFWEEK: Result := '(STRFTIME(''%w'', ' + A1 + ') + 1)';
efDAYOFYEAR: Result := 'CAST(STRFTIME(''%j'', ' + A1 + ') AS INT)';
efHOUR: Result := 'CAST(STRFTIME(''%H'', ' + A1 + ') AS INT)';
efMINUTE: Result := 'CAST(STRFTIME(''%M'', ' + A1 + ') AS INT)';
efMONTH: Result := 'CAST(STRFTIME(''%m'', ' + A1 + ') AS INT)';
efMONTHNAME:
begin
Result := 'CASE STRFTIME(''%m'', ' + A1 + ')';
for i := 1 to 12 do
Result := Result + ' WHEN ''' + Format('%.2d', [i]) + ''' THEN ''' +
AnsiUpperCase(FormatSettings.LongMonthNames[i]) + '''';
Result := Result + ' END';
end;
efSECOND: Result := 'CAST(STRFTIME(''%S'', ' + A1 + ') AS INT)';
efWEEK: Result := '(STRFTIME(''%W'', ' + A1 + ') + 1)';
efYEAR: Result := 'CAST(STRFTIME(''%Y'', ' + A1 + ') AS INT)';
efEXTRACT,
efQUARTER,
efTIMESTAMPADD,
efTIMESTAMPDIFF:
Result := sName + AddArgs;
else
UnsupportedEscape(ASeq);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteMetadata.InternalGetSQLCommandKind(
const ATokens: TStrings): TFDPhysCommandKind;
var
sToken: String;
begin
sToken := ATokens[0];
if sToken = 'BEGIN' then
Result := skStartTransaction
else if sToken = 'END' then
Result := skCommit
else if sToken = 'EXPLAIN' then
Result := skSelect
else if sToken = 'REPLACE' then
Result := skMerge
else if sToken = 'UPDATE' then
if ATokens.Count < 3 then
Result := skNotResolved
else if (ATokens[1] = 'OR') and (ATokens[2] = 'INSERT') then
Result := skMerge
else
Result := skUpdate
else if sToken = 'INSERT' then
if (ATokens.Count = 1) or
(ATokens.Count = 2) and (ATokens[1] = 'OR') then
Result := skNotResolved
else if (ATokens.Count = 3) and (ATokens[1] = 'OR') and (ATokens[2] = 'UPDATE') then
Result := skMerge
else
Result := skInsert
else if sToken = 'VALUES' then
Result := skSelect
else
Result := inherited InternalGetSQLCommandKind(ATokens);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysSQLiteCommandGenerator }
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetIdentity(ASessionScope: Boolean): String;
begin
// LAST_INSERT_AUTOGEN is a custom function registered by FireDAC.Phys.SQLiteWrapper.
// It returns last auto-inc value from a target dataset in LocalSQL mode, otherwise
// redirects to LAST_INSERT_ROWID.
Result := 'LAST_INSERT_AUTOGEN()';
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetRowId(var AAlias: String): String;
begin
Result := 'ROWID';
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetReadGenerator(const AName,
AAlias: String; ANextValue, AFullSelect: Boolean): String;
begin
if ANextValue or (AName <> '') and not AFullSelect then
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
if AName = '' then
Result := inherited GetReadGenerator(AName, AAlias, ANextValue, AFullSelect)
else begin
Result := 'SELECT seq ';
if AAlias <> '' then
Result := Result + ' AS ' + AAlias;
Result := Result + ' FROM sqlite_sequence WHERE name = ''' + AName + '''';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String;
begin
Result := GenerateSelect(False);
if Result <> '' then
Result := AStmt + ';' + BRK + Result
else
Result := AStmt;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetCall(const AName: String): String;
begin
Result := 'SELECT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetSavepoint(const AName: String): String;
begin
Result := 'SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetCommitSavepoint(const AName: String): String;
begin
Result := 'RELEASE SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetRollbackToSavepoint(const AName: String): String;
begin
Result := 'ROLLBACK TO SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String;
var
lWasWhere: Boolean;
sCat, sDatabase, sWhere, sScope: String;
procedure AddWhere(const ACond: String);
begin
if lWasWhere then
Result := Result + ' AND ' + ACond
else begin
Result := Result + ' WHERE ' + ACond;
lWasWhere := True;
end;
end;
begin
if (ACatalog <> '') and (CompareText(ACatalog, 'MAIN') <> 0) then begin
sCat := ACatalog + '.';
sDatabase := ACatalog;
end
else begin
sCat := '';
sDatabase := 'MAIN';
end;
lWasWhere := False;
Result := '';
case AKind of
mkCatalogs:
Result := 'PRAGMA database_list';
mkSchemas:
;
mkTables:
begin
if CompareText(ACatalog, 'TEMP') = 0 then
sCat := '';
Result := 'SELECT NULL AS RECNO, ''' + sDatabase + ''' AS CATALOG_NAME, ' +
'NULL AS SCHEMA_NAME, tbl_name AS TABLE_NAME, ' +
'CASE type ' +
'WHEN ''table'' THEN ' +
'CASE tmp '+
'WHEN 0 THEN ' + IntToStr(Integer(tkTable)) +
' ELSE ' + IntToStr(Integer(tkTempTable)) +
' END ' +
'WHEN ''view'' THEN ' + IntToStr(Integer(tkView)) +
' END AS TABLE_TYPE, ' +
'CASE ' +
'WHEN instr(tbl_name, ''sqlite_'')=1 THEN ' + IntToStr(Integer(osSystem)) +
' ELSE ' + IntToStr(Integer(osMy)) +
' END AS TABLE_SCOPE ' +
'FROM (' +
'SELECT t1.*, 0 AS tmp FROM ' + sCat + 'sqlite_master t1 ' +
'UNION ALL ' +
'SELECT t2.*, 1 AS tmp FROM sqlite_temp_master t2 ' +
'UNION ALL ' +
'SELECT ''table'', ''sqlite_master'', ''sqlite_master'', 0, null, 0 ' +
'UNION ALL ' +
'SELECT ''table'', ''sqlite_temp_master'', ''sqlite_temp_master'', 0, null, 1 ' +
')';
sWhere := '';
if CompareText(ACatalog, 'TEMP') = 0 then
AddWhere('tmp = 1');
if tkTable in ATableKinds then
sWhere := sWhere + ' OR type = ''table'' AND tmp = 0';
if tkTempTable in ATableKinds then
sWhere := sWhere + ' OR type = ''table'' AND tmp = 1';
if tkView in ATableKinds then
sWhere := sWhere + ' OR type = ''view''';
if ([tkSynonym, tkLocalTable] * ATableKinds <> []) or
(ATableKinds = []) then
sWhere := sWhere + ' OR 0 = 1';
AddWhere('(' + Copy(sWhere, 5, MAXINT) + ')');
if AObjectScopes * [osMy, osSystem] <> [osMy, osSystem] then begin
sScope := '';
if osMy in AObjectScopes then
sScope := 'instr(tbl_name, ''sqlite_'')=0 OR ';
if osSystem in AObjectScopes then
sScope := 'instr(tbl_name, ''sqlite_'')=1 OR ';
if sScope <> '' then
AddWhere('(' + Copy(sScope, 1, Length(sScope) - 4) + ')');
end;
if AWildcard <> '' then
AddWhere('tbl_name LIKE ''' + AWildcard + '''');
Result := Result + ' ORDER BY UPPER(tbl_name)';
end;
mkTableFields,
mkPrimaryKey:
Result := 'PRAGMA ' + sCat + 'table_info("' + AObject + '")';
mkPrimaryKeyFields:
Result := 'PRAGMA ' + sCat + 'table_info("' + ABaseObject + '")';
mkIndexes:
Result := 'PRAGMA ' + sCat + 'index_list("' + AObject + '")';
mkIndexFields:
if FConnMeta.ServerVersion >= svSQLite030809 then
Result := 'PRAGMA ' + sCat + 'index_xinfo("' + AObject + '")'
else
Result := 'PRAGMA ' + sCat + 'index_info("' + AObject + '")';
mkForeignKeys:
Result := 'PRAGMA ' + sCat + 'foreign_key_list("' + AObject + '")';
mkForeignKeyFields:
Result := 'PRAGMA ' + sCat + 'foreign_key_list("' + ABaseObject + '")';
mkPackages,
mkProcs,
mkProcArgs,
mkGenerators,
mkResultSetFields,
mkTableTypeFields:
;
else
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetLimitSelect(const ASQL: String;
ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String;
begin
if (ASkip > 0) and (ARows + ASkip <> MAXINT) then
Result := ASQL + BRK + 'LIMIT ' + IntToStr(ARows) + ' OFFSET ' + IntToStr(ASkip)
else if ASkip > 0 then
Result := ASQL + BRK + 'LIMIT -1 OFFSET ' + IntToStr(ASkip)
else if ARows >= 0 then
Result := ASQL + BRK + 'LIMIT ' + IntToStr(ARows)
else begin
Result := ASQL;
AOptions := [];
end;
end;
{-------------------------------------------------------------------------------}
// http://docwiki.embarcadero.com/RADStudio/en/Using_SQLite_with_FireDAC#Mapping_SQLite_to_FireDAC_Data_Types
function TFDPhysSQLiteCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String;
begin
if (caAutoInc in AColumn.ActualAttributes) and
((AColumn.DataType in [dtSByte, dtInt16, dtInt32, dtInt64, dtByte, dtUInt16, dtUInt32, dtUInt64]) or
(AColumn.DataType in [dtBCD, dtFmtBCD, dtSingle, dtDouble, dtExtended]) and (AColumn.Scale = 0)) then begin
// SQLite auto-incrementing column must be INTEGER PRIMARY KEY.
// Otherwise syntax error is returned. Here PRIMARY KEY is optimistic,
// but in most cases will work.
Result := 'INTEGER PRIMARY KEY AUTOINCREMENT';
Exit;
end;
case AColumn.DataType of
dtBoolean:
Result := 'BOOLEAN';
dtSByte:
Result := 'TINYINT';
dtInt16:
Result := 'SMALLINT';
dtInt32:
Result := 'INTEGER';
dtInt64:
Result := 'BIGINT';
dtByte:
Result := 'TINYINT UNSIGNED';
dtUInt16:
Result := 'SMALLINT UNSIGNED';
dtUInt32:
Result := 'INTEGER UNSIGNED';
dtUInt64:
Result := 'BIGINT UNSIGNED';
dtSingle:
Result := 'SINGLE';
dtDouble,
dtExtended:
Result := 'DOUBLE';
dtCurrency:
Result := 'MONEY';
dtBCD,
dtFmtBCD:
Result := 'NUMERIC' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1,
FOptions.FormatOptions.MaxBcdPrecision, 0);
dtDateTime:
Result := 'DATETIME';
dtTime:
Result := 'TIME';
dtDate:
Result := 'DATE';
dtDateTimeStamp:
Result := 'TIMESTAMP';
dtAnsiString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'CHAR'
else
Result := 'VARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtWideString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'NCHAR'
else
Result := 'NVARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtByteString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'BINARY'
else
Result := 'VARBINARY';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtBlob,
dtHBlob,
dtHBFile:
Result := 'BLOB';
dtMemo,
dtHMemo:
Result := 'MEMO';
dtWideMemo,
dtWideHMemo:
Result := 'TEXT';
dtXML:
Result := 'XML';
dtGUID:
Result := 'GUID';
dtUnknown,
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef,
dtParentRowRef,
dtObject:
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysSQLiteCommandGenerator.GetMerge(AAction: TFDPhysMergeAction): String;
begin
Result := '';
case AAction of
maInsertUpdate: Result := 'INSERT OR REPLACE INTO ' + GetFrom + BRK + GetInsert('');
maInsertIgnore: Result := 'INSERT OR IGNORE INTO ' + GetFrom + BRK + GetInsert('');
end;
end;
{-------------------------------------------------------------------------------}
initialization
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.SQLite, S_FD_SQLite_RDBMS);
end.
|
unit OriIniFile;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Classes, IniFiles;
type
TOriIniFile = class(TIniFile)
private
FSection: String;
FFormat: TFormatSettings;
public
constructor Create; reintroduce;
destructor Destroy; override;
property Section: String read FSection write FSection;
procedure WriteString(const Key, Value: String); overload;
procedure WriteInteger(const Key: string; Value: Longint); overload;
procedure WriteBool(const Key: string; Value: Boolean); overload;
procedure WriteFloat(const Key: string; Value: Extended); overload;
procedure WriteDate(const Key: string; Value: TDateTime); overload;
procedure WriteTime(const Key: string; Value: TDateTime); overload;
procedure WriteDateTime(const Key: string; Value: TDateTime); overload;
function ReadString(const Key, Value: String): String; overload;
function ReadInteger(const Key: string; Value: Longint): Longint; overload;
function ReadBool(const Key: string; Value: Boolean): Boolean; overload;
function ReadFloat(const Key: string; Value: Extended): Extended; overload;
function ReadDate(const Key: string; Value: TDateTime): TDateTime; overload;
function ReadTime(const Key: string; Value: TDateTime): TDateTime; overload;
function ReadDateTime(const Key: string; Value: TDateTime): TDateTime; overload;
procedure Init;
procedure UpdateFile; override;
end;
{ Pointer to a function returning path to application ini-file.
It is used by TOriIniFile when its constructor is called without parameters.
The GetIniFileName function is used by default.
}
var GetIniName: function(): String;
{ The flag defines if application is portable. Portable application stores all
its settings, templates and various user-specific infomation near the program
executable file. So application must have write access to a folder where it
is located. Non-portable (normal) application stores its settings in user
profile catalog (~/.config/appname/ on Linux, $(APPDATA)\appname\ on Windows).
}
var IsPortable: Boolean;
const CMainSection = 'PREFERENCES';
implementation
uses
FileUtil, Math;
{%region Ini File Location}
var IniFileName: String;
function GetLocalIniFileName: String;
begin
Result := ChangeFileExt(ParamStrUTF8(0), '.cfg');
end;
function GetIniFileName: String;
begin
if IniFileName = '' then
begin
if IsPortable then
IniFileName := GetLocalIniFileName
else
begin
// Windows: c:\Users\<user name>\AppData\Local\spectrum\spectrum.cfg
IniFileName := GetAppConfigFileUTF8(False, {$ifdef WINDOWS}False{$else}True{$endif});
end;
end;
Result := IniFileName;
end;
{%endregion}
{%region TOriIniFile}
constructor TOriIniFile.Create;
begin
FSection := CMainSection;
if Assigned(GetIniName)
then inherited Create(GetIniName())
else inherited Create(GetIniFileName);
Init;
end;
destructor TOriIniFile.Destroy;
begin
if Dirty then UpdateFile;
inherited;
end;
procedure TOriIniFile.Init;
begin
FFormat.DecimalSeparator := '.';
FFormat.DateSeparator := '.';
FFormat.TimeSeparator := ':';
FFormat.ShortDateFormat := 'dd.mm.yyyy';
FFormat.ShortTimeFormat := 'hh:nn';
FFormat.LongDateFormat := 'dd mmmm yyyy';
FFormat.LongTimeFormat := 'hh:nn:ss.zzzz';
CaseSensitive := True;
CacheUpdates := True;
end;
procedure TOriIniFile.UpdateFile;
var
Dir: String;
begin
if not Dirty then Exit;
Dir := TrimFilename(ExtractFilePath(FileName));
if not DirectoryExistsUTF8(Dir) then
if not CreateDirUTF8(Dir) then
raise Exception.CreateFmt('Unable to create directory "%s"', [Dir]);
inherited;
end;
{%region Common Types}
procedure TOriIniFile.WriteString(const Key, Value: String);
begin
WriteString(FSection, Key, Value);
end;
function TOriIniFile.ReadString(const Key, Value: String): String;
begin
Result := ReadString(FSection, Key, Value);
end;
procedure TOriIniFile.WriteInteger(const Key: string; Value: Longint);
begin
WriteInteger(FSection, Key, Value);
end;
function TOriIniFile.ReadInteger(const Key: string; Value: Longint): Longint;
begin
Result := ReadInteger(FSection, Key, Value);
end;
procedure TOriIniFile.WriteBool(const Key: string; Value: Boolean);
begin
WriteBool(FSection, Key, Value);
end;
function TOriIniFile.ReadBool(const Key: string; Value: Boolean): Boolean;
begin
Result := ReadBool(FSection, Key, Value);
end;
procedure TOriIniFile.WriteFloat(const Key: string; Value: Extended);
begin
WriteString(FSection, Key, FloatToStr(Value, FFormat));
end;
function TOriIniFile.ReadFloat(const Key: string; Value: Extended): Extended;
var S: String;
begin
S := UpperCase(Trim(ReadString(FSection, Key, '')));
if S = 'INF' then
Result := Infinity
else if S = '-INF' then
Result := -Infinity
else
Result := StrToFloatDef(S, Value, FFormat);
end;
{%endregion}
{%region Date and Time}
procedure TOriIniFile.WriteDate(const Key: string; Value: TDateTime);
begin
WriteString(FSection, Key, DateToStr(Value, FFormat));
end;
procedure TOriIniFile.WriteTime(const Key: string; Value: TDateTime);
begin
WriteString(FSection, Key, TimeToStr(Value, FFormat));
end;
procedure TOriIniFile.WriteDateTime(const Key: string; Value: TDateTime);
begin
WriteString(FSection, Key, DateTimeToStr(Value, FFormat));
end;
function TOriIniFile.ReadDate(const Key: string; Value: TDateTime): TDateTime;
begin
if not TryStrToDate(ReadString(FSection, Key, ''), Result, FFormat) then Result := Value;
end;
function TOriIniFile.ReadTime(const Key: string; Value: TDateTime): TDateTime;
begin
if not TryStrToTime(ReadString(FSection, Key, ''), Result, FFormat) then Result := Value;
end;
function TOriIniFile.ReadDateTime(const Key: string; Value: TDateTime): TDateTime;
begin
if not TryStrToDateTime(ReadString(FSection, Key, ''), Result, FFormat) then Result := Value;
end;
{%endregion}
{%endregion}
initialization
GetIniName := @GetIniFileName;
IsPortable := FileExistsUTF8(GetLocalIniFileName);
end.
|
(* SynTreeUnit: Rittberger, 2020-04-25 *)
(* ------ *)
(* Unit for the Tree Procedures & for Syntax analisys *)
(* ========================================================================= *)
UNIT SynTreeUnit;
INTERFACE
TYPE
kanTree = POINTER;
PROCEDURE NewTree(VAR t: kanTree);
PROCEDURE DisposeTree(VAR t: kanTree);
PROCEDURE WriteTree(t: kanTree);
PROCEDURE S(VAR t: kanTree);
PROCEDURE WriteT(t: kanTree);
VAR
line: STRING;
IMPLEMENTATION
TYPE
NodePtr= ^Node;
Node = RECORD
firstChild, sibling: NodePtr;
val: STRING; (* nonterminal, operator or operand as string*)
END;(*Node*)
TreePtr= NodePtr;
//Tree actions
PROCEDURE NewTree(VAR t: kanTree);
BEGIN (* NewStrMSet *)
TreePtr(t) := NIL;
END; (* NewStrMSet *)
PROCEDURE DisposeTree(VAR t: kanTree);
BEGIN (* DisposeStrMSet *)
IF (TreePtr(t) <> NIL) THEN BEGIN
DisposeTree(TreePtr(t)^.firstChild);
DisposeTree(TreePtr(t)^.sibling);
Dispose(TreePtr(t));
TreePtr(t) := NIL;
END; (* IF *)
END; (* DisposeStrMSet *)
FUNCTION NewNode(content: STRING): TreePtr;
VAR
n: TreePtr;
BEGIN (* NewNode *)
New(n);
n^.val := content;
n^.firstChild := NIL;
n^.sibling := NIL;
NewNode := n;
END; (* NewNode *)
PROCEDURE WriteT(t: kanTree);
BEGIN
Write(TreePtr(t)^.sibling^.val);
END;
PROCEDURE WriteTree(t: kanTree);
BEGIN (* WriteTree *)
IF (TreePtr(t) <> NIL) THEN BEGIN
Write(TreePtr(t)^.val, ' ');
WriteTree(TreePtr(t)^.firstChild);
WriteTree(TreePtr(t)^.sibling);
END; (* IF *)
END; (* WriteTree *)
//--end Tree actions
//analysis
CONST
EOS = Chr(0);
TYPE
SymbolCode = (
eosSy, noSy, //eos .... end of string
plusSy, minusSy,
timesSy, divSy, //timesSy = *
leftParSy, rightParSy,
number);
VAR
ch: CHAR;
cnr: INTEGER;
sy: SymbolCode;
success: BOOLEAN;
numberVal: STRING;
(* ---- SCANNER ----*)
PROCEDURE NewCh;
BEGIN (* NewCh *)
IF (cnr < Length(line)) THEN BEGIN
Inc(cnr);
ch := line[cnr];
END ELSE BEGIN
ch := EOS;
END; (* IF *)
END; (* NewCh *)
PROCEDURE NewSy;
BEGIN (* NewSy *)
CASE ch OF
EOS: BEGIN
sy := eosSy;
END;
'+': BEGIN
sy := plusSy;
NewCh;
END;
'-': BEGIN
sy := minusSy;
NewCh;
END;
'*': BEGIN
sy := timesSy;
NewCh;
END;
'/': BEGIN
sy := divSy;
NewCh;
END;
'(': BEGIN
sy := leftParSy;
NewCh;
END;
')': BEGIN
sy := rightParSy;
NewCh;
END;
'0'..'9': BEGIN
sy := number;
numberVal := ch;
NewCh;
WHILE ((ch >= '0') AND ( ch <= '9')) DO BEGIN
numberVal := numberVal + ch;
NewCh;
END; (* WHILE *)
//Write(numberVal, ' ');
END;
ELSE
sy := noSy; //hängt davon ab was ich danach mache
END; (* CASE *)
END; (* NewSy *)
(* ---- Parser ----*)
//forward declaration
PROCEDURE Expr(VAR t: TreePtr); FORWARD;
PROCEDURE Term(VAR i: TreePtr); FORWARD;
PROCEDURE Fact(VAR f: TreePtr); FORWARD;
PROCEDURE S(VAR t: kanTree);
BEGIN (* S *)
NewCh;
NewSy;
t := NewNode('Expr');
Expr(TreePtr(t));
IF NOT success THEN Exit;
IF sy <> eosSy THEN BEGIN
success := FALSE;
Write(success);
Exit;
END;
END; (* S *)
PROCEDURE Expr(VAR t: TreePtr);
VAR
i: TreePtr;
BEGIN (* Expr *)
i := t;
i^.firstChild := NewNode('Term');
Term(i^.firstChild);
IF NOT success THEN Exit;
WHILE (sy = plusSy) OR (sy = minusSy) DO BEGIN
CASE sy OF
plusSy: BEGIN
//sem
t := t^.firstChild^.sibling;
t := NewNode('+');
Write('#', t^.val);
t := t^.sibling;
//--end sem
NewSy;
t := NewNode('Term');
Term(t); IF NOT success THEN Exit;
END;
minusSy: BEGIN
//sem
t := t^.firstChild^.sibling;
t := NewNode('-');
t := t^.sibling;
//--end sem
NewSy;
t := NewNode('Term');
Term(t); IF NOT success THEN Exit;
END;
END; (*CASE*)
END; (*WHILE*)
END; (* Expr *)
PROCEDURE Term(VAR i: TreePtr);
VAR
e: TreePtr;
BEGIN (* Term *)
e := i;
e^.firstChild := NewNode('Fact');
Fact(e^.firstChild);
IF NOT success THEN Exit;
WHILE (sy = timesSy) OR (sy = divSy) DO BEGIN
CASE sy OF
timesSy: BEGIN
//sem
i := i^.sibling;
i := NewNode('*');
i := i^.sibling;
i := NewNode('Term');
//--end sem
NewSy;
i^.firstChild := NewNode('Fact');
Fact(i); IF NOT success THEN Exit;
END;
divSy: BEGIN
//sem
i := i^.sibling;
i := NewNode('/');
i := i^.sibling;
//--end sem
NewSy;
i^.firstChild := NewNode('Fact');
Fact(i); IF NOT success THEN Exit;
END;
END; (*CASE*)
END; (*WHILE*)
END; (* Term *)
PROCEDURE Fact(VAR f: TreePtr);
BEGIN (* Fact *)
CASE sy OF
number: BEGIN
//NewSy;
//sem
f^.firstChild := NewNode(numberVal);
numberVal := '';
//--end sem
NewSy;
END;
leftParSy: BEGIN
NewSy;
f := NewNode('Expr');
Expr(f);
IF NOT success THEN Exit;
IF sy <> rightParSy THEN BEGIN success := FALSE;
Exit;
END;
NewSy;
END;
ELSE BEGIN
success := FALSE;
END;
END; (*CASE*)
END; (* Fact *)
//--end analysis
BEGIN (* SynTreeUnit *)
END. (* SynTreeUnit *)
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{ *************************************************************************** }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit Web.WebFileDispatcher;
{$IF SizeOf(LongInt) = 8}
{$DEFINE LONGINT64}
{$ENDIF}
interface
uses System.Classes, System.SysUtils, System.Masks, System.Generics.Collections;
type
TWebFileExtensions = class;
TWebDirectories = class;
TWebFileDispatcherProperties = class;
TDispatchFileRequest = class
private
FProperties: TWebFileDispatcherProperties;
function QualifyFileName(AFileName: string): string;
function IsDispatchFileName(const APathInfo: string): Boolean;
function GetDispatchFileName(const APathInfo: string; out AFileName: string): Boolean;
function CanDispatchFileName(const AFileName: string): Boolean;
function IsIncludeDirectory(const ADirectory: string): Boolean;
function SetResponse(const AFileName: string): Boolean;
function GetMimeType(const FileName: string): string;
procedure UpdateExtensionMimeType;
function FixupPath(const APath: string; out AIgnorePath: Boolean): string;
protected
function GetApplicationPath: string; virtual;
function IsGetRequest: Boolean; virtual; abstract;
function IsHeadRequest: Boolean; virtual; abstract;
procedure SetErrorCode(AStatusCode: Integer); virtual; abstract;
function GetIfModifiedSince: TDateTime; virtual; abstract;
procedure SetContentStream(AStream: TStream); virtual; abstract;
procedure SetContentLength(ALength: Integer); virtual; abstract;
procedure SetContentType(const AValue: string); virtual; abstract;
procedure SetLastModified(AValue: TDateTime); virtual; abstract;
function GetExceptionClass: TClass; virtual; abstract;
procedure DoBeforeDispatch(const AFileName: string; var AHandled: Boolean); virtual; abstract;
procedure DoAfterDispatch(const AFileName: string; var AHandled: Boolean); virtual; abstract;
function GetRequestPathInfo: string; virtual; abstract;
function GetResponseSent: Boolean; virtual; abstract;
public
constructor Create(AProperties: TWebFileDispatcherProperties);
destructor Destroy; override;
function DispatchFileRequest: Boolean;
end;
TWebFileDispatcherProperties = class(TComponent)
private
FRootDirectory: string;
FVirtualPath: string;
FExtensionMimeType: TDictionary<string, string>;
FWebFileExtensions: TWebFileExtensions;
FWebDirectories: TWebDirectories;
FDefaultFile: string;
procedure SetWebFileExtension(const Value: TWebFileExtensions);
procedure SetWebDirectories(const Value: TWebDirectories);
function GetRootDirectory: string;
function GetVirtualPath: string;
procedure SetVirtualPath(const Value: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property RootDirectory: string read GetRootDirectory write FRootDirectory;
property WebFileExtensions: TWebFileExtensions read FWebFileExtensions write SetWebFileExtension;
property WebDirectories: TWebDirectories read FWebDirectories write SetWebDirectories;
/// <summary>URL path to files. For example, if VirtualPath = 'myfiles' the following URL would be used to
/// access the file ./index.html: http://localhost:8080/myfiles/index.html.</summary>
property VirtualPath: string read GetVirtualPath write SetVirtualPath;
/// <summary>File name to dispatch automatically. For example, if DefaultFile = 'index.html', then
/// response will be content of index.html when browsing to the root directory.
/// </summary>
property DefaultFile: string read FDefaultFile write FDefaultFile;
end;
TWebFileExtensionItem = class(TCollectionItem)
private
FExtensions : String;
FMimeType : String;
procedure SetMimeType(const Value: String);
procedure SetExtensions(const Value: String);
function GetComponentState: TComponentState;
property ComponentState: TComponentState read GetComponentState;
protected
function GetDisplayName: string; override;
public
constructor Create(AOwner: TCollection; const AMimeType, AExtensions: string); reintroduce;
published
property MimeType : String read FMimeType write SetMimeType;
property Extensions : String read FExtensions write SetExtensions;
end;
TWebFileExtensions = class(TCollection)
private
FOwner: TComponent;
procedure SetDefaultExtensions;
protected
function GetItem(Index: Integer) : TWebFileExtensionItem;
procedure SetItem(Index: Integer; const Value: TWebFileExtensionItem );
function GetAttrCount: Integer; override;
function GetAttr(Index: Integer): string; override;
function GetItemAttr(Index, ItemIndex: Integer): string; override;
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TComponent);
function Add: TWebFileExtensionItem;
property Items[Index: Integer]: TWebFileExtensionItem read GetItem
write SetItem; default;
end;
TWebDirectoryAction = (dirInclude, dirExclude);
TWebDirectoryItem = class(TCollectionItem)
private
FDirectoryAction : TWebDirectoryAction;
FDirectoryMask : string;
FMask: TMask;
procedure UpdateMask;
procedure SetDirectoryMask(const Value: String);
protected
function GetDisplayName: string; override;
public
constructor Create(AOwner: TCollection; ADirectoryAction: TWebDirectoryAction; const ADirectoryMask: string); reintroduce;
destructor Destroy; override;
published
property DirectoryAction: TWebDirectoryAction read FDirectoryAction write FDirectoryAction;
property DirectoryMask : String read FDirectoryMask write SetDirectoryMask;
end;
TWebDirectories = class(TCollection)
private
FOwner: TComponent;
procedure SetDefaultDirectories;
protected
function GetItem(Index: Integer) : TWebDirectoryItem;
procedure SetItem(Index: Integer; const Value: TWebDirectoryItem );
function GetAttrCount: Integer; override;
function GetAttr(Index: Integer): string; override;
function GetItemAttr(Index, ItemIndex: Integer): string; override;
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TComponent);
function Add: TWebDirectoryItem;
property Items[Index: Integer]: TWebDirectoryItem read GetItem
write SetItem; default;
end;
TLookupMimeType = function(const AExtensions: string): string;
TLookupExtensions = function(const AMimeType: string): string;
TExtensionMethod = reference to function(AExt: PChar; ALength: Integer): Boolean;
function EnumerateExtensions(const Extensions: string; WithDot: Boolean; Method: TExtensionMethod): Boolean;
var
FLookupMimeType: TLookupMimeType;
FLookupExtensions: TLookupExtensions;
implementation
uses System.DateUtils, System.StrUtils, Web.WebConst, System.IOUtils, Web.HTTPApp;
type
TSkipPreambleStream = class(TStream)
private
FEncodingLength: Integer;
FStream: TStream;
protected
function GetSize: Int64; override;
{$IF not defined(LONGINT64)}
procedure SetSize(NewSize: Longint); overload; override;
{$ENDIF !LONGINT64}
procedure SetSize(const NewSize: Int64); overload; override;
public
constructor Create(AStream: TStream; AEncodingLength: Integer);
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
{$IF not defined(LONGINT64)}
function Seek(Offset: Longint; Origin: Word): Longint; overload; override;
{$ENDIF !LONGINT64}
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; overload; override;
end;
function EnumerateExtensions(const Extensions: string; WithDot: Boolean; Method: TExtensionMethod): Boolean;
var
I, J: Integer;
Ext: array[0..255] of Char;
begin
I := Low(Extensions);
while I <= High(Extensions) do
begin
if WithDot then
begin
Ext[0] := '.';
J := 1;
end
else
J := 0;
while (I <= High(Extensions)) and (Extensions[I] <> ';') do
begin
if Extensions[I] <> ' ' then
begin
Ext[J] := Extensions[I];
Inc(J);
end;
Inc(I);
end;
Ext[J] := #0;
if not Method(Ext, J) then
Exit(False);
Inc(I);
end;
Result := True;
end;
function TDispatchFileRequest.IsIncludeDirectory(const ADirectory: string): Boolean;
var
I: Integer;
LItem: TWebDirectoryItem;
begin
if FProperties.FWebDirectories.Count = 0 then
Exit(False);
Result := False;
for I := 0 to FProperties.FWebDirectories.Count - 1 do
begin
LItem := FProperties.FWebDirectories[I];
LItem.UpdateMask;
if LItem.FMask <> nil then
begin
case LItem.FDirectoryAction of
dirInclude:
if LItem.FMask.Matches(ADirectory) then
Result := True;
dirExclude:
if LItem.FMask.Matches(ADirectory) then
Result := False;
end;
end;
end;
end;
function TDispatchFileRequest.CanDispatchFileName(
const AFileName: string): Boolean;
begin
Result := IsIncludeDirectory(ExtractFilePath(AFileName));
end;
constructor TDispatchFileRequest.Create(AProperties: TWebFileDispatcherProperties);
begin
FProperties := AProperties;
end;
destructor TDispatchFileRequest.Destroy;
begin
inherited Destroy;
end;
function TDispatchFileRequest.GetApplicationPath: string;
var
LModuleName: string;
begin
LModuleName := GetModuleName(MainInstance);
// UNC issue in Vista.
if Pos('\\?\', LModuleName) = 1 then
Delete(LModuleName, 1, 4);
Result := ExtractFilePath(LModuleName);
end;
function TDispatchFileRequest.QualifyFileName(AFileName: string): string;
var
LRootDirectory: string;
begin
LRootDirectory := IncludeTrailingPathDelimiter(FProperties.FRootDirectory);
if TPath.IsDriveRooted(LRootDirectory) or TPath.IsUNCPath(LRootDirectory) then //Drive and UNC
Result := LRootDirectory + AFileName
else if TPath.IsRelativePath(LRootDirectory) then //Relative
Result := GetApplicationPath + LRootDirectory + AFileName
else
Result := ExtractFileDrive(GetApplicationPath) + LRootDirectory + AFileName;
// Absolute path
Result := ExpandFileName(Result);
end;
function TDispatchFileRequest.GetMimeType(const FileName: string): string;
begin
UpdateExtensionMimeType;
if not FProperties.FExtensionMimeType.TryGetValue(Lowercase(ExtractFileExt(FileName)), Result) then
Result := 'application/octet-stream';
end;
function TDispatchFileRequest.SetResponse(const AFileName: string): Boolean;
var
LStream: TStream;
LFileAge: TDateTime;
LIfModifiedSince: TDateTime;
LMimeType: string;
LBytes: TBytes;
LEncodingLength: Integer;
LEncoding: TEncoding;
begin
if not FileExists(AFileName) then
begin
SetErrorCode(404);
Exit(True);
end;
LIfModifiedSince := GetIfModifiedSince;
if LIfModifiedSince <> -1 then
begin
LIfModifiedSince := TTimeZone.Local.ToLocalTime(GetIfModifiedSince);
FileAge(AFileName, LFileAge);
if Abs(LFileAge - LIfModifiedSince) < OneSecond then
begin
LMimeType := GetMimeType(AFileName);
SetContentType(LMimeType);
SetErrorCode(304);
Exit(True);
end;
end;
LStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
LMimeType := GetMimeType(AFileName);
if System.StrUtils.StartsText('text/', Lowercase(LMimeType)) then
begin
SetLength(LBytes, Length(TEncoding.UTF8.GetPreamble));
// Detect UTF-8 encoding, remove BOM and set content type
if LStream.Read(LBytes[0], Length(LBytes)) = Length(LBytes) then
begin
LEncoding := nil;
LEncodingLength := TEncoding.GetBufferEncoding(LBytes, LEncoding, TEncoding.ANSI);
if (LEncodingLength > 0) and (LEncoding = TEncoding.UTF8) then
begin
if Pos('charset', Lowercase(LMimeType)) <= 0 then // Do not localize
LMimeType := LMimeType + '; charset=utf-8'; // Do not localize
LStream.Position := 0;
LStream := TSkipPreambleStream.Create(LStream, LEncodingLength);
end;
end
end;
LStream.Position := 0;
try
if IsGetRequest then
begin
SetContentStream(LStream);
LStream := nil;
end
else
SetContentLength(LStream.Size);
FileAge(AFileName, LFileAge);
SetLastModified(TTimeZone.Local.ToUniversalTime(LFileAge));
SetContentType(LMimeType);
finally
LStream.Free;
end;
Result := True;
end;
function TDispatchFileRequest.FixupPath(const APath: string; out AIgnorePath: Boolean): string;
var
LPath: string;
LChanged: Boolean;
LIgnorePath: Boolean;
begin
Assert(FProperties.VirtualPath <> '');
Assert((FProperties.VirtualPath = '/') or not FProperties.VirtualPath.EndsWith('/'));
LIgnorePath := False;
LChanged := False;
LPath := APath;
if (LPath = '') or (LPath.Chars[0] <> '/') then
LPath := LPath.Insert(0, '/');
// Handle VirtualPath
if FProperties.VirtualPath <> '/' then
begin
if LPath.StartsWith(FProperties.VirtualPath, True) then // Ignore case
begin
LPath := LPath.Substring(Length(FProperties.VirtualPath));
if (LPath = '') or (LPath.Chars[0] <> '/') then // Leave '/'
LPath := LPath.Insert(0, '/');
LChanged := True;
end
else
LIgnorePath := True;
end;
// Handle DefaultFile
if (not LIgnorePath) and (LPath = '/') and (FProperties.DefaultFile <> '') then
begin
LPath := '/' + FProperties.DefaultFile;
LChanged := True;
end;
AIgnorePath := LIgnorePath;
if (not LIgnorePath) and LChanged then
Result := LPath
else
Result := APath;
end;
function TDispatchFileRequest.DispatchFileRequest: Boolean;
var
LFileName: string;
LPathInfo: string;
LIgnorePath: Boolean;
begin
Result := False;
LPathInfo := GetRequestPathInfo;
LPathInfo := FixupPath(LPathInfo, LIgnorePath);
if (not LIgnorePath) and (IsHeadRequest or IsGetRequest) and IsDispatchFileName(LPathInfo) then
begin
if GetDispatchFileName(LPathInfo, LFileName) and
CanDispatchFileName(LFileName) then
begin
LFileName := QualifyFileName(LFileName);
DoBeforeDispatch(LFileName, Result);
if not Result then
begin
Result := SetResponse(LFileName);
end;
if Result and not GetResponseSent then
DoAfterDispatch(LFileName, Result);
end;
end;
end;
function TDispatchFileRequest.GetDispatchFileName(
const APathInfo: string; out AFileName: string): Boolean;
begin
Result := True;
if PathDelim <> '/' then
AFileName := StringReplace(APathInfo, '/', PathDelim, [rfReplaceAll])
else
AFileName := APathInfo;
end;
procedure TDispatchFileRequest.UpdateExtensionMimeType;
var
LItem: TWebFileExtensionItem;
LLookupMimeType: string;
I: Integer;
LException: Exception;
begin
if FProperties.FExtensionMimeType = nil then
begin
FProperties.FExtensionMimeType := TDictionary<string, string>.Create;
for I := 0 to FProperties.FWebFileExtensions.Count - 1 do
begin
LItem := FProperties.FWebFileExtensions[I];
EnumerateExtensions(Lowercase(LItem.Extensions), True,
function(AExt: PChar; ALength: Integer): Boolean
begin
Result := True;
if FProperties.FExtensionMimeType.TryGetValue(AExt, LLookupMimeType) then
begin
if LLookupMimeType <> Lowercase(LItem.MimeType) then
begin
LException := Exception(GetExceptionClass.Create);
LException.Message := Format(sDuplicateMimeTypes, [AExt]);
raise LException;
end;
end
else
FProperties.FExtensionMimeType.Add(AExt, Lowercase(LItem.MimeType));
end
);
end;
end;
end;
function TDispatchFileRequest.IsDispatchFileName(
const APathInfo: string): Boolean;
begin
UpdateExtensionMimeType;
Result := FProperties.FExtensionMimeType.ContainsKey(Lowercase(ExtractFileExt(APathInfo)));
end;
{ TWebFileExtensionItem }
constructor TWebFileExtensionItem.Create(AOwner: TCollection; const AMimeType, AExtensions: string);
begin
inherited Create(AOwner);
FExtensions := AExtensions;
FMimeType := AMimeType;
end;
function TWebFileExtensionItem.GetComponentState: TComponentState;
begin
if Collection.Owner is TComponent then
Result := TComponent(Collection.Owner).ComponentState
else
Result := [];
end;
function TWebFileExtensionItem.GetDisplayName: string;
begin
Result := Format(sWebFileExtensionsItemDisplayName,
[FMimeType, FExtensions]);
end;
procedure TWebFileExtensionItem.SetMimeType(const Value: String);
var
LLookup: string;
LLast: string;
begin
LLast := FMimeType;
FMimeType := Value;
if (not (csLoading in ComponentState)) and
(csDesigning in ComponentState) then
begin
if Assigned(FLookupExtensions) and Assigned(FLookupMimeType) then
LLookup := FLookupExtensions(FMimeType);
if LLookup <> '' then
if (FExtensions = '') or SameText(FLookupMimeType(FExtensions), LLast) then
FExtensions := LLookup;
end;
end;
procedure TWebFileExtensionItem.SetExtensions(const Value: String);
var
LLookup: string;
LLast: string;
begin
LLast := FExtensions;
FExtensions := Value;
if (not (csLoading in ComponentState)) and
(csDesigning in ComponentState) then
begin
if Assigned(FLookupExtensions) and Assigned(FLookupMimeType) then
LLookup := FLookupMimeType(FExtensions);
if LLookup <> '' then
if (FMimeType = '') or SameText(FLookupMimeType(LLast), FMimeType) then
FMimeType := LLookup;
end;
end;
{ TWebFileExtensions }
function TWebFileExtensions.Add: TWebFileExtensionItem;
begin
Result := TWebFileExtensionItem(inherited Add);
end;
constructor TWebFileExtensions.Create(AOwner: TComponent);
begin
FOwner := AOwner;
inherited Create(TWebFileExtensionItem);
SetDefaultExtensions;
end;
procedure TWebFileExtensions.SetDefaultExtensions;
begin
TWebFileExtensionItem.Create(Self, 'text/css', 'css');
TWebFileExtensionItem.Create(Self, 'text/html', 'html;htm');
TWebFileExtensionItem.Create(Self, 'application/javascript', 'js');
TWebFileExtensionItem.Create(Self, 'image/jpeg', 'jpeg;jpg');
TWebFileExtensionItem.Create(Self, 'image/png', 'png');
end;
function TWebFileExtensions.GetItem(Index: Integer): TWebFileExtensionItem;
begin
Result := TWebFileExtensionItem(inherited GetItem(Index));
end;
procedure TWebFileExtensions.SetItem(Index: Integer;
const Value: TWebFileExtensionItem);
begin
inherited SetItem(Index,Value);
end;
function TWebFileExtensions.GetAttrCount: Integer;
begin
Result := 2;
end;
function TWebFileExtensions.GetAttr(Index: Integer): string;
begin
case Index of
0: Result := sWebFileExtensionItemExtensions;
1: Result := sWebFileExtensionItemMimeType;
else
Result := '';
end;
end;
function TWebFileExtensions.GetItemAttr(Index, ItemIndex: Integer): string;
begin
case Index of
0: Result := Items[ItemIndex].Extensions;
1: Result := Items[ItemIndex].MimeType;
else
Result := '';
end;
end;
function TWebFileExtensions.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{ TWebDirectoryItem }
constructor TWebDirectoryItem.Create(AOwner: TCollection; ADirectoryAction: TWebDirectoryAction; const ADirectoryMask: string);
begin
inherited Create(AOwner);
FDirectoryAction := ADirectoryAction;
FDirectoryMask := ADirectoryMask;
end;
destructor TWebDirectoryItem.Destroy;
begin
FMask.Free;
inherited;
end;
function TWebDirectoryItem.GetDisplayName: string;
var
LDirectoryAction: string;
begin
case FDirectoryAction of
dirInclude: LDirectoryAction := sWebDirectoryInclude;
dirExclude: LDirectoryAction := sWebDirectoryInclude;
end;
Result := Format(sWebDirectoryItemDisplayName,
[LDirectoryAction, FDirectoryMask]);
end;
procedure TWebDirectoryItem.SetDirectoryMask(const Value: String);
begin
if Value <> FDirectoryMask then
begin
FDirectoryMask := Value;
FreeAndNil(FMask);
end;
end;
procedure TWebDirectoryItem.UpdateMask;
var
S: string;
begin
if FMask = nil then
begin
S := Trim(FDirectoryMask);
if S <> '' then
begin
if S[Low(string)] <> PathDelim then
// Force leading path delimiter
S := PathDelim + S;
FMask := TMask.Create(S);
end;
end;
end;
{ TWebDirectories }
function TWebDirectories.Add: TWebDirectoryItem;
begin
Result := TWebDirectoryItem(inherited Add);
end;
constructor TWebDirectories.Create(AOwner: TComponent);
begin
FOwner := AOwner;
inherited Create(TWebDirectoryItem);
SetDefaultDirectories;
end;
procedure TWebDirectories.SetDefaultDirectories;
begin
TWebDirectoryItem.Create(Self, TWebDirectoryAction.dirInclude, '*');
TWebDirectoryItem.Create(Self, TWebDirectoryAction.dirExclude, '\templates\*');
end;
function TWebDirectories.GetItem(Index: Integer): TWebDirectoryItem;
begin
Result := TWebDirectoryItem(inherited GetItem(Index));
end;
procedure TWebDirectories.SetItem(Index: Integer;
const Value: TWebDirectoryItem);
begin
inherited SetItem(Index,Value);
end;
function TWebDirectories.GetAttrCount: Integer;
begin
Result := 2;
end;
function TWebDirectories.GetAttr(Index: Integer): string;
begin
case Index of
0: Result := sWebFileDirectoryItemAction;
1: Result := sWebFileDirectoryItemMask;
else
Result := '';
end;
end;
function TWebDirectories.GetItemAttr(Index, ItemIndex: Integer): string;
begin
case Index of
0:
case Items[ItemIndex].DirectoryAction of
dirInclude: Result := 'Include';
dirExclude: Result := 'Exclude';
end;
1: Result := Items[ItemIndex].DirectoryMask;
else
Result := '';
end;
end;
function TWebDirectories.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{ TWebFileDispatcherProperties }
constructor TWebFileDispatcherProperties.Create(AOwner: TComponent);
begin
inherited;
FWebFileExtensions := TWebFileExtensions.Create(AOwner);
FWebDirectories := TWebDirectories.Create(AOwner);
end;
destructor TWebFileDispatcherProperties.Destroy;
begin
inherited Destroy;
FWebFileExtensions.Free;
FWebDirectories.Free;
FExtensionMimeType.Free;
end;
function TWebFileDispatcherProperties.GetRootDirectory: string;
begin
if Trim(FRootDirectory) = '' then
Result := '.'
else
Result := FRootDirectory;
end;
function TWebFileDispatcherProperties.GetVirtualPath: string;
begin
if Trim(FVirtualPath) = '' then
Result := '/'
else
Result := FVirtualPath;
end;
procedure TWebFileDispatcherProperties.SetWebFileExtension(
const Value: TWebFileExtensions);
begin
FWebFileExtensions.Assign(Value);
end;
procedure TWebFileDispatcherProperties.SetVirtualPath(const Value: string);
var
LPath: string;
begin
LPath := Trim(Value);
if LPath <> '' then LPath := DosPathToUnixPath(LPath);
if LPath = '/' then
LPath := ''
else
begin
// Normalize path
if (LPath <> '') and (LPath.Chars[0] <> '/') then Insert('/', LPath, 1);
if Length(LPath) > 1 then
LPath := LPath.TrimRight(['/']);
end;
FVirtualPath := LPath;
end;
procedure TWebFileDispatcherProperties.SetWebDirectories(
const Value: TWebDirectories);
begin
FWebDirectories.Assign(Value);
end;
{ TSkipPreambleStream }
constructor TSkipPreambleStream.Create(AStream: TStream;
AEncodingLength: Integer);
begin
FStream := AStream;
FStream.Position := AEncodingLength;
FEncodingLength := AEncodingLength;
end;
destructor TSkipPreambleStream.Destroy;
begin
FStream.Free;
inherited;
end;
function TSkipPreambleStream.GetSize: Int64;
begin
Result := FStream.Size - FEncodingLength;
end;
function TSkipPreambleStream.Read(var Buffer; Count: LongInt): Longint;
begin
Result := FStream.Read(Buffer, Count);
end;
{$IF not defined(LONGINT64)}
function TSkipPreambleStream.Seek(Offset: Integer; Origin: Word): Longint;
begin
if Origin = soFromBeginning then
Result := FStream.Seek(Offset + FEncodingLength, Origin) - FEncodingLength
else
Result := FStream.Seek(Offset, Origin) - FEncodingLength
end;
{$ENDIF !LONGINT64}
function TSkipPreambleStream.Seek(const Offset: Int64;
Origin: TSeekOrigin): Int64;
begin
if Origin = TSeekOrigin.soBeginning then
Result := FStream.Seek(Offset + FEncodingLength, Origin) - FEncodingLength
else
Result := FStream.Seek(Offset, Origin) - FEncodingLength
end;
{$IF not defined(LONGINT64)}
procedure TSkipPreambleStream.SetSize(NewSize: LongInt);
begin
FStream.Size := NewSize;
end;
{$ENDIF LONGINT64}
procedure TSkipPreambleStream.SetSize(const NewSize: Int64);
begin
FStream.Size := NewSize;
end;
{$IF defined(LONGINT64)}
function TSkipPreambleStream.Write(const Buffer; Count: LongInt): LongInt;
{$ELSE !LONGINT64}
function TSkipPreambleStream.Write(const Buffer; Count: Integer): Longint;
{$ENDIF !LONGINT64}
begin
Result := FStream.Write(Buffer, Count);
end;
end.
|
{ Sample Program # 12, Source: FractalForest.pas, Date: 04.05.2011 0:14:38
Copyright (C) 2011 ViPetroFF ViktorPetroFF@mail.ru
This source is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option)
any later version.
This code is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
A copy of the GNU General Public License is available on the World Wide Web
at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing
to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA.
}
unit FractalForest;
{$mode objfpc}{$H+}
interface
{Uses WinGraph Unit v1.1 (03-2010) - http://math.ubbcluj.ro/~sberinde/wingraph}
uses
WinGraph, FractalTree;
type
THardwoodTreeA=class(TTree)
private
protected
procedure DrawTrunk(rLength, rPhi : Real; wLevel : Word=0); override;
procedure DrawLeave(rLength, rPhi : Real; wLevel : Word=0); override;
procedure DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word=0); override;
public
constructor Create(lx, ly, lHigh : LongInt);
procedure Dump; override;
end;
THardwoodTreeB=class(TTree)
private
protected
procedure DrawTrunk(rLength, rPhi : Real; wLevel : Word=0); override;
procedure DrawLeave(rLength, rPhi : Real; wLevel : Word=0); override;
procedure DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word=0); override;
public
constructor Create(lx, ly, lHigh : LongInt);
procedure Dump; override;
end;
TAtomicTreeA=class(TTree)
private
protected
procedure DrawTrunk(rLength, rPhi : Real; wLevel : Word=0); override;
procedure DrawLeave(rLength, rPhi : Real; wLevel : Word=0); override;
procedure DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word=0); override;
public
constructor Create(lx, ly, lHigh : LongInt);
procedure Dump; override;
end;
TAtomicTreeB=class(TAtomicTreeA)
private
protected
procedure DrawTrunk(rLength, rPhi : Real; wLevel : Word=0); override;
procedure DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word=0); override;
public
procedure Dump; override;
end;
TConiferousTreeA=class(TTree)
private
protected
procedure DrawTrunk(rLength, rPhi : Real; wLevel : Word=0); override;
procedure DrawLeave(rLength, rPhi : Real; wLevel : Word=0); override;
procedure DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word=0); override;
public
constructor Create(lx, ly, lHigh : LongInt);
procedure Dump; override;
end;
TConiferousTreeB=class(TConiferousTreeA)
private
protected
procedure DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word=0); override;
public
procedure Dump; override;
end;
implementation
procedure THardwoodTreeA.DrawTrunk(rLength, rPhi : Real; wLevel : Word);
var rThickness : Real; color : LongWord; infoLn : LineSettingsType;
begin
color:=GetColor; GetLineSettings(infoLn);
rThickness:=4*High*MaxLevel; rThickness:=rThickness/(100.0*Succ(wLevel));
SetColor(SaddleBrown); SetLineStyle(SolidLn, 0, Round(rThickness));
LineRel(Round(rLength*cos(rPhi)), -Round(rLength*sin(rPhi)));
SetColor(color); SetLineStyle(infoLn.linestyle, infoLn.pattern, infoLn.thickness);
end;
procedure THardwoodTreeA.DrawLeave(rLength, rPhi : Real; wLevel : Word);
var
wR : Word;
srcX, srcY : SmallInt;
color : LongWord;
rR : Real;
fill : FillSettingsType;
begin
color:=GetColor; GetFillSettings(fill);
rR:=4*High*MaxLevel; rR:=rR/(100.0*Succ(wLevel));
if rR < 2.0 then rR:=2.0;
SetColor(DarkGreen); SetFillStyle(SolidFill, ForestGreen);
wR:=Round(rR);
srcX:=GetX+Round(rLength*cos(rPhi));
srcY:=GetY-Round(rLength*sin(rPhi));
FillEllipse(srcX, srcY, 2*wR, wR);
SetColor(color); SetFillStyle(fill.pattern, fill.color);
end;
procedure THardwoodTreeA.DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word);
var fromX, fromY : SmallInt; rNewLength : Real;
begin
fromX:=GetX; fromY:=GetY;
DrawTwig(rLength, rPhi, wLevel);
if wLevel < MaxLevel then
begin
rNewLength:=rLength/Succ(wLevel)*0.78;
fromX:=fromX+Round((rLength-rNewLength)*cos(rPhi));
fromY:=fromY-Round((rLength-rNewLength)*sin(rPhi));
MoveTo(fromX, fromY); DrawLeaveFractal(rNewLength, rPhi+Pi/8, Succ(wLevel));
MoveTo(fromX, fromY); DrawLeaveFractal(rNewLength, rPhi-Pi/8, Succ(wLevel));
end;
end;
constructor THardwoodTreeA.Create(lx, ly, lHigh : LongInt);
begin
inherited Create(lx, ly, lHigh, 3);
end;
procedure THardwoodTreeA.Dump;
begin
WriteLn('THardwoodTreeA.Dump');
end;
procedure THardwoodTreeB.DrawTrunk(rLength, rPhi : Real; wLevel : Word);
var rThickness : Real; color : LongWord; infoLn : LineSettingsType;
begin
color:=GetColor; GetLineSettings(infoLn);
rThickness:=rLength*0.12;
SetColor(SaddleBrown); SetLineStyle(SolidLn, 0, Round(rThickness));
LineRel(Round(rLength*cos(rPhi)), -Round(rLength*sin(rPhi)));
SetColor(color); SetLineStyle(infoLn.linestyle, infoLn.pattern, infoLn.thickness);
end;
procedure THardwoodTreeB.DrawLeave(rLength, rPhi : Real; wLevel : Word);
var
wR : Word;
srcX, srcY : SmallInt;
color : LongWord;
rR : Real;
fill : FillSettingsType;
begin
if wLevel=MaxLevel then
begin
color:=GetColor; GetFillSettings(fill);
rR:=8*High; rR:=rR/100.0;
if rR < 2.0 then rR:=2.0;
SetColor(DarkGreen); SetFillStyle(SolidFill, ForestGreen);
wR:=Round(rR);
srcX:=GetX+Round(rLength*cos(rPhi));
srcY:=GetY-Round(rLength*sin(rPhi));
FillEllipse(srcX, srcY, wR, wR);
SetColor(color); SetFillStyle(fill.pattern, fill.color);
end;
end;
procedure THardwoodTreeB.DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word);
var fromX, fromY : SmallInt;
begin
DrawTwig(rLength, rPhi, wLevel);
fromX:=GetX; fromY:=GetY;
if wLevel < MaxLevel then
begin
DrawLeaveFractal(rLength*0.7, rPhi+pi/4, Succ(wLevel));
MoveTo(fromX, fromY);
DrawLeaveFractal(rLength*0.7, rPhi-pi/6, Succ(wLevel));
end;
end;
constructor THardwoodTreeB.Create(lx, ly, lHigh : LongInt);
begin
inherited Create(lx, ly, lHigh, 8);
end;
procedure THardwoodTreeB.Dump;
begin
WriteLn('THardwoodTreeB.Dump');
end;
procedure TAtomicTreeA.DrawTrunk(rLength, rPhi : Real; wLevel : Word);
var rThickness : Real; color : LongWord; infoLn : LineSettingsType;
begin
color:=GetColor; GetLineSettings(infoLn);
rThickness:=rLength*0.12;
SetColor(SaddleBrown); SetLineStyle(SolidLn, 0, Round(rThickness));
LineRel(Round(rLength*cos(rPhi)), -Round(rLength*sin(rPhi)));
SetColor(color); SetLineStyle(infoLn.linestyle, infoLn.pattern, infoLn.thickness);
end;
procedure TAtomicTreeA.DrawLeave(rLength, rPhi : Real; wLevel : Word);
var
wR : Word;
srcX, srcY : SmallInt;
color : LongWord;
rR : Real;
fill : FillSettingsType;
begin
if wLevel=MaxLevel then
begin
color:=GetColor; GetFillSettings(fill);
rR:=8*High; rR:=rR/100.0;
if rR < 2.0 then rR:=2.0;
SetColor(DarkGreen); SetFillStyle(SolidFill, ForestGreen);
wR:=Round(rR);
srcX:=GetX+Round(rLength*cos(rPhi));
srcY:=GetY-Round(rLength*sin(rPhi));
PieSlice(srcX, srcY, Round((rPhi-Pi/6)*360/(2*pi)), Round((rPhi+Pi/6)*360/(2*pi)), wR);
PieSlice(srcX, srcY, Round((rPhi-Pi/6+2*pi/3)*360/(2*pi)), Round((rPhi+Pi/6+2*pi/3)*360/(2*pi)), wR);
PieSlice(srcX, srcY, Round((rPhi-Pi/6-2*pi/3)*360/(2*pi)), Round((rPhi+Pi/6-2*pi/3)*360/(2*pi)), wR);
SetColor(color); SetFillStyle(fill.pattern, fill.color);
end;
end;
procedure TAtomicTreeA.DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word);
var fromX, fromY : SmallInt;
begin
DrawTwig(rLength, rPhi, wLevel);
if wLevel < MaxLevel then
begin
fromX:=GetX; fromY:=GetY;
DrawLeaveFractal(rLength*0.4, rPhi+14*pi/30, Succ(wLevel));
MoveTo(fromX, fromY);
DrawLeaveFractal(rLength*0.4, rPhi-14*pi/30, Succ(wLevel));
MoveTo(fromX, fromY);
DrawLeaveFractal(rLength*0.7, rPhi+Pi/30, Succ(wLevel));
end;
end;
constructor TAtomicTreeA.Create(lx, ly, lHigh : LongInt);
begin
inherited Create(lx, ly, lHigh);
end;
procedure TAtomicTreeA.Dump;
begin
WriteLn('TAtomicTreeA.Dump');
end;
procedure TAtomicTreeB.DrawTrunk(rLength, rPhi : Real; wLevel : Word);
begin
inherited DrawTrunk(rLength, rPhi, wLevel);
end;
procedure TAtomicTreeB.DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word);
var fromX, fromY : SmallInt;
begin
DrawTwig(rLength, rPhi, wLevel);
if wLevel < MaxLevel then
begin
fromX:=GetX; fromY:=GetY;
DrawLeaveFractal(rLength*0.4, rPhi-pi/4, Succ(wLevel));
MoveTo(fromX+Round(rLength*0.4*cos(rPhi)), fromY-Round(rLength*0.4*sin(rPhi)));
DrawLeaveFractal(rLength*0.4, rPhi+pi/4, Succ(wLevel));
MoveTo(fromX, fromY);
DrawLeaveFractal(rLength*0.7, rPhi, Succ(wLevel));
end;
end;
procedure TAtomicTreeB.Dump;
begin
WriteLn('TAtomicTreeB.Dump');
end;
procedure TConiferousTreeA.DrawTrunk(rLength, rPhi : Real; wLevel : Word);
var rThickness : Real; color : LongWord; infoLn : LineSettingsType;
begin
color:=GetColor; GetLineSettings(infoLn);
if wLevel > (MaxLevel-2) then
begin
SetColor(DarkGreen); SetFillStyle(SolidFill, ForestGreen);
end else
begin
rThickness:=rLength*0.08;
SetColor(SaddleBrown); SetLineStyle(SolidLn, 0, Round(rThickness));
end;
LineRel(Round(rLength*cos(rPhi)), -Round(rLength*sin(rPhi)));
SetColor(color); SetLineStyle(infoLn.linestyle, infoLn.pattern, infoLn.thickness);
end;
procedure TConiferousTreeA.DrawLeave(rLength, rPhi : Real; wLevel : Word);
var
color : LongWord;
fill : FillSettingsType;
begin
if wLevel=MaxLevel then
begin
color:=GetColor; GetFillSettings(fill);
SetColor(DarkGreen); SetFillStyle(SolidFill, ForestGreen);
color:=GetColor;
MoveRel(Round(rLength*cos(rPhi)), Round(-rLength*sin(rPhi)));
PutPixel(GetX+1, GetY+1, color); PutPixel(GetX-1, GetY-1, color);
PutPixel(GetX+1, GetY-1, color); PutPixel(GetX-1, GetY+1, color);
SetColor(color); SetFillStyle(fill.pattern, fill.color);
end;
end;
procedure TConiferousTreeA.DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word);
var fromX, fromY : SmallInt;
begin
DrawTwig(rLength, rPhi, wLevel);
fromX:=GetX; fromY:=GetY;
if wLevel < MaxLevel then
begin
DrawLeaveFractal(rLength*0.33, rPhi+pi/2+pi/6, Succ(wLevel));
MoveTo(fromX, fromY);
DrawLeaveFractal(rLength*0.33, rPhi-pi/2-pi/6, Succ(wLevel));
MoveTo(fromX, fromY);
DrawLeaveFractal(rLength*0.77, rPhi, Succ(wLevel));
end;
end;
constructor TConiferousTreeA.Create(lx, ly, lHigh : LongInt);
begin
inherited Create(lx, ly, lHigh, 7);
end;
procedure TConiferousTreeA.Dump;
begin
WriteLn('TConiferousTreeA.Dump');
end;
procedure TConiferousTreeB.DrawLeaveFractal(rLength, rPhi : Real; wLevel : Word);
var fromX, fromY : SmallInt;
begin
DrawTwig(rLength, rPhi, wLevel);
if wLevel < MaxLevel then
begin
fromX:=GetX; fromY:=GetY;
MoveTo(fromX+Round(rLength*0.4*cos(rPhi)), fromY-Round(rLength*0.4*sin(rPhi)));
DrawLeaveFractal(rLength*0.4, rPhi-pi/4, Succ(wLevel));
MoveTo(fromX, fromY);
DrawLeaveFractal(rLength*0.4, rPhi+pi/4, Succ(wLevel));
MoveTo(fromX, fromY);
DrawLeaveFractal(rLength*0.7, rPhi-pi/30, Succ(wLevel));
end;
end;
procedure TConiferousTreeB.Dump;
begin
WriteLn('TConiferousTreeB.Dump');
end;
end.
|
(* MPPC: SWa, MM, 2020-05-20 *)
(* ----- *)
(* MidiPascal parser with semantics for compilation. *)
(* ======================================================================== *)
UNIT MPPC;
INTERFACE
VAR
success: BOOLEAN;
PROCEDURE S;
IMPLEMENTATION
USES
MPL, SymTab, CodeDef, CodeGen, syntaxtree;
FUNCTION SyIsNot(expected: Symbol): BOOLEAN;
BEGIN (* SyIsNot *)
IF (sy <> expected) THEN BEGIN
success := FALSE;
END; (* IF *)
SyIsNot := NOT success;
END; (* SyIsNot *)
PROCEDURE SemErr(msg: STRING);
BEGIN (* SemErr *)
WriteLn(' ### ERROR: ', msg);
success := FALSE;
END; (* SemErr *)
PROCEDURE MP; FORWARD;
PROCEDURE VarDecl; FORWARD;
PROCEDURE StatSeq; FORWARD;
PROCEDURE Stat; FORWARD;
PROCEDURE Expr(VAR e: SynTree); FORWARD;
PROCEDURE Term(VAR t: SynTree); FORWARD;
PROCEDURE Fact(VAR f: SynTree); FORWARD;
PROCEDURE S;
BEGIN (* S *)
success := TRUE;
MP; IF (NOT success) THEN Exit;
IF (SyIsNot(eofSy)) THEN Exit;
END; (* S *)
PROCEDURE MP;
BEGIN (* MP *)
(*SEM*)
InitSymbolTable;
InitCodeGenerator;
(*ENDSEM*)
IF (SyIsNot(programSy)) THEN Exit;
NewSy;
IF (SyIsNot(ident)) THEN Exit;
NewSy;
IF (SyIsNot(semiColonSy)) THEN Exit;
NewSy;
IF (sy = varSy) THEN BEGIN
VarDecl; IF (NOT success) THEN Exit;
END; (* IF *)
IF (SyIsNot(beginSy)) THEN Exit;
NewSy;
StatSeq; IF (NOT success) THEN Exit;
(*SEM*) Emit1(EndOpc); (*ENDSEM*)
IF (SyIsNot(endSy)) THEN Exit;
NewSy;
IF (SyIsNot(dotSy)) THEN Exit;
NewSy;
END; (* MP *)
PROCEDURE VarDecl;
VAR
ok: BOOLEAN;
BEGIN (* VarDecl *)
IF (SyIsNot(varSy)) THEN Exit;
NewSy;
IF (SyIsNot(ident)) THEN Exit;
(*SEM*) DeclVar(identStr, ok); (*ENDSEM*)
NewSy;
WHILE (sy = commaSy) DO BEGIN
NewSy;
IF (SyIsNot(ident)) THEN Exit;
(*SEM*)
DeclVar(identStr, ok);
IF (NOT ok) THEN SemErr('variable declared multiple times');
(*ENDSEM*)
NewSy;
END; (* WHILE *)
IF (SyIsNot(colonSy)) THEN Exit;
NewSy;
IF (SyIsNot(integerSy)) THEN Exit;
NewSy;
IF (SyIsNot(semiColonSy)) THEN Exit;
NewSy;
END; (* VarDecl *)
PROCEDURE StatSeq;
BEGIN (* StatSeq *)
Stat; IF (NOT success) THEN Exit;
WHILE (sy = semiColonSy) DO BEGIN
NewSy;
Stat; IF (NOT success) THEN Exit;
END; (* WHILE *)
END; (* StatSeq *)
PROCEDURE Stat;
VAR
destId: STRING;
address1, address2: INTEGER;
e: SynTree;
BEGIN (* Stat *)
CASE sy OF
ident: BEGIN (* assignment *)
(*SEM*)
destId := identStr;
IF (NOT IsDecl(destId)) THEN SemErr('variable not declared')
ELSE Emit2(LoadAddrOpc, AddrOf(destId));
(*ENDSEM*)
NewSy;
IF (SyIsNot(assignSy)) THEN Exit;
NewSy;
Expr(e); IF (NOT success) THEN Exit;
EmitCodeForExprTree(e);
(*SEM*) IF (IsDecl(destId)) THEN Emit1(StoreOpc); (*ENDSEM*)
END; (* assignment *)
readSy: BEGIN (* read statement *)
NewSy;
IF (SyIsNot(leftParSy)) THEN Exit;
NewSy;
IF (SyIsNot(ident)) THEN Exit;
(*SEM*)
IF (NOT IsDecl(identStr)) THEN SemErr('variable not declared')
ELSE Emit2(ReadOpc, AddrOf(identStr));
(*ENDSEM*)
NewSy;
IF (SyIsNot(rightParSy)) THEN Exit;
NewSy;
END; (* read statement *)
writeSy: BEGIN (* write statement *)
NewSy;
IF (SyIsNot(leftParSy)) THEN Exit;
NewSy;
Expr(e); IF (NOT success) THEN Exit;
EmitCodeForExprTree(e);
(*SEM*) Emit1(WriteOpc); (*ENDSEM*)
IF (SyIsNot(rightParSy)) THEN Exit;
NewSy;
END; (* write statement *)
beginSy: BEGIN (* begin statement *)
NewSy;
StatSeq; IF (NOT success) THEN Exit;
IF (SyIsNot(endSy)) THEN Exit;
NewSy;
IF (SyIsNot(semiColonSy)) THEN Exit;
END; (* begin statement *)
ifSy: BEGIN (* if statement *)
NewSy; IF (SyIsNot(ident)) THEN Exit;
(*SEM*)
IF (NOT IsDecl(identStr)) THEN SemErr('variable not declared');
Emit2(LoadValOpc, AddrOf(identStr));
Emit2(JmpZOpc, 0); (* 0 as dummy address *)
address1 := CurAddr - 2;
(*ENDSEM*)
NewSy; IF (SyIsNot(thenSy)) THEN Exit;
NewSy;
Stat; IF (NOT success) THEN Exit;
NewSy;
IF (SyIsNot(elseSy)) THEN Exit
ELSE BEGIN
(*SEM*)
Emit2(JmpOpc, 0); (* 0 as dummy address *)
FixUp(address1, CurAddr);
address1 := CurAddr - 2;
(*ENDSEM*)
NewSy;
Stat; IF (NOT success) THEN Exit;
END; (* ELSE *)
(*SEM*)
FixUp(address1, CurAddr);
(*ENDSEM*)
END; (* if statement *)
whileSy: BEGIN (* while statement *)
NewSy; IF (SyIsNot(ident)) THEN Exit;
(*SEM*)
IF (NOT IsDecl(identStr)) THEN SemErr('variable not declared');
address1 := CurAddr;
Emit2(LoadValOpc, AddrOf(identStr));
Emit2(JmpZOpc, 0); (* 0 as dummy address *)
address2 := CurAddr - 2;
(*ENDSEM*)
NewSy; IF (SyIsNot(doSy)) THEN Exit;
NewSy;
Stat; IF (NOT success) THEN Exit;
(*SEM*)
Emit2(JmpOpc, address1);
FixUp(address2, CurAddr);
(*ENDSEM*)
END; (* while statement *)
END; (* CASE *)
END; (* Stat *)
PROCEDURE Expr(VAR e: SynTree);
VAR t: SynTree;
BEGIN (* Expr *)
Term(e); IF (NOT success) THEN Exit;
WHILE ((sy = plusSy) OR (sy = minusSy)) DO BEGIN
CASE sy OF
plusSy: BEGIN
NewSy;
Term(t); IF (NOT success) THEN Exit;
e := TreeOf('+', e, t);
END;
minusSy: BEGIN
NewSy;
Term(t); IF (NOT success) THEN Exit;
e := TreeOf('-', e, t);
END;
END; (* CASE *)
END; (* WHILE *)
END; (* Expr *)
PROCEDURE Term(VAR t: SynTree);
VAR f: SynTree;
BEGIN (* Term *)
Fact(t); IF (NOT success) THEN Exit;
WHILE ((sy = timesSy) OR (sy = divSy)) DO BEGIN
CASE sy OF
timesSy: BEGIN
NewSy;
Fact(f); IF (NOT success) THEN Exit;
t := TreeOf('*', t, f);
END;
divSy: BEGIN
NewSy;
Fact(f); IF (NOT success) THEN Exit;
t := TreeOf('/', t, f);
END;
END; (* CASE *)
END; (* WHILE *)
END; (* Term *)
PROCEDURE Fact(VAR f: SynTree);
VAR n: STRING;
BEGIN (* Fact *)
CASE sy OF
ident: BEGIN
IF (NOT IsDecl(identStr)) THEN SemErr('variable not declared')
ELSE f := TreeOf(identStr, NIL, NIL);
NewSy;
END;
number: BEGIN
Str(numberVal, n);
f := TreeOf(n, NIL, NIL);
NewSy;
END;
leftParSy: BEGIN
NewSy;
Expr(f); IF (NOT success) THEN Exit;
IF (sy <> rightParSy) THEN BEGIN
success := FALSE;
Exit;
END; (* IF *)
NewSy;
END;
ELSE BEGIN
success := FALSE;
Exit;
END;
END; (* CASE *)
END; (* Fact *)
END. (* MPPC *)
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.NetEncoding;
interface
{$SCOPEDENUMS ON}
uses System.Classes, System.SysUtils;
type
TURLEncoding = class;
TNetEncoding = class
private
class var
FBase64Encoding: TNetEncoding;
FHTMLEncoding: TNetEncoding;
FURLEncoding: TURLEncoding;
class function GetBase64Encoding: TNetEncoding; static;
class function GetHTMLEncoding: TNetEncoding; static;
class function GetURLEncoding: TURLEncoding; static;
class destructor Destroy;
protected
function DoDecode(const Input, Output: TStream): NativeInt; overload; virtual;
function DoDecode(const Input: array of Byte): TBytes; overload; virtual;
function DoDecode(const Input: string): string; overload; virtual; abstract;
function DoEncode(const Input, Output: TStream): NativeInt; overload; virtual;
function DoEncode(const Input: array of Byte): TBytes; overload; virtual;
function DoEncode(const Input: string): string; overload; virtual; abstract;
function DoDecodeStringToBytes(const Input: string): TBytes; virtual;
function DoEncodeBytesToString(const Input: array of Byte): string; overload; virtual;
function DoEncodeBytesToString(const Input: Pointer; Size: Integer): string; overload; virtual;
public
function Decode(const Input, Output: TStream): Integer; overload;
function Decode(const Input: array of Byte): TBytes; overload;
function Decode(const Input: string): string; overload;
function Encode(const Input, Output: TStream): Integer; overload;
function Encode(const Input: array of Byte): TBytes; overload;
function Encode(const Input: string): string; overload;
function DecodeStringToBytes(const Input: string): TBytes;
function EncodeBytesToString(const Input: array of Byte): string; overload;
function EncodeBytesToString(const Input: Pointer; Size: Integer): string; overload;
class property Base64: TNetEncoding read GetBase64Encoding;
class property HTML: TNetEncoding read GetHTMLEncoding;
class property URL: TURLEncoding read GetURLEncoding;
end;
TBase64Encoding = class(TNetEncoding)
protected
const
kCharsPerLine = 76;
DecodeTable: array[0..79] of Int8 = (
62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1,
-1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
-1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51);
EncodeTable: array[0..63] of Byte = (
Ord('A'),Ord('B'),Ord('C'),Ord('D'),Ord('E'),Ord('F'),Ord('G'),Ord('H'),Ord('I'),Ord('J'),Ord('K'),Ord('L'),Ord('M'),
Ord('N'),Ord('O'),Ord('P'),Ord('Q'),Ord('R'),Ord('S'),Ord('T'),Ord('U'),Ord('V'),Ord('W'),Ord('X'),Ord('Y'),Ord('Z'),
Ord('a'),Ord('b'),Ord('c'),Ord('d'),Ord('e'),Ord('f'),Ord('g'),Ord('h'),Ord('i'),Ord('j'),Ord('k'),Ord('l'),Ord('m'),
Ord('n'),Ord('o'),Ord('p'),Ord('q'),Ord('r'),Ord('s'),Ord('t'),Ord('u'),Ord('v'),Ord('w'),Ord('x'),Ord('y'),Ord('z'),
Ord('0'),Ord('1'),Ord('2'),Ord('3'),Ord('4'),Ord('5'),Ord('6'),Ord('7'),Ord('8'),Ord('9'),Ord('+'),Ord('/'));
type
TEncodeStep = (EncodeByteStepA, EncodeByteStepB, EncodeByteStepC,
EncodeWordStepA, EncodeWordStepB, EncodeWordStepC);
TDecodeStep = (DecodeStepA, DecodeStepB, DecodeStepC, DecodeStepD);
TEncodeState = record
Step: TEncodeStep;
Result: Byte;
StepCount: Integer;
end;
TDecodeState = record
Step: TDecodeStep;
Result: Byte;
end;
protected
FCharsPerline: Integer;
FLineSeparator: string;
procedure InitEncodeState(var State: TEncodeState; const CharSize: Integer);
procedure InitDecodeState(var State: TDecodeState);
function EstimateEncodeLength(const InputLength: UInt64; const CharSize: Integer): UInt64;
function EstimateDecodeLength(const InputLength: UInt64): UInt64;
function DecodeValue(const Code: Byte): Integer; inline;
function EncodeValue(const Code: Integer): Byte; inline;
function EncodeBytes(Input, Output: PByte; InputLen: Integer; LineSeparator: array of Byte;
var State: TEncodeState): Integer;
function EncodeBytesEnd(Output: PByte; var State: TEncodeState): Integer;
function DecodeBytes(Input, Output: PByte; InputLen: Integer; CharSize: Integer;
var State: TDecodeState): Integer;
function DoDecode(const Input, Output: TStream): NativeInt; override;
function DoDecode(const Input: array of Byte): TBytes; overload; override;
function DoDecode(const Input: string): string; overload; override;
function DoEncode(const Input, Output: TStream): NativeInt; override;
function DoEncode(const Input: array of Byte): TBytes; overload; override;
function DoEncode(const Input: string): string; overload; override;
function DoDecodeStringToBytes(const Input: string): TBytes; override;
function DoEncodeBytesToString(const Input: array of Byte): string; overload; override;
function DoEncodeBytesToString(const Input: Pointer; Size: Integer): string; overload; override;
public
constructor Create; overload; virtual;
constructor Create(CharsPerLine: Integer); overload; virtual;
constructor Create(CharsPerLine: Integer; LineSeparator: string); overload; virtual;
end;
TURLEncoding = class(TNetEncoding)
public
type
//UnsafeChar = 32..127;
UnsafeChar = Byte;
TUnsafeChars = set of UnsafeChar;
TEncodeOption = (SpacesAsPlus, EncodePercent);
TEncodeOptions = set of TEncodeOption;
TDecodeOption = (PlusAsSpaces);
TDecodeOptions = set of TDecodeOption;
private // Values from: https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/HttpUrl.java
// FormUnsafeChars = '"'':;<=>@[]^`{}|/\?#&!$(),~';
// AuthUnsafeChars = '"'':;<=>@[]^`{}|/\?#';
// PathUnsafeChars = '"<>^`{}|/\?#+';
// QueryUnsafeChars= '"''<>#';
const FormUnsafeChars: TUnsafeChars = [Ord('"'), Ord(''''), Ord(':'), Ord(';'), Ord('<'), Ord('='), Ord('>'),
Ord('@'), Ord('['), Ord(']'), Ord('^'), Ord('`'), Ord('{'), Ord('}'), Ord('|'), Ord('/'), Ord('\'), Ord('?'), Ord('#'),
Ord('&'), Ord('!'), Ord('$'), Ord('('), Ord(')'), Ord(','), Ord('~')];
const AuthUnsafeChars: TUnsafeChars = [Ord('"'), Ord(''''), Ord(':'), Ord(';'), Ord('<'), Ord('='), Ord('>'),
Ord('@'), Ord('['), Ord(']'), Ord('^'), Ord('`'), Ord('{'), Ord('}'), Ord('|'), Ord('/'), Ord('\'), Ord('?'), Ord('#')];
const PathUnsafeChars: TUnsafeChars = [Ord('"'), Ord('<'), Ord('>'), Ord('^'), Ord('`'), Ord('{'), Ord('}'), Ord('|'),
Ord('/'), Ord('\'), Ord('?'), Ord('#'), Ord('+')];
const QueryUnsafeChars: TUnsafeChars = [Ord('"'), Ord(''''), Ord('<'), Ord('>'), Ord('#')];
// function InternalEncode(const Input: string; const ASet, ExtraUnsafeChars: TUnsafeChars;
// SpacesAsPlus, EncodePercent: Boolean): string;
// function InternalDecode(const AValue: string; PlusAsSpaces: Boolean): string;
protected
function DoDecode(const Input: string): string; overload; override;
function DoEncode(const Input: string): string; overload; override;
public
function EncodePath(const APath: string; const AExtraUnsafeChars: TUnsafeChars = []): string;
function EncodeAuth(const Auth: string; const AExtraUnsafeChars: TUnsafeChars = []): string; inline;
function EncodeQuery(const AQuery: string; const AExtraUnsafeChars: TUnsafeChars = []): string; inline;
function EncodeForm(const AInput: string; const AExtraUnsafeChars: TUnsafeChars = []; AEncoding: TEncoding = nil): string; inline;
function URLDecode(const AValue: string): string; inline;
function FormDecode(const AValue: string; AEncoding: TEncoding = nil): string; inline;
function Encode(const AInput: string; const ASet: TUnsafeChars; const AOptions: TEncodeOptions; AEncoding: TEncoding = nil): string; overload;
function Decode(const AValue: string; const AOptions: TDecodeOptions; AEncoding: TEncoding = nil): string; overload;
// function Encode(const Input: string; const ASet, AExtraUnsafeChars: TUnsafeChars;
// SpacesAsPlus, EncodePercent: Boolean): string; overload;
// function Decode(const Input: string): string; overload;
end;
THTMLEncoding = class(TNetEncoding)
protected
function DoDecode(const AInput: string): string; overload; override;
function DoEncode(const AInput: string): string; overload; override;
end;
EHTTPException = class(Exception)
end;
implementation
uses
System.RTLConsts;
type
TPointerStream = class(TCustomMemoryStream)
public
constructor Create(P: Pointer; Size: Integer);
function Write(const Buffer; Count: LongInt): LongInt; override;
end;
{ TNetEncoding }
function TNetEncoding.DoDecode(const Input: array of Byte): TBytes;
begin
if Length(Input) > 0 then
Result := TEncoding.UTF8.GetBytes(DoDecode(TEncoding.UTF8.GetString(Input)))
else
SetLength(Result, 0);
end;
function TNetEncoding.DoDecode(const Input, Output: TStream): NativeInt;
var
InBuf: array of Byte;
OutBuf: TBytes;
begin
if Input.Size > 0 then
begin
SetLength(InBuf, Input.Size);
Input.Read(InBuf[0], Input.Size);
OutBuf := DoDecode(InBuf);
Result := Length(OutBuf);
Output.Write(OutBuf, Result);
SetLength(InBuf, 0);
end
else
Result := 0;
end;
function TNetEncoding.DoDecodeStringToBytes(const Input: string): TBytes;
begin
Result := TEncoding.UTF8.GetBytes(DoDecode(Input));
end;
function TNetEncoding.Decode(const Input: array of Byte): TBytes;
begin
Result := DoDecode(Input);
end;
function TNetEncoding.Decode(const Input, Output: TStream): Integer;
begin
Result := DoDecode(Input, Output);
end;
function TNetEncoding.Decode(const Input: string): string;
begin
Result := DoDecode(Input);
end;
function TNetEncoding.DecodeStringToBytes(const Input: string): TBytes;
begin
Result := DoDecodeStringToBytes(Input);
end;
class destructor TNetEncoding.Destroy;
begin
FreeAndNil(FBase64Encoding);
FreeAndNil(FHTMLEncoding);
FreeAndNil(FURLEncoding);
end;
function TNetEncoding.DoEncode(const Input: array of Byte): TBytes;
begin
if Length(Input) > 0 then
Result := TEncoding.UTF8.GetBytes(DoEncode(TEncoding.UTF8.GetString(Input)))
else
SetLength(Result, 0);
end;
function TNetEncoding.DoEncodeBytesToString(const Input: array of Byte): string;
begin
Result := TEncoding.UTF8.GetString(DoEncode(Input));
end;
function TNetEncoding.Encode(const Input: array of Byte): TBytes;
begin
Result := DoEncode(Input);
end;
function TNetEncoding.Encode(const Input, Output: TStream): Integer;
begin
Result := DoEncode(Input, Output);
end;
function TNetEncoding.Encode(const Input: string): string;
begin
Result := DoEncode(Input);
end;
function TNetEncoding.EncodeBytesToString(const Input: array of Byte): string;
begin
Result := DoEncodeBytesToString(Input);
end;
function TNetEncoding.EncodeBytesToString(const Input: Pointer; Size: Integer): string;
begin
Result := DoEncodeBytesToString(Input, Size);
end;
function TNetEncoding.DoEncodeBytesToString(const Input: Pointer; Size: Integer): string;
var
InStr: TPointerStream;
OutStr: TBytesStream;
begin
InStr := TPointerStream.Create(Input, Size);
try
OutStr := TBytesStream.Create;
try
Encode(InStr, OutStr);
SetString(Result, MarshaledAString(OutStr.Memory), OutStr.Size);
finally
OutStr.Free;
end;
finally
InStr.Free;
end;
end;
function TNetEncoding.DoEncode(const Input, Output: TStream): NativeInt;
var
InBuf: array of Byte;
OutBuf: TBytes;
begin
if Input.Size > 0 then
begin
SetLength(InBuf, Input.Size);
Input.Read(InBuf[0], Input.Size);
OutBuf := DoEncode(InBuf);
Result := Length(OutBuf);
Output.Write(OutBuf, Result);
SetLength(InBuf, 0);
end
else
Result := 0;
end;
class function TNetEncoding.GetBase64Encoding: TNetEncoding;
var
LEncoding: TBase64Encoding;
begin
if FBase64Encoding = nil then
begin
LEncoding := TBase64Encoding.Create;
if AtomicCmpExchange(Pointer(FBase64Encoding), Pointer(LEncoding), nil) <> nil then
LEncoding.Free
{$IFDEF AUTOREFCOUNT}
else
FBase64Encoding.__ObjAddRef
{$ENDIF AUTOREFCOUNT};
end;
Result := FBase64Encoding;
end;
class function TNetEncoding.GetHTMLEncoding: TNetEncoding;
var
LEncoding: THTMLEncoding;
begin
if FHTMLEncoding = nil then
begin
LEncoding := THTMLEncoding.Create;
if AtomicCmpExchange(Pointer(FHTMLEncoding), Pointer(LEncoding), nil) <> nil then
LEncoding.Free
{$IFDEF AUTOREFCOUNT}
else
FHTMLEncoding.__ObjAddRef
{$ENDIF AUTOREFCOUNT};
end;
Result := FHTMLEncoding;
end;
class function TNetEncoding.GetURLEncoding: TURLEncoding;
var
LEncoding: TURLEncoding;
begin
if FURLEncoding = nil then
begin
LEncoding := TURLEncoding.Create;
if AtomicCmpExchange(Pointer(FURLEncoding), Pointer(LEncoding), nil) <> nil then
LEncoding.Free
{$IFDEF AUTOREFCOUNT}
else
FURLEncoding.__ObjAddRef
{$ENDIF AUTOREFCOUNT};
end;
Result := FURLEncoding;
end;
{ TBase64Encoding }
function TBase64Encoding.DecodeValue(const Code: Byte): Integer;
var
LCode: Integer;
begin
LCode := Code - 43;
if (LCode < Low(DecodeTable)) or (LCode > High(DecodeTable)) then
Result := -1
else
Result := DecodeTable[LCode];
end;
function TBase64Encoding.EncodeValue(const Code: Integer): Byte;
begin
Result := EncodeTable[Code];
end;
function TBase64Encoding.EstimateDecodeLength(const InputLength: UInt64): UInt64;
begin
Result := InputLength div 4 * 3 + 4;
end;
function TBase64Encoding.EstimateEncodeLength(const InputLength: UInt64; const CharSize: Integer): UInt64;
begin
Result := InputLength div 3 * 4 + 4;
if FCharsPerLine > 0 then
Result := Result + Result div UInt64(FCharsPerLine) * UInt64(Length(FLineSeparator)*CharSize);
end;
function TBase64Encoding.DoDecode(const Input: array of Byte): TBytes;
const
CharSize = SizeOf(Byte);
var
Len: Integer;
State: TDecodeState;
begin
if Length(Input) > 0 then
begin
SetLength(Result, EstimateDecodeLength(Length(Input)));
InitDecodeState(State);
Len := DecodeBytes(@Input[0], PByte(Result), Length(Input) * CharSize, CharSize, State);
SetLength(Result, Len);
end
else
SetLength(Result, 0)
end;
constructor TBase64Encoding.Create;
begin
Create(kCharsPerLine, sLineBreak);
end;
constructor TBase64Encoding.Create(CharsPerLine: Integer);
begin
Create(CharsPerLine, sLineBreak);
end;
constructor TBase64Encoding.Create(CharsPerLine: Integer; LineSeparator: string);
begin
FCharsPerline := CharsPerLine;
FLineSeparator := LineSeparator;
end;
function TBase64Encoding.DecodeBytes(Input, Output: PByte;
InputLen: Integer; CharSize: Integer; var State: TDecodeState): Integer;
var
POut: PByte;
Fragment: Integer;
P, PEnd: PByte;
begin
POut := Output;
P := Input;
PEnd := P + InputLen;
POut^ := State.Result;
while True do
begin
case State.Step of
TDecodeStep.DecodeStepA:
begin
repeat
if P = PEnd then
begin
State.Result := POut^;
Exit(POut - Output);
end;
Fragment := DecodeValue(Ord(P^));
Inc(P, CharSize);
until (Fragment >= 0) ;
POut^ := (Fragment and $03F) shl 2;
State.Step := TDecodeStep.DecodeStepB;
end;
TDecodeStep.DecodeStepB:
begin
repeat
if P = PEnd then
begin
State.Result := POut^;
Exit(POut - Output);
end;
Fragment := DecodeValue(Ord(P^));
Inc(P, CharSize);
until (Fragment >= 0) ;
POut^ := (POut^ or ((Fragment and $030) shr 4));
Inc(POut);
POut^ := ((Fragment and $00F) shl 4);
State.Step := TDecodeStep.DecodeStepC;
end;
TDecodeStep.DecodeStepC:
begin
repeat
if P = PEnd then
begin
State.Result := POut^;
Exit(POut - Output);
end;
Fragment := DecodeValue(Ord(P^));
Inc(P, CharSize);
until (Fragment >= 0) ;
POut^ := (POut^ or ((Fragment and $03C) shr 2));
Inc(POut);
POut^ := ((Fragment and $003) shl 6);
State.Step := TDecodeStep.DecodeStepD;
end;
TDecodeStep.DecodeStepD:
begin
repeat
if P = PEnd then
begin
State.Result := POut^;
Exit(POut - Output);
end;
Fragment := DecodeValue(Ord(P^));
Inc(P, CharSize);
until (Fragment >= 0) ;
POut^ := (POut^ or (Fragment and $03F));
Inc(POut);
State.Step := TDecodeStep.DecodeStepA;
end;
end;
end;
end;
function TBase64Encoding.DoDecode(const Input, Output: TStream): NativeInt;
var
InBuf: array[0..1023] of Byte;
OutBuf: array[0..767] of Byte;
BytesRead, BytesWrite: Integer;
State: TDecodeState;
begin
InitDecodeState(State);
Result := 0;
repeat
BytesRead := Input.Read(InBuf[0], Length(InBuf));
BytesWrite := DecodeBytes(@InBuf[0], @OutBuf[0], BytesRead, 1, State);
Output.Write(Outbuf, BytesWrite);
Result := Result + BytesWrite;
until BytesRead = 0;
end;
function TBase64Encoding.DoDecode(const Input: string): string;
begin
Result := TEncoding.UTF8.GetString(DoDecodeStringToBytes(Input));
end;
function TBase64Encoding.DoDecodeStringToBytes(const Input: string): TBytes;
const
CharSize = SizeOf(Char);
var
Len: Integer;
State: TDecodeState;
begin
SetLength(Result, EstimateDecodeLength(Length(Input) * CharSize));
InitDecodeState(State);
Len := DecodeBytes(PByte(Input), PByte(Result), Length(Input) * CharSize, CharSize, State);
SetLength(Result, Len);
end;
function TBase64Encoding.DoEncode(const Input: array of Byte): TBytes;
const
CharSize = SizeOf(Byte);
var
Len: Integer;
State: TEncodeState;
LineSeparator: TBytes;
begin
if Length(Input) > 0 then
begin
LineSeparator := TEncoding.UTF8.GetBytes(FLineSeparator);
SetLength(Result, EstimateEncodeLength(Length(Input), CharSize));
InitEncodeState(State, CharSize);
Len := EncodeBytes(@Input[0], PByte(Result), Length(Input), LineSeparator, State);
Len := EncodeBytesEnd(PByte(PByte(Result) + Len), State) + Len;
SetLength(Result, Len);
end
else
SetLength(Result, 0)
end;
function TBase64Encoding.EncodeBytesEnd(Output: PByte; var State: TEncodeState): Integer;
var
POut: PByte;
begin
POut := Output;
case State.Step of
TEncodeStep.EncodeByteStepB:
begin
POut^ := EncodeTable[State.Result];
Inc(POut);
POut^ := Byte('=');
Inc(POut);
POut^ := Byte('=');
Inc(POut);
end;
TEncodeStep.EncodeWordStepB:
begin
PWord(POut)^ := Word(EncodeTable[State.Result]);
Inc(POut, 2);
PWord(POut)^ := Word('=');
Inc(POut, 2);
PWord(POut)^ := Word('=');
Inc(POut, 2);
end;
TEncodeStep.EncodeByteStepC:
begin
POut^ := EncodeTable[State.Result];
Inc(POut);
POut^ := Byte('=');
Inc(POut);
end;
TEncodeStep.EncodeWordStepC:
begin
PWord(POut)^ := Word(EncodeTable[State.Result]);
Inc(POut, 2);
PWord(POut)^ := Word('=');
Inc(POut, 2);
end;
end;
Result := POut - Output;
end;
function TBase64Encoding.EncodeBytes(Input, Output: PByte; InputLen: Integer;
LineSeparator: array of Byte; var State: TEncodeState): Integer;
var
B, C: Byte;
P, PEnd, POut: PByte;
begin
P := Input;
PEnd := P + InputLen;
POut := Output;
C := State.Result;
while P <> PEnd do
begin
B := P^;
Inc(P);
case State.Step of
TEncodeStep.EncodeByteStepA:
begin
C := (B and $FC) shr 2;
POut^ := EncodeValue(C);
Inc(POut);
C := (B and $3) shl 4;
State.Step := TEncodeStep.EncodeByteStepB;
end;
TEncodeStep.EncodeWordStepA:
begin
C := (B and $FC) shr 2;
PWord(POut)^ := Word(EncodeValue(C));
Inc(POut, 2);
C := (B and $3) shl 4;
State.Step := TEncodeStep.EncodeWordStepB;
end;
TEncodeStep.EncodeByteStepB:
begin
C := C or (B and $F0) shr 4;
POut^ := EncodeValue(C);
Inc(POut);
C := (B and $F) shl 2;
State.Step := TEncodeStep.EncodeByteStepC;
end;
TEncodeStep.EncodeWordStepB:
begin
C := C or (B and $F0) shr 4;
PWord(POut)^ := Word(EncodeValue(C));
Inc(POut, 2);
C := (B and $F) shl 2;
State.Step := TEncodeStep.EncodeWordStepC;
end;
TEncodeStep.EncodeByteStepC:
begin
C := C or (B and $C0) shr 6;
POut^ := EncodeValue(C);
Inc(POut);
C := (B and $3F) shr 0;
POut^ := EncodeValue(C);
Inc(POut);
Inc(State.StepCount);
if (FCharsPerLine > 0) and (State.StepCount >= FCharsPerLine div 4) then
begin
Move(LineSeparator[0], POut^, Length(LineSeparator));
Inc(POut, Length(LineSeparator));
State.StepCount := 0;
end;
State.Step := TEncodeStep.EncodeByteStepA;
end;
TEncodeStep.EncodeWordStepC:
begin
C := C or (B and $C0) shr 6;
PWord(POut)^ := Word(EncodeValue(C));
Inc(POut, 2);
C := (B and $3F) shr 0;
PWord(POut)^ := Word(EncodeValue(C));
Inc(POut, 2);
Inc(State.StepCount);
if (FCharsPerLine > 0) and (State.StepCount >= FCharsPerLine div 4) then
begin
Move(LineSeparator[0], POut^, Length(LineSeparator));
Inc(POut, Length(LineSeparator));
State.StepCount := 0;
end;
State.Step := TEncodeStep.EncodeWordStepA;
end;
end;
end;
State.Result := C;
Exit(POut - Output);
end;
function TBase64Encoding.DoEncodeBytesToString(const Input: array of Byte): string;
begin
if Length(Input) > 0 then
Result := EncodeBytesToString(@Input[0], Length(Input))
else
Result := '';
end;
function TBase64Encoding.DoEncode(const Input, Output: TStream): NativeInt;
var
InBuf: array[0..767] of Byte;
OutBuf: array[0..1023] of Byte;
BytesRead, BytesWrite: Integer;
State: TEncodeState;
LineSeparator: TBytes;
begin
LineSeparator := TEncoding.UTF8.GetBytes(FLineSeparator);
InitEncodeState(State, SizeOf(Byte));
Result := 0;
repeat
BytesRead := Input.Read(InBuf[0], Length(InBuf));
BytesWrite := EncodeBytes(@InBuf[0], @OutBuf[0], BytesRead, LineSeparator, State);
Output.Write(Outbuf, BytesWrite);
Result := Result + BytesWrite;
until BytesRead = 0;
BytesWrite := EncodeBytesEnd (@OutBuf[0], State);
Result := Result + BytesWrite;
Output.Write(Outbuf, BytesWrite);
end;
function TBase64Encoding.DoEncode(const Input: string): string;
begin
Result := DoEncodeBytesToString(TEncoding.UTF8.GetBytes(Input));
end;
function TBase64Encoding.DoEncodeBytesToString(const Input: Pointer; Size: Integer): string;
const
CharSize = SizeOf(Char);
var
Len: Integer;
State: TEncodeState;
LineSeparator: TBytes;
Estimate: Integer;
begin
LineSeparator := TEncoding.Unicode.GetBytes(FLineSeparator);
Estimate := EstimateEncodeLength(Size, CharSize);
SetLength(Result, Estimate);
InitEncodeState(State, CharSize);
Len := EncodeBytes(Input, PByte(Result), Size, LineSeparator, State);
Len := EncodeBytesEnd(PByte(Result) + Len, State) + Len;
SetLength(Result, Len div CharSize);
end;
procedure TBase64Encoding.InitDecodeState(var State: TDecodeState);
begin
State.Step := TDecodeStep.DecodeStepA;
State.Result := 0;
end;
procedure TBase64Encoding.InitEncodeState(var State: TEncodeState; const CharSize: Integer);
begin
case CharSize of
1: State.Step := TEncodeStep.EncodeByteStepA;
2: State.Step := TEncodeStep.EncodeWordStepA;
end;
State.Result := 0;
State.StepCount := 0;
end;
{ TURLEncoding }
function TURLEncoding.DoDecode(const Input: string): string;
function DecodeHexChar(const C: Char): Byte;
begin
case C of
'0'..'9': Result := Ord(C) - Ord('0');
'A'..'F': Result := Ord(C) - Ord('A') + 10;
'a'..'f': Result := Ord(C) - Ord('a') + 10;
else
raise EConvertError.Create('');
end;
end;
function DecodeHexPair(const C1, C2: Char): Byte; inline;
begin
Result := DecodeHexChar(C1) shl 4 + DecodeHexChar(C2)
end;
var
Sp, Cp: PChar;
I: Integer;
Bytes: TBytes;
begin
SetLength(Bytes, Length(Input) * 4);
I := 0;
Sp := PChar(Input);
Cp := Sp;
try
while Sp^ <> #0 do
begin
case Sp^ of
'+':
Bytes[I] := Byte(' ');
'%':
begin
Inc(Sp);
// Look for an escaped % (%%)
if (Sp)^ = '%' then
Bytes[I] := Byte('%')
else
begin
// Get an encoded byte, may is a single byte (%<hex>)
// or part of multi byte (%<hex>%<hex>...) character
Cp := Sp;
Inc(Sp);
if ((Cp^ = #0) or (Sp^ = #0)) then
raise EHTTPException.CreateFmt(sErrorDecodingURLText, [Cp - PChar(Input)]);
Bytes[I] := DecodeHexPair(Cp^, Sp^)
end;
end;
else
// Accept single and multi byte characters
if Ord(Sp^) < 128 then
Bytes[I] := Byte(Sp^)
else
I := I + TEncoding.UTF8.GetBytes([Sp^], 0, 1, Bytes, I) - 1
end;
Inc(I);
Inc(Sp);
end;
except
on E: EConvertError do
raise EConvertError.CreateFmt(sInvalidURLEncodedChar, [Char('%') + Cp^ + Sp^, Cp - PChar(Input)])
end;
SetLength(Bytes, I);
Result := TEncoding.UTF8.GetString(Bytes);
end;
function TURLEncoding.DoEncode(const Input: string): string;
// The NoConversion set contains characters as specificed in RFC 1738 and
// should not be modified unless the standard changes.
const
NoConversion = [Ord('A')..Ord('Z'), Ord('a')..Ord('z'), Ord('*'), Ord('@'),
Ord('.'), Ord('_'), Ord('-'), Ord('0')..Ord('9'), Ord('$'),
Ord('!'), Ord(''''), Ord('('), Ord(')')];
procedure AppendByte(B: Byte; var Buffer: PChar);
const
Hex = '0123456789ABCDEF';
begin
Buffer[0] := '%';
Buffer[1] := Hex[B shr 4 + Low(string)];
Buffer[2] := Hex[B and $F + Low(string)];
Inc(Buffer, 3);
end;
var
Sp, Rp: PChar;
MultibyteChar: TBytes;
I, ByteCount: Integer;
begin
// Characters that require more than 1 byte are translated as "percent-encoded byte"
// which will be encoded with 3 chars per byte -> %XX
// Example: U+00D1 ($F1 in CodePage 1252)
// UTF-8 representation: $C3 $91 (2 bytes)
// URL encode representation: %C3%91
//
// So the worst case is 4 bytes(max) per Char, and 3 characters to represent each byte
SetLength(Result, Length(Input) * 4 * 3);
Sp := PChar(Input);
Rp := PChar(Result);
SetLength(MultibyteChar, 4);
while Sp^ <> #0 do
begin
if Ord(Sp^) in NoConversion then
begin
Rp^ := Sp^;
Inc(Rp)
end
else if Sp^ = ' ' then
begin
Rp^ := '+';
Inc(Rp)
end
else
begin
if (Ord(Sp^) < 128) then
// Single byte char
AppendByte(Ord(Sp^), Rp)
else
begin
// Multi byte char
ByteCount := TEncoding.UTF8.GetBytes([Sp^], 0, 1, MultibyteChar, 0);
for I := 0 to ByteCount - 1 do
AppendByte(MultibyteChar[I], Rp);
end
end;
Inc(Sp);
end;
SetLength(Result, Rp - PChar(Result));
end;
function TURLEncoding.EncodeAuth(const Auth: string; const AExtraUnsafeChars: TUnsafeChars): string;
begin
Result := Encode(Auth, AuthUnsafeChars + AExtraUnsafeChars, []);
end;
function TURLEncoding.EncodeForm(const AInput: string;
const AExtraUnsafeChars: TUnsafeChars; AEncoding: TEncoding): string;
begin
Result := Encode(AInput, FormUnsafeChars + AExtraUnsafeChars,
[TEncodeOption.SpacesAsPlus, TEncodeOption.EncodePercent], AEncoding);
end;
function TURLEncoding.EncodePath(const APath: string; const AExtraUnsafeChars: TUnsafeChars): string;
var
LSubPaths: TArray<string>;
I: Integer;
begin
if APath = '' then
Result := '/'
else
begin
if APath[Low(APath)] <> '/' then
Result := '/'
else
Result := '';
LSubPaths := APath.Split([Char('/')], TStringSplitOptions.ExcludeLastEmpty);
for I := 0 to Length(LSubPaths) - 1 do
Result := Result + Encode(LSubPaths[I], PathUnsafeChars + AExtraUnsafeChars, []) + '/';
if (Result <> '/') and (APath[High(APath)] <> '/') then
Result := Result.Substring(0, Result.Length - 1); //Remove last '/'
end;
end;
function TURLEncoding.EncodeQuery(const AQuery: string; const AExtraUnsafeChars: TUnsafeChars): string;
begin
Result := Encode(AQuery, QueryUnsafeChars + AExtraUnsafeChars, []);
end;
function TURLEncoding.FormDecode(const AValue: string; AEncoding: TEncoding = nil): string;
begin
Result := Decode(AValue, [TDecodeOption.PlusAsSpaces], AEncoding);
end;
function TURLEncoding.Decode(const AValue: string; const AOptions: TDecodeOptions; AEncoding: TEncoding = nil): string;
const
H2BConvert: array[Ord('0')..Ord('f')] of SmallInt =
( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,10,11,12,13,14,15);
function IsHexChar(C: Byte): Boolean; inline;
begin
Result := C in [Ord('0')..Ord('9'), Ord('A')..Ord('F'), Ord('a')..Ord('f')];
end;
var
ValueBuff: TBytes;
Buff: TBytes;
Cnt: Integer;
Pos: Integer;
Len: Integer;
begin
Cnt := 0;
Pos := 0;
ValueBuff := TEncoding.ASCII.GetBytes(AValue);
Len := Length(ValueBuff);
SetLength(Buff, Len);
while Pos < Len do
begin
if (ValueBuff[Pos] = Ord('%')) and ((Pos + 2) < Len) and IsHexChar(ValueBuff[Pos + 1]) and IsHexChar(ValueBuff[Pos + 2]) then
begin
Buff[Cnt] := (H2BConvert[ValueBuff[Pos + 1]]) shl 4 or H2BConvert[ValueBuff[Pos + 2]];
Inc(Pos, 3);
end
else
begin
if (TDecodeOption.PlusAsSpaces in AOptions) and (ValueBuff[Pos] = Ord('+')) then
Buff[Cnt] := Ord(' ')
else
Buff[Cnt] := ValueBuff[Pos];
Inc(Pos);
end;
Inc(Cnt);
end;
if AEncoding = nil then
AEncoding := TEncoding.UTF8;
Result := AEncoding.GetString(Buff, 0, Cnt);
end;
function TURLEncoding.Encode(const AInput: string; const ASet: TUnsafeChars; const AOptions: TEncodeOptions; AEncoding: TEncoding = nil): string;
function IsHexChar(C: Byte): Boolean; inline;
begin
Result := C in [Ord('0')..Ord('9'), Ord('A')..Ord('F'), Ord('a')..Ord('f')];
end;
const
XD: array[0..15] of char = ('0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
var
Buff: TBytes;
I: Integer;
Len: Integer;
LSet: TUnsafeChars;
begin
Result := '';
if AInput <> '' then
begin
if AEncoding = nil then
AEncoding := TEncoding.UTF8;
Buff := AEncoding.GetBytes(AInput);
Len := Length(Buff);
I := 0;
if (TEncodeOption.SpacesAsPlus in AOptions) then
LSet := ASet + [Ord('+')]
else
LSet := ASet;
if (TEncodeOption.EncodePercent in AOptions) then
LSet := LSet + [Ord('%')];
while I < Len do
begin
if not(TEncodeOption.EncodePercent in AOptions) and (I + 2 < Len) and (Buff[I] = Ord('%')) and
IsHexChar(Buff[I + 1]) and IsHexChar(Buff[I + 2]) then
begin
Result := Result + '%' + Char(Buff[I + 1]) + Char(Buff[I + 2]);
Inc(I, 3);
end
else
begin
if (Buff[I] >= $21) and (Buff[I] <= $7E) then
begin
if Buff[I] in LSet then
Result := Result + '%' + XD[(Buff[I] shr 4) and $0F] + XD[Buff[I] and $0F]
else
Result := Result + Char(Buff[I]);
end
else if (TEncodeOption.SpacesAsPlus in AOptions) and (Buff[I] = Ord(' ')) then
Result := Result + '+'
else
Result := Result + '%' + XD[(Buff[I] shr 4) and $0F] + XD[Buff[I] and $0F];
Inc(I);
end;
end;
end;
end;
function TURLEncoding.URLDecode(const AValue: string): string;
begin
Result := Decode(AValue, []);
end;
{ THTMLEncoding }
function THTMLEncoding.DoEncode(const AInput: string): string;
var
Sp, Rp: PChar;
begin
SetLength(Result, Length(AInput) * 10);
Sp := PChar(AInput);
Rp := PChar(Result);
// Convert: &, <, >, "
while Sp^ <> #0 do
begin
case Sp^ of
'&':
begin
StrCopy(Rp, '&');
Inc(Rp, 5);
end;
'<':
begin
StrCopy(Rp, '<');
Inc(Rp, 4);
end;
'>':
begin
StrCopy(Rp, '>');
Inc(Rp, 4);
end;
'"':
begin
StrCopy(Rp, '"');
Inc(Rp, 6);
end;
else
begin
Rp^ := Sp^;
Inc(Rp);
end;
end;
Inc(Sp);
end;
SetLength(Result, Rp - PChar(Result));
end;
function THTMLEncoding.DoDecode(const AInput: string): string;
var
Sp, Rp, Cp, Tp: PChar;
S: string;
I, Code: Integer;
Valid: Boolean;
begin
SetLength(Result, Length(AInput));
Sp := PChar(AInput);
Rp := PChar(Result);
while Sp^ <> #0 do
begin
case Sp^ of
'&':
begin
Cp := Sp;
Inc(Sp);
Valid := False;
case Sp^ of
'a':
if AnsiStrPos(Sp, 'amp;') = Sp then { do not localize }
begin
Inc(Sp, 3);
Rp^ := '&';
Valid := True;
end;
'l':
if AnsiStrPos(Sp, 'lt;') = Sp then { do not localize }
begin
Inc(Sp, 2);
Rp^ := '<';
Valid := True;
end;
'g':
if AnsiStrPos(Sp, 'gt;') = Sp then { do not localize }
begin
Inc(Sp, 2);
Rp^ := '>';
Valid := True;
end;
'q':
if AnsiStrPos(Sp, 'quot;') = Sp then { do not localize }
begin
Inc(Sp, 4);
Rp^ := '"';
Valid := True;
end;
'#':
begin
Tp := Sp;
Inc(Tp);
while (Sp^ <> ';') and (Sp^ <> #0) do
Inc(Sp);
SetString(S, Tp, Sp - Tp);
Val(S, I, Code);
if Code = 0 then
begin
if I >= $10000 then
begin
// DoDecode surrogate pair
Rp^ := Char(((I - $10000) div $400) + $D800);
Inc(Rp);
Rp^ := Char(((I - $10000) and $3FF) + $DC00);
end
else
Rp^ := Chr((I));
Valid := True;
end
else
Sp := Tp - 1;
end;
end;
if not Valid then
begin
Sp := Cp;
Rp^ := Sp^;
end;
end
else
Rp^ := Sp^;
end;
Inc(Rp);
Inc(Sp);
end;
SetLength(Result, Rp - PChar(Result));
end;
{ TPointerStream }
constructor TPointerStream.Create(P: Pointer; Size: Integer);
begin
SetPointer(P, Size);
end;
function TPointerStream.Write(const Buffer; Count: LongInt): LongInt;
var
Pos, EndPos, Size: LongInt;
Mem: Pointer;
begin
Pos := Self.Position;
if (Pos >= 0) and (Count > 0) then
begin
EndPos := Pos + Count;
Size := Self.Size;
if EndPos > Size then
raise EStreamError.CreateRes(@SMemoryStreamError);
Mem := Self.Memory;
System.Move(Buffer, Pointer(NativeInt(Mem) + Pos)^, Count);
Self.Position := Pos;
Result := Count;
Exit;
end;
Result := 0;
end;
end.
|
program mytime;
uses sysutils;
var
t:real;
begin
t:=now;
writeln((now-t)*86400:0:4);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 2000-2001 Borland Software Corp. }
{ }
{*******************************************************}
unit WebFact;
interface
uses
Classes, HTTPApp;
type
TBaseWebModuleFactory = class(TAbstractWebModuleFactory)
private
FComponentClass: TComponentClass;
FCacheMode: TWebModuleCacheMode;
FCreateMode: TWebModuleCreateMode;
protected
function GetModuleName: string; override;
function GetIsAppModule: Boolean; override;
function GetCreateMode: TWebModuleCreateMode; override;
function GetCacheMode: TWebModuleCacheMode; override;
function GetComponentClass: TComponentClass; override;
constructor Create(AComponentClass: TComponentClass;
ACreateMode: TWebModuleCreateMode;
ACacheMode: TWebModuleCacheMode);
public
procedure PreventDestruction; override;
function GetModule: TComponent; override;
end;
TWebPageAccessFlags = (wpPublished, wpLoginRequired);
TWebPageAccess = set of TWebPageAccessFlags;
TBaseWebPageInfo = class(TAbstractWebPageInfo)
private
FFile: string;
FName: string;
FAccess: TWebPageAccess;
FDescription: string;
FTitle: string;
FViewAccess: string;
protected
constructor Create(
AAccess: TWebPageAccess;
const AFile, AName: string;
const ATitle, ADescription: string;
const AViewAccess: string);
function GetPageFile: string; override;
function GetPageHREF: string; override;
function GetPageName: string; override;
function GetIsPublished: Boolean; override;
function GetIsLoginRequired: Boolean; override;
function GetPageDescription: string; override;
function GetPageTitle: string; override;
function GetViewAccess: string; override;
procedure SetFactory(AFactory: TAbstractWebPageModuleFactory); override;
end;
TWebPageInfo = class(TBaseWebPageInfo)
public
constructor Create(
AAccess: TWebPageAccess = [wpPublished];
const APageFile: string = '.html'; const APageName: string = '';
const ACaption: string = ''; const ADescription: string = '';
const AViewAccess: string = '');
end;
TBaseWebPageModuleFactory = class(TAbstractWebPageModuleFactory)
private
FComponentClass: TComponentClass;
FCacheMode: TWebModuleCacheMode;
FCreateMode: TWebModuleCreateMode;
protected
constructor Create(AComponentClass: TComponentClass;
AWebPageInfo: TAbstractWebPageInfo;
ACreateMode: TWebModuleCreateMode;
ACacheMode: TWebModuleCacheMode);
function GetModuleName: string; override;
function GetIsAppModule: Boolean; override;
function GetCreateMode: TWebModuleCreateMode; override;
function GetCacheMode: TWebModuleCacheMode; override;
function GetComponentClass: TComponentClass; override;
public
procedure PreventDestruction; override;
function GetModule: TComponent; override;
end;
TWebPageModuleFactory = class(TBaseWebPageModuleFactory)
public
constructor Create(AComponentClass: TComponentClass;
AWebPageInfo: TAbstractWebPageInfo;
ACreateMode: TWebModuleCreateMode = crOnDemand;
ACacheMode: TWebModuleCacheMode = caCache);
end;
TWebDataModuleFactory = class(TBaseWebModuleFactory)
public
constructor Create(AComponentClass: TComponentClass;
ACreateMode: TWebModuleCreateMode = crOnDemand;
ACacheMode: TWebModuleCacheMode = caCache);
end;
TWebAppDataModuleFactory = class(TBaseWebModuleFactory)
protected
function GetIsAppModule: Boolean; override;
public
constructor Create(AComponentClass: TComponentClass;
ACacheMode: TWebModuleCacheMode = caCache);
end;
TWebAppPageModuleFactory = class(TBaseWebPageModuleFactory)
protected
function GetIsAppModule: Boolean; override;
public
constructor Create(AComponentClass: TComponentClass;
AWebPageInfo: TAbstractWebPageInfo;
ACacheMode: TWebModuleCacheMode = caCache);
end;
implementation
uses
TypInfo, WebComp, SysUtils, WebCntxt, SiteComp;
{ TBaseWebModuleFactory }
constructor TBaseWebModuleFactory.Create(AComponentClass: TComponentClass;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode);
begin
inherited Create;
FComponentClass := AComponentClass;
FCacheMode := ACacheMode;
FCreateMode := ACreateMode;
end;
function TBaseWebModuleFactory.GetCacheMode: TWebModuleCacheMode;
begin
Result := FCacheMode;
end;
function TBaseWebModuleFactory.GetComponentClass: TComponentClass;
begin
Result := FComponentClass;
end;
function TBaseWebModuleFactory.GetCreateMode: TWebModuleCreateMode;
begin
Assert((not IsAppModule) or (FCreateMode = crAlways), 'Invalid createmode');
Result := FCreateMode;
end;
function TBaseWebModuleFactory.GetIsAppModule: Boolean;
begin
Result := False;
end;
function TBaseWebModuleFactory.GetModule: TComponent;
begin
Result := FComponentClass.Create(nil);
end;
function TBaseWebModuleFactory.GetModuleName: string;
begin
Result := Copy(FComponentClass.ClassName, 2, MaxInt);
end;
procedure TBaseWebModuleFactory.PreventDestruction;
begin
FCacheMode := caCache;
end;
{ TBaseWebPageModuleFactory }
constructor TBaseWebPageModuleFactory.Create(AComponentClass: TComponentClass;
AWebPageInfo: TAbstractWebPageInfo;
ACreateMode: TWebModuleCreateMode;
ACacheMode: TWebModuleCacheMode);
begin
FComponentClass := AComponentClass;
FCacheMode := ACacheMode;
FCreateMode := ACreateMode;
inherited Create(AWebPageInfo);
end;
function TBaseWebPageModuleFactory.GetModule: TComponent;
begin
Result := FComponentClass.Create(nil);
end;
function TBaseWebPageModuleFactory.GetCacheMode: TWebModuleCacheMode;
begin
Result := FCacheMode;
end;
function TBaseWebPageModuleFactory.GetComponentClass: TComponentClass;
begin
Result := FComponentClass;
end;
function TBaseWebPageModuleFactory.GetCreateMode: TWebModuleCreateMode;
begin
Assert((not IsAppModule) or (FCreateMode = crAlways), 'Invalid createmode');
Result := FCreateMode;
end;
function TBaseWebPageModuleFactory.GetIsAppModule: Boolean;
begin
Result := False;
end;
function TBaseWebPageModuleFactory.GetModuleName: string;
begin
Result := Copy(FComponentClass.ClassName, 2, MaxInt);
end;
procedure TBaseWebPageModuleFactory.PreventDestruction;
begin
FCacheMode := caCache;
end;
{ TWebAppPageModuleFactory }
constructor TWebAppPageModuleFactory.Create(AComponentClass: TComponentClass;
AWebPageInfo: TAbstractWebPageInfo;
ACacheMode: TWebModuleCacheMode);
begin
inherited Create(AComponentClass, AWebPageInfo, crAlways, ACacheMode);
end;
function TWebAppPageModuleFactory.GetIsAppModule: Boolean;
begin
Result := True;
end;
{ TWebPageModuleFactory }
constructor TWebPageModuleFactory.Create(AComponentClass: TComponentClass;
AWebPageInfo: TAbstractWebPageInfo;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode);
begin
inherited;
end;
{ TWebAppDataModuleFactory }
constructor TWebAppDataModuleFactory.Create(
AComponentClass: TComponentClass; ACacheMode: TWebModuleCacheMode);
begin
inherited Create(AComponentClass, crAlways, ACacheMode);
end;
function TWebAppDataModuleFactory.GetIsAppModule: Boolean;
begin
Result := True;
end;
{ TWebDataModuleFactory }
constructor TWebDataModuleFactory.Create(AComponentClass: TComponentClass;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode);
begin
inherited;
end;
{ TBaseWebPageInfo }
constructor TBaseWebPageInfo.Create(
AAccess: TWebPageAccess;
const AFile, AName: string;
const ATitle, ADescription, AViewAccess: string);
begin
FAccess := AAccess;
FFile := AFile;
FName := AName;
FDescription := ADescription;
FTitle := ATitle;
FViewAccess := AViewAccess;
end;
function TBaseWebPageInfo.GetIsPublished: Boolean;
begin
Result := wpPublished in FAccess;
end;
function TBaseWebPageInfo.GetIsLoginRequired: Boolean;
begin
Result := wpLoginRequired in FAccess;
end;
function TBaseWebPageInfo.GetPageTitle: string;
begin
Result := FTitle;
end;
function TBaseWebPageInfo.GetPageDescription: string;
begin
Result := FDescription;
end;
function TBaseWebPageInfo.GetPageFile: string;
begin
Result := FFile;
end;
function TBaseWebPageInfo.GetPageHREF: string;
begin
if WebContext.Request <> nil then
Result := WebContext.Request.InternalScriptName + '/' + PageName
else
Result := '';
end;
function TBaseWebPageInfo.GetPageName: string;
begin
Result := FName;
end;
procedure TBaseWebPageInfo.SetFactory(
AFactory: TAbstractWebPageModuleFactory);
begin
inherited;
if FName = '' then
FName := Copy(Factory.ComponentClass.ClassName, 2, MaxInt);
if (FFile <> '') then
if AnsiCompareFileName(ExtractFileExt(FFile), FFile) = 0 then
// FFile is a file ext
FFile := ChangeFileExt(GetTypeData(Factory.ComponentClass.ClassInfo)^.UnitName, FFile)
end;
function TBaseWebPageInfo.GetViewAccess: string;
begin
Result := FViewAccess;
end;
{ TWebPageInfo }
constructor TWebPageInfo.Create(AAccess: TWebPageAccess; const APageFile, APageName: string;
const ACaption, ADescription, AViewAccess: string);
begin
inherited;
end;
end.
|
unit Ths.Erp.Database.Table.AyarBarkodTezgah;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table,
Ths.Erp.Database.Table.Ambar;
type
TAyarBarkodTezgah = class(TTable)
private
FTezgahAdi: TFieldDB;
FAmbarID: TFieldDB;
FAmbar: TFieldDB;
protected
vAmbar: TAmbar;
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property TezgahAdi: TFieldDB read FTezgahAdi write FTezgahAdi;
Property AmbarID: TFieldDB read FAmbarID write FAmbarID;
Property Ambar: TFieldDB read FAmbar write FAmbar;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TAyarBarkodTezgah.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'ayar_barkod_tezgah';
SourceCode := '1000';
FTezgahAdi := TFieldDB.Create('tezgah_adi', ftString, '');
FAmbarID := TFieldDB.Create('ambar_id', ftInteger, 0);
FAmbar := TFieldDB.Create('ambar', ftString, '');
end;
procedure TAyarBarkodTezgah.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
vAmbar := TAmbar.Create(Database);
try
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
getRawDataByLang(TableName, FTezgahAdi.FieldName),
TableName + '.' + FAmbarID.FieldName,
ColumnFromIDCol(vAmbar.AmbarAdi.FieldName, vAmbar.TableName, FAmbarID.FieldName, FAmbar.FieldName, TableName)
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FTezgahAdi.FieldName).DisplayLabel := 'Tezgah Adư';
Self.DataSource.DataSet.FindField(FAmbarID.FieldName).DisplayLabel := 'Ambar ID';
Self.DataSource.DataSet.FindField(FAmbar.FieldName).DisplayLabel := 'Ambar';
end;
finally
vAmbar.Free;
end;
end;
end;
procedure TAyarBarkodTezgah.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
vAmbar := TAmbar.Create(Database);
try
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
getRawDataByLang(TableName, FTezgahAdi.FieldName),
TableName + '.' + FAmbarID.FieldName,
ColumnFromIDCol(vAmbar.AmbarAdi.FieldName, vAmbar.TableName, FAmbarID.FieldName, FAmbar.FieldName, TableName)
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FTezgahAdi.Value := FormatedVariantVal(FieldByName(FTezgahAdi.FieldName).DataType, FieldByName(FTezgahAdi.FieldName).Value);
FAmbarID.Value := FormatedVariantVal(FieldByName(FAmbarID.FieldName).DataType, FieldByName(FAmbarID.FieldName).Value);
FAmbar.Value := FormatedVariantVal(FieldByName(FAmbar.FieldName).DataType, FieldByName(FAmbar.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
finally
vAmbar.Free;
end;
end;
end;
procedure TAyarBarkodTezgah.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FTezgahAdi.FieldName,
FAmbarID.FieldName
]);
NewParamForQuery(QueryOfInsert, FTezgahAdi);
NewParamForQuery(QueryOfInsert, FAmbarID);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TAyarBarkodTezgah.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FTezgahAdi.FieldName,
FAmbarID.FieldName
]);
NewParamForQuery(QueryOfUpdate, FTezgahAdi);
NewParamForQuery(QueryOfUpdate, FAmbarID);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TAyarBarkodTezgah.Clone():TTable;
begin
Result := TAyarBarkodTezgah.Create(Database);
Self.Id.Clone(TAyarBarkodTezgah(Result).Id);
FTezgahAdi.Clone(TAyarBarkodTezgah(Result).FTezgahAdi);
FAmbarID.Clone(TAyarBarkodTezgah(Result).FAmbarID);
FAmbar.Clone(TAyarBarkodTezgah(Result).FAmbar);
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls,
SysUtils, Dialogs, OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
DC: HDC;
hrc: HGLRC;
Pos, Angle, Delta : GLfloat;
procedure Init;
procedure SetDCPixelFormat;
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
const
Cylinder = 1;
var
frmGL: TfrmGL;
Closed : Boolean = False;
implementation
{$R *.DFM}
{=======================================================================
Инициализация}
procedure TfrmGL.Init;
var
Quadric : GLUquadricObj;
begin
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
Quadric := gluNewQuadric;
glNewList (Cylinder, GL_COMPILE);
gluCylinder (Quadric, 1.0, 1.0, 5.0, 50, 50);
glEndList;
gluDeleteQuadric (Quadric);
end;
{=======================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
const
ambFront : Array [0..3] of GLfloat = (0.0, 0.0, 1.0, 1.0);
ambBack : Array [0..3] of GLfloat = (1.0, 0.0, 0.0, 1.0);
begin
BeginPaint(Handle, ps);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glTranslatef (Pos, Pos, Pos);
glRotatef (Angle, 1.0, 1.0, 0.0);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @ambFront);
glMaterialfv (GL_BACK, GL_AMBIENT_AND_DIFFUSE, @ambBack);
glCallList(Cylinder);
glPopMatrix;
SwapBuffers(DC);
EndPaint(Handle, ps);
If not Closed then begin
Angle := Angle + 2;
If Angle > 360.0 then Angle := 0.0;
Pos := Pos + Delta;
If Pos > 2.0
then Delta := -0.1
else If Pos < -2.0 then
Delta := 0.1;
Application.ProcessMessages;
InvalidateRect(Handle, nil, False);
end;
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
Pos := 0.0;
Delta := 0.1;
Angle := 0.0;
Init;
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight );
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
glFrustum(-1.0, 1.0, -1.0, 1.0, 2.0, 25.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0.0, 0.0, -12.0);
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
glDeleteLists (Cylinder, 1);
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
{=======================================================================
Обработка нажатия клавиши}
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
procedure TfrmGL.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
Closed := True;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995-2001 Borland Software Corporation }
{ }
{*******************************************************}
unit ActnMenus;
interface
uses Windows, Messages, Classes, Controls, Contnrs, Registry, Graphics,
ActnList, ToolWin, ExtCtrls, ActnMan, ActnCtrls, Menus;
type
{ TMenuStack }
TCustomActionMenuBar = class;
TMenuStack = class(TStack)
private
function GetBars(const Index: Integer): TCustomActionMenuBar;
protected
property Bars[const Index: Integer]: TCustomActionMenuBar read GetBars;
public
procedure Push(Container: TCustomActionMenuBar);
function Pop: TCustomActionMenuBar;
function Peek: TCustomActionMenuBar;
end;
{ TCustomActionMenuBar }
TAnimationStyle = (asNone, asDefault, asUnFold, asSlide, asFade);
TMenuPopupEvent = procedure(Sender: TObject;
Item: TCustomActionControl) of object;
TCustomActionPopupMenu = class;
TCustomPopupClass = class of TCustomActionPopupMenu;
TGetPopupClassEvent = procedure(Sender: TObject;
var PopupClass: TCustomPopupClass);
TCustomActionMenuBar = class(TCustomActionDockBar)
private
FAnimatePopups: Boolean;
FAnimationStyle: TAnimationStyle;
FCommandSound: String;
FDelayItem: TCustomActionControl;
FDragItem: TCustomActionControl;
FExpandable: Boolean;
FExpanded: Boolean;
FInMenuLoop: Boolean;
FItemKeyed: Boolean;
FParentMenu: TCustomActionMenuBar;
FParentControl: TCustomActionControl;
FPopupStack: TMenuStack;
FRegistry: TRegistry;
FOnPopup: TMenuPopupEvent;
FExpandDelay: Integer;
FPopupSound: string;
FRootMenu: TCustomActionMenuBar;
FDefaultFont: Boolean;
FOnGetPopupClass: TGetPopupClassEvent;
procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
procedure CMEnterMenuLoop(var Message: TMessage); message CM_ENTERMENULOOP;
procedure CMItemClicked(var Message: TCMItemMsg); message CM_ITEMCLICKED;
procedure WMMouseActivate(var Message: TWMMouseActivate); message WM_MOUSEACTIVATE;
procedure WMSysKeyDown(var Message: TWMSysKeyDown); message WM_SYSKEYDOWN;
procedure SetParentMenu(const Value: TCustomActionMenuBar);
procedure CMItemKeyed(var Message: TCMItemMsg); message CM_ITEMKEYED;
protected
FChildMenu: TCustomActionMenuBar;
FExpandTimer: TTimer;
FPopupTimer: TTimer;
procedure Animate(Show: Boolean = True);
procedure ClearSubMenus;
procedure CleanupStack;
function CreateControl(AnItem: TActionClientItem): TCustomActionControl; override;
function CreatePopup(AOwner: TCustomActionMenuBar;
Item: TCustomActionControl): TCustomActionPopupMenu; virtual;
procedure DoItemSelected(AnItem: TCustomActionControl);
function DoGetPopupClass: TCustomPopupClass; dynamic;
function DoItemClicked(AnItem: TCustomActionControl): TActionClientItem; virtual;
function DoItemKeyed(AnItem: TCustomActionControl): TActionClientItem; virtual;
procedure DoMenuDelay(Sender: TObject);
procedure DoneMenuLoop; virtual;
procedure ExecAction(Action: TContainedAction); virtual;
procedure Expand(Full: Boolean); virtual;
procedure ExpandTimer(Sender: TObject);
procedure GetDefaultSounds;
function GetDesignMode: Boolean; override;
function GetControlClass(AnItem: TActionClientItem): TCustomActionControlClass; override;
function GetPopupClass: TCustomPopupClass;
function GetMouseHoverItem(Msg: TMsg): TCustomActionControl;
function GetSelected: TActionClientItem;
procedure InitMenuLoop;
function IsDesignMsg(var Msg: TMsg): Boolean;
function NewPopup: TCustomActionPopupMenu; virtual;
property PopupStack: TMenuStack read FPopupStack;
function ProcessMenuLoop: TActionClientItem; virtual;
procedure ProcessMouseMsg(var Msg: TMsg); virtual;
procedure SelectItem(AnItem: TCustomActionControl);
procedure Select(const Forward: Boolean);
procedure SetDesignMode(const Value: Boolean); override;
procedure SetPersistentHotkeys(const Value: Boolean); override;
procedure WndProc(var Message: TMessage); override;
property DelayItem: TCustomActionControl read FDelayItem write FDelayItem;
property Expandable: Boolean read FExpandable write FExpandable;
property Expanded: Boolean read FExpanded write FExpanded;
property ParentMenu: TCustomActionMenuBar read FParentMenu write SetParentMenu;
property Selected: TActionClientItem read GetSelected;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CloseMenu; virtual;
procedure TrackMenu; virtual;
property AnimationStyle: TAnimationStyle read FAnimationStyle write FAnimationStyle;
property ExpandDelay: Integer read FExpandDelay write FExpandDelay;
property InMenuLoop: Boolean read FInMenuLoop write FInMenuLoop;
property ParentControl: TCustomActionControl read FParentControl write FParentControl;
property RootMenu: TCustomActionMenuBar read FRootMenu write FRootMenu;
property OnGetPopupClass: TGetPopupClassEvent read FOnGetPopupClass
write FOnGetPopupClass;
property OnPopup: TMenuPopupEvent read FOnPopup write FOnPopup;
end;
{ TCustomMenuExpandBtn }
TCustomMenuExpandBtn = class(TCustomUtilityButton)
protected
procedure DrawBackground(var PaintRect: TRect); override;
procedure DrawFrame(ARect: TRect; Down: Boolean); override;
procedure DragOver(Source: TObject; X: Integer; Y: Integer;
State: TDragState; var Accept: Boolean); override;
end;
{ TCustomActionPopupMenu }
TCustomMenuItem = class;
TCustomActionPopupMenu = class(TCustomActionMenuBar)
private
FExpandBtn: TCustomMenuExpandBtn;
FExpandedSize: TPoint;
FMenuSize: TPoint;
protected
procedure AddEdges(AnItem: TCustomMenuItem); virtual;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure CMVisibleChanged(var Message: TMessage);
message CM_VISIBLECHANGED;
function CreateControl(AnItem: TActionClientItem): TCustomActionControl; override;
procedure CreateControls; override;
procedure CreateParams(var Params: TCreateParams); override;
function DesignWndProc(var Message: TMessage): Boolean; override;
procedure ExecAction(Action: TContainedAction); override;
procedure ExpandClick(Sender: TObject);
function GetBarHeight: Integer; override;
function GetControlClass(AnItem: TActionClientItem): TCustomActionControlClass; override;
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
procedure PositionPopup(AnOwner: TCustomActionBar;
ParentItem: TCustomActionControl);
procedure SetActionClient(const Value: TActionClient); override;
procedure SetupExpandBtn;
procedure SetOrientation(const Value: TBarOrientation); override;
procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
procedure WMPrint(var Message: TMessage); message WM_PRINT;
procedure WMPrintClient(var Message: TMessage); message WM_PRINTCLIENT;
procedure VisibleChanging; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CloseMenu; override;
procedure Expand(Full: Boolean); override;
procedure Popup(X, Y: Integer);
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
property ExpandBtn: TCustomMenuExpandBtn read FExpandBtn write FExpandBtn;
end;
{ TCustomizeActionToolBar }
TCustomizeActionToolBarClass = class of TCustomizeActionToolBar;
TCustomizeActionToolBar = class(TCustomActionPopupMenu)
private
FActionBar: TCustomActionToolBar;
FAddlItem: TActionClientItem;
FResetAction: TCustomAction;
FResetItem: TActionClientItem;
procedure CMItemSelected(var Message: TCMItemMsg); message CM_ITEMSELECTED;
protected
function CanAutoSize(var NewWidth: Integer;
var NewHeight: Integer): Boolean; override;
procedure Clear; override;
function DoItemClicked(AnItem: TCustomActionControl): TActionClientItem; override;
function GetActionControl(const Index: Integer): TCustomActionControl; override;
function GetControlClass(AnItem: TActionClientItem): TCustomActionControlClass; override;
procedure GetSubMenuControlClass(Sender: TCustomActionBar; AnItem: TActionClient;
var ControlClass: TCustomActionControlClass);
function DoGetPopupClass: TCustomPopupClass; override;
function NewPopup: TCustomActionPopupMenu; override;
procedure SetActionClient(const Value: TActionClient); override;
public
constructor Create(AOwner: TComponent); override;
procedure CloseMenu; override;
function ItemCount: Integer; override;
destructor Destroy; override;
end;
{ TCustomizeActionLink }
TCustomizeActionLink = class(TActionClientLink)
protected
procedure SetEnabled(Value: Boolean); override;
end;
{ TCustomizeActionClientItem }
TCustomizeActionClientItem = class(TActionClientItem)
protected
function GetActionLinkClass: TActionClientLinkClass; override;
end;
{ TCustomActionMainMenuBar }
TCustomActionMainMenuBar = class(TCustomActionMenuBar)
private
FInActive: Boolean;
procedure SetInActive(const Value: Boolean);
protected
procedure AlignControls(AControl: TControl; var Rect: TRect); override;
function CanAutoSize(var NewWidth: Integer;
var NewHeight: Integer): Boolean; override;
function CreateControl(AnItem: TActionClientItem): TCustomActionControl; override;
procedure DoneMenuLoop; override;
function GetControlClass(AnItem: TActionClientItem): TCustomActionControlClass; override;
procedure ProcessMouseMsg(var Msg: tagMSG); override;
procedure SetDesignMode(const Value: Boolean); override;
procedure CMWininichange(var Message: TMessage);
message CM_WININICHANGE;
procedure WndProc(var Message: TMessage); override;
procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
public
constructor Create(AOwner: TComponent); override;
procedure CloseMenu; override;
property Inactive: Boolean read FInActive write SetInActive;
property PersistentHotKeys;
end;
{ TActionMainMenuBar }
TActionMainMenuBar = class(TCustomActionMainMenuBar)
published
property ActionManager;
property Align default alTop;
property AllowHiding default False;
property Anchors;
property AnimationStyle default asDefault;
property BiDiMode default bdLeftToRight;
property Caption;
property Color default clMenu;
property Constraints;
property EdgeBorders;
property EdgeInner;
property EdgeOuter;
property Enabled;
property ExpandDelay default 4000;
property Font;
property HorzMargin;
property ParentBiDiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property ShowHint;
property Spacing;
property VertMargin;
property Visible;
property OnCanResize;
property OnClick;
property OnControlCreated;
property OnConstrainedResize;
property OnContextPopup;
property OnDockDrop;
property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetControlClass;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnPaint;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
end;
{ TCustomMenuItem }
TMenuEdges = set of TEdgeBorder;
TCustomMenuItem = class(TCustomActionControl)
private
FEdges: TMenuEdges;
FMenu: TCustomActionMenuBar;
FMouseSelected: Boolean;
FShortCutBounds: TRect;
procedure SetEdges(const Value: TMenuEdges);
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMTextchanged(var Message: TMessage); message CM_TEXTCHANGED;
protected
procedure CalcLayout; override;
procedure DoDragDrop(DragObject: TObject; X: Integer; Y: Integer); override;
procedure DrawDesignFocus(var PaintRect: TRect); override;
procedure DrawEdge(Edges: TMenuEdges); virtual;
procedure DrawSubMenuGlyph; virtual;
procedure DrawUnusedEdges; virtual;
function GetImageSize: TPoint; override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer;
Y: Integer); override;
procedure Paint; override;
procedure PositionChanged; override;
procedure SetSelected(Value: Boolean); override;
procedure DragOver(Source: TObject; X: Integer; Y: Integer;
State: TDragState; var Accept: Boolean); override;
property Menu: TCustomActionMenuBar read FMenu;
property MouseSelected: Boolean read FMouseSelected;
property ShortCutBounds: TRect read FShortCutBounds write FShortCutBounds;
public
constructor Create(AOwner: TComponent); override;
procedure CalcBounds; override;
procedure Click; override;
destructor Destroy; override;
procedure Keyed; override;
procedure DragDrop(Source: TObject; X: Integer; Y: Integer); override;
property Edges: TMenuEdges read FEdges write SetEdges;
end;
{ TCustomMenuButton }
TCustomMenuButton = class(TCustomButtonControl)
protected
procedure BeginAutoDrag; override;
procedure DragOver(Source: TObject; X: Integer; Y: Integer;
State: TDragState; var Accept: Boolean); override;
procedure DrawText(var ARect: TRect; var Flags: Cardinal; Text: string); override;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X: Integer; Y: Integer); override;
procedure Paint; override;
public
destructor Destroy; override;
procedure Click; override;
procedure Keyed; override;
end;
{ TCustomAddRemoveItem }
TCustomAddRemoveItem = class(TCustomMenuItem)
protected
procedure SetEnabled(Value: Boolean); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer;
Y: Integer); override;
public
procedure CalcBounds; override;
end;
TMenuItemControlClass = class of TCustomMenuItem;
TAddRemoveItemClass = class of TCustomAddRemoveItem;
TMenuButtonControlClass = class of TCustomMenuButton;
var
MenuItemControlClass: TMenuItemControlClass;
MenuAddRemoveItemClass: TAddRemoveItemClass;
MenuButtonControlClass: TMenuButtonControlClass;
MenuPopupClass: TCustomPopupClass;
MenuCustomizePopupClass: TCustomizeActionToolBarClass;
implementation
uses SysUtils, Forms, Dialogs, StdCtrls, Consts, MMSystem, GraphUtil,
CommCtrl, Buttons, StdActnMenus, ExtActns, ListActns;
{ TMenuStack }
function TMenuStack.GetBars(const Index: Integer): TCustomActionMenuBar;
begin
Result := TCustomActionMenuBar(List[Index]);
end;
function TMenuStack.Peek: TCustomActionMenuBar;
begin
Result := TCustomActionMenuBar(inherited PeekItem);
end;
function TMenuStack.Pop: TCustomActionMenuBar;
begin
Result := TCustomActionMenuBar(PopItem);
end;
procedure TMenuStack.Push(Container: TCustomActionMenuBar);
begin
PushItem(Pointer(Container));
end;
type
TApplicationClass = class(TApplication);
{ TMenuList }
TMenuList = class(TList)
private
function GetMenu(const Index: Integer): TCustomActionMenuBar;
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
property Menus[const Index: Integer]: TCustomActionMenuBar read GetMenu;
end;
{ TMenuList }
function TMenuList.GetMenu(const Index: Integer): TCustomActionMenuBar;
begin
Result := TCustomActionMenuBar(Items[Index]);
end;
var
MenuKeyHook: HHOOK;
MenuCallWndHook: HHOOK;
MenuList: TMenuList;
ActiveMenu: TCustomActionMenuBar;
{ Hooks required for Main Menu Support }
function GetMsgHook(Code: Integer; WParam: wParam; Msg: PMsg): Longint; stdcall;
function HandleMsg: Boolean;
begin
Result := (Msg.Message = WM_SYSKEYDOWN) or (Msg.Message = WM_SYSCHAR) or
(Msg.Message = WM_SYSKEYUP);
end;
function ParentFormEnabled(Ctrl: TWinControl): Boolean;
var
ParentFrm: TCustomForm;
begin
Result := False;
ParentFrm := GetParentForm(Ctrl);
if Assigned(ParentFrm) then
Result := GetWindowLong(ParentFrm.Handle, GWL_STYLE) and WS_DISABLED <> WS_DISABLED;
end;
var
I: Integer;
Item: TActionClientItem;
begin
if (Code = HC_ACTION) and HandleMsg then
case Msg.Message of
WM_SYSKEYDOWN:
if Assigned(ActiveMenu) and not ActiveMenu.DesignMode then
begin
if ActiveMenu.InMenuLoop and (Msg.wParam = VK_MENU) then
begin
ActiveMenu.CloseMenu;
Application.ProcessMessages;
FillChar(Msg^, SizeOf(TMsg), 0);
end;
end
else
for I := 0 to MenuList.Count - 1 do
if (ActiveMenu = nil) and (Msg.wParam = VK_MENU) and
(MenuList.Menus[I] is TCustomActionMainMenuBar) and
ParentFormEnabled(MenuList.Menus[I]) then
begin
MenuList.Menus[I].PersistentHotkeys := True;
ActiveMenu := MenuList.Menus[I];
FillChar(Msg^, SizeOf(Msg), 0);
end;
WM_SYSKEYUP:
if Assigned(ActiveMenu) and (Msg.wParam <> VK_SPACE) and
not ActiveMenu.InMenuLoop then
begin
if Msg.wParam = VK_MENU then
if (ActiveMenu.Items.Count > 0) then
begin
Item := ActiveMenu.FindFirstVisibleItem;
if Assigned(Item) then
Item.Control.Selected := True;
end;
PostMessage(ActiveMenu.Handle, CM_ENTERMENULOOP, 0, 0);
end;
WM_SYSCHAR:
begin
for I := 0 to MenuList.Count - 1 do
begin
Item := MenuList.Menus[I].FindAccelItem(Msg.wParam);
if (Item <> nil) and ParentFormEnabled(MenuList.Menus[I]) then
begin
ActiveMenu := MenuList.Menus[I];
GetParentForm(ActiveMenu).SetFocus;
Item.Control.Keyed;
PostMessage(ActiveMenu.Handle, CM_ENTERMENULOOP, 0, 0);
end;
end;
if Msg.wParam <> VK_SPACE then
FillChar(Msg^, SizeOf(Msg), 0);
end;
end;
Result := CallNextHookEx(MenuKeyHook, Code, WParam, Longint(Msg));
end;
function CallWndHook(Code: Integer; WParam: wParam; Msg: PCWPStruct): Longint; stdcall;
var
I: Integer;
ParentForm: TCustomForm;
begin
case Msg.message of
WM_SYSCOMMAND:
case Msg.wParam and $FFF0 of
SC_MINIMIZE:
if Assigned(ActiveMenu) then
begin
ParentForm := GetParentForm(ActiveMenu);
if Assigned(ParentForm) and (ParentForm.Handle = Msg.hwnd) and
Assigned(ActiveMenu) then
ActiveMenu.CloseMenu;
end;
end;
WM_WINDOWPOSCHANGING:
if Assigned(ActiveMenu) then
begin
ParentForm := GetParentForm(ActiveMenu);
if Assigned(ParentForm) and (ParentForm.Handle = Msg.hwnd) then
if (PWindowPos(Msg.lParam).flags and SWP_NOMOVE <> SWP_NOMOVE) or
(PWindowPos(Msg.lParam).flags and SWP_HIDEWINDOW = SWP_HIDEWINDOW) then
begin
ActiveMenu.CloseMenu;
ActiveMenu := nil;
end;
end;
WM_ACTIVATEAPP:
begin
if Assigned(ActiveMenu) then
begin
ActiveMenu.CloseMenu;
ActiveMenu := nil;
Application.ProcessMessages;
end;
if not Assigned(ActionBarDesigner) then
for I := 0 to MenuList.Count - 1 do
if MenuList.Menus[I] is TCustomActionMainMenuBar then
TCustomActionMainMenuBar(MenuList.Menus[I]).Inactive := Msg.wParam = 0;
end;
end;
Result := CallNextHookEx(MenuCallWndHook, Code, WParam, Longint(Msg));
end;
procedure AddMenuToList(Menu: TCustomActionMenuBar);
begin
if MenuList = nil then
MenuList := TMenuList.Create;
if Assigned(Menu) and (MenuList.IndexOf(Menu) = -1) then
MenuList.Add(Menu);
end;
procedure RemoveMenuFromList(Menu: TCustomActionMenuBar);
begin
if Assigned(MenuList) then
MenuList.Remove(Menu);
if MenuList.Count = 0 then
FreeAndNil(MenuList);
end;
procedure TMenuList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if (Action = lnAdded) and (Count = 1) then
MenuCallWndHook := SetWindowsHookEx(WH_CALLWNDPROC, @CallWndHook, 0,
GetCurrentThreadID)
else if (Action = lnDeleted) and (Count = 0) then
begin
if MenuKeyHook <> 0 then
UnHookWindowsHookEx(MenuKeyHook);
if MenuCallWndHook <> 0 then
UnHookWindowsHookEx(MenuCallWndHook);
end;
inherited Notify(Ptr, Action);
end;
{ TCustomActionMenuBar }
constructor TCustomActionMenuBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAnimationStyle := asDefault;
FRegistry := TRegistry.Create;
EdgeOuter := esNone;
// Expand delay interval should probably come from the registry (somewhere)
FExpandDelay := 4000;
FDefaultFont := True;
FAnimatePopups := True;
AddMenuToList(Self);
end;
destructor TCustomActionMenuBar.Destroy;
begin
RemoveMenuFromList(Self);
if Assigned(FParentMenu) then
FParentMenu.FChildMenu := nil;
FreeAndNil(FRegistry);
inherited Destroy;
end;
procedure TCustomActionMenuBar.Animate(Show: Boolean = True);
type
TAnimationStyle = array[Boolean] of Integer;
var
Animate: BOOL;
P: TPoint;
const
HideShow: array[Boolean] of Integer = (AW_HIDE, 0);
UnfoldAnimationStyle: TAnimationStyle =
(AW_VER_POSITIVE or AW_HOR_POSITIVE or AW_SLIDE,
AW_VER_NEGATIVE or AW_HOR_POSITIVE or AW_SLIDE);
SlideAnimationStyle: TAnimationStyle =
(AW_VER_POSITIVE or AW_SLIDE, AW_VER_NEGATIVE or AW_SLIDE);
FadeAnimationStyle: TAnimationStyle = (AW_BLEND, AW_BLEND);
procedure DefaultSystemAnimation;
begin
SystemParametersInfo(SPI_GETMENUANIMATION, 0, @Animate, 0);
if Assigned(AnimateWindowProc) and (FParentMenu.FAnimatePopups or
not Show) and Animate then
begin
SystemParametersInfo(SPI_GETMENUFADE, 0, @Animate, 0);
if Animate then
AnimateWindowProc(Handle, 180, AW_BLEND or HideShow[Show])
else
begin
P := FParentControl.ClientToScreen(Point(FParentControl.Left, FParentControl.Top));
AnimateWindowProc(Handle, 180, UnfoldAnimationStyle[Top < P.Y] or
HideShow[Show]);
end;
end;
end;
procedure DoAnimation(Style: TAnimationStyle);
begin
if Assigned(AnimateWindowProc) and FParentMenu.FAnimatePopups or not Show then
begin
P := FParentControl.ClientToScreen(Point(FParentControl.Left, FParentControl.Top));
AnimateWindowProc(Handle, 180, Style[P.X < P.Y] or HideShow[Show]);
end;
end;
begin
if DesignMode then exit;
case FAnimationStyle of
asDefault: DefaultSystemAnimation;
asUnFold : DoAnimation(UnfoldAnimationStyle);
asSlide : DoAnimation(SlideAnimationStyle);
asFade : DoAnimation(FadeAnimationStyle);
end;
end;
procedure TCustomActionMenuBar.CleanupStack;
begin
if not FPopupStack.Peek.FInMenuLoop then
FPopupStack.Peek.CloseMenu;
end;
procedure TCustomActionMenuBar.ClearSubMenus;
var
I: Integer;
begin
if not FInMenuLoop then exit;
for I := 1 to FPopupStack.Count - 1 do
FPopupStack.Peek.CloseMenu;
Application.ProcessMessages;
end;
procedure TCustomActionMenuBar.CloseMenu;
begin
if Assigned(RootMenu) then
RootMenu.DelayItem := nil;
if Assigned(ParentMenu) then
ParentMenu.FAnimatePopups := False;
InMenuLoop := False;
if Assigned(RootMenu) and Assigned(RootMenu.PopupStack) then
begin
if RootMenu.PopupStack.Peek = RootMenu then
begin
FInMenuLoop := False;
if Assigned(Selected) then
Selected.Control.Selected := False;
end
else
RootMenu.PopupStack.Pop.Free;
end;
end;
procedure TCustomActionMenuBar.CMItemClicked(var Message: TCMItemMsg);
begin
if not FInMenuLoop then
begin
PostMessage(Handle, Message.Msg, 0, LongInt(Message.Sender));
TrackMenu;
end;
end;
procedure TCustomActionMenuBar.CMEnterMenuLoop(var Message: TMessage);
begin
TrackMenu;
end;
procedure TCustomActionMenuBar.CMItemKeyed(var Message: TCMItemMsg);
begin
if not FInMenuLoop then
begin
PostMessage(Handle, CM_ITEMKEYED, 0, LongInt(Message.Sender));
TrackMenu;
end;
end;
function TCustomActionMenuBar.CreateControl(
AnItem: TActionClientItem): TCustomActionControl;
const
Alignment: array [TBarOrientation] of TAlign = (alNone, alNone, alTop,
alTop);
begin
Result := inherited CreateControl(AnItem);
Result.ShowHint := False;
AnItem.ShowCaption := True;
if not Result.Separator then
Result.Enabled := Result.Enabled and (Assigned(AnItem.Action) or
(AnItem.HasItems and (AnItem.Items.VisibleCount > 0)));
end;
function TCustomActionMenuBar.CreatePopup(AOwner: TCustomActionMenuBar;
Item: TCustomActionControl): TCustomActionPopupMenu;
var
OldVisible: Boolean;
begin
Result := nil;
if not InMenuLoop or (AOwner = nil) or (Item = nil) or (FPopupStack.Count = 0) or
(FPopupStack.Peek.ParentControl = Item) or (Item.ActionClient = nil) or
(Item.ActionClient.Items.VisibleCount = 0) then
exit;
FDelayItem := nil;
Result := NewPopup;
with Result do
begin
RootMenu := Self.RootMenu;
Item.ActionClient.ChildActionBar := Result;
ParentMenu := AOwner;
FInMenuLoop := True;
ParentControl := Item;
Parent := Self;
OldVisible := Item.ActionClient.Visible;
ActionClient := Item.ActionClient;
Item.ActionClient.Visible := OldVisible;
if Assigned(FOnPopup) then
FOnPopup(Self, Item);
Expanded := Self.Expanded or Self.DesignMode or (FindFirstVisibleItem = nil);
if Expanded then
Expand(False);
DesignMode := AOwner.DesignMode;
Show;
end;
FPopupStack.Push(Result);
FExpandTimer.Enabled := Result.Expandable and not Result.Expanded;
end;
procedure TCustomActionMenuBar.DoItemSelected(AnItem: TCustomActionControl);
begin
if AnItem is TCustomMenuItem then
RootMenu.FDelayItem := AnItem
else
FDelayItem := nil;
RootMenu.FPopupTimer.Enabled := True;
// Reset the expand timer every time new item is selected
if not RootMenu.FPopupStack.Peek.Expandable {or (AnItem.Owner = Self)} then
exit;
RootMenu.FExpandTimer.Enabled := False;
// Tag = 1 indicates that when the timer fires that it should only
// highlight the expand button rather than expand the popup menu
if Selected <> FindFirstVisibleItem then
RootMenu.FExpandTimer.Tag := 1;
RootMenu.FExpandTimer.Enabled := not DesignMode;
end;
procedure TCustomActionMenuBar.ExecAction(Action: TContainedAction);
begin
if (Action = nil) or (csDesigning in ComponentState) then exit;
if not DesignMode then
begin
if Length(RootMenu.FCommandSound) > 0 then
sndPlaySound(PChar(RootMenu.FCommandSound), SND_NOSTOP or SND_ASYNC);
Action.Execute;
end;
end;
function TCustomActionMenuBar.DoGetPopupClass: TCustomPopupClass;
begin
if Assigned(FOnGetPopupClass) then
FOnGetPopupClass(Self, Result)
else
Result := GetPopupClass;
end;
function TCustomActionMenuBar.DoItemClicked(
AnItem: TCustomActionControl): TActionClientItem;
var
SelectionFade: BOOL;
I: Integer;
begin
Result := nil;
// if DesignMode then Windows.SetFocus(Parent.Handle);
// if it's a top level item then close all submenus
if (AnItem.Owner = Self) then
begin
if Assigned(AnItem.ActionClient.ChildActionBar) then
begin
CloseMenu;
exit;
end;
ClearSubMenus;
FDelayItem := nil;
end;
if AnItem.ActionClient.HasItems then
begin
if Assigned(FDelayItem) {and (FDelayItem.Parent <> nil) }then
begin
while FPopupStack.Peek <> FDelayItem.Parent do
FPopupStack.Pop.Free;
FDelayItem := nil;
end;
CreatePopup(FPopupStack.Peek, AnItem);
FAnimatePopups := False;
end
else
begin
Result := AnItem.ActionClient;
if not DesignMode then
begin
SystemParametersInfo(SPI_GETSELECTIONFADE, 0, @SelectionFade, 0);
if (FPopupStack.Count > 1) and SelectionFade then
begin
for I := 1 to FPopupStack.Count - 2 do
FPopupStack.Bars[I].Visible := False;
FPopupStack.Peek.Animate(False);
end;
ClearSubMenus;
CloseMenu;
end;
end;
end;
function TCustomActionMenuBar.DoItemKeyed(
AnItem: TCustomActionControl): TActionClientItem;
var
Item: TActionClientItem;
begin
FItemKeyed := True;
Result := DoItemClicked(AnItem);
if not Assigned(Result) then
begin
// if the keyboard was used to display the popup then automatically
// select the first item if the mouse was used no item is selected
Item := FPopupStack.Peek.FindFirstVisibleItem;
if Assigned(Item) and Assigned(Item.Control) then
Item.Control.Selected := True;
end;
end;
procedure TCustomActionMenuBar.GetDefaultSounds;
function ReadSoundSetting(KeyStr: string): string;
var
S: string;
begin
FRegistry.RootKey := HKEY_CURRENT_USER;
Result := '';
if FRegistry.OpenKeyReadOnly('\AppEvents\Schemes\Apps\.Default\' + KeyStr) then { do not localize }
try
S := FRegistry.ReadString('');
SetLength(Result, 4096);
SetLength(Result, ExpandEnvironmentStrings(PChar(S), PChar(Result), 4096) - 1);
finally
FRegistry.CloseKey;
end;
end;
begin
FPopupSound := ReadSoundSetting('MenuPopup\.Current'); { do not localize }
FCommandSound := ReadSoundSetting('MenuCommand\.Current'); { do not localize }
end;
function TCustomActionMenuBar.IsDesignMsg(var Msg: TMsg): Boolean;
var
ParentForm: TCustomForm;
begin
Result := DesignMode and not Mouse.IsDragging;
if Result then
begin
Result := Assigned(FDragItem) or Mouse.IsDragging;
if Result then // Allow mouse up to end the drag operation
begin
Result := (Msg.message <> WM_LBUTTONUP) {and not (Msg.message = WM_MOUSEMOVE)};
exit;
end;
ParentForm := GetParentForm(RootMenu);
Result := Assigned(ParentForm) and (GetForeGroundWindow <> ParentForm.Handle);
if csDesigning in ComponentState then
Result := Result and (Msg.Message <> CM_ITEMCLICKED);
end;
end;
procedure TCustomActionMenuBar.DoMenuDelay(Sender: TObject);
var
P: TPoint;
begin
FPopupTimer.Enabled := False;
if DelayItem = nil then exit;
if (FDelayItem.Parent = nil) or
Assigned(FDelayItem.ActionClient.ChildActionBar) then exit;
while (RootMenu.PopupStack.Count > 1) and
(RootMenu.PopupStack.Peek <> FDelayItem.Parent) do
RootMenu.PopupStack.Pop.Free;
GetCursorPos(P);
if PtInRect(FDelayItem.BoundsRect, FPopupStack.Peek.ScreenToClient(P)) then
CreatePopup(FPopupStack.Peek, FDelayItem);
end;
procedure TCustomActionMenuBar.DoneMenuLoop;
begin
CloseMenu;
ActiveMenu := nil;
if Assigned(ActionBarDesigner) then
ActionBarDesigner.SetActiveMenu(nil);
FAnimatePopups := True;
ShowCaret(0);
FreeAndNil(FPopupTimer);
FreeAndNil(FPopupStack);
FreeAndNil(FExpandTimer);
end;
procedure TCustomActionMenuBar.Expand(Full: Boolean);
var
I: Integer;
begin
FExpanded := True;
if Full then
RootMenu.Expanded := Full;
FExpandable := False;
if not HasItems then exit;
DisableAlign;
try
for I := 0 to Items.Count - 1 do
Items[I].Control.Visible := Items[I].Visible;
finally
EnableAlign;
end;
end;
procedure TCustomActionMenuBar.ExpandTimer(Sender: TObject);
begin
FExpandTimer.Enabled := False;
if RootMenu.PopupStack.Peek.Expandable then
// Tag = 1 indicates that when the timer fires that it should only
// highlight the expand button rather than expand the popup menu
if FExpandTimer.Tag = 1 then
with TCustomActionPopupMenu(FPopupStack.Peek).ExpandBtn do
Flat := False
else
begin
FExpanded := True;
FPopupStack.Peek.Expand(True);
end;
end;
function TCustomActionMenuBar.GetControlClass(
AnItem: TActionClientItem): TCustomActionControlClass;
begin
Result := MenuItemControlClass
end;
function TCustomActionMenuBar.GetDesignMode: Boolean;
begin
Result := inherited GetDesignMode;
if not Result and Assigned(FParentMenu) then
Result := FParentMenu.DesignMode;
end;
function TCustomActionMenuBar.GetMouseHoverItem(Msg: TMsg): TCustomActionControl;
var
I: Integer;
Control: TControl;
ARootMenu: TCustomActionMenuBar;
begin
Result := nil;
Control := nil;
ARootMenu := RootMenu;
if Assigned(ARootMenu) then
begin
for I := ARootMenu.PopupStack.Count - 1 downto 0 do
if WindowFromPoint(Msg.pt) = ARootMenu.PopupStack.Bars[I].Handle then
with ARootMenu.PopupStack.Bars[I] do
Control := ControlAtPos(ScreenToClient(Msg.Pt), True);
if Control is TCustomActionControl then
Result := TCustomActionControl(Control);
end;
end;
function TCustomActionMenuBar.GetPopupClass: TCustomPopupClass;
begin
Result := MenuPopupClass;
end;
function TCustomActionMenuBar.GetSelected: TActionClientItem;
var
I: Integer;
begin
Result := nil;
for I := 0 to ItemCount - 1 do
if Assigned(ActionControls[I]) and ActionControls[I].Selected then
begin
Result := ActionControls[I].ActionClient;
break;
end;
end;
procedure TCustomActionMenuBar.InitMenuLoop;
var
DelayTime: DWORD;
begin
GetDefaultSounds;
FExpanded := False;
FDelayItem := nil;
if csDesigning in ComponentState then
DelayTime := 1
else
SystemParametersInfo(SPI_GETMENUSHOWDELAY, 0, @DelayTime, 0);
FPopupTimer := TTimer.Create(nil);
FPopupTimer.OnTimer := DoMenuDelay;
FPopupTimer.Interval := DelayTime;
FPopupStack := TMenuStack.Create;
FPopupStack.Push(Self);
FExpandTimer := TTimer.Create(nil);
with FExpandTimer do
begin
Enabled := False;
Interval := FExpandDelay;
OnTimer := ExpandTimer;
end;
FInMenuLoop := True;
HideCaret(0);
ActiveMenu := Self;
if Assigned(ActionBarDesigner) then
ActionBarDesigner.SetActiveMenu(ActiveMenu);
end;
procedure TCustomActionMenuBar.ProcessMouseMsg(var Msg: TMsg);
var
Item: TCustomActionControl;
Control: TControl;
begin
Item := GetMouseHoverItem(Msg);
if not Assigned(Item) then
case Msg.message of
WM_MOUSEMOVE:
if Mouse.IsDragging and (Msg.hwnd <> RootMenu.PopupStack.Peek.Handle) then
begin
Control := ControlAtPos(Msg.pt, False, True);
if Assigned(Control) and ((Control is TCustomActionBar) or
(Control is TCustomActionControl)) then
RootMenu.CloseMenu;
end;
// WM_LBUTTONUP,
WM_MBUTTONDOWN,
WM_RBUTTONDOWN,
WM_LBUTTONDOWN:
// if DesignMode then // Allow menu items to be deleted with drag/drop
RootMenu.CloseMenu;
end;
DispatchMessage(Msg);
end;
function TCustomActionMenuBar.ProcessMenuLoop: TActionClientItem;
var
Msg: TMsg;
begin
Result := nil;
if FInMenuLoop then exit;
InitMenuLoop;
try
repeat
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
// Allow keystroke messages to be propagated to the IDE at designtime
if (csDesigning in ComponentState) and
TApplicationClass(Application).IsKeyMsg(Msg) then
Continue;
if IsDesignMsg(Msg) then
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
Continue;
end;
case Msg.message of
CM_RELEASE,
WM_CLOSE:
begin
CloseMenu;
Application.ProcessMessages;
DispatchMessage(Msg);
end;
WM_NCRBUTTONDOWN,
WM_NCLBUTTONDOWN:
begin
if not (csDesigning in ComponentState) or
(Msg.hwnd = GetParentForm(Self).Handle) then
begin
CloseMenu;
Application.ProcessMessages;
end;
DispatchMessage(Msg);
end;
WM_KEYFIRST..WM_KEYLAST:
begin
if not PersistentHotKeys then
PersistentHotkeys := True;
FPopupStack.Peek.WndProc(TMessage((@Msg.message)^));
end;
WM_MOUSEFIRST..WM_MOUSELAST: ProcessMouseMsg(Msg);
CM_ITEMSELECTED: DoItemSelected(TCustomActionControl(Msg.lParam));
CM_ITEMKEYED :
Result := DoItemKeyed(TCustomActionControl(Msg.lParam));
CM_ITEMCLICKED:
Result := DoItemClicked(TCustomActionControl(Msg.lParam));
else
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
CleanupStack;
end
else
TApplicationClass(Application).Idle(Msg);
until not FInMenuLoop;
finally
DoneMenuLoop;
end;
end;
procedure TCustomActionMenuBar.Select(const Forward: Boolean);
var
NextItem: TActionClientItem;
procedure SkipItems(const Forward: Boolean);
begin
while Assigned(NextItem) and ((NextItem.Separator) or
(Assigned(NextItem.Control) and (not NextItem.Control.Visible))) do
if Forward then
NextItem := FindNext(NextItem)
else
NextItem := FindPrevious(NextItem);
end;
begin
if Forward then
NextItem := FindNext(Selected)
else
NextItem := FindPrevious(Selected);
if not DesignMode then
SkipItems(Forward);
if NextItem = nil then exit;
if (RootMenu.PopupStack.Peek = Self) then
if DesignMode and (KeyboardStateToShiftState = [ssCtrl]) and
Assigned(NextItem) and Assigned(Selected) then
Selected.Index := NextItem.Index
else
SelectItem(NextItem.Control)
else
if (NextItem.Control.Parent = Self) and Assigned(NextItem.Action) then
begin
RootMenu.PopupStack.Peek.FInMenuLoop := False;
RootMenu.FDelayItem := nil;
NextItem.Control.Selected := True;
end
else
NextItem.Control.Keyed;
end;
procedure TCustomActionMenuBar.SelectItem(AnItem: TCustomActionControl);
begin
if AnItem = nil then exit;
AnItem.Selected := True;
end;
procedure TCustomActionMenuBar.SetDesignMode(const Value: Boolean);
begin
if DesignMode and not Value and FInMenuLoop then
CloseMenu;
inherited SetDesignMode(Value);
end;
procedure TCustomActionMenuBar.SetParentMenu(
const Value: TCustomActionMenuBar);
begin
if FParentMenu <> Value then
begin
FParentMenu := Value;
if Assigned(FParentMenu) then
begin
FParentMenu.FChildMenu := Self;
PersistentHotkeys := FParentMenu.PersistentHotkeys;
if Assigned(FParentMenu.OnGetControlClass) then
OnGetControlClass := FParentMenu.OnGetControlClass;
FAnimationStyle := FParentMenu.AnimationStyle;
end;
end;
end;
procedure TCustomActionMenuBar.SetPersistentHotkeys(const Value: Boolean);
var
I: Integer;
UpdatePopups: Boolean;
begin
UpdatePopups := (Value <> PersistentHotkeys) and Value;
inherited SetPersistentHotkeys(Value);
if UpdatePopups and Assigned(FPopupStack) then
for I := 0 to FPopupStack.Count - 1 do
TCustomActionMenuBar(FPopupStack.List[I]).PersistentHotkeys := True;
end;
procedure TCustomActionMenuBar.TrackMenu;
var
Item: TActionClientItem;
begin
if InMenuLoop then exit;
FRootMenu := Self;
Item := ProcessMenuLoop;
if Assigned(Item) then
ExecAction(Item.Action);
end;
procedure TCustomActionMenuBar.WndProc(var Message: TMessage);
begin
case Message.Msg of
WM_NCHITTEST: Message.Result := HTCLIENT;
end;
inherited WndProc(Message);
end;
procedure TCustomActionMenuBar.WMKeyDown(var Message: TWMKeyDown);
var
Item: TActionClientItem;
begin
inherited;
if not FInMenuLoop then exit;
if (RootMenu <> nil) and (Chr(Message.CharCode) in ['0'..'9', 'A'..'Z']) then
begin
Item := RootMenu.PopupStack.Peek.FindAccelItem(Message.CharCode);
if Assigned(Item) then
Item.Control.Keyed;
end;
case Message.CharCode of
VK_UP : Select(False);
VK_DOWN: Select(True);
VK_HOME: SelectItem(FindFirstVisibleItem.Control);
VK_END : SelectItem(FindLastVisibleItem.Control);
VK_RETURN:
if {!!not DesignMode and }Assigned(Selected) then
begin
Selected.Control.Keyed;
{!! if DesignMode then
PostMessage(RootMenu.Handle, CM_EDITACTION, 0, 0);}
end;
VK_ESCAPE:
if DesignMode and Assigned(FDragItem) then
DragDone(False)
else
if Mouse.IsDragging then
CancelDrag
else
CloseMenu;
end;
end;
procedure TCustomActionMenuBar.WMMouseActivate(var Message: TWMMouseActivate);
begin
inherited;
if{!! not (csDesigning in ComponentState) and }FInMenuLoop then
Message.Result := MA_NOACTIVATE;
end;
procedure TCustomActionMenuBar.WMSysKeyDown(var Message: TWMSysKeyDown);
var
Item: TActionClientItem;
begin
inherited;
if not FInMenuLoop then exit;
if (RootMenu <> nil) and
(Chr(Message.CharCode) in ['0'..'9', 'A'..'Z']) then
begin
Item := RootMenu.PopupStack.Peek.FindAccelItem(Message.CharCode);
if Assigned(Item) and Assigned(Item.Control) then
Item.Control.Keyed;
end; // Prevents the IDE's main menu from working via the keyboard
if (Message.CharCode = VK_MENU) {!!and not (csDesigning in ComponentState) }then
RootMenu.CloseMenu;
end;
{ TCustomMenuExpandBtn }
procedure TCustomMenuExpandBtn.DragOver(Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
// This control should not participate in drag/drop at all
end;
procedure TCustomMenuExpandBtn.DrawBackground(var PaintRect: TRect);
begin
OffsetRect(PaintRect, 0, 1);
InflateRect(PaintRect, -2, -4);
if MouseInControl then
Canvas.Brush.Color := GetHighLightColor(Color)
else
Canvas.Brush.Color := Color;
inherited DrawBackGround(PaintRect);
end;
procedure TCustomMenuExpandBtn.DrawFrame(ARect: TRect; Down: Boolean);
begin
OffsetRect(ARect, 0, 1);
InflateRect(ARect, -2, -4);
inherited DrawFrame(ARect, Down);
end;
{ TCustomActionPopupMenu }
constructor TCustomActionPopupMenu.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csNoDesignVisible];
Visible := False;
Align := alNone;
Orientation := boTopToBottom;
EdgeBorders := [ebLeft, ebTop, ebRight, ebBottom];
EdgeInner := esRaised;
EdgeOuter := esRaised;
VertMargin := 1;
FExpandBtn := nil;
if AOwner is TCustomActionBar then
ActionManager := TCustomActionBar(AOwner).ActionManager;
end;
destructor TCustomActionPopupMenu.Destroy;
begin
if Assigned(ActionClient) then
ActionClient.ChildActionBar := nil;
Visible := False;
FreeAndNil(FExpandBtn);
inherited Destroy;
end;
procedure TCustomActionPopupMenu.AddEdges(AnItem: TCustomMenuItem);
var
PrevItem: TActionClientItem;
NextItem: TActionClientItem;
Edges: TMenuEdges;
begin
if (AnItem = nil) or (AnItem.ActionClient = nil) then exit;
PrevItem := FindPreviousVisibleItem(AnItem.ActionClient);
NextItem := FindNextVisibleItem(AnItem.ActionClient);
if AnItem.ActionClient.Unused then
begin
Edges := [];
if FExpanded and ((PrevItem = nil) or not PrevItem.Unused) then
if AnItem.ActionClient <> FindFirst then
Edges := Edges + [ebTop];
if FExpanded and ((NextItem = nil) or not NextItem.Unused) then
if AnItem.ActionClient <> FindLast then
Edges := Edges + [ebBottom];
AnItem.Edges := Edges;
end
else
begin
if Assigned(PrevItem) and PrevItem.Unused then
if PrevItem.Control is TCustomMenuItem then
with PrevItem.Control as TCustomMenuItem do
Edges := Edges + [ebBottom];
if Assigned(NextItem) and NextItem.Unused then
if NextItem.Control is TCustomMenuItem then
with NextItem.Control as TCustomMenuItem do
Edges := Edges + [ebTop];
end;
end;
procedure TCustomActionPopupMenu.CMMouseLeave(var Message: TMessage);
begin
inherited;
{ if Mouse.IsDragging and DesignMode then
begin
if not PtInRect(BoundsRect, Mouse.CursorPos) then
CloseMenu;
exit;
end;}
if Assigned(Selected) and not Assigned(Selected.ChildActionBar) then
Selected.Control.Selected := False;
end;
procedure TCustomActionPopupMenu.CMVisibleChanged(var Message: TMessage);
begin
inherited;
if not (csDesigning in ComponentState) and Visible and Assigned(RootMenu) and
(Length(RootMenu.FPopupSound) > 0) then
sndPlaySound(PChar(RootMenu.FPopupSound), SND_NOSTOP or SND_ASYNC);
end;
function TCustomActionPopupMenu.CreateControl(
AnItem: TActionClientItem): TCustomActionControl;
begin
Result := inherited CreateControl(AnItem);
if (Result is TCustomMenuItem) {and ActionClient.Items.HideUnused }then
AddEdges(Result as TCustomMenuItem);
if not Expanded and Result.ActionClient.Unused then
begin
FExpandable := True;
Result.Visible := False;
end;
Result.CalcBounds;
if Result.Visible then
begin
Inc(FMenuSize.Y, Result.Height);
if Result.Width > FMenuSize.X then
FMenuSize.X := Result.Width + 3;
end;
Inc(FExpandedSize.Y, Result.Height);
if Result.Width + 3 > FExpandedSize.X then
FExpandedSize.X := Result.Width + 3;
if Visible then
if Expanded then
SetBounds(Left, Top, FExpandedSize.X, FExpandedSize.Y)
else
SetBounds(Left, Top, FMenuSize.X, FMenuSize.Y)
end;
procedure TCustomActionPopupMenu.CreateControls;
var
I: Integer;
begin
FMenuSize := Point(4, VertMargin * 2 + 4);
FExpandedSize := Point(3, VertMargin * 2 + 4);
inherited CreateControls;
I := GetBannerWidth(beEither);
Inc(FMenuSize.X, I);
Inc(FExpandedSize.X, I);
if FExpandable and (FindFirstVisibleItem <> nil) then
begin
SetupExpandBtn;
Inc(FMenuSize.Y, GetSystemMetrics(SM_CYMENU));
end;
SetBounds(Left, Top, FMenuSize.X, FMenuSize.Y);
end;
procedure TCustomActionPopupMenu.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
begin
if Assigned(Parent) and not (Parent is TCustomForm) then
Style := Style and not WS_CHILD or WS_POPUP or WS_OVERLAPPED;
WindowClass.Style := CS_SAVEBITS or CS_DBLCLKS or not (CS_HREDRAW or not CS_VREDRAW);
if not DesignMode then
ExStyle := ExStyle or WS_EX_TOPMOST;
end;
end;
function TCustomActionPopupMenu.DesignWndProc(var Message: TMessage): Boolean;
begin
Result := True;
end;
procedure TCustomActionPopupMenu.ExecAction(Action: TContainedAction);
begin
Hide;
inherited ExecAction(Action);
end;
procedure TCustomActionPopupMenu.Expand(Full: Boolean);
var
I: Integer;
begin
FExpanded := True;
FExpandedSize.Y := VertMargin * 2 + 4;
DisableAlign;
try
inherited Expand(Full);
for I := 0 to Items.Count - 1 do
if Items[I].Visible and (Items[I].Control is TCustomMenuItem) then
begin
AddEdges(TCustomMenuItem(Items[I].Control));
Items[I].Control.CalcBounds;
Inc(FExpandedSize.Y, Items[I].Control.Height);
end
else
Inc(FExpandedSize.Y, Items[I].Control.Height);
// Reposition menu in case new size no longer fits at the previous location
SetBounds(Left, Top, Width, Height);
if Assigned(FParentControl) then
PositionPopup(TCustomActionBar(FParentControl.Owner), FParentControl);
finally
EnableAlign;
end;
end;
procedure TCustomActionPopupMenu.ExpandClick(Sender: TObject);
begin
while RootMenu.PopupStack.Peek <> Self do
RootMenu.PopupStack.Pop.Free;
Expand(True);
end;
function TCustomActionPopupMenu.GetBarHeight: Integer;
begin
if Expanded then
if AlignDisabled then
Result := Height
else
Result := FExpandedSize.Y
else
Result := FMenuSize.Y;
end;
procedure TCustomActionPopupMenu.Popup(X, Y: Integer);
begin
if ItemCount = 0 then exit;
ParentWindow := Application.Handle;
SetBounds(X, Y, FMenuSize.X, FMenuSize.Y);
FRootMenu := Self;
Show;
if FindFirstVisibleItem = nil then
Expand(False);
Visible := True;
TrackMenu;
Visible := False;
end;
procedure TCustomActionPopupMenu.PositionPopup(AnOwner: TCustomActionBar;
ParentItem: TCustomActionControl);
function MonitorSize(A, B: Integer): Integer;
begin
Result := B;
if A > 0 then
Inc(Result, A);
end;
var
P: TPoint;
R: TRect;
Item: TActionClientItem;
LeftAlign: BOOL;
Monitor: TMonitor;
begin
if (AnOwner = nil) or (ParentControl = nil) then exit;
with ParentControl do
case AnOwner.Orientation of
boLeftToRight: P := AnOwner.ClientToScreen(Point(Left + 1, Top + Height));
boRightToLeft: P := AnOwner.ClientToScreen(Point(Left - Self.Width +
Width, Top + Height));
else
// Popup menus overlap slightly
if AnOwner.FindFirstVisibleItem.Control = FParentControl then
P := AnOwner.ClientToScreen(Point(Left + Width - 5, Top - 3))
else
begin
Item := FindFirstVisibleItem;
if Assigned(Item) then
P := AnOwner.ClientToScreen(Point(Left + Width - 5, Top - 3));
end;
end;
// Adjust the position if the menu goes off the edge of the screen
LeftAlign := True;
SystemParametersInfo(SPI_GETMENUDROPALIGNMENT, 0, @LeftAlign, 0);
R.TopLeft := FParentControl.ClientToScreen(FParentControl.BoundsRect.TopLeft);
R.BottomRight := FParentControl.ClientToScreen(FParentControl.BoundsRect.BottomRight);
Monitor := Screen.MonitorFromRect(R, mdNearest);
if P.X < Monitor.Left then P.X := Monitor.Left;
if P.X + Width > MonitorSize(Monitor.Left, Monitor.Width) then
begin
P.X := MonitorSize(Monitor.Left, Monitor.Width) - Width;
if P.X + Width > Monitor.Left + Monitor.Width - AnOwner.Left +
AnOwner.Width then
P.X := AnOwner.Left - Width + 2;
end;
if P.Y + Height > MonitorSize(Monitor.Top, Monitor.Height) then
P.Y := P.Y - FParentControl.Height - Height;
SetBounds(P.X, P.Y, Width, Height);
end;
procedure TCustomActionPopupMenu.SetActionClient(const Value: TActionClient);
const
InnerEdge: array[Boolean] of TEdgeStyle = (esRaised, esNone);
begin
FExpandable := False;
inherited SetActionClient(Value);
end;
procedure TCustomActionPopupMenu.SetBounds(ALeft, ATop, AWidth,
AHeight: Integer);
begin
if Expanded then
inherited SetBounds(ALeft, ATop, FExpandedSize.X, FExpandedSize.Y)
else
inherited SetBounds(ALeft, ATop, FMenuSize.X, FMenuSize.Y);
end;
procedure TCustomActionPopupMenu.SetupExpandBtn;
begin
if FExpandBtn = nil then
begin
FExpandBtn := TCustomMenuExpandBtn.Create(Self);
with FExpandBtn do
begin
Align := alCustom;
AutoScroll := True;
Parent := Self;
ArrowSize := 2;
Hint := SExpand;
ArrowType := atArrows;
Direction := sdDown;
Transparent := Self.ActionClient.HasBackground and
not (Self.ActionClient.BackgroundLayout in [blLeftBanner, blRightBanner]);
OnClick := ExpandClick;
end;
end;
end;
procedure TCustomActionPopupMenu.SetOrientation(const Value: TBarOrientation);
begin
// Popup menus can only have vertical orientation
if Value in [boTopToBottom, boBottomToTop] then
inherited SetOrientation(Value);
end;
procedure TCustomActionPopupMenu.WMKeyDown(var Message: TWMKeyDown);
var
Item: TActionClientItem;
SelIndex: Integer;
begin
case Message.CharCode of
VK_LEFT:
if Assigned(FChildMenu) then
begin
FChildMenu.FInMenuLoop := False;
Message.Result := 0;
end
else
if Assigned(FParentMenu) then
FParentMenu.Dispatch(Message);
VK_RIGHT:
begin
if Assigned(Selected) and Assigned(Selected) then
begin
if DesignMode and not Selected.HasItems and
not Selected.Separator and (Selected.Action = nil) then
if ssCtrl in KeyboardStateToShiftState then
begin
Selected.Items.Add;
Selected.Control.Invalidate;
end;
// Need to handle
if Selected.HasItems and
(Selected.Control.Enabled or DesignMode) then
Selected.Control.Keyed
else
if FPopupStack = nil then
Parent.Dispatch(Message);
end
else
Parent.Dispatch(Message);
end;
VK_DOWN:
if (Message.CharCode = VK_DOWN) and FExpandable and
((Selected = FindLastVisibleItem) or
(ssCtrl in KeyboardStateToShiftState)) then
begin
FExpandBtn.Click;
SelectItem(FindFirst.Control);
exit;
end;
VK_INSERT:
begin
if not (csDesigning in ComponentState) then exit;
if Selected = nil then exit;
Item := Selected;
SelIndex := Item.Index;
if (ssShift in KeyboardStateToShiftState) then
Inc(SelIndex);
ActionClient.Items.Insert(SelIndex);
ActionControls[SelIndex].Selected := True;
NotifyDesigner(Self);
end;
VK_DELETE:
begin
if Selected = nil then exit;
Item := Selected;
if Item.HasItems and
(MessageDlg(Format(SDeleteItemWithSubItems,
[Item.Caption]), mtConfirmation, mbOKCancel, 0) <> mrOk) then
exit;
SelIndex := Item.Index;
if SelIndex = ItemCount - 1 then
Item := FindPrevious(Item, False)
else
Item := FindNext(Item, False);
Dec(FExpandedSize.Y, ActionClient.Items[SelIndex].Control.Height);
ActionClient.Items.Delete(SelIndex);
if Assigned(Item) then
Item.Control.Selected := True
else
PostMessage(RootMenu.Handle, CM_ITEMSELECTED, 0,
LongInt(ParentControl));
SetBounds(Left, Top, Width, FExpandedSize.Y);
NotifyDesigner(Self);
end;
end;
inherited;
end;
procedure TCustomActionPopupMenu.WMPrint(var Message: TMessage);
begin
inherited;
NCPaint(Message.WParam);
end;
procedure TCustomActionPopupMenu.WMPrintClient(var Message: TMessage);
var
AHandle: HDC;
begin
inherited;
AHandle := Canvas.Handle;
try
Canvas.Handle := Message.WParam;
Canvas.Brush.Color := Color;
Canvas.FillRect(ClientRect);
PaintTo(Message.WParam, 0, 0);
finally
Canvas.Handle := AHandle;
end;
end;
procedure TCustomActionPopupMenu.VisibleChanging;
var
Item: TActionClientItem;
begin
inherited VisibleChanging;
if not Visible then
begin
Item := FindFirstVisibleItem;
if Assigned(Item) and Item.Separator then
begin
Item.Control.Visible := False;
Dec(FMenuSize.Y, Item.Control.Height);
end;
Item := FindLastVisibleItem;
if Assigned(Item) and Item.Separator then
begin
Item.Control.Visible := False;
Dec(FMenuSize.Y, Item.Control.Height);
end;
PositionPopup(FParentMenu, FParentControl);
if Assigned(FParentMenu) then
Animate(True);
end;
end;
function TCustomActionPopupMenu.GetControlClass(
AnItem: TActionClientItem): TCustomActionControlClass;
begin
Result := MenuItemControlClass;
end;
procedure TCustomActionPopupMenu.CloseMenu;
begin
Visible := False;
inherited CloseMenu;
end;
{ TCustomAddRemoveItem }
procedure TCustomAddRemoveItem.CalcBounds;
var
R: TRect;
begin
inherited CalcBounds;
Width := Width + 18;
GlyphPos := Point(GlyphPos.X + 18, GlyphPos.Y);
R := TextBounds;
OffsetRect(R, 18,0);
TextBounds := R;
end;
procedure TCustomAddRemoveItem.MouseUp(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
inherited MouseUp(Button, Shift, X, Y);
Invalidate;
end;
procedure TCustomAddRemoveItem.SetEnabled(Value: Boolean);
begin
inherited SetEnabled(True);
end;
{ TCustomizeActionToolBar }
constructor TCustomizeActionToolBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if AOwner is TCustomActionToolBar then
FActionBar := TCustomActionToolBar(AOwner);
end;
destructor TCustomizeActionToolBar.Destroy;
begin
FResetAction.Free;
inherited Destroy;
end;
procedure TCustomizeActionToolBar.Clear;
begin
end;
procedure TCustomizeActionToolBar.CMItemSelected(var Message: TCMItemMsg);
begin
CloseMenu;
end;
function TCustomizeActionToolBar.GetActionControl(
const Index: Integer): TCustomActionControl;
begin
if (Index >= 0) and (Index < ItemCount) then
Result := ActionClient.Items[Index].Control
else
Result := nil;
end;
function TCustomizeActionToolBar.ItemCount: Integer;
begin
if Assigned(ActionClient) then
Result := ActionClient.Items.Count
else
Result := 0;
end;
function TCustomizeActionToolBar.GetControlClass(
AnItem: TActionClientItem): TCustomActionControlClass;
begin
if AnItem.ParentItem <> TCustomizeActionToolbar(RootMenu).FAddlItem then
Result := MenuItemControlClass
else
Result := MenuAddRemoveItemClass;
end;
type
TWinCtrlClass = class(TWinControl);
function TCustomizeActionToolBar.DoItemClicked(
AnItem: TCustomActionControl): TActionClientItem;
begin
if not AnItem.Separator and (AnItem is MenuAddRemoveItemClass) then
begin
with FActionBar.ActionClient.Items[AnItem.ActionClient.Index] do
Visible := not Visible;
FActionBar.Realign;
with FActionBar do
FActionBar.SetBounds(Left, Top, Width, Height);
Result := nil;
end
else if AnItem.ActionClient = FResetItem then
begin
CloseMenu;
Result := AnItem.ActionClient;
PostMessage(FActionBar.Handle, CM_RESETBAR, 0, 0);
end
else
Result := inherited DoItemClicked(AnItem);
end;
function TCustomizeActionToolBar.DoGetPopupClass: TCustomPopupClass;
begin
Result := MenuPopupClass;
end;
type
TActionManagerClass = class(TCustomActionManager);
procedure TCustomizeActionToolBar.SetActionClient(
const Value: TActionClient);
procedure AddSeparator(ActionClients: TActionClients);
begin
with ActionClients.Add do
begin
Caption := '-';
UsageCount := -1;
ChangesAllowed := [];
end;
end;
var
Item: TActionClientItem;
I: Integer;
ActionBarItem: TActionBarItem;
begin
if Assigned(Value) and Assigned(FActionBar) then
begin
ActionBarItem := nil;
if Assigned(FActionBar.ActionManager.DefaultActionBars) then
with FActionBar do
ActionBarItem := TActionBarItem(ActionManager.DefaultActionBars.FindItemID(ActionClient.Index));
if Assigned(ActionBarItem) then
begin
AddSeparator(Value.Items);
FAddlItem := Value.Items.Add;
FAddlItem.Caption := SAddRemoveButtons;
for I := 0 to ActionBarItem.Items.Count - 1 do
begin
Item := FAddlItem.Items.Add;
Item.Assign(ActionBarItem.Items[I]);
Item.Items := nil;
Item.UsageCount := -1;
Item.ChangesAllowed := [];
end;
if ActionBarItem.Items.Count > 0 then
begin
FResetAction := TCustomAction.Create(Self);
with FResetAction do
Caption := SResetActionToolbar;
if FAddlItem.Items.Count > 0 then
AddSeparator(Value.Items);
FResetItem := Value.Items.Add;
with FResetItem do
begin
Action := FResetAction;
UsageCount := -1;
ChangesAllowed := [];
end;
end;
end;
end;
inherited SetActionClient(Value);
ActionClient.Items.Customizable := False;
end;
procedure TCustomizeActionToolBar.CloseMenu;
begin
inherited CloseMenu;
end;
{ TCustomizeActionLink }
procedure TCustomizeActionLink.SetEnabled(Value: Boolean);
begin
if Assigned(FClient.Control) then
FClient.Control.Enabled := True;
end;
{ TCustomizeActionClientItem }
function TCustomizeActionClientItem.GetActionLinkClass: TActionClientLinkClass;
begin
Result := TCustomizeActionLink;
end;
{ TCustomActionMainMenuBar }
constructor TCustomActionMainMenuBar.Create(AOwner: TComponent);
var
HotKeys: BOOL;
begin
inherited Create(AOwner);
SystemParametersInfo(SPI_GETMENUUNDERLINES, 0, @HotKeys, 0);
Align := alTop;
PersistentHotKeys := HotKeys;
AllowHiding := False;
HorzMargin := 1;
Height := 29;
AddMenuToList(Self);
if (MenuKeyHook = 0) and not Assigned(ActionBarDesigner) then
MenuKeyHook := SetWindowsHookEx(WH_GETMESSAGE, @GetMsgHook, 0,
GetCurrentThreadID);
end;
procedure TCustomActionMainMenuBar.AlignControls(AControl: TControl;
var Rect: TRect);
begin
if AControl is TCustomActionPopupMenu then exit; {!!}
inherited AlignControls(AControl, Rect);
end;
procedure TCustomActionMainMenuBar.WMKeyDown(var Message: TWMKeyDown);
var
Popup: TCustomActionBar;
begin
case Orientation of
boLeftToRight,
boRightToLeft:
case Message.CharCode of
VK_RIGHT: Select(Orientation = boLeftToRight);
VK_LEFT : Select(Orientation <> boLeftToRight);
VK_DOWN,
VK_UP:
if Assigned(Selected) and Assigned(Selected) then
begin
if DesignMode and not Selected.HasItems then
if ssCtrl in KeyboardStateToShiftState then
begin
Selected.Items.Add;
NotifyDesigner(Self);
end
else
exit;
if Selected.HasItems then
begin
Popup := CreatePopup(Self, Selected.Control);
Popup.FindFirst.Control.Selected := True;
Message.CharCode := 0;
exit;
end;
end;
end;
boTopToBottom,
boBottomToTop:
case Message.CharCode of
VK_RIGHT:
if Assigned(Selected) and Assigned(Selected) and
Selected.HasItems then
Selected.Control.Keyed;
VK_LEFT: Select(True);
end;
end;
inherited;
end;
type
TCustomFormType = class(TCustomForm);
function TCustomActionMainMenuBar.CreateControl(
AnItem: TActionClientItem): TCustomActionControl;
begin
Result := inherited CreateControl(AnItem);
with Result as GetControlClass(AnItem) do
Spacing := 2;
end;
procedure TCustomActionMainMenuBar.DoneMenuLoop;
var
HotKeys: BOOL;
begin
inherited DoneMenuLoop;
SystemParametersInfo(SPI_GETMENUUNDERLINES, 0, @HotKeys, 0);
if not HotKeys then
PersistentHotkeys := False;
end;
procedure TCustomActionMainMenuBar.WndProc(var Message: TMessage);
begin
if csDesigning in ComponentState then
case Message.Msg of
WM_KEYDOWN:
if Message.WParam = VK_ESCAPE then
CloseMenu;
end;
inherited WndProc(Message);
end;
function TCustomActionMainMenuBar.GetControlClass(
AnItem: TActionClientItem): TCustomActionControlClass;
begin
Result := MenuButtonControlClass;
end;
procedure TCustomActionMainMenuBar.WMNCHitTest(var Message: TWMNCHitTest);
begin
inherited;
if DesignMode then
Message.Result := HTCLIENT;
end;
procedure TCustomActionMainMenuBar.ProcessMouseMsg(var Msg: tagMSG);
var
Item: TCustomActionControl;
begin
inherited ProcessMouseMsg(Msg);
case Msg.message of
WM_LBUTTONDOWN,
WM_RBUTTONDOWN:
begin
Item := GetMouseHoverItem(Msg);
if Assigned(Item) then
begin
if (Item.Owner = Self) then
if not Item.Selected then
Item.Click;
end
else
begin
if not DesignMode then
CloseMenu;
DispatchMessage(Msg);
end;
end;
end;
end;
procedure TCustomActionMainMenuBar.CMWininichange(var Message: TMessage);
begin
inherited;
Font.Assign(Screen.MenuFont);
Resize;
end;
function TCustomActionMainMenuBar.CanAutoSize(var NewWidth,
NewHeight: Integer): Boolean;
begin
Result := False;
if not AlignDisabled then
begin
NewHeight := GetBarHeight;
NewWidth := GetBarWidth;
end;
end;
procedure TCustomActionMainMenuBar.SetDesignMode(const Value: Boolean);
begin
if DesignMode and not Value then
begin
ClearSubMenus;
CloseMenu;
end;
inherited SetDesignMode(Value);
end;
procedure TCustomActionMainMenuBar.SetInActive(const Value: Boolean);
begin
if FInActive <> Value then
begin
FInActive := Value;
Invalidate;
end;
end;
{ TCustomMenuItem }
constructor TCustomMenuItem.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csCaptureMouse];
Margins := Rect(2,0,10,0);
Spacing := 5; // Distance between Caption and ShortcutText
if AOwner is TCustomActionMenuBar then
FMenu := TCustomActionMenuBar(AOwner);
end;
destructor TCustomMenuItem.Destroy;
begin
if Assigned(ActionClient) and (ActionClient.ChildActionBar is TCustomActionMenuBar) then
TCustomActionMenuBar(ActionClient.ChildActionbar).CloseMenu;
inherited Destroy;
end;
procedure TCustomMenuItem.DrawSubMenuGlyph;
const
ArrowPos = 11;
ArrowColor: array[Boolean] of Integer = (clBtnText, clWhite);
begin
with Canvas do
begin
Pen.Color := ArrowColor[Selected];
Brush.Color := Pen.Color;
end;
if Selected then
Canvas.Pen.Color := clHighlightText;
DrawArrow(Canvas, sdRight, Point(Width - ArrowPos, Height div 2 - 3), 3);
end;
procedure TCustomMenuItem.Paint;
var
Flags: Cardinal;
ShortCutRect: TRect;
begin
inherited Paint;
if IsChecked and not HasGlyph then
DrawGlyph(GlyphPos);
if ShowShortCut then
begin
Flags := DrawTextBiDiModeFlags(DT_RIGHT);
ShortCutRect := FShortCutBounds;
OffsetRect(ShortCutRect, Width - 21 - FShortCutBounds.Right, 0);
DrawText(ShortCutRect, Flags, ActionClient.ShortCutText);
end;
if Assigned(ActionClient) and ActionClient.HasItems and
(ActionClient.Items.VisibleCount > 0) then
DrawSubMenuGlyph;
DrawUnusedEdges;
end;
procedure TCustomMenuItem.DrawUnusedEdges;
const
Edge: array[Boolean] of Integer = (BDR_RAISEDINNER, BDR_SUNKENOUTER);
var
PaintRect: TRect;
begin
PaintRect := ClientRect;
if (ebTop in FEdges) then
Windows.DrawEdge(Canvas.Handle, PaintRect, Edge[ActionClient.Unused], Byte(Edges));
if (ebBottom in FEdges) then
Windows.DrawEdge(Canvas.Handle, PaintRect, Edge[ActionClient.Unused], BF_BOTTOM);
if (ebRight in FEdges) then
if ebTop in Edges then
Inc(PaintRect.Top);
end;
procedure TCustomMenuItem.Click;
begin
GetParentForm(Menu.RootMenu).SetFocus;
// Do nothing here since menu items are only ever really clicked when the
// user lets the mouse button up while over an item
end;
function TCustomMenuItem.GetImageSize: TPoint;
begin
Result := inherited GetImageSize;
if (Result.X > 0) and (Result.X < 16) then
Result.X := 16;
end;
procedure TCustomMenuItem.Keyed;
begin
SetSelected(True);
FMouseSelected := False;
if Action is TCustomAction then
with TCustomAction(Action) do
Checked := GroupIndex > 0;
inherited Keyed;
end;
procedure TCustomMenuItem.SetEdges(const Value: TMenuEdges);
var
NewHeight: Integer;
LastItem: TActionClientItem;
begin
if FEdges <> Value then
begin
NewHeight := Height;
if (ebTop in Value) and not (ebTop in FEdges) then
Inc(NewHeight)
else
if not (ebTop in Value) and (ebTop in FEdges) then
Dec(NewHeight);
if (ebBottom in Value) and not (ebBottom in FEdges) then
Inc(NewHeight)
else
if not (ebBottom in Value) and (ebBottom in FEdges) then
Dec(NewHeight);
LastItem := ActionBar.FindLastVisibleItem;
if Assigned(LastItem) and (Self = LastItem.Control) then
Inc(NewHeight);
FEdges := Value;
Height := NewHeight;
Invalidate;
end;
end;
type
TMenuActionBarClass = class(TCustomActionMenuBar);
procedure TCustomMenuItem.CMMouseEnter(var Message: TMessage);
begin
inherited;
if (DragMode = dmAutomatic) or Assigned(ActionClient) and
Assigned(ActionClient.ChildActionBar) then
exit;
if csDesigning in ComponentState then
SetSelected(True)
else
if not Separator then
if Enabled then
begin
SetSelected(True);
if not ActionBar.DesignMode then
FMouseSelected := True;
end
else
if Assigned(Menu) then
with TMenuActionBarClass(Menu) do
TMenuActionBarClass(RootMenu).DelayItem := nil;
end;
procedure TCustomMenuItem.SetSelected(Value: Boolean);
begin
if not Value then
FMouseSelected := False;
inherited SetSelected(Value);
if Assigned(Menu) then
TMenuActionBarClass(Menu).DoItemSelected(Self);
end;
procedure TCustomMenuItem.DrawDesignFocus(var PaintRect: TRect);
begin
with Canvas, ClientRect do
begin
Brush.Color := clHighlight;
if not ActionClient.HasItems then
begin
Pen.Color := clBlack;
Brush.Style := bsClear;
end
else
Pen.Color := clGreen;
Pen.Width := 2;
if Assigned(ActionClient) and ActionClient.HasItems then
begin
PatBlt(Handle, Left, Top, Width, 2, PATINVERT);
PatBlt(Handle, Left + Width - 4, Top + 2, 2, Height, PATINVERT);
PatBlt(Handle, Left + 3, Top + Height - 2, Width - 7, 2, PATINVERT);
PatBlt(Handle, Left + 1, Top + 2, 2, Height, PATINVERT);
end
else
begin
PaintRect := ClientRect;
Inc(PaintRect.Left, 2);
if ActionClient.Unused then
begin
Inc(PaintRect.Top);
Dec(PaintRect.Bottom);
end
else
begin
Inc(PaintRect.Top);
Dec(PaintRect.Right, 2);
end;
inherited DrawDesignFocus(PaintRect);
end;
end;
end;
procedure TCustomMenuItem.DragDrop(Source: TObject; X, Y: Integer);
begin
inherited DragDrop(Source, X, Y);
if (ActionBar is TCustomActionMenuBar) then
with ActionBar as TCustomActionMenuBar do
if (RootMenu <> nil) and Assigned(RootMenu.Parent) then
Windows.SetFocus(RootMenu.Parent.Handle);
end;
procedure TCustomMenuItem.DragOver(Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
if (Source is TActionItemDragObject) then
with Source as TActionItemDragObject do
begin
if (ActionClient = ClientItem) and
(ActionClient.ChildActionBar is TCustomActionMenuBar) then
with ActionClient.ChildActionBar as TCustomActionMenuBar do
CloseMenu;
if Assigned(Menu.RootMenu.DelayItem) and
(Menu.RootMenu.DelayItem.ActionClient = ClientItem) then
Menu.RootMenu.DelayItem := nil;
end;
inherited DragOver(Source, X, Y, State, Accept);
if Accept and (ActionBar is TCustomActionMenuBar) then
if TCustomActionMenuBar(ActionBar).InMenuLoop then
Selected := True
end;
procedure TCustomMenuItem.CMTextchanged(var Message: TMessage);
begin
inherited;
if Separator then
Height := GetSystemMetrics(SM_CYMENU) div 2
else
Height := GetSystemMetrics(SM_CYMENU);
end;
procedure TCustomMenuItem.CalcBounds;
const
ImageOffset: array[Boolean] of Integer = (24, 0);
var
AWidth, AHeight: Integer;
NewTextBounds: TRect;
begin
inherited CalcBounds;
if Separator then
AHeight := GetSystemMetrics(SM_CYMENU) div 3 * 2
else
if Height < GetSystemMetrics(SM_CYMENU) then
AHeight := GetSystemMetrics(SM_CYMENU)
else
AHeight := Height;
if ActionClient = nil then exit;
NewTextBounds := TextBounds;
OffsetRect(NewTextBounds, 24 - TextBounds.Left,
AHeight div 2 - TextBounds.Bottom div 2 - 1);
TextBounds := NewTextBounds;
ShortCutBounds := Rect(0,0,0,0);
if ActionClient.ShortCut <> 0 then
begin
Windows.DrawText(Canvas.Handle, PChar(ActionClient.ShortCutText), -1,
FShortCutBounds, DT_CALCRECT);
// Left offset is determined when the item is painted to make it ight justified
OffsetRect(FShortCutBounds, 0, TextBounds.Top);
AWidth := Width + FShortCutBounds.Right + ImageOffset[HasGlyph] + Spacing + 21;
end
else
AWidth := TextBounds.Right + TextBounds.Left;
SetBounds(Left, Top, AWidth, AHeight);
end;
procedure TCustomMenuItem.CalcLayout;
begin
inherited CalcLayout;
GlyphPos := Point(Margins.Left, Height div 2 - GetImageSize.Y div 2 + 1);
end;
procedure TCustomMenuItem.DrawEdge(Edges: TMenuEdges);
var
Clrs: array[Boolean] of TColor;
begin
Clrs[False] := GetHighLightColor(ActionBar.Color);
Clrs[True] := GetShadowColor(ActionBar.Color);
Canvas.Pen.Color := Clrs[False];
Canvas.MoveTo(ClientRect.Right, ClientRect.Top);
if ebTop in Edges then
Canvas.LineTo(ClientRect.Left, ClientRect.Top)
else
Canvas.MoveTo(ClientRect.Left, ClientRect.Top);
if ebLeft in Edges then
Canvas.LineTo(ClientRect.Left, ClientRect.Bottom)
else
Canvas.MoveTo(ClientRect.Left, ClientRect.Bottom);
Canvas.Pen.Color := Clrs[True];
Canvas.Pen.Width := 1;
Canvas.MoveTo(ClientRect.Right - 1, ClientRect.Top);
Canvas.LineTo(ClientRect.Right - 1, ClientRect.Bottom);
Canvas.MoveTo(ClientRect.Right - 2, ClientRect.Top);
Canvas.Pen.Color := Clrs[True];
if Assigned(ActionClient) and not ActionClient.Unused and (ebRight in Edges) then
Canvas.LineTo(ClientRect.Right - 2, ClientRect.Bottom + 1)
else
Canvas.MoveTo(ClientRect.Right - 2, ClientRect.Bottom - 1);
if ebBottom in Edges then
Canvas.LineTo(ClientRect.Left, ClientRect.Bottom - 1);
end;
procedure TCustomMenuItem.PositionChanged;
begin
inherited PositionChanged;
TMenuActionBarClass(Menu).Expand(True);
end;
type
TActionBarClass = class(TCustomActionBar);
procedure TCustomMenuItem.DoDragDrop(DragObject: TObject; X, Y: Integer);
var
NewItem, NewCategory: TActionClientItem;
I, Idx: Integer;
begin
if Assigned(ActionClient) then
Idx := ActionClient.Index
else
Idx := 0;
if DragObject is TCategoryDragObject then
begin
ActionBar.DisableAlign;
ActionBar.ActionClient.Items.BeginUpdate;
with DragObject as TCategoryDragObject do
begin
with TActionManagerClass(ActionBar.ActionManager) do
NewCategory := GetActionClientItemClass.Create(ActionBar.ActionClient.Items);
try
try
NewCategory.UsageCount := 1;
NewCategory.Index := Idx;
NewCategory.LastSession := ActionBar.ActionManager.ActionBars.SessionCount;
NewCategory.Caption := Category;
NewCategory.Items.BeginUpdate;
for I := 0 to ActionCount - 1 do
begin
NewItem := TActionClientItem.Create(NewCategory.Items);
NewItem.Action := Actions[I];
NewItem.LastSession := NewCategory.LastSession;
end;
NewCategory.Control.Enabled := ActionCount > 0;
finally
NewCategory.Items.EndUpdate;
end;
finally
ActionBar.ActionClient.Items.EndUpdate;
ActionBar.EnableAlign;
NotifyDesigner(ActionBar);
end;
end;
end
else
inherited DoDragDrop(DragObject, X, Y);
end;
procedure TCustomMenuItem.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited MouseUp(Button, Shift, X, Y);
if Button <> mbLeft then exit;
if Assigned(ActionClient) and Assigned(ActionClient.ChildActionBar) then exit;
if Action is TCustomAction then
with TCustomAction(Action) do
Checked := GroupIndex > 0;
ResetUsageData;
PostMessage(Parent.Handle, CM_ITEMCLICKED, 0, LongInt(Self));
end;
{ TCustomMenuButton }
procedure TCustomMenuButton.BeginAutoDrag;
begin
Click;
inherited BeginAutoDrag;
end;
procedure TCustomMenuButton.Click;
begin
SetSelected(True);
inherited Click;
if Assigned(ActionClient) and not Assigned(ActionClient.Action) then
PostMessage(ActionBar.Handle, CM_ITEMCLICKED, 0, LongInt(Self));
end;
procedure TCustomMenuButton.CMMouseEnter(var Message: TMessage);
begin
inherited;
if Assigned(ActionClient) and Assigned(ActionClient.Action) then exit;
if ActionBar is TCustomActionMenuBar then
if not ActionBar.DesignMode and not Selected and
TCustomActionMenuBar(ActionBar).InMenuLoop then
Click;
end;
destructor TCustomMenuButton.Destroy;
begin
if Assigned(ActionClient) and (ActionClient.ChildActionBar is TCustomActionMenuBar) then
TCustomActionMenuBar(ActionClient.ChildActionbar).CloseMenu;
inherited Destroy;
end;
procedure TCustomMenuButton.DragOver(Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
inherited DragOver(Source, X, Y, State, Accept);
if Accept and (ActionBar is TCustomActionMenuBar) then
begin
if Source is TActionItemDragObject then
with Source as TActionItemDragObject do
if (ClientItem = ActionClient) and Assigned(ActionBar) and
(ActionBar is TCustomActionMenuBar) then
with ActionBar as TCustomActionMenuBar do
ClearSubMenus;
if not Selected then
Click;
end;
end;
procedure TCustomMenuButton.DrawText(var ARect: TRect; var Flags: Cardinal;
Text: string);
var
S: string;
begin
S := Text;
if Parent is TCustomActionMainMenuBar then
with Parent as TCustomActionMainMenuBar do
if not PersistentHotkeys then
begin
if Pos('&', S) > 0 then
Delete(S, Pos('&', S), 1);
end;
inherited DrawText(ARect, Flags, S);
end;
procedure TCustomMenuButton.Keyed;
begin
SetSelected(True);
inherited Keyed;
end;
procedure TCustomMenuButton.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if (Button = mbLeft) and (ActionBar is TCustomActionMainMenuBar) and
not TCustomActionMainMenuBar(ActionBar).InMenuLoop then
Click
else
inherited MouseDown(Button, Shift, X, Y);
end;
procedure TCustomMenuButton.Paint;
var
OldState: TButtonState;
begin
OldState := State;
if Assigned(ActionClient.ChildActionBar) then
FState := bsDown;
inherited Paint;
FState := OldState;
end;
procedure TCustomActionPopupMenu.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
if AComponent is TControl then
with AComponent as TControl do
begin
Visible := False;
AdjustSize;
end;
end;
function TCustomizeActionToolBar.CanAutoSize(var NewWidth,
NewHeight: Integer): Boolean;
begin
Result := False;
end;
function TCustomActionMenuBar.NewPopup: TCustomActionPopupMenu;
begin
Result := DoGetPopupClass.Create(Self);
end;
function TCustomizeActionToolBar.NewPopup: TCustomActionPopupMenu;
begin
Result := inherited NewPopup;
Result.OnGetControlClass := GetSubMenuControlClass;
end;
procedure TCustomizeActionToolBar.GetSubMenuControlClass(
Sender: TCustomActionBar; AnItem: TActionClient;
var ControlClass: TCustomActionControlClass);
begin
if AnItem is TActionClientItem then
with AnItem as TActionClientItem do
if ParentItem = FAddlItem then
ControlClass := MenuAddRemoveItemClass
else
ControlClass := MenuItemControlClass;
end;
procedure TCustomActionMainMenuBar.CloseMenu;
begin
ClearSubMenus;
inherited CloseMenu;
end;
initialization
RegisterStandardMenus;
MenuKeyHook := 0;
MenuCallWndHook := 0;
MenuList := nil;
end.
|
unit siniflar;
interface
type
TDurum = (Hatali, Basarili, Isleniyor);
TYon = (GIDEN, GELEN);
TBelge = (FATURA, ZARF, CEVAP, YANIT);
TSenaryo = (TEMELFATURA, TICARIFATURA, EARSIVFATURA, IHRACAT);
TTip = (SATIS, IADE, ISTISNA);
TMuhatap = class
private
public
public VKN, Adi, Soyadi, VergiDairesi, Il, Ilce, UlkeKodu, UlkeAdi, Adres: string;
constructor Yarat(VKN, Adi, Soyadi, VergiDairesi, Il, Ilce, UlkeKodu, UlkeAdi, Adres: String);
end;
TVergi = class
private
public
public Tevkifat: Boolean;
public Kodu, Adi: string;
public Matrah, Oran, Tutar: Double;
constructor Yarat(Kodu, Adi: String; Matrah, Oran, Tutar: Double; Tevkifat: Boolean = false);
end;
TIskonto = class
private
public
public Matrah, Oran, Tutar: Double;
constructor Yarat(Matrah, Oran, Tutar: Double);
end;
TKalem = class
private
public
public Kodu, Adi, OlcuBirimi: String;
public Miktar, BirimFiyat, Tutar: Double;
public Iskonto: TIskonto;
public Vergiler: TArray<TVergi>;
constructor Yarat(Kodu, Adi, OlcuBirimi: String; Miktar, BirimFiyat, Tutar: Double);
end;
implementation
constructor TMuhatap.Yarat(VKN, Adi, Soyadi, VergiDairesi, Il, Ilce, UlkeKodu, UlkeAdi, Adres: String);
begin
Self.VKN := VKN;
Self.Adi := Adi;
Self.Soyadi := Soyadi;
Self.VergiDairesi := VergiDairesi;
Self.Il := Il;
Self.Ilce := Ilce;
Self.UlkeKodu := UlkeKodu;
Self.UlkeAdi := UlkeAdi;
Self.Adres := Adres;
end;
constructor TVergi.Yarat(Kodu, Adi: String; Matrah, Oran, Tutar: Double; Tevkifat: Boolean = false);
begin
Self.Tevkifat := Tevkifat;
Self.Kodu := Kodu;
Self.Adi := Adi;
Self.Matrah := Matrah;
Self.Oran := Oran;
Self.Tutar := Tutar;
end;
constructor TIskonto.Yarat(Matrah, Oran, Tutar: Double);
begin
Self.Matrah := Matrah;
Self.Oran := Oran;
Self.Tutar := Tutar;
end;
constructor TKalem.Yarat(Kodu, Adi, OlcuBirimi: String; Miktar, BirimFiyat, Tutar: Double);
begin
Self.Kodu := Kodu;
Self.Adi := Adi;
Self.OlcuBirimi := OlcuBirimi;
Self.Miktar := Miktar;
Self.BirimFiyat := BirimFiyat;
Self.Tutar := Tutar;
SetLength(Self.Vergiler, 0);
end;
end.
|
{*********************************************}
{ TeeGrid Software Library }
{ Tree Emulation Virtual Data class }
{ Copyright (c) 2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit Tee.Grid.Data.Tree;
interface
uses
Tee.Grid, Tee.Grid.Columns, Tee.Painter, Tee.Renders, Tee.Grid.Data;
type
PNode=^TNode;
TNodes=Array of PNode;
TNode=record
public
Data : TVirtualData;
Text : String;
Items : TNodes;
function Add(const AText:String):PNode;
function Count:Integer; inline;
end;
TTreeGridData=class(TVirtualData)
private
FItems : TNodes;
class function NodeOf(const AColumn:TColumn):PNode; inline; static;
protected
public
Constructor Create;
Destructor Destroy; override;
procedure AddColumns(const AColumns:TColumns); override;
function AsFloat(const AColumn:TColumn; const ARow:Integer):TFloat; override;
function AsString(const AColumn:TColumn; const ARow:Integer):String; override;
function AutoWidth(const APainter:TPainter; const AColumn:TColumn):Single; override;
function CanExpand(const Sender:TRender; const ARow:Integer):Boolean; override;
function CanSortBy(const AColumn:TColumn):Boolean; override;
function Count:Integer; override;
function GetDetail(const ARow:Integer; const AColumns:TColumns; out AParent:TColumn): TVirtualData; override;
function IsSorted(const AColumn:TColumn; out Ascending:Boolean):Boolean; override;
procedure Load; override;
procedure SetValue(const AColumn:TColumn; const ARow:Integer; const AText:String); override;
procedure SortBy(const AColumn:TColumn); override;
end;
implementation
|
unit ncgBackupPrinters;
interface
uses SysUtils, Windows, Classes, WinSvc;
procedure BackupPrinters(const aIgnoraSeJaExiste: Boolean = True);
procedure RestorePrinters(const aApagaArqs: Boolean = True);
implementation
uses ncPRConsts, ncDebug, ncShellStart;
const
DeleteKey1 = 'HKCU\Printers';
DeleteKey2 = 'HKCU\Software\Microsoft\Windows NT\CurrentVersion\Devices';
DeleteKey3 = 'HKCU\Software\Microsoft\Windows NT\CurrentVersion\PrinterPorts';
DeleteKey4 = 'HKLM\SYSTEM\CurrentControlSet\Control\Print';
function isServiceStarted( sMachine, sService : string ) : boolean;
var
schm : SC_Handle; // service control manager handle
schs : SC_Handle; // service handle
ss : TServiceStatus; // service status
begin
result := false;
// connect to the service control manager
schm := OpenSCManager( PChar(sMachine), Nil, SC_MANAGER_CONNECT);
// if successful...
if(schm > 0)then begin
// open a handle to the specified service
schs := OpenService( schm, PChar(sService), SERVICE_STOP or SERVICE_QUERY_STATUS);
// if successful...
if(schs > 0)then begin
if(QueryServiceStatus( schs, ss))then
result := (SERVICE_RUNNING = ss.dwCurrentState);
// close service handle
CloseServiceHandle(schs);
end;
// close service control manager handle
CloseServiceHandle(schm);
end;
end;
var
schm : SC_Handle; // service control manager handle
schs : SC_Handle; // service handle
ss : _Service_Status; // service status
psTemp : PChar; // temp char pointer
dwChkP : DWord; // check point
function ServiceStart(sMachine, sService : string ) : boolean;
begin
ss.dwCurrentState := maxint;
// connect to the service control manager
schm := OpenSCManager( PChar(sMachine), Nil, SC_MANAGER_CONNECT);
// if successful...
if(schm > 0)then begin
// open a handle to
// the specified service
schs := OpenService( schm, PChar(sService), SERVICE_START or SERVICE_QUERY_STATUS);
// if successful...
if(schs > 0)then begin
psTemp := Nil;
if(StartService( schs, 0, psTemp))then begin
// check status
if ControlService(schs, SERVICE_CONTROL_INTERROGATE, ss) then begin
while(SERVICE_RUNNING <> ss.dwCurrentState)do begin
// dwCheckPoint contains a value that the service increments periodically
// to report its progress during a lengthy operation. save current value
dwChkP := ss.dwCheckPoint;
// wait a bit before checking status again
// dwWaitHint is the estimated amount of time the calling program
// should wait before calling QueryServiceStatus() again
// idle events should be handled here...
Sleep(ss.dwWaitHint);
if not ControlService(schs, SERVICE_CONTROL_INTERROGATE, ss) then
// couldn't check status break from the loop
break;
if(ss.dwCheckPoint < dwChkP)then
// QueryServiceStatus didn't increment dwCheckPoint as it should have.
// avoid an infinite loop by breaking
break;
end;
end;
end;
// close service handle
CloseServiceHandle(schs);
end;
// close service control manager handle
CloseServiceHandle(schm);
end;
// return TRUE if the service status is running
Result := SERVICE_RUNNING = ss.dwCurrentState;
end;
// stop service
// return TRUE if successful
// sMachine:
// machine name, ie: \\SERVER
// empty = local machine
// sService
// service name, ie: Alerter
//
function ServiceStop( sMachine, sService : string ) : boolean;
var
schm : SC_Handle; // service control manager handle
schs : SC_Handle; // service handle
ss : _Service_Status; // service status
dwChkP : DWord; // check point
begin
// connect to the service control manager
schm := OpenSCManager( PChar(sMachine), Nil, SC_MANAGER_CONNECT);
// if successful...
if(schm > 0)then begin
// open a handle to the specified service
schs := OpenService( schm, PChar(sService), SERVICE_STOP or SERVICE_QUERY_STATUS);
// if successful...
if(schs > 0)then
begin
if (ControlService( schs, SERVICE_CONTROL_STOP, ss))then begin
// check status
if ControlService(schs, SERVICE_CONTROL_INTERROGATE, ss) then begin
while(SERVICE_STOPPED <> ss.dwCurrentState)do begin
// dwCheckPoint contains a value that the service increments periodically
// to report its progress during a lengthy operation. save current value
dwChkP := ss.dwCheckPoint;
// wait a bit before checking status again
// dwWaitHint is the estimated amount of time the calling program
// should wait before calling QueryServiceStatus() again
// idle events should be handled here...
Sleep(ss.dwWaitHint);
if not ControlService(schs, SERVICE_CONTROL_INTERROGATE, ss) then
Break;
if(ss.dwCheckPoint < dwChkP)then begin
// QueryServiceStatus didn't increment dwCheckPoint as it should have.
// avoid an infinite loop by breaking
break;
end;
end;
end;
end;
// close service handle
CloseServiceHandle(schs);
end;
// close service control manager handle
CloseServiceHandle(schm);
end;
// return TRUE if the service status is stopped
Result := SERVICE_STOPPED = ss.dwCurrentState;
end;
function WinExecAndWait32(FileName: string; Dir: String; Visibility: Integer; aWait: Boolean): Longword;
var { by Pat Ritchey }
zAppName: array[0..512] of Char;
zCurDir: array[0..255] of Char;
WorkDir: string;
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
begin
StrPCopy(zAppName, FileName);
GetDir(0, WorkDir);
StrPCopy(zCurDir, WorkDir);
FillChar(StartupInfo, SizeOf(StartupInfo), #0);
StartupInfo.cb := SizeOf(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := Visibility;
if not CreateProcess(nil,
zAppName, // pointer to command line string
nil, // pointer to process security attributes
nil, // pointer to thread security attributes
False, // handle inheritance flag
CREATE_NEW_CONSOLE or // creation flags
NORMAL_PRIORITY_CLASS,
nil, //pointer to new environment block
PChar(Dir), // pointer to current directory name
StartupInfo, // pointer to STARTUPINFO
ProcessInfo) // pointer to PROCESS_INF
then Result := WAIT_FAILED
else
begin
if aWait then begin
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
GetExitCodeProcess(ProcessInfo.hProcess, Result);
end;
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
end;
end;
function SaveRegKey(k,fn,dir:string):boolean;
var s: string;
begin
s := '/ES '+fn+' "'+k+'"';
DebugMsg('SaveRegKey - '+s);
WinExecAndWait32(SysUtils.GetEnvironmentVariable('windir')+'\regedit.exe '+s, dir, sw_hide, true);
End;
function RestoreRegKey(k,fn, dir:string):boolean;
var s: string;
begin
s := '/CS '+fn+' "'+k+'"';
DebugMsg('RestoreRegKey - '+s);
WinExecAndWait32(SysUtils.GetEnvironmentVariable('windir')+'\regedit.exe '+s, dir, sw_hide, true);
End;
function DeleteRegKey(k, dir:string):boolean;
var s: string;
begin
s := ' DELETE ' + K + ' /f';
DebugMsg('DeleteRegKey - '+k);
WinExecAndWait32(SysUtils.GetEnvironmentVariable('windir')+'\system32\reg.exe '+s, dir, sw_hide, true);
End;
procedure BackupPrinters(const aIgnoraSeJaExiste: Boolean = true);
var s: string;
begin
DebugMsg('BackupPrinters');
S := PRFolder(prfolder_backup);
if (not aIgnoraSeJaExiste) or
(not FileExists(S+'printers.reg')) or
(not FileExists(S+'devices.reg')) or
(not FileExists(S+'printerports.reg')) or
(not FileExists(S+'print.reg'))
then begin
S := ExtractFileDir(S);
DebugMsg('BackupPrinters - Destino: ' + S);
ForceDirectories(S);
ChDir(ExtractFileDir(S));
SaveRegKey( 'HKEY_CURRENT_USER\Printers', 'printers.reg', s);
SaveRegKey( 'HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices', 'devices.reg', s);
SaveRegKey( 'HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\PrinterPorts', 'printerports.reg', s);
SaveRegKey( 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print', 'print.reg', s);
end;
end;
procedure RestorePrinters(const aApagaArqs: Boolean = true);
var
s: string;
begin
S := PRFolder(prfolder_backup);
if not DirectoryExists(S) then Exit;
DebugMsg('RestorePrinters - Origem: ' + S);
if FileExists(S+'printers.reg') and
FileExists(S+'devices.reg') and
FileExists(S+'printerports.reg') and
FileExists(S+'print.reg') then
begin
if isServiceStarted('','Spooler') then ServiceStop('','Spooler');
DeleteRegKey(DeleteKey1, s);
DeleteRegKey(DeleteKey2, s);
DeleteRegKey(DeleteKey3, s);
DeleteRegKey(DeleteKey4, s);
ChDir(S);
RestoreRegKey( 'HKEY_CURRENT_USER\Printers', 'printers.reg', s);
RestoreRegKey( 'HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices', 'devices.reg', s);
RestoreRegKey( 'HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\PrinterPorts', 'printerports.reg', s);
RestoreRegKey( 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print', 'print.reg', s);
if not isServiceStarted('','Spooler') then ServiceStart('','Spooler');
end;
if aApagaArqs then begin
DebugMsg('RestorePrinters - Apagar');
DeleteFile(PAnsiChar(S+'devices.reg'));
DeleteFile(PAnsiChar(S+'printerports.reg'));
DeleteFile(PAnsiChar(S+'print.reg'));
DeleteFile(PAnsiChar(S+'printers.reg'));
end else
DebugMsg('RestorePrinters - Não apagar');
end;
end.
|
unit StamGeraeteKlassenFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
System.Generics.Collections, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.Mask, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids, classesArbeitsmittel, MainFrm, Helpers, SuchenFrm, XStammdatenFrm;
type
TStamGeraeteKlassenForm = class(TXStammdatenForm)
BezeichnungEdit: TEdit;
Label1: TLabel;
procedure AnzeigeUmschalten(Status: TFormStatus);
procedure AnzeigeFuellen;
procedure NeuButtonClick(Sender: TObject);
procedure AbbrechenButtonClick(Sender: TObject);
procedure LoeschenButtonClick(Sender: TObject);
procedure SpeichernButtonClick(Sender: TObject);
procedure SuchenButtonClick(Sender: TObject);
private
ArbeitsmittelKlasse: TArbeitsmittelKlasse;
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
StamGeraeteKlassenForm: TStamGeraeteKlassenForm;
implementation
{$R *.dfm}
{ TStamGeraeteKlassenForm }
procedure TStamGeraeteKlassenForm.AbbrechenButtonClick(Sender: TObject);
begin
if Assigned(self.ArbeitsmittelKlasse) and (self.FormStatus = fsNeu) then
self.AnzeigeUmschalten(fsGesperrt)
else
self.AnzeigeUmschalten(fsLeer)
end;
procedure TStamGeraeteKlassenForm.AnzeigeFuellen;
begin
if (Assigned(self.ArbeitsmittelKlasse)) and (self.FormStatus <> fsNeu) then
self.BezeichnungEdit.Text := self.ArbeitsmittelKlasse.Bezeichnung
else
self.BezeichnungEdit.Clear;
end;
procedure TStamGeraeteKlassenForm.AnzeigeUmschalten(Status: TFormStatus);
begin
inherited;
self.BezeichnungEdit.Enabled := self.FormStatus in [fsNeu, fsBearbeiten];
self.AnzeigeFuellen;
end;
procedure TStamGeraeteKlassenForm.LoeschenButtonClick(Sender: TObject);
begin
inherited;
if messagedlg(Format('Möchten sie die Arbeitsmittelklasse %s wirklich löschen?',
[self.ArbeitsmittelKlasse.Bezeichnung]), mtConfirmation,
[mbYes, mbCancel], 0) = mrYes THEN
if self.ArbeitsmittelKlasse.Loeschen then
begin
freeAndNil(self.ArbeitsmittelKlasse);
self.AnzeigeUmschalten(fsLeer);
end
else
messagedlg('Beim Löschen trat ein Fehler auf. Bitte wenden Sie sich an den Administrator', mtInformation,
[mbOk], 0);
end;
procedure TStamGeraeteKlassenForm.NeuButtonClick(Sender: TObject);
begin
inherited;
if Assigned(self.ArbeitsmittelKlasse) then
freeAndNil(self.ArbeitsmittelKlasse);
self.AnzeigeUmschalten(fsNeu);
end;
procedure TStamGeraeteKlassenForm.SpeichernButtonClick(Sender: TObject);
begin
inherited;
if not Assigned(self.ArbeitsmittelKlasse) then
self.ArbeitsmittelKlasse := TArbeitsmittelKlasse.Create(BezeichnungEdit.Text, MainForm.MainConnection);
if self.ArbeitsmittelKlasse.Speichern then
self.AnzeigeUmschalten(fsGesperrt)
else
messagedlg('Beim Speichern trat ein Fehler auf. Bitte wenden Sie sich an den Administrator', mtInformation,
[mbOk], 0);
end;
procedure TStamGeraeteKlassenForm.SuchenButtonClick(Sender: TObject);
var
SuchenForm : TSuchenForm;
SuchEintraege: TList<TSucheintrag>;
begin
SuchEintraege := TList<TSucheintrag>.Create;
SuchEintraege.Add(TSucheintrag.Create('Bezeichnung', 'Nachname'));
SuchenForm := TSuchenForm.Create(application, 'ArbeitsmittelKlasse', SuchEintraege, MainForm.MainConnection);
if SuchenForm.ShowModal = mrOK then
begin
if Assigned(self.ArbeitsmittelKlasse) then
FreeAndNil(self.ArbeitsmittelKlasse);
self.ArbeitsmittelKlasse := TArbeitsmittelKlasse.CreateFromId(SuchenForm.Ergebnis, MainForm.MainConnection);
self.AnzeigeUmschalten(fsGesperrt);
end;
end;
end.
|
unit DirSearchFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ChildFrm, StdCtrls, Grids, Outline, DirOutln, FileCtrl, ImgList;
type
TDirSearchForm = class(TChildForm)
drvcbb1: TDriveComboBox;
ListBox1: TListBox;
dirol1: TDirectoryOutline;
lblFileMask: TLabel;
edtFileMask: TEdit;
btn1: TButton;
procedure btn1Click(Sender: TObject);
procedure drvcbb1Change(Sender: TObject);
private
{ Private declarations }
FFileName: string;
function GetDirectoryName(Dir: string): string;
procedure FindFiles(Apath: string);
public
{ Public declarations }
end;
var
DirSearchForm: TDirSearchForm;
implementation
{$R *.dfm}
procedure TDirSearchForm.btn1Click(Sender: TObject);
begin
//inherited;
Screen.Cursor := crHourGlass;
try
ListBox1.Items.Clear;
FFileName := edtFileMask.Text;
FindFiles(dirol1.Directory);
finally
Screen.Cursor := crDefault;
end;
end;
procedure TDirSearchForm.drvcbb1Change(Sender: TObject);
begin
//inherited;
dirol1.Drive := drvcbb1.Drive;
end;
procedure TDirSearchForm.FindFiles(Apath: string);
var
FSearchRec, DsearchRec: TSearchRec;
FindResult: Integer;
function IsDirNotation(ADirName: string): Boolean;
begin
Result := (ADirName = '.') or (ADirName = '..');
end;
begin
Apath := GetDirectoryName(Apath);
FindResult := FindFirst(Apath + FFileName, faAnyFile + faHidden + faSysFile +
faReadOnly, FSearchRec);
try
while FindResult = 0 do
begin
ListBox1.Items.Add(LowerCase(Apath + FSearchRec.Name));
FindResult := FindNext(FSearchRec);
end;
FindResult := FindFirst(Apath + '*.*', faDirectory, DSearchRec);
while FindResult = 0 do
begin
if ((DSearchRec.Attr and faDirectory) = faDirectory) and not
IsDirNotation(DsearchRec.Name) then
FindFiles(Apath + DSearchRec.Name);
FindResult := FindNext(DsearchRec);
end;
finally
FindClose(FSearchRec);
end;
end;
function TDirSearchForm.GetDirectoryName(Dir: string): string;
begin
if Dir[Length(Dir)] <> '\' then
Result := Dir + '\'
else
Result := Dir;
end;
end.
|
unit u_xpl_rawset;
{==============================================================================
UnitName = u_xpl_rawset
UnitDesc = Generic class used to hold header message elements
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
1.5 : Added fControlInput property to override read/write controls needed for OPC
}
{$i xpl.inc}
interface
uses Classes
, SysUtils
, u_xpl_common
;
type // TxPLRawSet ============================================================
TxPLRawSet = class(TInterfacedPersistent, IxPLCommon, IxPLRaw)
protected
fRawxPL : TStringList;
fMaxSizes : IntArray;
fOnRawError : TStrParamEvent;
fControlInput : boolean;
procedure Set_RawxPL(const AValue: string);
function Get_RawxPL: string;
public
constructor Create;
destructor Destroy; override;
procedure ResetValues;
procedure Assign(aRawSet : TPersistent); override;
function Equals(const aRawSet : TxPLRawSet) : boolean; reintroduce; overload;
function IsValid : boolean;
function IsEmpty : boolean;
function AsFilter : string; virtual;
function Get_Element(AIndex: integer): string; virtual;
procedure Set_Element(AIndex: integer; const AValue: string); virtual;
property ControlInput : boolean read fControlInput write fControlInput;
published
property RawxPL : string read Get_RawxPL write Set_RawxPL stored false;
end;
implementation // =============================================================
uses StrUtils
;
// TxPLRawSet =================================================================
constructor TxPLRawSet.Create;
begin
inherited Create;
fControlInput := true;
fRawxPL := TStringList.Create;
fRawxPL.Delimiter:='.';
ResetValues;
end;
destructor TxPLRawSet.Destroy;
begin
fRawxPL.Free;
inherited Destroy;
end;
procedure TxPLRawSet.ResetValues;
var i,m : integer;
begin
fRawxPL.Clear;
if fControlInput
then m := High(fMaxSizes)
else m := 0;
For i := 0 to m do fRawxPL.Add('');
end;
procedure TxPLRawSet.Assign(aRawSet: TPersistent);
begin
if aRawSet is TxPLRawSet
then begin
fRawxPL.Assign(TxPLRawSet(aRawSet).fRawxPL);
fControlInput := TxPLRawSet(aRawSet).ControlInput;
end else inherited;
end;
function TxPLRawSet.Equals(const aRawSet: TxPLRawSet): boolean;
begin
result := fRawxPL.Equals(aRawSet.fRawxPL);
end;
function TxPLRawSet.Get_RawxPL: string;
begin
if fControlInput then Result := fRawxPL.DelimitedText
else Result := fRawxPL[0];
end;
procedure TxPLRawSet.Set_RawxPL(const AValue: string);
var list : TStringList;
i : integer;
begin
ResetValues;
list := TStringList.Create;
list.Delimiter := fRawxPL.Delimiter;
if fControlInput then list.DelimitedText := aValue
else list.Text := aValue;
For i := 0 to Pred(list.count) do Set_Element(i,list[i]);
list.free;
end;
function TxPLRawSet.IsValid: boolean;
var i : integer;
begin
if not fControlInput then exit(true);
Result := fRawxPL.Count <> 0; // At this level, check we have elements
for i := 0 to Pred(fRawxPL.Count) do
Result := Result and IsValidxPLIdent(fRawxPL[i]) // they are valid xPL syntax elements
and (length(fRawxPL[i])<=fMaxSizes[i]); // and conform to max element size
end;
function TxPLRawSet.IsEmpty: boolean;
var i : integer;
begin
i := Pred(fRawxPL.Count);
result := true;
while result and (i>=0) do begin
result := result and AnsiSameText(fRawxPL[i],'');
dec(i);
end;
end;
function TxPLRawSet.AsFilter: string;
var i : integer;
begin
Result := '';
for i := 0 to Pred(fRawxPL.Count) do
Result := Result + IfThen( fRawxPL[i] <> '', fRawxPL[i], '*') + '.';
Result := AnsiLeftStr(Result,length(Result)-1); // drop last '.'
end;
function TxPLRawSet.Get_Element(AIndex: integer): string;
begin
result := fRawxPL[aIndex];
end;
procedure TxPLRawSet.Set_Element(AIndex: integer; const AValue: string);
begin
fRawxPL[aIndex] := AnsiLowerCase(aValue);
end;
end.
|
unit PascalCoin.NodeRecord;
interface
uses PascalCoin.Wallet.Interfaces, System.Generics.Collections;
type
IPascalCoinNodeRec = interface
['{D550EB51-DB79-4C81-B485-2B4DF03D2059}']
function GetName: string;
procedure SetName(const Value: string);
function GetURL: string;
procedure SetURL(const Value: string);
function GetNetType: TPascalCoinNetType;
procedure SetNetType(const Value: TPascalCoinNetType);
property Name: string read GetName write SetName;
property URL: string read GetURL write SetURL;
property NetType: TPascalCoinNetType read GetNetType write SetNetType;
end;
IPascalCoinNodeRecList = interface
['{75AD7A89-B00E-42BA-B71A-4BD32374FBBF}']
function GetNode(const Index: Integer): IPascalCoinNodeRec;
procedure Delete(const index: Integer);
function Count: Integer;
function Add(ANode: IPascalCoinNodeRec): Integer;
procedure AddNode(const AName: string; const AURL: string;
const ANetType: string);
function NodeByURL(const AURL: string): IPascalCoinNodeRec;
function NodeIndexByURL(const AURL: string): Integer;
property Node[const Index: Integer]: IPascalCoinNodeRec read GetNode; default;
end;
TPascalCoinNodeRec = Class(TInterfacedObject, IPascalCoinNodeRec)
private
FName: string;
FURL: string;
FNetType: TPascalCoinNetType;
protected
function GetName: string;
procedure SetName(const Value: string);
function GetURL: string;
procedure SetURL(const Value: string);
function GetNetType: TPascalCoinNetType;
procedure SetNetType(const Value: TPascalCoinNetType);
End;
TPascalCoinNodeRecList = class(TInterfacedObject, IPascalCoinNodeRecList)
private
FNodes: TList<IPascalCoinNodeRec>;
protected
function GetNode(const Index: Integer): IPascalCoinNodeRec;
procedure Delete(const index: Integer);
function Count: Integer;
function Add(ANode: IPascalCoinNodeRec): Integer;
procedure AddNode(const AName: string; const AURL: string;
const ANetType: string);
function NodeByURL(const AURL: string): IPascalCoinNodeRec;
function NodeIndexByURL(const AURL: string): Integer;
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses System.SysUtils, System.Rtti;
{ TPascalCoinNodeRec }
function TPascalCoinNodeRec.GetName: string;
begin
result := FName;
end;
function TPascalCoinNodeRec.GetNetType: TPascalCoinNetType;
begin
result := FNetType;
end;
function TPascalCoinNodeRec.GetURL: string;
begin
result := FURL;
end;
procedure TPascalCoinNodeRec.SetName(const Value: string);
begin
FName := Value;
end;
procedure TPascalCoinNodeRec.SetNetType(const Value: TPascalCoinNetType);
begin
FNetType := Value;
end;
procedure TPascalCoinNodeRec.SetURL(const Value: string);
begin
FURL := Value;
end;
{ TPascalCoinNodeRecList }
function TPascalCoinNodeRecList.Add(ANode: IPascalCoinNodeRec): Integer;
begin
//Exists?
result := FNodes.Add(ANode);
end;
procedure TPascalCoinNodeRecList.AddNode(const AName: string; const AURL:
string; const ANetType: string);
var lNode: IPascalCoinNodeRec;
begin
if NodeByURL(AURL) = nil then
begin
lNode := TPascalCoinNodeRec.Create;
lNode.Name := AName;
lNode.URL := AURL;
lNode.NetType := TRttiEnumerationType.GetValue<TPascalCoinNetType>(ANetType);
Add(lNode);
end;
end;
function TPascalCoinNodeRecList.Count: Integer;
begin
result := FNodes.Count;
end;
constructor TPascalCoinNodeRecList.Create;
begin
inherited Create;
FNodes := TList<IPascalCoinNodeRec>.Create;
end;
procedure TPascalCoinNodeRecList.Delete(const index: Integer);
begin
FNodes.Delete(index);
end;
destructor TPascalCoinNodeRecList.Destroy;
begin
FNodes.Free;
inherited;
end;
function TPascalCoinNodeRecList.GetNode(
const Index: Integer): IPascalCoinNodeRec;
begin
result := FNodes[index];
end;
function TPascalCoinNodeRecList.NodeByURL(
const AURL: string): IPascalCoinNodeRec;
var lNode: IPascalCoinNodeRec;
begin
result := nil;
for lNode in FNodes do
begin
if SameText(lNode.URL, AURL) then
Exit(lNode);
end;
end;
function TPascalCoinNodeRecList.NodeIndexByURL(const AURL: string): Integer;
var
I: Integer;
begin
result := -1;
for I := 0 to FNodes.Count - 1 do
begin
if SameText(FNodes[I].URL, AURL) then
begin
Exit(I);
end;
end;
end;
end.
|
type
TPoint = record
X: Integer;
Y: Integer;
end;
Triangle = array[1..3] of TPoint;
// distance 2 points[A, B]
function Le(A, B: TPoint): Real;
begin
Le := Sqrt(Sqr(A.X - B.X) + Sqr(A.Y - B.Y));
end;
// in-out circle[M]
function IOC(M, C: TPoint; Ra: Real): Boolean;
begin
IOC := False;
if Le(M, C) <= Ra then IOC := True;
end;
// distance point[M] and line[AB]
function DPL(M, A, B: TPoint): Real;
var
S: Real;
begin
S := Abs((M.X - A.X)*(B.Y - A.Y) - (M.Y - A.Y)*(B.X - A.X));
DPL := S / Sqrt(Sqr(A.X - B.X) + Sqr(A.Y - B.Y));
end;
// line(2 points [A,B]) meets circle[M]
function LMC(A, B, M: TPoint; Ra: Real): Boolean;
var
XH, YH, R, T: Real;
begin
LMC := False;
if (IOC(M, A, Ra) and not IOC(M, B, Ra))
or (IOC(M, B, Ra) and not IOC(M, A, Ra)) then
LMC := True;
if (DPL(M, A, B) <= Ra) and not IOC(M, A, Ra) and not IOC(M, B, Ra) then
begin
R := A.X * B.Y - A.Y * B.X;
T := M.X * (B.X - A.X) + M.Y * (B.Y - A.Y);
XH := (R*(B.Y - A.Y) + T*(B.X - A.X))/(Sqr(B.Y - A.Y) + Sqr(B.X - A.X));
YH := (T*(B.Y - A.Y) - R*(B.X - A.X))/(Sqr(B.Y - A.Y) + Sqr(B.X - A.X));
if (A.X - B.X)*(M.Y - B.Y) - (A.Y - B.Y)*(M.X - B.X) = 0 then
LMC := True;
end;
end;
// triangle meets circle[M]
function TMC(T: Triangle; M: TPoint; Ra: Real): Boolean;
begin
TMC := False;
if LMC(T[1],T[2], M,Ra) or LMC(T[2],T[3], M,Ra) or LMC(T[3],T[1], M,Ra)
then TMC := True;
end;
(* ----------------------------------------------------------- *)
// choose 3 indexes [IZ, JZ, KZ]
procedure Choose(var IZ, JZ, KZ: Integer);
begin
if KZ < High() then
Inc(KZ)
else
begin
if JZ < High()-1 then
Inc(JZ)
else
begin
Inc(IZ);
JZ := IZ + 1;
end;
KZ := JZ + 1;
end;
end;
(* ----------------------------------------------------------- *)
(* choose N indexes *)
type
Index = array[1..5] of Integer;
procedure DEF(var A: Index);
var
I: Integer;
begin
for I := 1 to 5 do
A[I] := I;
end;
procedure Swap(var X, Y: Integer);
var
Temp: Integer;
begin
Temp := X; X:= Y; Y := Temp;
end;
procedure Choose(N: Integer; var Z: Index);
var
I, J, H, K: Integer;
begin
I := N-1;
while (I > 0) and (Z[I] > Z[I+1]) do
Dec(I);
if I > 0 then
begin
K := N;
while Z[I] > Z[K] do Dec(K);
Swap(Z[I], Z[K]);
for J := I+1 to N-1 do
for H := N downto J + 1 do
if Z[H] < Z[H-1] then
Swap(Z[H], Z[H-1]);
end;
end;
procedure Print(A: Index);
var
I: Integer;
begin
for I := 1 to 5 do
Write((A[I]-1):3);
WriteLn;
end;
var
A: Index;
begin
DEF(A);
repeat
Choose(5, A); Print(A);
ReadLn;
until 1=2;
end.
|
UNIT Sculpt3D;
interface
{$I FLOAT.INC}
TYPE
FaceProperty = WORD;
VertexPtr = ^VertexRec;
EdgeListPtr = ^EdgeListRec;
EdgePtr = ^EdgeRec;
FacePtr = ^FaceRec;
ObjectPtr = ^ObjectRec;
VertexRec = RECORD
next : VertexPtr;
pos : ARRAY[0..2] OF SINGLE;
edgelist : EdgeListPtr;
index : WORD;
END;
EdgeListRec = RECORD
next : EdgeListPtr;
edge : EdgePtr;
END;
EdgeRec = RECORD
next : EdgePtr;
vertices : ARRAY[0..1] OF VertexPtr;
END;
FaceRec = RECORD
next : FacePtr;
vertices : ARRAY[0..2] OF VertexPtr;
properties : FaceProperty;
END;
ObjectRec = RECORD
vertices : VertexPtr;
edges : EdgePtr;
faces : FacePtr;
END;
PROCEDURE WriteCoord(v : VertexPtr);
FUNCTION NewVertex(x,y,z : SINGLE; NextV : VertexPtr) : VertexPtr;
FUNCTION NewEdgeList( NewEdge : EdgePtr;
NextEL : EdgeListPtr) : EdgeListPtr;
FUNCTION NewEdge(v1,v2 : VertexPtr; NextE : EdgePtr) : EdgePtr;
FUNCTION NewFace( v1,v2, v3 : VertexPtr;
properties : WORD;
NextF : FacePtr) : FacePtr;
PROCEDURE NewObject(VAR obj : ObjectRec);
Function GetEulerNum : LONGINT;
PROCEDURE Link( object : ObjectPtr;
v1, v2 : VertexPtr;
properties : WORD);
implementation
CONST
Debug = TRUE;
VAR
EdgeCount, FaceCount,
VertexCount,
EulerNumber : LONGINT;
p,
ExitPtr : POINTER (* Termination Code *);
PROCEDURE MemErr(msg : String);
BEGIN
Writeln('Ran out of Memory making a new ',msg);
HALT;
END;
PROCEDURE WriteCoord(v : VertexPtr);
BEGIN
Write(v^.pos[0]:3:0,',');
Write(v^.pos[1]:3:0,',');
Write(v^.pos[2]:3:0);
END;
FUNCTION NewVertex(x, y, z : SINGLE; NextV : VertexPtr) : VertexPtr;
VAR
v : VertexPtr;
BEGIN
GetMem(v,SizeOf(VertexRec));
IF v = NIL THEN MemErr('Vertex');
v^.pos[0] := x;
v^.pos[1] := y;
v^.pos[2] := z;
v^.edgelist := NIL;
v^.next := NextV;
INC(VertexCount);
NewVertex := v;
END;
FUNCTION NewEdgeList( NewEdge : EdgePtr;
NextEL : EdgeListPtr) : EdgeListPtr;
VAR
EL : EdgeListPtr;
BEGIN
GetMem(EL,SizeOf(EdgeListRec));
IF EL = NIL THEN MemErr('EdgeList');
EL^.edge := NewEdge;
EL^.next := NextEL;
NewEdgeList := EL;
END;
FUNCTION NewEdge(v1,v2 : VertexPtr; NextE : EdgePtr) : EdgePtr;
VAR
E : EdgePtr;
BEGIN
GetMem(E,SizeOf(EdgeRec));
IF E = NIL THEN MemErr('Edge');
E^.vertices[0] := v1;
E^.vertices[1] := v2;
E^.next := NextE;
INC(EdgeCount);
NewEdge := E;
END;
FUNCTION NewFace( v1,v2, v3 : VertexPtr;
properties : WORD;
NextF : FacePtr) : FacePtr;
VAR
F : FacePtr;
BEGIN
GetMem(F,SizeOf(FaceRec));
IF F = NIL THEN MemErr('Face');
F^.vertices[0] := v1;
F^.vertices[1] := v2;
F^.vertices[2] := v3;
F^.next := NextF;
INC(FaceCount);
NewFace := F;
END;
PROCEDURE NewObject(VAR obj : ObjectRec);
BEGIN
EulerNumber := 0;
EdgeCount := 0;
FaceCount := 0;
VertexCount := 0;
obj.vertices := NIL;
obj.edges := NIL;
obj.faces := NIL;
END;
Function GetEulerNum : LONGINT;
BEGIN
GetEulerNum := FaceCount + VertexCount - EdgeCount;
END;
FUNCTION OtherEnd(VAR e : EdgePtr; VAR v : VertexPtr) : VertexPtr;
(* called by Link *)
BEGIN
IF e^.vertices[0] <> v THEN
OtherEnd := e^.vertices[0]
ELSE
OtherEnd := e^.vertices[1]
END;
PROCEDURE Link( object : ObjectPtr;
v1, v2 : VertexPtr;
properties : WORD);
VAR
Edge1 : EdgePtr;
EList1,
EList2 : EdgeListPtr;
v3 : VertexPtr;
Face1 : FacePtr;
LinkExists : BOOLEAN;
BEGIN
LinkExists := FALSE;
EList1 := v1^.edgelist;
WHILE (EList1 <> NIL) AND NOT LinkExists DO
BEGIN
LinkExists := (OtherEnd(EList1^.edge,v1) = v2);
EList1 := EList1^.next;
END;
IF Debug THEN
BEGIN
WriteCoord(v1);
Write(' <--> ');
WriteCoord(v2);
IF LinkExists THEN
Write(' Already linked.')
ELSE
Write(' Linking.');
END;
IF NOT LinkExists THEN (* make the link *)
BEGIN
object^.edges := NewEdge(v1, v2, object^.edges);
Edge1 := object^.edges;
v1^.edgelist := NewEdgeList(Edge1, v1^.edgelist);
v2^.edgelist := NewEdgeList(Edge1, v2^.edgelist);
{ check for face completion }
EList1 := v1^.edgelist;
WHILE EList1 <> NIL DO
BEGIN
v3 := OtherEnd(EList1^.edge, v1);
IF v3 <> v2 THEN
BEGIN
EList2 := v3^.edgelist;
WHILE EList2 <> NIL DO
BEGIN
IF OtherEnd(Elist2^.edge,v3) = v2 THEN
BEGIN
IF Debug THEN
BEGIN
WriteCoord(v3);
Write('Face!');
END;
object^.faces :=
newface(v1, v2, v3, properties, object^.faces);
END;
EList2 := EList2^.next;
END;
END;
EList1 := EList1^.next;
END;
END;
WriteLn;
END {Link};
(* ------------------------------------------------------- *)
{$F+}
PROCEDURE CleanUp;
BEGIN
ExitProc := ExitPtr;
Release(p);
END;
{$F-}
BEGIN
ExitPtr := ExitProc;
ExitProc := @CleanUp;
Mark(p);
EulerNumber := 0;
END { Sculpt3D }. |
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Реализация ордера для TestServer См проект
"X:\Trade\Forecaster\Stock Server"
Внимание
History:
-----------------------------------------------------------------------------}
unit FC.Trade.Brokers.TestServer.Order;
{$I Compiler.inc}
interface
uses
SysUtils,BaseUtils, StockChart,StockServer_TLB,
Serialization, FC.Definitions,StockChart.Definitions;
type
//Специальное расширение для поддержки нас
IStockBrokerTestServerSupport = interface
['{CAFBB2D1-1E2C-499E-A585-99EB8FCEF041}']
function GetNative: IStockServerBroker;
end;
{ TStockOrder }
TStockOrder = class (TInterfacedObject,IStockOrder)
private
FTraderID : TGUID;
FBroker : IStockBroker; //TStockBroker
FID : TGUID;
FNative : IStockServerOrder;
public
//Уникальный идентификатор ордера
function GetID: TGUID;
//Под каким брокером выдан ордер
function GetBroker: IStockBroker;
//Какой трейдер создал ордер. Cсылку сохранить нельзя, сохраняем ID
function GetTraderID: TGUID;
//Тип ордера - на покупку или продажу
function GetKind : TStockOrderKind;
//Текущее состояние - пустой, открыт, закрыт
function GetState: TStockOrderState;
//Кол-во лотов. Rate = 1 означает 0.1 лотов
function GetRate: integer;
//Атрибуты открытия
function GetOpenTime : TDateTime;
function GetOpenPrice: TStockRealNumber;
function GetOpenComment: string;
//Атрибуты закрытия
function GetCloseTime : TDateTime;
function GetClosePrice: TStockRealNumber;
function GetCloseComment: string;
//Худшее состояние за все время ордера
function GetWorstProfit: TStockRealNumber;
//максимальный профит, который был за все время ордера
function GetBestProfit: TStockRealNumber;
//Дать текущий профит
function GetCurrentProfit: TStockRealNumber;
//Установить уровень StopLoss (в реальных ценовых единицах)
procedure SetTrailingStop(aPriceDelta: TStockRealNumber);
function GetTrailingStop:TStockRealNumber;
//Установить уровень StopLoss (в пунктах)
procedure SetStopLoss(aPrice: TStockRealNumber);
function GetStopLoss:TStockRealNumber;
//Установить уровень TakeProfit (в пунктах)
procedure SetTakeProfit(aPrice: TStockRealNumber);
function GetTakeProfit:TStockRealNumber;
//Закрыть по текущей цене
procedure Close(const aComment: string);
//Открыть ордер по текущей цене
procedure Open(aKind: TStockOrderKind; aRate: integer);
//Открыть ордер по указанной цене
//aRate указывает отношение pt:$, отношение 1:1 означает 0.1 лота
procedure OpenAt(aKind: TStockOrderKind; aPrice: TStockRealNumber; aRate: integer);
//Получить затребованную цену открытия (см. OpenAt)
//Эту функцию имеет смысл только, если ордер открывался через OpenAt. В противном случае будет выброшено исключение
function GetPendingOpenPrice: TStockRealNumber;
//Получить тип отложенного ордера (лимитный или стоповый)
//Эту функцию имеет смысл только, если ордер открывался через OpenAt. В противном случае будет выброшено исключение
function GetPendingType: TStockOrderPendingType;
//Implementation
procedure Dispose;
property Native:IStockServerOrder read FNative;
constructor Create(const aStockBroker: IStockBrokerTestServerSupport; const aStockTrader: IStockTrader);
end;
implementation
uses Math,FC.Trade.Brokers.TestServer.Broker;
{ TStockOrder }
constructor TStockOrder.Create(const aStockBroker: IStockBrokerTestServerSupport; const aStockTrader: IStockTrader);
begin
FTraderID:=aStockTrader.GetID;
FBroker:=aStockBroker as IStockBroker;
FNative:=aStockBroker.GetNative.CreateOrder;
CreateGUID(FID);
end;
procedure TStockOrder.Dispose;
begin
FBroker:=nil;
end;
function TStockOrder.GetOpenTime: TDateTime;
begin
result:=FNative.GetOpenTime;
end;
function TStockOrder.GetPendingOpenPrice: TStockRealNumber;
begin
//Если открывались не через OpenAt
raise ENotSupported.Create;
//if FNative.GetQueriedOpenPrice=0 then
// raise EStockError.Create('Order is not pending');
//result:=FNative.GetQueriedOpenPrice;
end;
function TStockOrder.GetPendingType: TStockOrderPendingType;
begin
raise ENotSupported.Create;
end;
function TStockOrder.GetKind: TStockOrderKind;
begin
result:=TStockOrderKind(FNative.GetKind);
end;
function TStockOrder.GetTakeProfit: TStockRealNumber;
begin
result:=FNative.GetTakeProfit;
end;
function TStockOrder.GetTraderID: TGUID;
begin
result:=FTraderID;
end;
function TStockOrder.GetTrailingStop: TStockRealNumber;
begin
result:=FNative.GetTrailingStop;
end;
procedure TStockOrder.SetStopLoss(aPrice: TStockRealNumber);
begin
FNative.SetStopLoss(aPrice);
end;
procedure TStockOrder.SetTakeProfit(aPrice: TStockRealNumber);
begin
FNative.SetTakeProfit(aPrice);
end;
procedure TStockOrder.SetTrailingStop(aPriceDelta: TStockRealNumber);
begin
FNative.SetTrailingStop(aPriceDelta);
end;
function TStockOrder.GetOpenComment: string;
begin
result:=FNative.GetOpenComment;
end;
function TStockOrder.GetOpenPrice: TStockRealNumber;
begin
result:=FNative.GetOpenPrice;
end;
function TStockOrder.GetCloseTime: TDateTime;
begin
result:=FNative.GetCloseTime;
end;
function TStockOrder.GetClosePrice: TStockRealNumber;
begin
result:=FNative.GetClosePrice;
end;
procedure TStockOrder.Close(const aComment: string);
begin
FNative.Close(aComment);
end;
procedure TStockOrder.Open(aKind: TStockOrderKind; aRate: integer);
begin
FNative.Open(integer(aKind),aRate);
end;
procedure TStockOrder.OpenAt(aKind: TStockOrderKind; aPrice: TStockRealNumber; aRate: integer);
begin
FNative.OpenAt(integer(aKind),aPrice,aRate);
end;
function TStockOrder.GetID: TGUID;
begin
result:=FID;
end;
function TStockOrder.GetBroker: IStockBroker;
begin
result:=FBroker;
end;
function TStockOrder.GetState: TStockOrderState;
begin
result:=TStockOrderState(FNative.GetState);
end;
function TStockOrder.GetStopLoss: TStockRealNumber;
begin
result:=FNative.GetStopLoss;
end;
function TStockOrder.GetCurrentProfit: TStockRealNumber;
begin
result:=FNative.GetCurrentProfit;
end;
function TStockOrder.GetCloseComment: string;
begin
result:=FNative.GetCloseComment;
end;
function TStockOrder.GetRate: integer;
begin
result:=FNative.GetRate;
end;
function TStockOrder.GetWorstProfit: TStockRealNumber;
begin
result:=-1;
end;
function TStockOrder.GetBestProfit: TStockRealNumber;
begin
result:=-1;
end;
end.
|
unit UnitMain;
{$mode delphi}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TFormMain }
TFormMain = class(TForm)
ButtonOk: TButton;
EditName: TEdit;
LabelName: TLabel;
procedure ButtonOkClick(Sender: TObject);
private
public
end;
var
FormMain: TFormMain;
implementation
{$R *.lfm}
{ TFormMain }
procedure TFormMain.ButtonOkClick(Sender: TObject);
var
Name: string;
begin
Name := Self.EditName.Text;
ShowMessage('Hello ' + Name);
end;
end.
|
program dt; //Ignat Miagkov, CS 312
uses sysutils;
type
day_range = 1..31; //day can be from 1 to 31
month_range = 1..12; //month can be from 1 to 12
date_t = record //date is stored as a record
day : day_range;
month : month_range;
year : integer;
end;
procedure init_date (var dt : date_t; day : day_range; month : month_range; year : integer); //takes four parameters and initialized date_t record
begin
dt.day := day;
dt.month := month;
dt.year := year;
end;
procedure init_date1 (var dt : date_t); //specific to today's date
Var
YY,MM,DD : Word;
begin
DecodeDate(Date,YY,MM,DD);
dt.day := DD;
dt.month := MM;
dt.year := YY;
end;
function date_equal (date1 : date_t; date2 : date_t) : boolean; //checks if two dates are equal
Var
ret : boolean;
begin
if((date1.month = date2.month) and (date1.day = date2.day) and (date1.year = date2.year)) then //all must match
ret := True
else
ret := False;
date_equal := ret;
end;
function date_less_than (date1 : date_t; date2: date_t) : boolean;
Var
ret : boolean;
begin
ret := False;
if(date1.year < date2.year) then //checks years first
ret := True;
if((date1.year = date2.year) and (date1.month < date2.month)) then //then months
ret := True;
if((date1.year = date2.year) and (date1.month = date2.month) and (date1.day < date2.day)) then //then days
ret := True;
date_less_than := ret;
end;
function month_str (month : month_range) : string;
Var
ret : string; //formats month number to a string
begin
if(month = 1) then
ret := 'January';
if(month = 2) then
ret := 'February';
if(month = 3) then
ret := 'March';
if(month = 4) then
ret := 'April';
if(month = 5) then
ret := 'May';
if(month = 6) then
ret := 'June';
if(month = 7) then
ret := 'July';
if(month = 8) then
ret := 'August';
if(month = 9) then
ret := 'September';
if(month = 10) then
ret := 'October';
if(month = 11) then
ret := 'November';
if(month = 12) then
ret := 'December';
month_str := ret;
end;
procedure format_date (dt : date_t; var ret_str : string); //used to print date record as a string
Var
day_temp, month_temp, year_temp : String;
begin
str(dt.day, day_temp);
str(dt.year, year_temp);
month_temp := month_str(dt.month);
ret_str := month_temp + ' ' + day_temp + ', ' + year_temp;
end;
procedure next_day (var dt : date_t);
Var
is_leap : boolean; //declares is leap as a boolean
function leap_year (year : integer) : boolean;
Var
retur : boolean;
begin
if (year mod 4 = 0) then //if mod 4 is zero then it becoems true, but if mod 100 is zero and mod 400 is not zero then returns false
begin
retur := True;
if ((year mod 100 = 0) and (year mod 400 <> 0)) then
retur := False;
end
else
retur := False;
leap_year := retur;
end;
function month_length (month : month_range; leap : boolean) : day_range; //determines max number of days in month for next day procedure
Var
ret : day_range;
begin
if ((month = 1) or (month = 3) or (month = 5) or (month = 7) or (month = 8) or (month = 10) or (month = 12)) then
ret := 31;
if ((month = 4) or (month = 6) or (month = 9) or (month = 11)) then
ret := 30;
if ((month = 2) and (leap)) then //using leap functions here
ret := 29;
if ((month = 2) and (True<>leap)) then
ret := 28;
month_length := ret;
end;
begin
is_leap := leap_year(dt.year);
if(dt.day = month_length(dt.month, is_leap)) then //if the day = day count
begin
if dt.month = 12 then //if its december, advance to january 1 of next year
begin
dt.day := 1;
dt.month := 1;
dt.year := dt.year + 1;
end
else //if its just end of the month, advance to 1st day of next month
begin
dt.day := 1;
dt.month := dt.month + 1;
end;
end
else //otherwise, if not last day of the month, just add to next day
dt.day := dt.day + 1;
end;
Var
d1, d2, d3 : date_t;
format_str : string;
begin
init_date1(d1);
init_date(d2, 30, 12, 1999);
init_date(d3, 1, 1, 2000);
format_date(d1, format_str); //testing format_date
writeln('d1: ' + format_str);
format_date(d2, format_str);
writeln('d2: ' + format_str);
format_date(d3, format_str);
writeln('d3: ' + format_str);
writeln('');
writeln('d1 < d2? ', date_less_than(d1,d2)); //testing less than
writeln('d2 < d3? ', date_less_than(d2,d3));
writeln('');
next_day(d2);
format_date(d2, format_str);
writeln('next day d2: ', format_str); //testing next day not last day of the month
writeln('d2 < d3? ', date_less_than(d2,d3));
writeln('d2 = d3? ', date_equal(d2,d3));
writeln('d2 > d3? ', date_less_than(d3,d2));
writeln('');
next_day(d2);
format_date(d2, format_str); //testing next day when its last day of the year
writeln('next day d2: ', format_str);
writeln('d2 = d3? ', date_equal(d2,d3));
writeln('');
init_date(d1, 28, 2, 1529); //next 4 cases test all of the leap year conditions, with odd cases also testing the increment by one month
format_date(d1, format_str);
writeln('Initialized d1 to ', format_str);
next_day(d1);
format_date(d1, format_str);
writeln('next day d1: ', format_str);
writeln('');
init_date(d1, 28, 2, 1460);
format_date(d1, format_str);
writeln('Initialized d1 to ', format_str);
next_day(d1);
format_date(d1, format_str);
writeln('next day d1: ', format_str);
writeln('');
init_date(d1, 28, 2, 1700);
format_date(d1, format_str);
writeln('Initialized d1 to ', format_str);
next_day(d1);
format_date(d1, format_str);
writeln('next day d1: ', format_str);
writeln('');
init_date(d1, 28, 2, 1600);
format_date(d1, format_str);
writeln('Initialized d1 to ', format_str);
next_day(d1);
format_date(d1, format_str);
writeln('next day d1: ', format_str);
writeln('');
end. |
//Variables globales y lectura de archivos INI
unit UGlobales;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs,
IniFiles,VarRegEnv, fileinfo;
type
TGlobales=class
private
Procedure setInteger(variable:String;Valor:Integer);
Function getInteger(variable:String;Valordefault:Integer):Integer;
Procedure setVarstr(variable,Valor:String);
Function getVarStr(variable,Valordefault:String):String;
Procedure setBoolean(variable:String;Valor:Boolean);
Function getBoolean(variable:String;Valordefault:Boolean):Boolean;
//=================================================
Procedure setFdeFilePath(Valor:String);
Function getFdeFilepath():String;
Procedure setWebappsDir(Valor:String);
Function getWebappsDir():String;
Procedure setJavaHome(Valor:String);
Function getJavaHome():String;
Procedure setOcultarDirROOT(Valor:Boolean);
Function getOcultarDirROOT():Boolean;
Procedure setMostrarOK(Valor:Boolean);
Function getMostrarOK():Boolean;
Procedure setDelWars(Valor:Boolean);
Function getDelWars():Boolean;
Procedure setConfirmDel(Valor:Boolean);
Function getConfirmDel():Boolean;
Procedure setClrMemo(Valor:Boolean);
Function getClrMemo():Boolean;
Procedure setMostrarERR(Valor:Boolean);
Function getMostrarERR():Boolean;
Procedure setListBoxModuloValues(Valor:String);
Function getListBoxModuloValues():String;
Procedure setListBoxVersionValues(Valor:String);
Function getListBoxVersionValues():String;
Procedure setMostrarMSJ(Valor:Boolean);
Function getMostrarMSJ():Boolean;
Procedure setSoloDir(Valor:Boolean);
Function getSoloDir():Boolean;
Procedure setTrayMinimize(Valor:Boolean);
Function getTrayMinimize():Boolean;
Procedure setTrayScriptFDE(Valor:Boolean);
Function getTrayScriptFDE():Boolean;
Procedure setTrayGenWar(Valor:Boolean);
Function getTrayGenWar():Boolean;
Procedure setTrayRunAPP(Valor:Boolean);
Function getTrayRunAPP():Boolean;
Procedure setBeep(Valor:Boolean);
Function getBeep():Boolean;
Procedure setOpcSalir(Valor:Boolean);
Function getOpcSalir():Boolean;
Procedure setOrderByUso(Valor:Boolean);
Function getOrderByUso():Boolean;
Procedure setCompWebXml(Valor:Boolean);
Function getCompWebXml():Boolean;
Procedure setHideExDS(Valor:Boolean);
Function getHideExDS():Boolean;
Procedure setPageIndex(Valor:Integer);
Function getPageIndex():Integer;
Procedure setPDFReportselection(Valor:Integer);
Function getPDFReportselection():Integer;
Procedure setDSDescription(Valor:String);
Function getDSDescription():String;
Procedure setDSResType(Valor:String);
Function getDSResType():String;
Procedure setDSResAuth(Valor:String);
Function getDSResAuth():String;
Procedure setDSUseJdbcDatasource(Valor:Integer);
Function getDSUseJdbcDatasource():Integer;
Procedure setDSJdbcDataSource(Valor:String);
Function getDSJdbcDataSource():String;
Procedure setDSResRefName(Valor:String);
Function getDSResRefName():String;
Function getFdeIni():String;
Function getFdeDir():String;
Function getAppPath():String;
Function getProductVersion():String;
Function getIniUpdate():String;
public
COLOROK:TColor;
FicheroIni:TIniFile;
pathini:string;
Seccion:string;
Constructor Create;
//APP
Procedure setApp(App:String='APP1';Valor:String='');
Procedure setImgApp(App:String='APP1';Valor:String='');
Procedure setAPPNombre(APP:String;Valor:String);
Procedure setAPPuso(APP:String;Valor:Integer);
Procedure setAPPPar(APP:String;Valor:String);
Function getApp(App:String='APP1'):String;
Function getImgApp(App:String='APP1'):String;
Function getAPPNombre(APP:String):String;
Function getAppUso(App:String='APP1'):Integer;
Function getAPPPar(APP:String):String;
Procedure delAPP(App:String);
//PDFREPORT
Procedure setPDFReportRutaFonts(PDFREP:String;Valor:String);
Procedure setPDFReportTxt(PDFREP:String;Valor:String);
Procedure setPDFReportCopyFonts(PDFREP:String;Valor:Boolean);
Procedure delPDFReport(PDFREP:String);
Function getPDFReportRutafonts(PDFREP:String):String;
Function getPDFReportTxt(PDFREP:String):String;
Function getPDFReporCopyFonts(PDFREP:String):Boolean;
//DATASOURCES
Procedure setDataSource(DataSource,RefName:String);
Procedure delDataSource(DataSource:String);
Function getAllDataSources():TStringList;
Procedure setAllDataSources(DSSL:TStringList);
//____________________
//======================
// PROPERTIES
//======================
Property ListBoxModuloValues: string read getListBoxModuloValues write setListBoxModuloValues;
Property ListBoxVersionValues: string read getListBoxVersionValues write setListBoxVersionValues;
Property FdeFilePath: string read getFdeFilepath write setFdeFilePath;
Property WebAppsDir: String read getWebappsDir write setWebappsDir;
Property JavaHome: String read getJavaHome write setJavaHome;
Property OcultarDirROOT: Boolean read getOcultarDirROOT write setOcultarDirROOT;
Property MostrarOK: Boolean read getMostrarOK write setMostrarOK;
Property DelWars: Boolean read getDelWars write setDelWars;
Property ConfirmDel: Boolean read getConfirmDel write setConfirmDel;
Property ClearMemo: Boolean read getClrMemo write setClrMemo;
Property MostrarERR: Boolean read GetMostrarERR write setMostrarERR;
Property MostrarMSJ: Boolean read getMostrarMSJ write setMostrarMSJ;
Property SoloDir: Boolean read getSoloDir write setSoloDir;
Property TrayMinimize: Boolean read getTrayMinimize write setTrayMinimize;
Property TrayScriptFDE: Boolean read getTrayScriptFDE write setTrayScriptFDE;
Property TrayGenWar: Boolean read getTrayGenWar write setTrayGenWar;
Property TrayRunAPP: Boolean read getTrayRunAPP write setTrayRunAPP;
Property Beep: Boolean read getBeep write setBeep;
Property OpcSalir: Boolean read getOpcSalir write setOpcSalir;
Property OrderByUso: Boolean read getOrderByUso write setOrderByUso;
Property CompWebXml: Boolean read getCompWebXml write setCompWebXml;
Property OcultaEjemplosDS: Boolean read getHideExDS write setHideExDS;
Property PageIndex: Integer read getPageIndex write setPageIndex;
Property PDFReportselection: Integer read getPDFReportselection write setPDFReportselection;
Property FdeIni: String read getFdeIni;
Property FdeDir: String read getFdeDir;
Property AppPath: String read getAppPath;
Property ProductVersion: String read getProductVersion;
Property IniUpdate: String read getIniUpdate;
Property DSDescription:String read getDSDescription write setDSDescription;
Property DSResType:String read getDSResType write setDSResType;
Property DSResAuth:String read getDSResAuth write setDSResAuth;
Property DSUseJdbcDatasource:Integer read getDSUseJdbcDatasource write setDSUseJdbcDatasource;
Property DSJdbcDataSource:String read getDSJdbcDataSource write setDSJdbcDataSource;
Property DSResRefName:String read getDSResRefName write setDSResRefName;
end;
implementation
Constructor TGlobales.Create;
Begin
inherited;
//CREAR INI
If trim(pathini).IsEmpty then
pathini := ExtractFilePath(Application.ExeName)+'fde.ini';
If trim(Seccion).IsEmpty then
Seccion := 'CONFIG';
FicheroIni:=TIniFile.Create(pathini);
end;
Procedure TGlobales.setInteger(variable:String;Valor:Integer);
Begin
FicheroIni.WriteInteger(Seccion,variable,Valor);
end;
Function TGlobales.getInteger(variable:String;Valordefault:Integer):Integer;
Begin
FicheroIni.Free;
FicheroIni:=TIniFile.Create(pathini);
Result:=FicheroIni.ReadInteger(Seccion,variable,Valordefault);
end;
Function TGlobales.getVarStr(variable,Valordefault:String):String;
begin
FicheroIni.Free;
FicheroIni:=TIniFile.Create(pathini);
Result:=FicheroIni.ReadString(Seccion,variable,Valordefault);
end;
Procedure TGlobales.setVarstr(variable,Valor:String);
begin
If not trim(Valor).IsEmpty then
FicheroIni.WriteString(Seccion,variable,Valor);
end;
Procedure TGlobales.setBoolean(variable:String;Valor:Boolean);
begin
If not Valor then Valor:=False;
FicheroIni.WriteBool(Seccion,Variable,Valor);
end;
Function TGlobales.getBoolean(variable:String;Valordefault:Boolean):Boolean;
begin
FicheroIni.Free;
FicheroIni:=TIniFile.Create(pathini);
Result:=FicheroIni.ReadBool(Seccion,variable,Valordefault);
end;
procedure TGlobales.delAPP(App:String);
begin
FicheroIni.Free;
FicheroIni:=TIniFile.Create(pathini);
Seccion:='APPS';
FicheroIni.DeleteKey(Seccion,App);
end;
procedure TGlobales.delPDFReport(PDFREP:String);
begin
FicheroIni.Free;
FicheroIni:=TIniFile.Create(pathini);
Seccion:='PDFREPORT';
FicheroIni.DeleteKey(Seccion,PDFREP);
end;
{SETTER - GETTER}
Procedure TGlobales.setMostrarOK(Valor:Boolean);
begin
Seccion:='MEMO_CONSOLE';
setBoolean('MostrarOK',Valor);
end;
Procedure TGlobales.setDelWars(Valor:Boolean);
begin
Seccion:='OPCIONES';
setBoolean('PrevGenDelWar',Valor);
end;
Procedure TGlobales.setConfirmDel(Valor:Boolean);
begin
Seccion:='MEMO_CONSOLE';
setBoolean('ConfirmDEL',Valor);
end;
Procedure TGlobales.setClrMemo(Valor:Boolean);
begin
Seccion:='MEMO_CONSOLE';
setBoolean('ClrMemo',Valor);
end;
Procedure TGlobales.setMostrarERR(Valor:Boolean);
begin
Seccion:='MEMO_CONSOLE';
setBoolean('MostrarERR',Valor);
end;
Procedure TGlobales.setMostrarMSJ(Valor:Boolean);
begin
Seccion:='MEMO_CONSOLE';
setBoolean('MostrarMSJ',Valor);
end;
Procedure TGlobales.setFdeFilePath(Valor:String);
begin
Seccion:='CONFIG';
setVarstr('FdeFile',Valor);
end;
Procedure TGlobales.setWebappsDir(Valor:String);
begin
Seccion:='CONFIG';
setVarstr('WebappsDir',Valor);
end;
Procedure TGlobales.setOcultarDirROOT(Valor:Boolean);
begin
Seccion:='CONFIG';
setBoolean('OcultarDirROOT',Valor);
end;
Procedure TGlobales.setJavaHome(Valor:String);
begin
Seccion:='OPCIONES';
If Trim(Valor).IsEmpty Then
begin
FicheroIni.Free;
FicheroIni:=TIniFile.Create(pathini);
FicheroIni.DeleteKey(Seccion,'JAVA_HOME');
end
else setVarstr('JAVA_HOME',Valor);
end;
Procedure TGlobales.setApp(App:String='APP1';Valor:String='');
begin
Seccion:='APPS';
If Trim(Valor).IsEmpty Then delAPP(APP) else setVarstr(App,Valor);
end;
Procedure TGlobales.setImgApp(App:String='APP1';Valor:String='');
begin
Seccion:='APPS';
If Trim(Valor).IsEmpty Then delAPP(APP+'IMG') else setVarstr((App+'IMG'),Valor);
end;
Function TGlobales.getWebappsDir():String;
begin
Seccion:='CONFIG';
Result:=getVarStr('WebappsDir',ExtractFilePath(Application.ExeName));
end;
Function TGlobales.getJavaHome():String;
begin
Seccion:='OPCIONES';
Result:=getVarStr('JAVA_HOME','');
end;
Function TGlobales.getFdeFilepath():String;
begin
Seccion:='CONFIG';
Result:=getVarStr('FdeFile',' ');
end;
Function TGlobales.getFdeDir():String;
begin
Seccion:='CONFIG';
Result:=ExtractFilePath(Application.ExeName)+'FDE Files\';
If not DirectoryExists(Result) then
CreateDir(Result);
end;
Function TGlobales.getFdeIni():String;
begin
Seccion:='CONFIG';
Result:=pathini;
end;
Function TGlobales.getAppPath():String;
begin
Seccion:='CONFIG';
Result:=ExtractFilePath(Application.ExeName)
end;
Function TGlobales.getApp(App:String='APP1'):String;
begin
Seccion:='APPS';
Result:=getVarStr(App,'');
end;
Function TGlobales.getImgApp(App:String='APP1'):String;
begin
Seccion:='APPS';
Result:=getVarStr((App+'IMG'),'');
end;
Function TGlobales.getAppUso(App:String='APP1'):Integer;
begin
Seccion:='APPS';
Result:=getInteger((App+'USO'),0);
end;
Function TGlobales.getMostrarOK():Boolean;
begin
Seccion:='MEMO_CONSOLE';
Result:=getBoolean('MostrarOK',TRUE);
end;
Function TGlobales.getDelWars():Boolean;
begin
Seccion:='OPCIONES';
Result:=getBoolean('PrevGenDelWar',TRUE);
end;
Function TGlobales.getConfirmDel():Boolean;
begin
Seccion:='MEMO_CONSOLE';
Result:=getBoolean('ConfirmDEL',TRUE);
end;
Function TGlobales.getClrMemo():Boolean;
begin
Seccion:='MEMO_CONSOLE';
Result:=getBoolean('ClrMemo',FALSE);
end;
Function TGlobales.getMostrarERR():Boolean;
begin
Seccion:='MEMO_CONSOLE';
Result:=getBoolean('MostrarERR',TRUE);
end;
Function TGlobales.getMostrarMSJ():Boolean;
begin
Seccion:='MEMO_CONSOLE';
Result:=getBoolean('MostrarMSJ',TRUE);
end;
Function TGlobales.getSoloDir():Boolean;
begin
Seccion:='CONFIG';
Result:=getBoolean('SoloDir',TRUE);
end;
Procedure TGlobales.setSoloDir(Valor:Boolean);
begin
Seccion:='CONFIG';
setBoolean('SoloDir',Valor);
end;
Function TGlobales.getOcultarDirROOT():Boolean;
begin
Seccion:='CONFIG';
Result:=getBoolean('OcultarDirROOT',FALSE);
end;
Function TGlobales.getTrayMinimize():Boolean;
begin
Seccion:='OPCIONES';
Result:=getBoolean('MinimizeToTray',FALSE);
end;
Function TGlobales.getTrayScriptFDE():Boolean;
begin
Seccion:='OPCIONES';
Result:=getBoolean('TrayScriptFDE',FALSE);
end;
Function TGlobales.getTrayGenWar():Boolean;
begin
Seccion:='OPCIONES';
Result:=getBoolean('TrayGenWar',FALSE);
end;
Function TGlobales.getTrayRunAPP():Boolean;
begin
Seccion:='OPCIONES';
Result:=getBoolean('TrayRunAPP',FALSE);
end;
Function TGlobales.getBeep():Boolean;
begin
Seccion:='OPCIONES';
Result:=getBoolean('Beep',FALSE);
end;
Function TGlobales.getOpcSalir():Boolean;
begin
Seccion:='OPCIONES';
Result:=getBoolean('RecOpcSalir',FALSE);
end;
Function TGlobales.getOrderByUso():Boolean;
begin
Seccion:='OPCIONES';
Result:=getBoolean('OrderByUso',FALSE);
end;
Function TGlobales.getcompWebXml():Boolean;
Begin
Seccion:='CONFIG';
Result:=getBoolean('chkWebXml',FALSE);
end;
Function TGlobales.getHideExDs():Boolean;
Begin
Seccion:='CONFIG';
Result:=getBoolean('HideExDs',FALSE);
end;
Procedure TGlobales.setTrayMinimize(Valor:Boolean);
begin
Seccion:='OPCIONES';
setBoolean('MinimizeToTray',Valor);
end;
Procedure TGlobales.setTrayRunAPP(Valor:Boolean);
begin
Seccion:='OPCIONES';
setBoolean('TrayRunAPP',Valor);
end;
Procedure TGlobales.setTrayScriptFDE(Valor:Boolean);
begin
Seccion:='OPCIONES';
setBoolean('TrayScriptFDE',Valor);
end;
Procedure TGlobales.setTrayGenWar(Valor:Boolean);
begin
Seccion:='OPCIONES';
setBoolean('TrayGenWar',Valor);
end;
Procedure TGlobales.setBeep(Valor:Boolean);
begin
Seccion:='OPCIONES';
setBoolean('Beep',Valor);
end;
Procedure TGlobales.setOpcSalir(Valor:Boolean);
begin
Seccion:='OPCIONES';
setBoolean('RecOpcSalir',Valor);
end;
Procedure TGlobales.setOrderByUso(Valor:Boolean);
Begin
Seccion:='OPCIONES';
setBoolean('OrderByUso',Valor);
end;
Procedure TGlobales.setcompWebXml(Valor:Boolean);
Begin
Seccion:='CONFIG';
setBoolean('chkWebXml',Valor);
end;
Procedure TGlobales.setHideExDs(Valor:Boolean);
Begin
Seccion:='CONFIG';
setBoolean('HideExDs',Valor);
end;
Procedure TGlobales.setPageIndex(Valor:Integer);
Begin
Seccion:='CONFIG';
setInteger('PageIndex',Valor);
end;
Procedure TGlobales.setAPPuso(APP:String;Valor:Integer);
Begin
Seccion:='APPS';
If Valor = 0 Then delAPP(APP+'USO') else setInteger(APP+'USO',Valor);
end;
Procedure TGlobales.setPDFReportselection(Valor:Integer);
Begin
Seccion:='PDFREPORT';
setInteger('pdfreport',Valor);
end;
Procedure TGlobales.setAPPNombre(APP:String;Valor:String);
Begin
Seccion:='APPS';
If Trim(Valor).IsEmpty Then delAPP(APP+'NOM') else setVarstr(APP+'NOM',Valor);
end;
Procedure TGlobales.setPDFReportRutaFonts(PDFREP:String;Valor:String);
Begin
Seccion:='PDFREPORT';
If Trim(Valor).IsEmpty Then delPDFReport(PDFREP+'Path') else setVarstr(PDFREP+'Path',Valor);
end;
Procedure TGlobales.setPDFReportTxt(PDFREP:String;Valor:String);
Begin
Seccion:='PDFREPORT';
If Trim(Valor).IsEmpty Then delPDFReport(PDFREP+'txt') else setVarstr(PDFREP+'txt',Valor);
end;
Procedure TGlobales.setPDFReportCopyFonts(PDFREP:String;Valor:Boolean);
Begin
Seccion:='PDFREPORT';
setBoolean(PDFREP+'cpy',Valor);
end;
Procedure TGlobales.setAPPPar(APP:String;Valor:String);
Begin
Seccion:='APPS';
If Trim(Valor).IsEmpty Then delAPP(APP+'PAR') else setVarstr(APP+'PAR',Valor);
end;
Function TGlobales.getPageIndex():Integer;
begin
Seccion:='CONFIG';
Result:=getInteger('PageIndex',4);
end;
Function TGlobales.getAPPNombre(APP:String):String;
begin
Seccion:='APPS';
Result:=getVarStr(APP+'NOM','');
end;
Function TGlobales.getPDFReportRutaFonts(PDFREP:String):String;
var Defalultvalue:String;
begin
Seccion:='PDFREPORT';
Defalultvalue:=' ';
If (PDFREP='pdfreplin') Or (PDFREP='pdfrepper') Then Defalultvalue:='../fonts/';
Result:=getVarStr(PDFREP+'Path',Defalultvalue);
end;
Function TGlobales.getPDFReportTxt(PDFREP:String):String;
var Defaultvalue:String;
begin
Defaultvalue:='SearchNewFontsOnce= true{CRLF}Leading= 2{CRLF}TopMargin= 0.75{CRLF}DashedStyle= 4;2{CRLF}AdjustToPaper= true{CRLF}LeftMargin= 0.75{CRLF}DEBUG= false{CRLF}ServerPrinting= false{CRLF}Embeed Fonts= false{CRLF}Version= 1.0.0.0{CRLF}FontsLocation= ../fonts;{CRLF}BottomMargin= 6{CRLF}LongDashedStyle= 6;2{CRLF}Barcode128AsImage= true{CRLF}OutputFileDirectory= .{CRLF}LineCapProjectingSquare= true{CRLF}SearchNewFonts= false{CRLF}DottedStyle= 1;2{CRLF}LongDotDashedStyle= 6;2;1;2{CRLF}{CRLF}[Fonts Location (Sun)]{CRLF}Microsoft Sans Serif= ../fonts/micross.ttf{CRLF}Verdana= ../fonts/verdana.ttf{CRLF}Arial Narrow= ../fonts/ARIALN.TTF{CRLF}Time New Roman= ../fonts/times.ttf{CRLF}Courier New= ../fonts/cour.ttf{CRLF}Courier New= ../fonts/couri.ttf{CRLF}';
case PDFREP of
'pdfrepwin': Defaultvalue:='SearchNewFontsOnce= true{CRLF}Leading= 2{CRLF}TopMargin= 0.75{CRLF}DashedStyle= 4;2{CRLF}AdjustToPaper= true{CRLF}LeftMargin= 0.75{CRLF}DEBUG= false{CRLF}ServerPrinting= false{CRLF}Embeed Fonts= false{CRLF}Version= 1.0.0.0{CRLF}FontsLocation= c:\windows\fonts;{CRLF}BottomMargin= 6{CRLF}LongDashedStyle= 6;2{CRLF}Barcode128AsImage= true{CRLF}OutputFileDirectory= .{CRLF}LineCapProjectingSquare= true{CRLF}SearchNewFonts= false{CRLF}DottedStyle= 1;2{CRLF}LongDotDashedStyle= 6;2;1;2{CRLF}{CRLF}[Fonts Location (Sun)]{CRLF}Microsoft Sans Serif= c:\windows\fonts\micross.ttf{CRLF}Verdana= c:\windows\fonts\verdana.ttf{CRLF}Arial Narrow= c:\windows\fonts\ARIALN.TTF{CRLF}Time New Roman= c:\windows\fonts\times.ttf{CRLF}Courier New= c:\windows\fonts\cour.ttf{CRLF}Courier New= c:\windows\fonts\couri.ttf{CRLF}';
'pdfreplin': Defaultvalue:='SearchNewFontsOnce= true{CRLF}Leading= 2{CRLF}TopMargin= 0.75{CRLF}DashedStyle= 4;2{CRLF}AdjustToPaper= true{CRLF}LeftMargin= 0.75{CRLF}DEBUG= false{CRLF}ServerPrinting= false{CRLF}Embeed Fonts= false{CRLF}Version= 1.0.0.0{CRLF}FontsLocation= ../fonts;{CRLF}BottomMargin= 6{CRLF}LongDashedStyle= 6;2{CRLF}Barcode128AsImage= true{CRLF}OutputFileDirectory= .{CRLF}LineCapProjectingSquare= true{CRLF}SearchNewFonts= false{CRLF}DottedStyle= 1;2{CRLF}LongDotDashedStyle= 6;2;1;2{CRLF}{CRLF}[Fonts Location (Sun)]{CRLF}Microsoft Sans Serif= ../fonts/micross.ttf{CRLF}Verdana= ../fonts/verdana.ttf{CRLF}Arial Narrow= ../fonts/ARIALN.TTF{CRLF}Time New Roman= ../fonts/times.ttf{CRLF}Courier New= ../fonts/cour.ttf{CRLF}Courier New= ../fonts/couri.ttf{CRLF}';
'pdfrepwas': Defaultvalue:='SearchNewFontsOnce= true{CRLF}Leading= 2{CRLF}TopMargin= 0.75{CRLF}DashedStyle= 4;2{CRLF}AdjustToPaper= true{CRLF}LeftMargin= 0.75{CRLF}DEBUG= false{CRLF}ServerPrinting= false{CRLF}Embeed Fonts= false{CRLF}Version= 1.0.0.0{CRLF}FontsLocation= /archivos/cguweb;{CRLF}BottomMargin= 6{CRLF}LongDashedStyle= 6;2{CRLF}Barcode128AsImage= true{CRLF}OutputFileDirectory= .{CRLF}LineCapProjectingSquare= true{CRLF}SearchNewFonts= false{CRLF}DottedStyle= 1;2{CRLF}LongDotDashedStyle= 6;2;1;2{CRLF}{CRLF}[Fonts Location (Sun)]{CRLF}Microsoft Sans Serif= /archivos/cguweb/micross.ttf{CRLF}Verdana= /archivos/cguweb/verdana.ttf{CRLF}Arial Narrow= /archivos/cguweb/ARIALN.TTF{CRLF}Time New Roman= /archivos/cguweb/times.ttf{CRLF}Courier New= /archivos/cguweb/cour.ttf{CRLF}Courier New= /archivos/cguweb/couri.ttf{CRLF}';
end;
Seccion:='PDFREPORT';
Result:=getVarStr(PDFREP+'txt',Defaultvalue);
end;
Function TGlobales.getPDFReporCopyFonts(PDFREP:String):Boolean;
var defaultValue:Boolean;
Begin
defaultValue:=((PDFREP='pdfreplin') Or (PDFREP='pdfrepper'));
Result:=getBoolean(PDFREP+'cpy',defaultValue);
end;
Function TGlobales.getAPPPar(APP:String):String;
begin
Seccion:='APPS';
Result:=getVarStr(APP+'PAR','');
end;
Function TGlobales.getProductVersion():String;
var FileVerInfo: TFileVersionInfo;
begin
FileVerInfo := TFileVersionInfo.Create(nil);
Try
FileVerInfo.ReadFileInfo;
Result := FileVerInfo.VersionStrings.Values['ProductVersion'];
finally
FileVerInfo.Free;
end;
end;
Function TGlobales.getIniUpdate():String;
begin
Seccion:='UPDATE';
Result:=getVarStr('LINK','https://filedn.com/l4o5bp4oGNf0AfR1x0lJ3xB/DelFind/update.ini');
end;
Function TGlobales.getPDFReportselection():Integer;
Begin
Seccion:='PDFREPORT';
Result:=getInteger('pdfreport',0);
end;
Function TGlobales.getListBoxModuloValues():String;
begin
Seccion:='DISPLAYNAME';
Result:=getVarStr('Modules','Adquisiciones,"Activo Fijo","Contratos de Arriendo","Cargas Automaticas",Contratos,"Documentos Adjuntos","Evaluación de Proveedores","Impresión Etiquetas",Existencias,"Flota de Vehiculos","Gestión de Autorizaciones",Licitaciones,Mantenimiento,Menu,"CGU Nucleo Auditoria",Pasajes,"Plan de Compras",Plantillas,"Portal Proveedores",Telefonia,"Vidal Vademecum","Versiones Modulos","Servicios Web"');
end;
Procedure TGlobales.setListBoxModuloValues(Valor:String);
begin
Seccion:='DISPLAYNAME';
FicheroIni.WriteString(Seccion,'Modules',Valor);
end;
Function TGlobales.getListBoxVersionValues():String;
begin
Seccion:='DISPLAYNAME';
Result:=getVarStr('Versions','');
end;
Procedure TGlobales.setListBoxVersionValues(Valor:String);
begin
Seccion:='DISPLAYNAME';
FicheroIni.WriteString(Seccion,'Versions',Valor);
end;
Procedure TGlobales.setDSDescription(Valor:String);
begin
Seccion:='DATASOURCE';
FicheroIni.WriteString(Seccion,'DESCRIPTION',Valor);
end;
Function TGlobales.getDSDescription():String;
begin
Seccion:='DATASOURCE';
Result:=getVarStr('DESCRIPTION','DB Connection');
end;
Procedure TGlobales.setDSResType(Valor:String);
begin
Seccion:='DATASOURCE';
FicheroIni.WriteString(Seccion,'RES-TYPE',Valor);
end;
Function TGlobales.getDSResType():String;
begin
Seccion:='DATASOURCE';
Result:=getVarStr('RES-TYPE','javax.sql.DataSource');
end;
Procedure TGlobales.setDSResAuth(Valor:String);
begin
Seccion:='DATASOURCE';
FicheroIni.WriteString(Seccion,'RES-AUTH',Valor);
end;
Function TGlobales.getDSResAuth():String;
begin
Seccion:='DATASOURCE';
Result:=getVarStr('RES-AUTH','Container');
end;
Procedure TGlobales.setDSUseJdbcDatasource(Valor:Integer);
begin
Seccion:='DATASOURCE';
setInteger('USE_JDBC_DATASOURCE',Valor);
end;
Function TGlobales.getDSUseJdbcDatasource():Integer;
begin
Seccion:='DATASOURCE';
Result:=getInteger('USE_JDBC_DATASOURCE',1);
end;
Procedure TGlobales.setDSJdbcDataSource(Valor:String);
begin
Seccion:='DATASOURCE';
FicheroIni.WriteString(Seccion,'JDBC_DATASOURCE',Valor);
end;
Function TGlobales.getDSJdbcDataSource():String;
begin
Seccion:='DATASOURCE';
Result:=getVarStr('JDBC_DATASOURCE','');
end;
Procedure TGlobales.setDSResRefName(Valor:String);
begin
Seccion:='DATASOURCE';
FicheroIni.WriteString(Seccion,'RES-REF-NAME',Valor);
end;
Function TGlobales.getDSResRefName():String;
begin
Seccion:='DATASOURCE';
Result:=getVarStr('RES-REF-NAME','');
end;
Procedure TGlobales.setDataSource(DataSource,RefName:String);
var DSSL:TStringList;
i,x:Integer;
begin
Seccion:='DATASOURCE';
delDataSource(DataSource);
DSSL:=getAllDataSources();
DSSL.Add(Trim(DataSource)+'#'+Trim(RefName));
setAllDataSources(DSSL);
end;
Procedure TGlobales.delDataSource(DataSource:String);
var DSSL:TStringList;
i,x: Integer;
begin
Seccion:='DATASOURCE';
x:=-1;
DSSL:=getAllDataSources();
for i := 0 to DSSL.Count - 1 do
begin
If (DSSL[i].Split('#')[0]= DataSource) Then x:=i;
end;
If x>-1 then DSSL.Delete(x);
If DSSL.Count=0 then FicheroIni.DeleteKey(Seccion,'DATASOURCELIST') else setAllDataSources(DSSL);
end;
Function TGlobales.getAllDataSources():TStringList;
var DSSL:TStringList;
begin
Seccion:='DATASOURCE';
DSSL:=TStringList.Create;
DSSL.Delimiter:=';';
DSSL.DelimitedText:=getVarStr('DATASOURCELIST','');
Result:=DSSL;
end;
Procedure TGlobales.setAllDataSources(DSSL:TStringList);
begin
Seccion:='DATASOURCE';
DSSL.Delimiter:=';';
FicheroIni.WriteString(Seccion,'DATASOURCELIST',DSSL.DelimitedText);
end;
end.
|
unit u_xpl_messages;
// These classes handle specific class of messages and their behaviour
{$i xpl.inc}
interface
uses Classes
, SysUtils
, u_xpl_message
, u_xpl_common
;
type // THeartBeatMsg =========================================================
{ TOsdBasic }
TOsdBasic = class(TxPLMessage)
private
function GetColumn: integer;
function GetCommand: string;
function GetDelay: integer;
function GetRow: integer;
function GetText: string;
procedure SetColumn(const AValue: integer);
procedure SetCommand(const AValue: string);
procedure SetDelay(const AValue: integer);
procedure SetRow(const AValue: integer);
procedure SetText(const AValue: string);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
published
property Command : string read GetCommand write SetCommand;
property Text : string read GetText write SetText;
property Row : integer read GetRow write SetRow;
property Column : integer read GetColumn write SetColumn;
property Delay : integer read GetDelay write SetDelay;
end;
{ TLogBasic }
{ TDawnDuskBasic }
TDawnDuskStatusType = (dawn,dusk,noon);
TDayNightStatusType = (day,night);
{ TDawnDuskBasicTrig }
TDawnDuskBasicTrig = class(TxPLMessage)
private
function GetStatus: TDawnDuskStatusType;
procedure SetStatus(aValue: TDawnDuskStatusType);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
published
property Status : TDawnDuskStatusType read GetStatus write SetStatus;
end;
{ TDawnDuskBasicStat }
TDawnDuskBasicStat = class(TxPLMessage)
private
function GetStatus: TDayNightStatusType;
procedure SetStatus(aValue: TDayNightStatusType);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
published
property Status : TDayNightStatusType read GetStatus write SetStatus;
end;
TLogBasic = class(TxPLMessage)
private
function GetCode: string;
function GetText: string;
function GetType: TEventType;
procedure SetCode(const AValue: string);
procedure SetText(const AValue: string);
procedure SetType(const AValue: TEventType);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
published
property Type_ : TEventType read GetType write SetType;
property Text : string read GetText write SetText;
property Code : string read GetCode write SetCode;
end;
TSendmsgBasic = class(TxPLMessage)
private
function GetText: string;
function GetTo: string;
procedure SetText(const AValue: string);
procedure SetTo(const AValue: string);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
published
property Text : string read GetText write SetText;
property To_ : string read GetTo write SetTo;
end;
{ TReceiveMsgBasic }
TReceiveMsgBasic = class(TSendmsgBasic)
private
function GetFrom: string;
procedure SetFrom(AValue: string);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
published
property From : string read GetFrom write SetFrom;
end;
{ TTimerBasic }
TTimerBasic = class(TxPLMessage)
private
function GetDevice : string;
function GetCurrent : string;
procedure SetCurrent(const AValue: string);
procedure SetDevice(const aValue : string);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
published
property Device : string read GetDevice write SetDevice;
property Current : string read GetCurrent write SetCurrent;
end;
{ TSensorBasic }
// http://xplproject.org.uk/wiki/index.php?title=Schema_-_SENSOR.BASIC
TSensorType = ( utUndefined, utBattery, utCount, utCurrent, utDirection,
utDistance, utEnergy, utFan, utGeneric, utHumidity,
utInput, utOutput, utPower, utPressure,utSetpoint,
utSpeed, utTemp, utUV, utVoltage, utVolume,
utWeight, utPresence );
const TSensorTypeLib : array[TSensorType] of string = ( 'undefined', 'battery', 'count', 'current', 'direction',
'distance', 'energy', 'fan', 'generic', 'humidity',
'input', 'output', 'power', 'pressure','setpoint',
'speed', 'temp', 'uv', 'voltage', 'volume',
'weight','presence' );
TSensorUnits : Array[TSensorType] of String = ('','%','','A','Deg','m','kWh','rpm',
'','%','','','kW','N/m2','DegC','mph',
'DegC','','V','m3','kg','');
type TSensorBasic = class(TxPLMessage)
private
function GetDevice : string;
function GetCurrent : string;
function GetType : TSensorType;
function GetUnits: string;
procedure SetType(const AValue: TSensorType);
procedure SetCurrent(const AValue: string);
procedure SetDevice(const aValue : string);
procedure SetUnits(const AValue: string);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
function SensorName : string;
published
property Device : string read GetDevice write SetDevice;
property Current : string read GetCurrent write SetCurrent;
property Type_ : TSensorType read GetType write SetType;
property Units : string read GetUnits write SetUnits;
end;
{ TConfigMessageFamily }
type TConfigMessageFamily = class(TxPLMessage)
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
end;
TConfigListCmnd = class(TConfigMessageFamily)
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
end;
{ TConfigListStat }
TConfigListStat = class(TConfigListCmnd)
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
public
function ItemMax(const i : integer) : integer;
function ItemName(const i : integer) : string;
end;
{ TConfigListMsg }
TConfigCurrentCmnd = class(TConfigListCmnd)
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
end;
{ TConfigResponseCmnd }
TConfigResponseCmnd = class(TConfigMessageFamily)
private
fMultiValued : TStringList;
function GetFilters : TStringList;
function GetGroups : TStringList;
procedure Read_Multivalued(const aListIndex : integer);
function Getinterval: integer;
function Getnewconf: string;
procedure Setinterval(const AValue: integer);
procedure Setnewconf(const AValue: string);
function GetMultiValued(const aValue : string) : TStringList;
procedure SlChanged(Sender : TObject);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
destructor Destroy; override;
function IsCoreValue(const aIndex : integer) : boolean;
published
property newconf : string read Getnewconf write Setnewconf stored false;
property interval: integer read Getinterval write Setinterval stored false;
property filters : TStringList read GetFilters stored false; //write SetFilters stored false;
property groups : TStringList read GetGroups stored false; // write SetGroups stored false;
end;
TConfigCurrentStat = class(TConfigResponseCmnd)
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
procedure Assign(aMessage : TPersistent); override;
published
property Interval;
property NewConf;
property Filters;
property Groups;
end;
THeartBeatReq = class(TxPLMessage)
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
end;
{ TDawnDuskReq }
TDawnDuskReq = class(TxPLMessage)
private
function GetQuery: string;
procedure SetQuery(aValue: string);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
published
property Query : string read GetQuery write SetQuery;
end;
THeartBeatMsg = class(TxPLMessage)
private
function GetAppName: string;
function GetInterval: integer;
function Getport: integer;
function Getremote_ip: string;
function GetVersion: string;
procedure SetAppName(const AValue: string);
procedure SetInterval(const AValue: integer);
procedure Setport(const AValue: integer);
procedure Setremote_ip(const AValue: string);
procedure SetVersion(const AValue: string);
public
constructor Create(const aOwner: TComponent; const aRawxPL : string = ''); reintroduce;
procedure Send;
published
property interval : integer read GetInterval write SetInterval;
property port : integer read Getport write Setport;
property remote_ip: string read Getremote_ip write Setremote_ip;
property appname : string read GetAppName write SetAppName;
property version : string read GetVersion write SetVersion;
end;
// TFragmentReq ==========================================================
{ TFragmentReqMsg }
TFragmentMsg = class(TxPLMessage)
end;
TFragmentReqMsg = class(TFragmentMsg)
private
function GetMessage: integer;
function GetParts: IntArray;
procedure SetMessage(const AValue: integer);
procedure SetParts(const AValue: IntArray);
public
constructor Create(const aOwner : TComponent); overload;
procedure AddPart(const aPart : integer);
published
property Parts : IntArray read GetParts write SetParts;
property Message : integer read GetMessage write SetMessage;
end;
{ TFragmentBasicMsg }
TFragBasicMsg = class(TFragmentMsg)
private
fPartNum, fPartMax, fUniqueId : integer;
procedure SetPartMax(const AValue: integer);
procedure SetPartNum(const AValue: integer);
procedure SetUniqueId(const AValue: integer);
procedure ReadPartIdElements;
procedure WritePartIdElements;
public
constructor Create(const aOwner : TComponent; const aSourceMsg : TxPLMessage; const FirstOne : boolean = false); reintroduce; overload;
function Identifier : string;
function IsTheFirst : boolean;
function ToMessage : TxPLMessage;
function IsValid : boolean; reintroduce;
property PartNum : integer read fPartNum write SetPartNum;
property PartMax : integer read fPartMax write SetPartMax;
property UniqueId : integer read fUniqueId write SetUniqueId;
end;
function MessageBroker(const aRawxPL : string) : TxPLMessage;
// ============================================================================
implementation
uses StrUtils
, TypInfo
, u_xpl_schema
, u_xpl_sender
, u_xpl_custom_listener
, uxplConst
;
const K_HBEAT_ME_INTERVAL = 'interval';
K_HBEAT_ME_PORT = 'port';
K_HBEAT_ME_REMOTEIP = 'remote-ip';
K_HBEAT_ME_VERSION = 'version';
K_HBEAT_ME_APPNAME = 'appname';
K_FRAGREQ_ME_MESSAGE = 'message';
K_FRAGBAS_ME_PARTID = 'partid';
K_CONFIG_RESPONSE_KEYS : Array[0..3] of string = ('newconf','interval','filter','group');
// ===========================================================================
function MessageBroker(const aRawxPL: string): TxPLMessage;
var aMsg : TxPLMessage;
begin
aMsg := TxPLMessage.Create(nil,aRawxPL);
if
aMsg.Schema.Equals(Schema_FragBasic) then result := TFragBasicMsg.Create(nil,aMsg)
else if
aMsg.Schema.Equals(Schema_FragReq) then result := TFragmentReqMsg.Create(nil,aRawxPL)
else if
aMsg.Schema.Equals(Schema_HBeatApp) then result := THeartBeatMsg.Create(nil,aRawxPL)
else if
aMsg.Schema.Equals(Schema_HBeatReq) then result := THeartBeatReq.Create(nil,aRawxPL)
else if
(aMsg.Schema.Equals(Schema_ConfigList)) and (aMsg.MessageType = cmnd) then result := TConfigListCmnd.Create(nil,aRawxPL)
else if
(aMsg.Schema.Equals(Schema_ConfigCurr)) and (aMsg.MessageType = cmnd) then result := TConfigCurrentCmnd.Create(nil,aRawxPL)
else if
(aMsg.Schema.Equals(Schema_ConfigResp)) and (aMsg.MessageType = cmnd) then result := TConfigResponseCmnd.Create(nil,aRawxPL)
else if
(aMsg.Schema.Equals(Schema_ConfigCurr)) and (aMsg.MessageType = stat) then result := TConfigCurrentStat.Create(nil,aRawxPL)
else if
(aMsg.Schema.Equals(Schema_DDBasic)) and (aMsg.MessageType = trig) then result := TDawnDuskBasicTrig.Create(nil,aRawxPL)
else if
(aMsg.Schema.Equals(Schema_DDBasic)) and (aMsg.MessageType = stat) then result := TDawnDuskBasicStat.Create(nil,aRawxPL)
else if
(aMsg.Schema.Equals(Schema_DDRequest)) and (aMsg.MessageType = cmnd) then result := TDawnDuskReq.Create(nil,aRawxPL)
else if
aMsg.Schema.RawxPL = 'log.basic' then result := TLogBasic.Create(nil,aRawxPL)
else if
aMsg.Schema.RawxPL = 'osd.basic' then result := TOsdBasic.Create(nil,aRawxPL)
else if
aMsg.Schema.RawxPL = 'sendmsg.basic' then result := TSendmsgBasic.Create(nil,aRawxPL)
else if
aMsg.Schema.RawxPL = 'rcvmsg.basic' then result := TReceivemsgBasic.Create(nil,aRawxPL)
else if
aMsg.Schema.RawxPL = 'sensor.basic' then result := TSensorBasic.Create(nil,aRawxPL)
else if
aMsg.Schema.RawxPL = 'timer.basic' then result := TTimerBasic.Create(nil,aRawxPL)
else result := aMsg;
if result<>aMsg then aMsg.Free;
end;
{ TDawnDuskBasicStat }
function TDawnDuskBasicStat.GetStatus: TDayNightStatusType;
begin
if Body.GetValueByKey('status')='day' then Result := day
else if Body.GetValueByKey('status')='night' then Result := night;
end;
procedure TDawnDuskBasicStat.SetStatus(aValue: TDayNightStatusType);
begin
case aValue of
day : Body.SetValueByKey('status','day');
night : Body.SetValueByKey('status','night');
end;
end;
constructor TDawnDuskBasicStat.Create(const aOwner: TComponent;
const aRawxPL: string);
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL='' then begin
Schema.Assign(Schema_DDBasic);
Target.IsGeneric := True;
MessageType := stat;
Body.AddKeyValuePairs( ['type','status'],['daynight','']);
end;
end;
{ TDawnDuskReq }
function TDawnDuskReq.GetQuery: string;
begin
Result := Body.GetValueByKey('query');
end;
procedure TDawnDuskReq.SetQuery(aValue: string);
begin
Body.SetValueByKey('query',aValue);
end;
constructor TDawnDuskReq.Create(const aOwner: TComponent; const aRawxPL: string
);
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL='' then begin
Schema.Assign(Schema_DDRequest);
Target.IsGeneric := True;
MessageType := cmnd;
Body.AddKeyValuePairs( ['command','query'],['status','daynight']);
end;
end;
{ TDawnDuskBasicTrig }
function TDawnDuskBasicTrig.GetStatus: TDawnDuskStatusType;
var s : string;
begin
s := Body.GetValueByKey('status');
if s = 'dawn' then Result := dawn
else if s ='dusk' then Result := dusk;
end;
procedure TDawnDuskBasicTrig.SetStatus(aValue: TDawnDuskStatusType);
begin
Body.SetValueByKey('status',GetEnumName(TypeInfo(TDawnDuskStatusType),Ord(aValue)));
end;
constructor TDawnDuskBasicTrig.Create(const aOwner: TComponent; const aRawxPL: string);
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL='' then begin
Schema.Assign(Schema_DDBasic);
Target.IsGeneric := True;
MessageType := trig;
Body.AddKeyValuePairs( ['type','status'],['dawndusk','']);
end;
end;
{ TTimerBasic }
function TTimerBasic.GetDevice: string;
begin
result := Body.GetValueByKey('device','');
end;
function TTimerBasic.GetCurrent: string;
begin
result := Body.GetValueByKey('current','');
end;
procedure TTimerBasic.SetCurrent(const AValue: string);
begin
Body.SetValueByKey('current',aValue);
end;
procedure TTimerBasic.SetDevice(const AValue: string);
begin
Body.SetValueByKey('device',aValue);
end;
constructor TTimerBasic.Create(const aOwner: TComponent; const aRawxPL: string);
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL='' then begin
Schema.RawxPL := 'timer.basic';
Target.IsGeneric := True;
MessageType := stat;
Body.AddKeyValuePairs( ['device','current'],['','']);
end;
end;
// TConfigMessageFamily =======================================================
constructor TConfigMessageFamily.Create(const aOwner: TComponent; const aRawxPL: string);
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL = '' then begin
Schema.Classe := 'config';
end;
end;
{ TConfigCurrentStat }
constructor TConfigCurrentStat.Create(const aOwner: TComponent; const aRawxPL: string);
begin
inherited Create(aOwner, aRawxPL);
if aRawxPL = '' then begin
Schema.Type_:= 'current';
MessageType := stat;
Target.IsGeneric:=true;
end;
end;
procedure TConfigCurrentStat.Assign(aMessage: TPersistent);
begin
Body.ResetValues;
inherited Assign(aMessage);
if aMessage is TConfigCurrentStat then begin
fMultiValued.Assign(tConfigCurrentStat(aMessage).fMultiValued);
end;
end;
{ TConfigListCmnd }
constructor TConfigListCmnd.Create(const aOwner: TComponent; const aRawxPL: string); // formerly TConfigReqMsg
begin
inherited Create(aOwner, aRawxPL);
if aRawxPL = '' then begin
Schema.Type_:= 'list';
MessageType := cmnd;
Body.AddKeyValuePairs( ['command'],['request']);
end;
end;
constructor TConfigListStat.Create(const aOwner: TComponent; const aRawxPL: string);
begin
inherited Create(aOwner, aRawxPL);
if aRawxPL = '' then begin
MessageType := stat;
Body.ResetValues;
Body.AddKeyValuePairs( ['reconf','option','option','option'],['newconf','interval','filter[16]','group[16]']);
end;
end;
function TConfigListStat.ItemMax(const i: integer): integer;
var sl : tstringlist;
s : string;
begin
sl := TStringList.Create;
s := AnsiReplaceStr(Body.Values[i],']','[');
sl.Delimiter := '[';
sl.DelimitedText := s;
if sl.Count=1 then result := 1 else result := StrToInt(sl[1]);
sl.free;
end;
function TConfigListStat.ItemName(const i: integer): string;
var sl : tstringlist;
s : string;
begin
sl := TStringList.Create;
s := AnsiReplaceStr(Body.Values[i],']','[');
sl.Delimiter := '[';
sl.DelimitedText := s;
result := sl[0];
sl.free;
end;
{ TConfigCurrentCmnd }
constructor TConfigCurrentCmnd.Create(const aOwner: TComponent; const aRawxPL: string); // formerly TConfigCurrMsg
begin
inherited Create(aOwner, aRawxPL);
if aRawxPL = '' then begin
Schema.Type_:= 'current';
end;
end;
// TConfigRespMsg =============================================================
constructor TConfigResponseCmnd.Create(const aOwner: TComponent; const aRawxPL: string); // formerly TConfigRespMsg
begin
inherited Create(aOwner, aRawxPL);
fMultiValued := TStringList.Create;
if aRawxPL = '' then begin
Schema.Type_:= 'response';
MessageType := cmnd;
Body.AddKeyValuePairs( K_CONFIG_RESPONSE_KEYS,['','','','']);
end;
end;
destructor TConfigResponseCmnd.Destroy;
var i : integer;
begin
for i:=0 to Pred(fMultivalued.Count) do
if Assigned(fMultiValued.Objects[i]) then
TStringList(fMultiValued.Objects[i]).Free;
fMultiValued.Free;
inherited Destroy;
end;
function TConfigResponseCmnd.GetFilters : TStringList;
begin
result := GetMultiValued('filter');
end;
function TConfigResponseCmnd.GetGroups : TStringList;
begin
result := GetMultiValued('group');
end;
procedure TConfigResponseCmnd.SlChanged(Sender: TObject);
var j,i : integer;
begin
for j:=0 to Pred(fMultiValued.Count) do begin
if (fMultiValued.Objects[j] = sender) then begin // Identify the sending stringlist
for i:=Pred(Body.ItemCount) downto 0 do
if Body.Keys[i] = fMultiValued[j] then Body.DeleteItem(i);
if TStringList(Sender).Count = 0
then Body.AddKeyValue(fMultiValued[j]+'=')
else for i:=0 to Pred(TStringList(Sender).Count) do
Body.AddKeyValue(fMultiValued[j] + '=' + TStringList(Sender)[i]);
end;
end;
end;
function TConfigResponseCmnd.GetMultiValued(const aValue: string): TStringList;
function NewList : TStringList;
begin
result := TStringList.Create;
result.Sorted := true;
result.Duplicates:=dupIgnore;
result.OnChange :=@slChanged;
end;
var i : integer;
begin
result := nil;
for i:=0 to Pred(fMultiValued.count) do
if fMultiValued[i] = aValue then
result := TStringList(fMultiValued.Objects[i]);
if (result = nil) then begin
result := NewList;
i := fMultiValued.AddObject(aValue,Result);
Read_MultiValued(i);
end;
end;
procedure TConfigResponseCmnd.Read_Multivalued(const aListIndex: integer);
var i : integer;
aSl : TStringList;
begin
aSL := TStringList(fMultiValued.Objects[aListIndex]);
aSL.BeginUpdate;
aSL.Clear;
for i := 0 to Pred(Body.ItemCount) do
if (Body.Keys[i] = fMultiValued[aListIndex]) and (Body.Values[i]<>'') then aSL.Add(Body.Values[i]);
aSL.EndUpdate;
end;
function TConfigResponseCmnd.Getinterval: integer;
begin
result := StrToIntDef(Body.GetValueByKey('interval',''),-1);
end;
function TConfigResponseCmnd.Getnewconf: string;
begin
result := Body.GetValueByKey('newconf','');
end;
procedure TConfigResponseCmnd.Setinterval(const AValue: integer);
begin
Body.SetValueByKey('interval',IntToStr(aValue));
end;
procedure TConfigResponseCmnd.Setnewconf(const AValue: string);
begin
Body.SetValueByKey('newconf',aValue);
end;
function TConfigResponseCmnd.IsCoreValue(const aIndex: integer): boolean;
begin
result := AnsiIndexStr(Body.Keys[aIndex],K_CONFIG_RESPONSE_KEYS) <>-1;
end;
// TSensorBasic ===============================================================
constructor TSensorBasic.Create(const aOwner: TComponent; const aRawxPL: string);
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL='' then begin
Schema.RawxPL := 'sensor.basic';
Target.IsGeneric := True;
MessageType := trig;
Body.AddKeyValuePairs( ['device','type','current'],['','','']);
end;
end;
function TSensorBasic.SensorName: string;
begin
// result := Source.AsFilter + '.' + Device;
result := Device;
end;
function TSensorBasic.GetDevice: string;
begin
result := Body.GetValueByKey('device','');
end;
procedure TSensorBasic.SetDevice(const AValue: string);
begin
Body.SetValueByKey('device',aValue);
end;
function TSensorBasic.GetType: TSensorType;
var s : string;
i : integer;
begin
s := Body.GetValueByKey('type','');
i := AnsiIndexStr(AnsiLowerCase(s),TSensorTypeLib);
if i=-1 then i := 0;
Result := TSensorType(i);
end;
procedure TSensorBasic.SetType(const AValue: TSensorType);
var {%H-}foo : string;
begin
Body.SetValueByKey('type',TSensorTypeLib[aValue]);
foo := GetUnits; // Will set the default unit for current value
end;
function TSensorBasic.GetCurrent: string;
begin
result := Body.GetValueByKey('current','');
end;
procedure TSensorBasic.SetCurrent(const AValue: string);
begin
Body.SetValueByKey('current',aValue);
end;
procedure TSensorBasic.SetUnits(const AValue: string);
begin
Body.SetValueByKey('units',aValue);
end;
function TSensorBasic.GetUnits: string;
begin
result := Body.GetValueByKey('units','');
if AnsiSameText(result,'') then begin // Si aucune unité indiquée, on renvoie celle par
result := TSensorUnits[Type_]; // défaut pour le type courant
if not AnsiSameText(result,'') then
SetUnits(result); // on indique l'unité dans le body au passage
end;
end;
// TSendmsgBasic ==============================================================
constructor TSendmsgBasic.Create(const aOwner: TComponent; const aRawxPL: string);
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL='' then begin
Schema.RawxPL := 'sendmsg.basic';
Target.IsGeneric := True;
MessageType := cmnd;
Body.AddKeyValuePairs( ['body','to'],['','']);
end;
end;
function TSendmsgBasic.GetTo: string;
begin
result := Body.GetValueByKey('to','');
end;
function TSendmsgBasic.GetText: string;
begin
result := Body.GetValueByKey('body');
end;
procedure TSendmsgBasic.SetText(const AValue: string);
begin
Body.SetValueByKey('body',aValue);
end;
procedure TSendmsgBasic.SetTo(const AValue: string);
begin
Body.SetValueByKey('to',aValue);
end;
{ TReceiveMsgBasic }
constructor TReceiveMsgBasic.Create(const aOwner: TComponent; const aRawxPL: string);
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL='' then begin
Schema.RawxPL := 'rcvmsg.basic';
MessageType := trig;
Body.AddKeyValuePairs( ['from'],['']);
end;
end;
function TReceiveMsgBasic.GetFrom: string;
begin
result := Body.GetValueByKey('from','');
end;
procedure TReceiveMsgBasic.SetFrom(AValue: string);
begin
Body.SetValueByKey('from',aValue);
end;
{ TLogBasic }
constructor TLogBasic.Create(const aOwner: TComponent; const aRawxPL: string);
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL='' then begin
Schema.RawxPL := 'log.basic';
Target.IsGeneric := True;
MessageType := trig;
Body.AddKeyValuePairs( ['type','text'],['','']);
end;
end;
function TLogBasic.GetCode: string;
begin
result := Body.GetValueByKey('code','');
end;
function TLogBasic.GetText: string;
begin
result := Body.GetValueByKey('text');
end;
function TLogBasic.GetType: TEventType;
begin
result := xPLLevelToEventType(Body.GetValueByKey('type'));
end;
procedure TLogBasic.SetCode(const AValue: string);
begin
Body.SetValueByKey('code',aValue);
end;
procedure TLogBasic.SetText(const AValue: string);
begin
Body.SetValueByKey('text',aValue);
end;
procedure TLogBasic.SetType(const AValue: TEventType);
begin
Body.SetValueByKey('type',EventTypeToxPLLevel(aValue));
end;
{ TOsdBasic }
function TOsdBasic.GetColumn: integer;
begin
result := StrToIntDef(Body.GetValueByKey('column'),0);
end;
function TOsdBasic.GetCommand: string;
begin
result := Body.GetValueByKey('command','write');
end;
function TOsdBasic.GetDelay: integer;
begin
result := StrToIntDef(Body.GetValueByKey('delay'),-1);
end;
function TOsdBasic.GetRow: integer;
begin
result := StrToIntDef(Body.GetValueByKey('row'),0);
end;
function TOsdBasic.GetText: string;
begin
result := Body.GetValueByKey('text');
end;
procedure TOsdBasic.SetColumn(const AValue: integer);
begin
Body.SetValueByKey('column',IntToStr(aValue));
end;
procedure TOsdBasic.SetCommand(const AValue: string);
begin
Body.SetValueByKey('command',aValue);
end;
procedure TOsdBasic.SetDelay(const AValue: integer);
begin
if GetDelay=-1 then Body.AddKeyValue('delay=');
Body.SetValueByKey('delay',IntToStr(aValue));
end;
procedure TOsdBasic.SetRow(const AValue: integer);
begin
Body.SetValueByKey('row',IntToStr(aValue));
end;
procedure TOsdBasic.SetText(const AValue: string);
begin
Body.SetValueByKey('text',aValue);
end;
constructor TOsdBasic.Create(const aOwner: TComponent; const aRawxPL: string);
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL='' then begin
Schema.RawxPL := 'osd.basic';
Target.IsGeneric := True;
MessageType := cmnd;
Body.AddKeyValuePairs( ['command','text'],['','']);
end;
end;
// TFragmentBasicMsg =========================================================
constructor TFragBasicMsg.Create(const aOwner: TComponent; const aSourceMsg : TxPLMessage; const FirstOne : boolean = false);
begin
fPartNum := -1;
fPartMax := -1;
fUniqueId := -1;
inherited Create(aOwner); // This object can be created from two purposes :
if aSourceMsg.schema.Equals(Schema_FragBasic) then begin // 1°/ Creating it from rawxpl received on the network
Assign(aSourceMsg);
ReadPartIdElements;
end else begin // 2°/ Having a big message of class.type schema to explode it
AssignHeader(aSourceMsg);
Schema.Assign(Schema_FragBasic);
Body.addkeyvaluepairs([K_FRAGBAS_ME_PARTID],['%d/%d:%d']);
if FirstOne then begin
Body.addkeyvaluepairs(['schema'],[aSourceMsg.Schema.RawxPL]);
fPartNum := 1;
end;
end;
end;
procedure TFragBasicMsg.SetPartMax(const AValue: integer);
begin
if aValue = fPartMax then exit;
fPartMax := aValue;
WritePartIdElements;
end;
procedure TFragBasicMsg.SetPartNum(const AValue: integer);
begin
if aValue = fPartNum then exit;
fPartNum := aValue;
WritePartIdElements;
end;
procedure TFragBasicMsg.SetUniqueId(const AValue: integer);
begin
if aValue = fUniqueId then exit;
fUniqueId := aValue;
WritePartIdElements;
end;
procedure TFragBasicMsg.ReadPartIdElements;
var List : TStringList;
partid : string;
begin
partid := AnsiReplaceStr(Body.GetValueByKey('partid'),'/',':');
List := TStringList.Create;
List.Delimiter := ':';
List.DelimitedText := partid;
if list.Count=3 then begin
fPartNum := StrToIntDef(list[0],-1);
fPartMax := StrToIntDef(list[1],-1);
fUniqueId := StrToIntDef(list[2],-1);
end;
list.Free;
end;
procedure TFragBasicMsg.WritePartIdElements;
begin
Body.SetValueByKey(K_FRAGBAS_ME_PARTID, Format('%d/%d:%d',[fPartNum, fPartMax, fUniqueID]));
end;
function TFragBasicMsg.ToMessage: TxPLMessage;
begin
if IsTheFirst then begin
Result := TxPLMessage.Create(owner);
if IsValid then begin
Result.Assign(self);
Result.schema.RawxPL := Body.GetValueByKey('schema');
Result.Body.DeleteItem(0); // Delete the partid line
if Result.Schema.IsValid then Result.Body.DeleteItem(0); // delete the schema line
end;
end else Result := nil;
end;
function TFragBasicMsg.IsValid: boolean;
begin
Result := inherited IsValid and ( (fPartNum * fPartMax * fUniqueId) >= 0);
if IsTheFirst then Result := Result and (Body.GetValueByKey('schema')<>'');
end;
function TFragBasicMsg.Identifier: string;
begin
result := AnsiReplaceStr(Source.AsFilter,'.','') + IntToStr(fUniqueId);
end;
function TFragBasicMsg.IsTheFirst: boolean;
begin
result := (fPartNum = 1);
end;
// TFragmentReq ==============================================================
constructor TFragmentReqMsg.Create(const aOwner: TComponent);
begin
inherited Create(aOwner);
Schema.Assign(Schema_FragReq);
MessageType := cmnd;
Body.AddKeyValuePairs( ['command',K_FRAGREQ_ME_MESSAGE], ['resend','']);
end;
function TFragmentReqMsg.GetMessage: integer;
begin
result := StrToIntDef(Body.GetValueByKey(K_FRAGREQ_ME_MESSAGE),-1);
end;
function TFragmentReqMsg.GetParts: IntArray;
var i : integer;
begin
SetLength(Result,0);
for i:=0 to Pred(Body.ItemCount) do
if Body.Keys[i]='part' then begin
SetLength(Result,Length(result)+1);
Result[length(result)-1] := StrToInt(Body.Values[i]);
end;
end;
procedure TFragmentReqMsg.SetMessage(const AValue: integer);
begin
Body.SetValueByKey(K_FRAGREQ_ME_MESSAGE,IntToStr(aValue));
end;
procedure TFragmentReqMsg.AddPart(const aPart: integer);
begin
Body.AddKeyValue('part=' + IntToStr(aPart));
end;
procedure TFragmentReqMsg.SetParts(const AValue: IntArray);
var i : integer;
begin
for i:=low(aValue) to high(aValue) do AddPart(aValue[i]);
end;
// THeartBeatReq ==============================================================
constructor THeartBeatReq.Create(const aOwner: TComponent; const aRawxPL : string = '');
begin
inherited Create(aOwner,aRawxPL);
if aRawxPL='' then begin
Schema.Assign(Schema_HBeatReq);
Target.IsGeneric := True;
MessageType := cmnd;
Body.AddKeyValuePairs( ['command'],['request']);
end;
end;
// THeartBeatMsg ==============================================================
constructor THeartBeatMsg.Create(const aOwner: TComponent; const aRawxPL : string = '');
begin
inherited Create(aOwner, aRawxPL);
if aRawxPL='' then begin
Schema.Assign(Schema_HBeatApp);
MessageType:= stat;
Target.IsGeneric := True;
Body.AddKeyValuePairs( [K_HBEAT_ME_INTERVAL,K_HBEAT_ME_PORT,K_HBEAT_ME_REMOTEIP,K_HBEAT_ME_APPNAME ,K_HBEAT_ME_VERSION],
['','','','','']);
if Owner is TxPLCustomListener then with TxPLCustomListener(Owner) do begin
Self.Interval := Config.Interval;
Self.AppName := AppName;
Self.Version := Version;
if not Config.IsValid then Schema.Classe := 'config';
if csDestroying in ComponentState then Schema.Type_ := 'end';
end;
end;
end;
procedure THeartBeatMsg.Send;
begin
if Owner is TxPLSender then
TxPLSender(Owner).Send(self);
end;
function THeartBeatMsg.GetAppName: string;
begin
result := Body.GetValueByKey('appname','');
end;
function THeartBeatMsg.GetInterval: integer;
begin
result := StrToIntDef(Body.GetValueByKey(K_HBEAT_ME_INTERVAL),MIN_HBEAT);
end;
function THeartBeatMsg.Getport: integer;
begin
Assert(Body.GetValueByKey(K_HBEAT_ME_PORT,'')<>'');
result := StrToIntDef(Body.GetValueByKey(K_HBEAT_ME_PORT),-1);
end;
function THeartBeatMsg.Getremote_ip: string;
begin
result := Body.GetValueByKey(K_HBEAT_ME_REMOTEIP);
end;
function THeartBeatMsg.GetVersion: string;
begin
result := Body.GetValueByKey('version','');
end;
procedure THeartBeatMsg.SetAppName(const AValue: string);
begin
Body.SetValueByKey('appname',aValue);
end;
procedure THeartBeatMsg.SetInterval(const AValue: integer);
begin
Body.SetValueByKey(K_HBEAT_ME_INTERVAL,IntToStr(aValue));
end;
procedure THeartBeatMsg.Setport(const AValue: integer);
begin
Body.SetValueByKey(K_HBEAT_ME_PORT,IntToStr(aValue));
end;
procedure THeartBeatMsg.Setremote_ip(const AValue: string);
begin
Body.SetValueByKey(K_HBEAT_ME_REMOTEIP,aValue);
end;
procedure THeartBeatMsg.SetVersion(const AValue: string);
begin
Body.SetValueByKey('version',aValue);
end;
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/primitives/transaction.h
// Bitcoin file: src/primitives/transaction.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TMutableTransaction;
interface
/** A mutable version of CTransaction. */
struct CMutableTransaction
{
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
int32_t nVersion;
uint32_t nLockTime;
CMutableTransaction();
explicit CMutableTransaction(const CTransaction& tx);
template <typename Stream>
inline void Serialize(Stream& s) const {
SerializeTransaction(*this, s);
}
template <typename Stream>
inline void Unserialize(Stream& s) {
UnserializeTransaction(*this, s);
}
template <typename Stream>
CMutableTransaction(deserialize_type, Stream& s) {
Unserialize(s);
}
/** Compute the hash of this CMutableTransaction. This is computed on the
* fly, as opposed to GetHash() in CTransaction, which uses a cached result.
*/
uint256 GetHash() const;
bool HasWitness() const
{
for (size_t i = 0; i < vin.size(); i++) {
if (!vin[i].scriptWitness.IsNull()) {
return true;
}
}
return false;
}
};
implementation
CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nLockTime(0) {}
CMutableTransaction::CMutableTransaction(const CTransaction& tx) : vin(tx.vin), vout(tx.vout), nVersion(tx.nVersion), nLockTime(tx.nLockTime) {}
uint256 CMutableTransaction::GetHash() const
{
return SerializeHash(*this, SER_GETHASH, SERIALIZE_TRANSACTION_NO_WITNESS);
}
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://211.90.38.54:18282/WebService/SolidWasteService?wsdl
// >Import : http://211.90.38.54:18282/WebService/SolidWasteService?wsdl=ISolidWasteService.wsdl
// >Import : http://211.90.38.54:18282/WebService/SolidWasteService?wsdl=ISolidWasteService.wsdl>0
// Encoding : UTF-8
// Version : 1.0
// (2018/10/19 9:49:25 - - $Rev: 90173 $)
// ************************************************************************ //
unit SolidWasteService;
interface
uses Soap.InvokeRegistry, Soap.SOAPHTTPClient, System.Types, Soap.XSBuiltIns;
const
IS_OPTN = $0001;
IS_UNQL = $0008;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Embarcadero types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:string - "http://www.w3.org/2001/XMLSchema"[Gbl]
// ************************************************************************ //
// Namespace : http://api.weighbridge.internet.shencai.com/
// transport : http://schemas.xmlsoap.org/soap/http
// style : document
// use : literal
// binding : SolidWasteServiceImplServiceSoapBinding
// service : SolidWasteServiceImplService
// port : SolidWasteServiceImplPort
// URL : http://211.90.38.54:18282/WebService/SolidWasteService
// ************************************************************************ //
ISolidWasteService = interface(IInvokable)
['{4C6FB50E-23F9-5664-0A8D-F79439A6E7E1}']
function process(const arg0: string): string; stdcall;
end;
function GetISolidWasteService(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): ISolidWasteService;
implementation
uses System.SysUtils;
function GetISolidWasteService(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): ISolidWasteService;
const
defWSDL = 'http://211.90.38.54:18282/WebService/SolidWasteService?wsdl';
defURL = 'http://211.90.38.54:18282/WebService/SolidWasteService';
defSvc = 'SolidWasteServiceImplService';
defPrt = 'SolidWasteServiceImplPort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as ISolidWasteService);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
initialization
{ ISolidWasteService }
//InvRegistry.RegisterInvokeOptions(TypeInfo(ISolidWasteService),ioDocument);
InvRegistry.RegisterInterface(TypeInfo(ISolidWasteService), 'http://api.weighbridge.internet.shencai.com/', 'UTF-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(ISolidWasteService), '');
InvRegistry.RegisterInvokeOptions(TypeInfo(ISolidWasteService), ioDocument);
{ ISolidWasteService.process }
InvRegistry.RegisterMethodInfo(TypeInfo(ISolidWasteService), 'process', '',
'[ReturnName="return"]', IS_OPTN or IS_UNQL);
InvRegistry.RegisterParamInfo(TypeInfo(ISolidWasteService), 'process', 'arg0', '',
'', IS_UNQL);
InvRegistry.RegisterParamInfo(TypeInfo(ISolidWasteService), 'process', 'return', '',
'', IS_UNQL);
end. |
unit ConnUtil;
interface
uses SysUtils, IniFiles;
function GetConnection(const appPath, AUser, APassword: string;
const core: boolean = false): string;
const
IFN_INI = 'ifn.ini';
implementation
function GetConnection(const appPath, AUser, APassword: string;
const core: boolean = false): string;
var
dir, inifile, section, connStr: string;
Ini: TInifile;
provider, user, pw, server, db, datasource: string;
begin
// application path parameter is only used by the windows service
if appPath = '' then
dir := GetCurrentDir
else
dir := appPath;
// specify section
if core then
section := 'CORE'
else
section := 'CONNECTION';
inifile := dir + '\' + IFN_INI;
Ini := TIniFile.Create(inifile);
provider := Ini.ReadString(section,'Provider','');
user := Ini.ReadString(section,'User','');
pw := Ini.ReadString(section,'Password','');
server := Ini.ReadString(section,'Server','BRYAN-PC\SQLEXPRESS');
db := Ini.ReadString(section,'Dbase','');
datasource := Ini.ReadString(section,'DataSource','');
// overwrite the username and password with the parameters
if AUser <> '' then
user := AUser;
if APassword <> '' then
pw := APassword;
connStr := 'Provider=' + provider + ';Password=' + pw + ';' +
'Persist Security Info=False;' +
'User ID=' + user + ';Initial Catalog=' + db +
';Data Source=' + datasource +
';Use Procedure for Prepare=1;' +
'Auto Translate=True;Packet Size=4096;' +
'Workstation ID=' + server +
';Use Encryption for Data=False;' +
'Tag with column collation when possible=False;' +
'MARS Connection=False;DataTypeCompatibility=0;' +
'Trust Server Certificate=False';
Result := connStr;
end;
end.
|
unit IdQotdServer;
interface
uses
Classes,
IdGlobal,
IdTCPServer;
type
TIdQOTDGetEvent = procedure(Thread: TIdPeerThread) of object;
TIdQOTDServer = class(TIdTCPServer)
protected
FOnCommandQOTD: TIdQOTDGetEvent;
function DoExecute(Thread: TIdPeerThread): boolean; override;
public
constructor Create(AOwner: TComponent); override;
published
property OnCommandQOTD: TIdQOTDGetEvent read fOnCommandQOTD
write fOnCommandQOTD;
property DefaultPort default IdPORT_QOTD;
end;
implementation
uses
SysUtils;
constructor TIdQOTDServer.Create(AOwner: TComponent);
begin
inherited;
DefaultPort := IdPORT_QOTD;
end;
function TIdQOTDServer.DoExecute(Thread: TIdPeerThread): boolean;
begin
result := true;
if Thread.Connection.Connected then
begin
if assigned(OnCommandQOTD) then
begin
OnCommandQOTD(Thread);
end;
end;
Thread.Connection.Disconnect;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.