text stringlengths 14 6.51M |
|---|
unit memmap;
{$mode fpc}
interface
const
MEMBANK_SIZE = 4*1024*1024;
const
MAINMEM_BASE = $0;
MAINMEM_SIZE = MEMBANK_SIZE;
(* peripherals are all mapped here *)
PERIPHERAL_BASE = ( $f0000000 );
(* system info *)
SYSINFO_REGS_BASE = ( PERIPHERAL_BASE );
SYSINFO_REGS_SIZE = MEMBANK_SIZE;
SYSINFO_FEATURES = ( SYSINFO_REGS_BASE + 0 );
SYSINFO_FEATURE_DISPLAY = $00000001;
SYSINFO_FEATURE_CONSOLE = $00000002;
SYSINFO_FEATURE_NETWORK = $00000004;
SYSINFO_FEATURE_BLOCKDEV = $00000008;
SYSINFO_TIME_LATCH = ( SYSINFO_REGS_BASE + 4 );
(* gettimeofday() style time values *)
SYSINFO_TIME_SECS = ( SYSINFO_REGS_BASE + 8 );
SYSINFO_TIME_USECS = ( SYSINFO_REGS_BASE + 12 );
(* display *)
DISPLAY_BASE = ( SYSINFO_REGS_BASE + SYSINFO_REGS_SIZE );
DISPLAY_SIZE = MEMBANK_SIZE;
DISPLAY_FRAMEBUFFER = DISPLAY_BASE;
DISPLAY_REGS_BASE = ( DISPLAY_BASE + DISPLAY_SIZE );
DISPLAY_REGS_SIZE = MEMBANK_SIZE;
DISPLAY_WIDTH = ( DISPLAY_REGS_BASE + 0 ); // pixels width/height read/only
DISPLAY_BPP = ( DISPLAY_REGS_BASE + 8 ); // bits per pixel (16/32)
(* console (keyboard controller *)
CONSOLE_REGS_BASE = ( DISPLAY_REGS_BASE + DISPLAY_REGS_SIZE );
CONSOLE_REGS_SIZE = MEMBANK_SIZE;
KYBD_STAT = ( CONSOLE_REGS_BASE + 0 );
KYBD_DATA = ( CONSOLE_REGS_BASE + 4 );
(* programmable timer *)
PIT_REGS_BASE = ( CONSOLE_REGS_BASE + CONSOLE_REGS_SIZE );
PIT_REGS_SIZE = MEMBANK_SIZE;
PIT_STATUS = ( PIT_REGS_BASE + 0 ); // status bit
PIT_CLEAR = ( PIT_REGS_BASE + 4 ); // a nonzero write clears any pending timer
PIT_CLEAR_INT = ( PIT_REGS_BASE + 8 ); // a nonzero write clears the pending interrupt
PIT_INTERVAL = ( PIT_REGS_BASE + 12 ); // set the countdown interval, and what the interval is reset to if periodic
PIT_START_ONESHOT = ( PIT_REGS_BASE + 16 ); // a nonzero write starts a oneshot countdown
PIT_START_PERIODIC = ( PIT_REGS_BASE + 20 ); // a nonzero write starts a periodic countdown
PIT_STATUS_ACTIVE = $1;
PIT_STATUS_INT_PEND = $2;
(* interrupt controller *)
PIC_REGS_BASE = ( PIT_REGS_BASE + PIT_REGS_SIZE );
PIC_REGS_SIZE = MEMBANK_SIZE;
(* Current vector mask, read-only *)
PIC_MASK = ( PIC_REGS_BASE + 0 );
(* Mask any of the 32 interrupt vectors by writing a 1 in the appropriate bit *)
PIC_MASK_LATCH = ( PIC_REGS_BASE + 4 );
(* Unmask any of the 32 interrupt vectors by writing a 1 in the appropriate bit *)
PIC_UNMASK_LATCH = ( PIC_REGS_BASE + 8 );
(* each bit corresponds to the current status of the interrupt line *)
PIC_STAT = ( PIC_REGS_BASE + 12 );
(* one bit set for the highest priority non-masked active interrupt *)
PIC_CURRENT_BIT = ( PIC_REGS_BASE + 16 );
(* holds the current interrupt number of the highest priority non-masked active interrupt,
* or 0xffffffff if no interrupt is active
*)
PIC_CURRENT_NUM = ( PIC_REGS_BASE + 20 );
(* interrupt map *)
INT_PIT = 0;
INT_KEYBOARD = 1;
INT_NET = 2;
PIC_MAX_INT = 32;
(* debug interface *)
DEBUG_REGS_BASE = ( PIC_REGS_BASE + PIC_REGS_SIZE );
DEBUG_REGS_SIZE = MEMBANK_SIZE;
DEBUG_STDOUT = ( DEBUG_REGS_BASE + 0 ); (* writes to this register are sent through to stdout *)
DEBUG_STDIN = ( DEBUG_REGS_BASE + 0 ); (* reads from this register return the contents of stdin
* or -1 if no data is pending *)
DEBUG_REGDUMP = ( DEBUG_REGS_BASE + 4 ); (* writes to this register cause the emulator to dump registers *)
DEBUG_HALT = ( DEBUG_REGS_BASE + 8 ); (* writes to this register will halt the emulator *)
DEBUG_MEMDUMPADDR = ( DEBUG_REGS_BASE + 12 ); (* set the base address of memory to dump *)
DEBUG_MEMDUMPLEN = ( DEBUG_REGS_BASE + 16 ); (* set the length of memory to dump *)
DEBUG_MEMDUMP_BYTE = ( DEBUG_REGS_BASE + 20 ); (* trigger a memory dump in byte format *)
DEBUG_MEMDUMP_HALFWORD = ( DEBUG_REGS_BASE + 24 ); (* trigger a memory dump in halfword format *)
DEBUG_MEMDUMP_WORD = ( DEBUG_REGS_BASE + 28 ); (* trigger a memory dump in word format *)
(* lets you set the trace level of the various subsystems from within the emulator *)
(* only works on emulator builds that support dynamic trace levels *)
DEBUG_SET_TRACELEVEL_CPU = ( DEBUG_REGS_BASE + 32 );
DEBUG_SET_TRACELEVEL_UOP = ( DEBUG_REGS_BASE + 36 );
DEBUG_SET_TRACELEVEL_SYS = ( DEBUG_REGS_BASE + 40 );
DEBUG_SET_TRACELEVEL_MMU = ( DEBUG_REGS_BASE + 44 );
DEBUG_CYCLE_COUNT = ( DEBUG_REGS_BASE + 48 );
DEBUG_INS_COUNT = ( DEBUG_REGS_BASE + 52 );
(* network interface *)
NET_REGS_BASE = ( DEBUG_REGS_BASE + DEBUG_REGS_SIZE );
NET_REGS_SIZE = MEMBANK_SIZE;
NET_BUF_LEN = 2048;
NET_IN_BUF_COUNT = 32;
NET_HEAD = ( NET_REGS_BASE + 0 ); (* current next buffer the hardware will write to *)
NET_TAIL = ( NET_REGS_BASE + 4 ); (* currently selected input buffer *)
NET_SEND = ( NET_REGS_BASE + 8 ); (* writes to this register sends whatever is in the out buf *)
NET_SEND_LEN = ( NET_REGS_BASE + 12 ); (* length of packet to send *)
NET_OUT_BUF = ( NET_REGS_BASE + NET_BUF_LEN );
NET_IN_BUF_LEN = ( NET_REGS_BASE + 16 ); (* length of the currently selected in buffer, via tail register *)
NET_IN_BUF = ( NET_REGS_BASE + NET_BUF_LEN * 2 );
(* block device interface *)
BDEV_REGS_BASE = ( NET_REGS_BASE + NET_REGS_SIZE );
BDEV_REGS_SIZE = MEMBANK_SIZE;
BDEV_CMD = ( BDEV_REGS_BASE + 0 ); (* command *)
BDEV_CMD_ADDR = ( BDEV_REGS_BASE + 4 ); (* address of next transfer, 32bit *)
BDEV_CMD_OFF = ( BDEV_REGS_BASE + 8 ); (* offset of next transfer, 64bit *)
BDEV_CMD_LEN = ( BDEV_REGS_BASE + 16 ); (* length of next transfer, 32bit *)
BDEV_LEN = ( BDEV_REGS_BASE + 20 ); (* length of block device, 64bit *)
(* BDEV_CMD bits *)
BDEV_CMD_MASK = ( $3 );
BDEV_CMD_NOP = ( 0 );
BDEV_CMD_READ = ( 1 );
BDEV_CMD_WRITE = ( 2 );
BDEV_CMD_ERASE = ( 3 );
BDEV_CMD_ERRSHIFT = 16;
BDEV_CMD_ERRMASK = ( $ffff shl BDEV_CMD_ERRSHIFT );
BDEV_CMD_ERR_NONE = ( 0 shl BDEV_CMD_ERRSHIFT );
BDEV_CMD_ERR_GENERAL = ( 1 shl BDEV_CMD_ERRSHIFT );
BDEV_CMD_ERR_BAD_OFFSET = ( 2 shl BDEV_CMD_ERRSHIFT );
implementation
end.
|
unit uProductController;
interface
uses System.Classes, uProduct;
type
TProductController = class (TProductBase)
private
FProductModel : TProduct;
FListProduct : TList;
procedure ClearList;
public
constructor Create(aSender: TComponent); overload;
destructor Destroy(); override;
function GetProduct(aIndex: integer): TProduct;
function Open(): TProductController;
function Count(): integer;
end;
implementation
{ TProductController }
procedure TProductController.ClearList;
var
I: Integer;
begin
for I := 0 to FListProduct.Count-1 do
TProduct(FListProduct[I]).Free;
end;
function TProductController.Count: integer;
begin
if not Assigned(FListProduct) then
FListProduct := TList.Create;
Result := FListProduct.Count;
end;
constructor TProductController.Create(aSender: TComponent);
begin
FProductModel := TProduct.Create(self);
FListProduct := TList.Create;
Filter := TFilterProduct.Create;
inherited Create(aSender);
end;
destructor TProductController.Destroy;
begin
if Assigned(FListProduct) then
begin
ClearList;
FListProduct.Free;
end;
Filter.Free;
inherited;
end;
function TProductController.GetProduct(aIndex: integer): TProduct;
begin
if not Assigned(FListProduct) then
FListProduct := TList.Create;
if (aIndex < 0) or (FListProduct.Count-1 < aIndex) then
begin
Result := nil;
exit;
end;
result := TProduct(FListProduct[aIndex]);
end;
function TProductController.Open: TProductController;
begin
if Assigned(FListProduct) then
begin
ClearList;
FListProduct.Free;
end;
FProductModel.Filter := Self.Filter;
FListProduct := FProductModel.Get;
end;
end.
|
program RepeatLoop;
uses SysUtils;
procedure Main();
var
temp : String;
begin
repeat
WriteLn('Hello World');
Write('Quit?');
ReadLn(temp);
until(temp = 'Yes') or (temp = 'y');
WriteLn('bye');
end;
begin
Main();
end. |
unit uAPI;
interface
uses IdTCPClient, IdGlobal, SysUtils, Variants, Classes, System.JSON, uHelper;
const
GM_LOSE = 0;
GM_TAKE = 1;
GM_GAME = 2;
type
TGameMode = (lose, take, game);
TLogOut = procedure (answer: String) of object ;
TGameBot = class
log: TLogOut;
host: String;
port: Integer;
conn: TIdTCPClient;
token: String;
gameId: String;
gameMode: TGameMode;
hand: THandCards;
card: TCard;
upddesc: boolean;
login: boolean;
constructor Create(host: String; port: Integer); overload;
private
public
procedure Connect();
procedure doStart;
procedure doRegister(name: String);
procedure doLogin(token: String = '');
procedure doNewGame(pass: String; amount: Integer; mode: TGameMode; deck: Integer; players: Integer);
procedure doReady;
procedure doLeaveGame;
procedure doGameOver;
procedure doTake;
procedure doSmile(id: Integer);
procedure doDone;
procedure doPutCard;
procedure doSetCard(b: TCard);
procedure doPutNextCard(rt: TCard);
procedure sendCmd(cmd: String);
end;
TAnswer = class (TThread)
private
bot: TGameBot;
answer: WideString;
procedure Output;
procedure PrintLog(log: String);
protected
procedure Execute; override;
public
constructor Create(_bot: TGameBot);
end;
implementation
constructor TAnswer.Create(_bot: TGameBot);
begin
self.bot := _bot;
inherited Create();
end;
procedure TAnswer.PrintLog(log: String);
begin
if (@bot.log <> nil) then
bot.log(log);
end;
procedure TAnswer.Output();
var
json: TJSONValue;
k, v, cmd: string;
begin
cmd := getCommand(self.answer);
json := getJson(self.answer);
if (cmd = 'set_token') then begin
bot.token := getJsonParam('token', '', json as TJSONObject);
bot.doLogin(bot.token);
PrintLog('Получили токен: ' + bot.token);
end;
if (cmd = 'game') then begin
bot.gameid := getJsonParam('id', '', json as TJSONObject);
SetLength(bot.hand, 0);
PrintLog('Создана игра с ID: ' + bot.gameId);
end;
if (cmd = 'btn_ready_on') then begin
bot.doReady;
bot.doSmile(random(24));
PrintLog('Готов к игре!');
end;
if (cmd = 'game_start') then begin
if (bot.gameMode = lose) then bot.doGameOver;
bot.doSmile(random(24));
bot.upddesc := true;
PrintLog('Игра запущена!');
end;
if (cmd = 'mode') then begin
k := getJsonParam('0', '', json as TJSONObject);
v := getJsonParam('1', '', json as TJSONObject);
if (k = '9') AND (v = '2') AND (bot.gameMode = take) then bot.doTake;
if (k = '1') AND (v = '8') AND (bot.gameMode = take) then bot.doGameOver;
if (k = '0') AND (v = '7') AND (bot.gameMode = game) then bot.doDone;
if (k = '9') AND (v = '2') AND (bot.gameMode = game) then begin end;
if (k = '1') AND (v = '8') AND (bot.gameMode = game) then begin
bot.doPutCard;
end;
end;
if (cmd = 'uu') then begin
k := getJsonParam('k', '', json as TJSONObject);
v := getJsonParam('v', '', json as TJSONObject);
if (k = 'points') then
PrintLog('Баланс: ' + v);
end;
if (cmd = 'p') then begin
PrintLog('Подключился пользователь: ' + getJsonParam('name', '', (json as TJsonObject).Values['user'] as TJsonObject));
end;
// Обновляем карты на руках
if (cmd = 'hand') then begin
bot.hand := getCards((json as TJSONObject).Values['cards'] as TJSONArray);
end;
if (cmd = 'b') then begin
bot.doPutNextCard(getCard(getJsonParam('b', '', json as TJsonObject)));
end;
if (cmd = 'rt') then begin
setUsesCard(bot.hand, getCard(getJsonParam('b', '', json as TJsonObject)), false);
bot.doDone;
end;
if (cmd = 't') then begin
// Бой
if (getJsonParam('id', '', json as TJsonObject) <> '') then
bot.doSetCard(getCard(getJsonParam('c', '', json as TJsonObject)));
//
end;
if (cmd = 'turn') then begin
bot.card := getCard(getJsonParam('trump', '', json as TJsonObject));
if (getJsonParam('deck', '0', json as TJsonObject) = '0') then
bot.upddesc := false else bot.upddesc := true;
end;
if (cmd = 'authorized') then begin
bot.login := true;
PrintLog('Авторизовались с ID: ' + getJsonParam('id', '', json as TJsonObject));
end;
end;
procedure TAnswer.Execute;
begin
inherited;
while self.bot.conn.Connected do begin
self.answer := self.bot.conn.IOHandler.ReadLn(IndyTextEncoding_UTF8);
Synchronize(Output);
end;
end;
{******************************************************************************}
constructor TGameBot.Create(host: String; port: Integer);
begin
{inherited;}
self.host := host;
self.port := port;
self.conn := TIdTCPClient.Create(nil);
self.conn.Host := host;
self.conn.Port := port;
self.login := false;
Connect;
end;
procedure TGameBot.sendCmd(cmd: String);
begin
self.conn.IOHandler.WriteLn(cmd + #$0A, IndyTextEncoding_UTF8);
end;
procedure TGameBot.Connect();
begin
self.conn.Connect;
TAnswer.Create(self);
end;
procedure TGameBot.doStart;
begin
self.sendCmd('client{"platform":"android","protocol":1,"tz":"+00:00","lang":"en","version":"1.0.4","name":"durak.android"}');
end;
procedure TGameBot.doRegister(name: String);
begin
doStart();
self.sendCmd('register{"name":"' + name + '"}');
end;
procedure TGameBot.doLogin(token: String = '');
begin
doStart();
if (token = '') then
self.sendCmd('auth{"token":"' + self.token + '"}')
else
self.sendCmd('auth{"token":"' + token + '"}')
end;
procedure TGameBot.doNewGame(pass: String; amount: Integer; mode: TGameMode; deck: Integer; players: Integer);
begin
self.gameMode := mode;
self.sendCmd('create{"ch":false,"nb":true,"deck":'+IntToStr(deck)+',"password":"' + pass + '","sw":false,"players":'+IntToStr(players)+',"bet":' + IntToStr(amount) + '}');
end;
procedure TGameBot.doReady;
begin
self.sendCmd('ready');
doSmile(random(24));
end;
procedure TGameBot.doTake;
begin
self.sendCmd('take');
doSmile(random(24));
end;
procedure TGameBot.doGameOver;
begin
self.sendCmd('surrender');
doSmile(random(24));
end;
procedure TGameBot.doLeaveGame;
begin
self.sendCmd('leave{"id":' + self.gameid + '}');
end;
procedure TGameBot.doPutNextCard(rt: TCard);
var
i: integer;
c: TCard;
begin
c := getNextCard(hand, rt);
if (c.cVal <> '') then begin
setUsesCard(hand, c);
sendCmd('t{"c":"'+c.cType+c.cVal+'"}');
for i := 0 to Length(hand) do
if (hand[i].cVal = c.cVal) AND (hand[i].cType <> c.cType) then begin
setUsesCard(hand, hand[i]);
sendCmd('t{"c":"'+hand[i].cType+hand[i].cVal+'"}');
end;
end else begin
if gameMode = lose then doGameOver else doDone;
end;
end;
procedure TGameBot.doPutCard();
var
i: integer;
c,b: TCard;
begin
c := getAnyCard(hand, card);
if (c.cVal <> '') then begin
setUsesCard(hand, c);
sendCmd('t{"c":"'+c.cType+c.cVal+'"}');
for i := 0 to Length(hand) do
if (hand[i].cVal = c.cVal) AND (hand[i].cType <> c.cType) then begin
setUsesCard(hand, hand[i]);
sendCmd('t{"c":"'+hand[i].cType+hand[i].cVal+'"}');
end;
end else begin
if gameMode = lose then doGameOver else doDone;
end;
doSmile(random(24));
end;
procedure TGameBot.doSetCard(b: TCard);
var
c: TCard;
begin
c := getRelevantCard(hand, b, card);
if (c.cVal <> '') then
sendCmd('b{"b":"'+c.cType+c.cVal+'","c":"'+b.cType+b.cVal+'"}')
else begin
doTake;
end;
setUsesCard(hand, c);
if (NOT upddesc) then
splitCard(hand, b);
doSmile(random(24));
end;
procedure TGameBot.doDone;
begin
sendCmd('done');
sendCmd('pass');
end;
procedure TGameBot.doSmile(id: Integer);
begin
sendCmd('smile{"id":'+IntToStr(id)+'}');
end;
end.
|
unit PosInterface;
interface
type
TMsgDescriptionProc = procedure(AMsgDescription : string) of object;
TPosProcessType = (pptProcess, pptThread);
TPosProcessState = (ppsUndefined, ppsWaiting, ppsOkConnection, ppsOkPayment, ppsOkRefund, ppsError);
IPos = interface
procedure SetMsgDescriptionProc(Value: TMsgDescriptionProc);
function GetMsgDescriptionProc: TMsgDescriptionProc;
function GetLastPosError : string;
function GetTextCheck : string;
function GetProcessType : TPosProcessType;
function GetProcessState : TPosProcessState;
function GetCanceled : Boolean;
function GetRRN : string;
function CheckConnection : Boolean;
function Payment(ASumma : Currency) : Boolean;
function Refund(ASumma : Currency; ARRN : String) : Boolean;
function ServiceMessage : Boolean;
procedure Cancel;
property OnMsgDescriptionProc: TMsgDescriptionProc read GetMsgDescriptionProc write SetMsgDescriptionProc;
property LastPosError : String read GetLastPosError;
property ProcessType : TPosProcessType read GetProcessType;
property ProcessState : TPosProcessState read GetProcessState;
property TextCheck : String read GetTextCheck;
property Canceled : Boolean read GetCanceled;
property RRN : String read GetRRN;
end;
implementation
end.
|
unit contactmanager;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, AndroidWidget;
type
{ TODO
TShowInListing = (ciAll, ciDisplayName, ciMobileNumber, ciHomeNumber, ciWorkNumber,
ciHomeEmail, ciWorkEmail, ciCompanyName, ciJobTitle, ciPhoto, ciID);
TShowInListingSet = Set of TShowInListing;
}
TOnGetContactsFinished = procedure(Sender: TObject; count: integer) of Object;
TOnGetContactsProgress = procedure(Sender: TObject; contactInfo: string; contactShortInfo: string;
contactPhotoUriAsString: string;
contactPhoto: jObject;
progress: integer; out continueListing: boolean) of Object;
{Draft Component code by "Lazarus Android Module Wizard" [6/16/2015 23:27:55]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jControl template}
jContactManager = class(jControl)
private
//FShowInListing: TShowInListingSet;
FOnGetContactsFinished: TOnGetContactsFinished;
FOnGetContactsProgress: TOnGetContactsProgress;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
function jCreate(): jObject;
procedure jFree();
function GetMobilePhoneNumber(_displayName: string): string;
function GetContactID(_displayName: string): string;
procedure UpdateDisplayName(_displayName: string; _newDisplayName: string);
procedure UpdateMobilePhoneNumber(_displayName: string; _newMobileNumber: string);
procedure UpdateWorkPhoneNumber(_displayName: string; _newWorkNumber: string);
procedure UpdateHomePhoneNumber(_displayName: string; _newHomeNumber: string);
procedure UpdateHomeEmail(_displayName: string; _newHomeEmail: string);
procedure UpdateWorkEmail(_displayName: string; _newWorkEmail: string);
procedure UpdateOrganization(_displayName: string; _newCompany: string; _newJobTitle: string);
procedure UpdatePhoto(_displayName: string; _bitmapImage: jObject);
function GetPhoto(_displayName: string): jObject;
procedure AddContact(_displayName: string; _mobileNumber: string; _homeNumber: string; _workNumber: string; _homeEmail: string; _workEmail: string; _companyName: string; _jobTitle: string; _bitmapImage: jObject); overload;
procedure GetContactsAsync(_delimiter: string);
procedure AddContact(_displayName: string; _mobileNumber: string); overload;
function GetDisplayName(_contactID: string): string;
procedure DeleteContact(_displayName: string);
function GetPhotoByUriAsString(_uriAsString: string): jObject;
function GetContactInfo(_displayName: string; _delimiter: string): string;
function GetContactsFromSIMCard(_delimiter: string): TDynArrayOfString;
//procedure DeleteContactFromSIMCard(_displayName: string);
procedure GenEvent_OnContactManagerContactsExecuted(Sender: TObject; count: integer);
procedure GenEvent_OnContactManagerContactsProgress(Sender: TObject; contactInfo: string;
contactShortInfo: string;
contactPhotoUriAsString: string;
contactPhoto: jObject; progress: integer; out continueListing: boolean);
published
//property ShowInListing: TShowInListingSet read FShowInListing write FShowInListing;
property OnGetContactsFinished: TOnGetContactsFinished read FOnGetContactsFinished write FOnGetContactsFinished;
property OnGetContactsProgress: TOnGetContactsProgress read FOnGetContactsProgress write FOnGetContactsProgress;
end;
function jContactManager_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
procedure jContactManager_jFree(env: PJNIEnv; _jcontactmanager: JObject);
function jContactManager_GetMobilePhoneNumber(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string): string;
function jContactManager_GetContactID(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string): string;
procedure jContactManager_UpdateDisplayName(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newDisplayName: string);
procedure jContactManager_UpdateMobilePhoneNumber(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newMobileNumber: string);
procedure jContactManager_UpdateWorkPhoneNumber(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newWorkNumber: string);
procedure jContactManager_UpdateHomePhoneNumber(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newHomeNumber: string);
procedure jContactManager_UpdateHomeEmail(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newHomeEmail: string);
procedure jContactManager_UpdateWorkEmail(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newWorkEmail: string);
procedure jContactManager_UpdateOrganization(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newCompany: string; _newJobTitle: string);
procedure jContactManager_UpdatePhoto(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _bitmapImage: jObject);
function jContactManager_GetPhoto(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string): jObject;
procedure jContactManager_AddContact(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _mobileNumber: string; _homeNumber: string; _workNumber: string; _homeEmail: string; _workEmail: string; _companyName: string; _jobTitle: string; _bitmapImage: jObject); overload;
procedure jContactManager_GetContactsAsync(env: PJNIEnv; _jcontactmanager: JObject; _delimiter: string);
procedure jContactManager_AddContact(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _mobileNumber: string); overload;
function jContactManager_GetDisplayName(env: PJNIEnv; _jcontactmanager: JObject; _contactID: string): string;
procedure jContactManager_DeleteContact(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string);
function jContactManager_GetPhotoByUriAsString(env: PJNIEnv; _jcontactmanager: JObject; _uriAsString: string): jObject;
function jContactManager_GetContactInfo(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _delimiter: string): string;
function jContactManager_GetContactsFromSIMCard(env: PJNIEnv; _jcontactmanager: JObject; _delimiter: string): TDynArrayOfString;
//procedure jContactManager_DeleteContactFromSIMCard(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string);
implementation
{--------- jContactManager --------------}
constructor jContactManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//your code here....
end;
destructor jContactManager.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jContactManager.Init;
begin
if FInitialized then Exit;
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jCreate(); if FjObject = nil then exit;
FInitialized:= True;
end;
function jContactManager.jCreate(): jObject;
begin
Result:= jContactManager_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis);
end;
procedure jContactManager.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_jFree(gApp.jni.jEnv, FjObject);
end;
function jContactManager.GetMobilePhoneNumber(_displayName: string): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jContactManager_GetMobilePhoneNumber(gApp.jni.jEnv, FjObject, _displayName);
end;
function jContactManager.GetContactID(_displayName: string): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jContactManager_GetContactID(gApp.jni.jEnv, FjObject, _displayName);
end;
procedure jContactManager.UpdateDisplayName(_displayName: string; _newDisplayName: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_UpdateDisplayName(gApp.jni.jEnv, FjObject, _displayName ,_newDisplayName);
end;
procedure jContactManager.UpdateMobilePhoneNumber(_displayName: string; _newMobileNumber: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_UpdateMobilePhoneNumber(gApp.jni.jEnv, FjObject, _displayName ,_newMobileNumber);
end;
procedure jContactManager.UpdateWorkPhoneNumber(_displayName: string; _newWorkNumber: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_UpdateWorkPhoneNumber(gApp.jni.jEnv, FjObject, _displayName ,_newWorkNumber);
end;
procedure jContactManager.UpdateHomePhoneNumber(_displayName: string; _newHomeNumber: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_UpdateHomePhoneNumber(gApp.jni.jEnv, FjObject, _displayName ,_newHomeNumber);
end;
procedure jContactManager.UpdateHomeEmail(_displayName: string; _newHomeEmail: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_UpdateHomeEmail(gApp.jni.jEnv, FjObject, _displayName ,_newHomeEmail);
end;
procedure jContactManager.UpdateWorkEmail(_displayName: string; _newWorkEmail: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_UpdateWorkEmail(gApp.jni.jEnv, FjObject, _displayName ,_newWorkEmail);
end;
procedure jContactManager.UpdateOrganization(_displayName: string; _newCompany: string; _newJobTitle: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_UpdateOrganization(gApp.jni.jEnv, FjObject, _displayName ,_newCompany ,_newJobTitle);
end;
procedure jContactManager.UpdatePhoto(_displayName: string; _bitmapImage: jObject);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_UpdatePhoto(gApp.jni.jEnv, FjObject, _displayName ,_bitmapImage);
end;
function jContactManager.GetPhoto(_displayName: string): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jContactManager_GetPhoto(gApp.jni.jEnv, FjObject, _displayName);
end;
procedure jContactManager.AddContact(_displayName: string; _mobileNumber: string; _homeNumber: string; _workNumber: string; _homeEmail: string; _workEmail: string; _companyName: string; _jobTitle: string; _bitmapImage: jObject);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_AddContact(gApp.jni.jEnv, FjObject, _displayName , _mobileNumber, _homeNumber ,_workNumber ,_homeEmail ,_workEmail ,_companyName ,_jobTitle ,_bitmapImage);
end;
procedure jContactManager.GetContactsAsync(_delimiter: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_GetContactsAsync(gApp.jni.jEnv, FjObject, _delimiter);
end;
procedure jContactManager.GenEvent_OnContactManagerContactsExecuted(Sender: TObject; count: integer);
begin
if Assigned(FOnGetContactsFinished) then FOnGetContactsFinished(Sender, count);
end;
procedure jContactManager.GenEvent_OnContactManagerContactsProgress(Sender: TObject; contactInfo: string;
contactShortInfo: string;
contactPhotoUriAsString: string;
contactPhoto: jObject; progress: integer; out continueListing: boolean);
begin
continueListing:= True;
if Assigned(FOnGetContactsProgress) then FOnGetContactsProgress(Sender, contactInfo, contactShortInfo,
contactPhotoUriAsString, contactPhoto,
progress, continueListing);
end;
procedure jContactManager.AddContact(_displayName: string; _mobileNumber: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_AddContact(gApp.jni.jEnv, FjObject, _displayName ,_mobileNumber);
end;
function jContactManager.GetDisplayName(_contactID: string): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jContactManager_GetDisplayName(gApp.jni.jEnv, FjObject, _contactID);
end;
procedure jContactManager.DeleteContact(_displayName: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_DeleteContact(gApp.jni.jEnv, FjObject, _displayName);
end;
function jContactManager.GetPhotoByUriAsString(_uriAsString: string): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jContactManager_GetPhotoByUriAsString(gApp.jni.jEnv, FjObject, _uriAsString);
end;
function jContactManager.GetContactInfo(_displayName: string; _delimiter: string): string;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jContactManager_GetContactInfo(gApp.jni.jEnv, FjObject, _displayName ,_delimiter);
end;
function jContactManager.GetContactsFromSIMCard(_delimiter: string): TDynArrayOfString;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jContactManager_GetContactsFromSIMCard(gApp.jni.jEnv, FjObject, _delimiter);
end;
{
procedure jContactManager.DeleteContactFromSIMCard(_displayName: string);
begin
//in designing component state: set value here...
if FInitialized then
jContactManager_DeleteContactFromSIMCard(gApp.jni.jEnv, FjObject, _displayName);
end;
}
{-------- jContactManager_JNI_Bridge ----------}
function jContactManager_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _Self;
jCls:= Get_gjClass(env);
jMethod:= env^.GetMethodID(env, jCls, 'jContactManager_jCreate', '(J)Ljava/lang/Object;');
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
end;
(*
//Please, you need insert:
public java.lang.Object jContactManager_jCreate(long _Self) {
return (java.lang.Object)(new jContactManager(this,_Self));
}
//to end of "public class Controls" in "Controls.java"
*)
procedure jContactManager_jFree(env: PJNIEnv; _jcontactmanager: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
env^.CallVoidMethod(env, _jcontactmanager, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jContactManager_GetMobilePhoneNumber(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string): string;
var
jStr: JString;
jBoo: JBoolean;
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'GetMobilePhoneNumber', '(Ljava/lang/String;)Ljava/lang/String;');
jStr:= env^.CallObjectMethodA(env, _jcontactmanager, jMethod, @jParams);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
function jContactManager_GetContactID(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string): string;
var
jStr: JString;
jBoo: JBoolean;
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'GetContactID', '(Ljava/lang/String;)Ljava/lang/String;');
jStr:= env^.CallObjectMethodA(env, _jcontactmanager, jMethod, @jParams);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_UpdateDisplayName(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newDisplayName: string);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_newDisplayName));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'UpdateDisplayName', '(Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_UpdateMobilePhoneNumber(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newMobileNumber: string);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_newMobileNumber));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'UpdateMobilePhoneNumber', '(Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_UpdateWorkPhoneNumber(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newWorkNumber: string);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_newWorkNumber));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'UpdateWorkPhoneNumber', '(Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_UpdateHomePhoneNumber(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newHomeNumber: string);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_newHomeNumber));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'UpdateHomePhoneNumber', '(Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_UpdateHomeEmail(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newHomeEmail: string);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_newHomeEmail));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'UpdateHomeEmail', '(Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_UpdateWorkEmail(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newWorkEmail: string);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_newWorkEmail));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'UpdateWorkEmail', '(Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_UpdateOrganization(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _newCompany: string; _newJobTitle: string);
var
jParams: array[0..2] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_newCompany));
jParams[2].l:= env^.NewStringUTF(env, PChar(_newJobTitle));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'UpdateOrganization', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env,jParams[2].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_UpdatePhoto(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _bitmapImage: jObject);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= _bitmapImage;
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'UpdatePhoto', '(Ljava/lang/String;Landroid/graphics/Bitmap;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
function jContactManager_GetPhoto(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'GetPhoto', '(Ljava/lang/String;)Landroid/graphics/Bitmap;');
Result:= env^.CallObjectMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_AddContact(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _mobileNumber: string; _homeNumber: string; _workNumber:
string; _homeEmail: string; _workEmail: string; _companyName: string; _jobTitle: string; _bitmapImage: jObject);
var
jParams: array[0..8] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_mobileNumber));
jParams[2].l:= env^.NewStringUTF(env, PChar(_homeNumber));
jParams[3].l:= env^.NewStringUTF(env, PChar(_workNumber));
jParams[4].l:= env^.NewStringUTF(env, PChar(_homeEmail));
jParams[5].l:= env^.NewStringUTF(env, PChar(_workEmail));
jParams[6].l:= env^.NewStringUTF(env, PChar(_companyName));
jParams[7].l:= env^.NewStringUTF(env, PChar(_jobTitle));
jParams[8].l:= _bitmapImage;
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'AddContact', '(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/graphics/Bitmap;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env,jParams[2].l);
env^.DeleteLocalRef(env,jParams[3].l);
env^.DeleteLocalRef(env,jParams[4].l);
env^.DeleteLocalRef(env,jParams[5].l);
env^.DeleteLocalRef(env,jParams[6].l);
env^.DeleteLocalRef(env,jParams[7].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_GetContactsAsync(env: PJNIEnv; _jcontactmanager: JObject; _delimiter: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_delimiter));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'GetContactsAsync', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_AddContact(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _mobileNumber: string);
var
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_mobileNumber));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'AddContact', '(Ljava/lang/String;Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
function jContactManager_GetDisplayName(env: PJNIEnv; _jcontactmanager: JObject; _contactID: string): string;
var
jStr: JString;
jBoo: JBoolean;
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_contactID));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'GetDisplayName', '(Ljava/lang/String;)Ljava/lang/String;');
jStr:= env^.CallObjectMethodA(env, _jcontactmanager, jMethod, @jParams);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
procedure jContactManager_DeleteContact(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'DeleteContact', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
function jContactManager_GetPhotoByUriAsString(env: PJNIEnv; _jcontactmanager: JObject; _uriAsString: string): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_uriAsString));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'GetPhotoByUriAsString', '(Ljava/lang/String;)Landroid/graphics/Bitmap;');
Result:= env^.CallObjectMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
function jContactManager_GetContactInfo(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string; _delimiter: string): string;
var
jStr: JString;
jBoo: JBoolean;
jParams: array[0..1] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jParams[1].l:= env^.NewStringUTF(env, PChar(_delimiter));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'GetContactInfo', '(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;');
jStr:= env^.CallObjectMethodA(env, _jcontactmanager, jMethod, @jParams);
case jStr = nil of
True : Result:= '';
False: begin
jBoo:= JNI_False;
Result:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env,jParams[1].l);
env^.DeleteLocalRef(env, jCls);
end;
function jContactManager_GetContactsFromSIMCard(env: PJNIEnv; _jcontactmanager: JObject; _delimiter: string): TDynArrayOfString;
var
jStr: JString;
jBoo: JBoolean;
resultSize: integer;
jResultArray: jObject;
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
i: integer;
begin
Result := nil;
jParams[0].l:= env^.NewStringUTF(env, PChar(_delimiter));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'GetContactsFromSIMCard', '(Ljava/lang/String;)[Ljava/lang/String;');
jResultArray:= env^.CallObjectMethodA(env, _jcontactmanager, jMethod, @jParams);
if jResultArray <> nil then
begin
resultSize:= env^.GetArrayLength(env, jResultArray);
SetLength(Result, resultSize);
for i:= 0 to resultsize - 1 do
begin
jStr:= env^.GetObjectArrayElement(env, jresultArray, i);
case jStr = nil of
True : Result[i]:= '';
False: begin
jBoo:= JNI_False;
Result[i]:= string( env^.GetStringUTFChars(env, jStr, @jBoo));
end;
end;
end;
end;
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
{
procedure jContactManager_DeleteContactFromSIMCard(env: PJNIEnv; _jcontactmanager: JObject; _displayName: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_displayName));
jCls:= env^.GetObjectClass(env, _jcontactmanager);
jMethod:= env^.GetMethodID(env, jCls, 'DeleteContactFromSIMCard', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jcontactmanager, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
}
end.
|
{$ifdef license}
(*
Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com )
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be
used to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
{$endif}
unit cwCollections.Dictionary.Standard;
{$ifdef fpc}
{$mode delphiunicode}
{$modeswitch nestedprocvars}
{$endif}
interface
uses
cwCollections
;
type
TStandardDictionary<K,V> = class( TInterfacedObject, ICollection, IReadOnlyDictionary<K,V>, IDictionary<K,V> )
private
{$ifdef fpc}
const rfGlobal = 1;
const rfObject = 2;
const rfNested = 3;
{$endif}
private
{$ifdef fpc}
fKeyCompare: pointer;
fKeyCompareType: uint8;
{$else}
fKeyCompare: TCompare<K>;
{$endif}
fKeys: array of K;
fItems: array of V;
fCapacity: nativeuint;
fCount: nativeuint;
fGranularity: nativeuint;
fPruned: boolean;
fOrdered: boolean;
private
function OrderedRemoveItem( const idx: nativeuint ): boolean;
function UnorderedRemoveItem( const idx: nativeuint ): boolean;
procedure PruneCapacity;
function CompareKeys( const KeyA: K; const KeyB: K ): TComparisonResult;
procedure Initialize(const Granularity: nativeuint = 32; const isOrdered: boolean = false; const isPruned: boolean = false);
private //- IReadOnlyDictionary<K,V> -//
function getCount: nativeuint;
function getKeyByIndex( const idx: nativeuint ): K;
function getValueByIndex( const idx: nativeuint ): V;
function getKeyExists( const key: K ): boolean;
function getValueByKey( const key: K ): V;
procedure setValueByIndex( const idx: nativeuint; const value: V );
{$ifdef fpc}
procedure ForEach( const Enumerate: TEnumeratePairGlobal<K,V> ); overload;
procedure ForEach( const Enumerate: TEnumeratePairOfObject<K,V> ); overload;
procedure ForEach( const Enumerate: TEnumeratePairIsNested<K,V> ); overload;
{$else}
procedure ForEach( const Enumerate: TEnumeratePair<K,V> ); overload;
{$endif}
function getAsReadOnly: IReadOnlyDictionary<K,V>;
strict private //- IDictionary<K,V> -//
procedure setValueByKey( const key: K; const value: V );
procedure removeByIndex( const idx: nativeuint );
procedure Clear;
public
{$ifdef fpc}
constructor Create( const KeyCompare: TCompareGlobal<K>; const Granularity: nativeuint = 32; const isOrdered: boolean = false; const isPruned: boolean = false ); reintroduce; overload;
constructor Create( const KeyCompare: TCompareOfObject<K>; const Granularity: nativeuint = 32; const isOrdered: boolean = false; const isPruned: boolean = false ); reintroduce; overload;
constructor Create( const KeyCompare: TCompareNested<K>; const Granularity: nativeuint = 32; const isOrdered: boolean = false; const isPruned: boolean = false ); reintroduce; overload;
{$else}
constructor Create( const KeyCompare: TCompare<K>; const Granularity: nativeuint = 32; const isOrdered: boolean = false; const isPruned: boolean = false ); reintroduce; overload;
{$endif}
destructor Destroy; override;
end;
implementation
procedure TStandardDictionary<K,V>.Initialize(const Granularity: nativeuint = 32; const isOrdered: boolean = false; const isPruned: boolean = false);
begin
// Set granularity control
if Granularity>0 then begin
fGranularity := Granularity;
end;
// Set granularity pruning.
fPruned := isPruned;
// Set order maintenance flag
fOrdered := isOrdered;
// Initialize the array.
fCount := 0;
fCapacity := 0;
SetLength( fKeys, fCapacity );
SetLength( fItems, fCapacity );
end;
{$ifdef fpc}
constructor TStandardDictionary<K,V>.Create( const KeyCompare: TCompareGlobal<K>; const Granularity: nativeuint = 32; const isOrdered: boolean = false; const isPruned: boolean = false );
begin
inherited Create;
Move(KeyCompare,fKeyCompare,Sizeof(pointer));
fKeyCompareType := rfGlobal;
Initialize(Granularity,isOrdered,isPruned);
end;
{$endif}
{$ifdef fpc}
constructor TStandardDictionary<K,V>.Create( const KeyCompare: TCompareOfObject<K>; const Granularity: nativeuint = 32; const isOrdered: boolean = false; const isPruned: boolean = false );
begin
inherited Create;
Move(KeyCompare,fKeyCompare,Sizeof(pointer));
fKeyCompareType := rfObject;
Initialize(Granularity,isOrdered,isPruned);
end;
{$endif}
{$ifdef fpc}
constructor TStandardDictionary<K,V>.Create( const KeyCompare: TCompareNested<K>; const Granularity: nativeuint = 32; const isOrdered: boolean = false; const isPruned: boolean = false );
begin
inherited Create;
Move(KeyCompare,fKeyCompare,Sizeof(pointer));
fKeyCompareType := rfNested;
Initialize(Granularity,isOrdered,isPruned);
end;
{$endif}
{$ifndef fpc}
constructor TStandardDictionary<K,V>.Create( const KeyCompare: TCompare<K>; const Granularity: nativeuint = 32; const isOrdered: boolean = false; const isPruned: boolean = false );
begin
inherited Create;
fKeyCompare := KeyCompare;
Initialize(Granularity,isOrdered,isPruned);
end;
{$endif}
destructor TStandardDictionary<K,V>.Destroy;
begin
SetLength( fKeys, 0 );
SetLength( fItems, 0 );
inherited Destroy;
end;
function TStandardDictionary<K,V>.getCount: nativeuint;
begin
Result := fCount;
end;
{$ifdef fpc}
procedure TStandardDictionary<K,V>.ForEach( const Enumerate: TEnumeratePairGlobal<K,V> );
var
idx: nativeuint;
begin
if getCount=0 then begin
exit;
end;
for idx := 0 to pred(getCount) do begin
Enumerate(getKeyByIndex(idx),getValueByIndex(idx));
end;
end;
{$endif}
{$ifdef fpc}
procedure TStandardDictionary<K,V>.ForEach( const Enumerate: TEnumeratePairOfObject<K,V> );
var
idx: nativeuint;
begin
if getCount=0 then begin
exit;
end;
for idx := 0 to pred(getCount) do begin
Enumerate(getKeyByIndex(idx),getValueByIndex(idx));
end;
end;
{$endif}
{$ifdef fpc}
procedure TStandardDictionary<K,V>.ForEach( const Enumerate: TEnumeratePairIsNested<K,V> );
var
idx: nativeuint;
begin
if getCount=0 then begin
exit;
end;
for idx := 0 to pred(getCount) do begin
Enumerate(getKeyByIndex(idx),getValueByIndex(idx));
end;
end;
{$endif}
{$ifndef fpc}
procedure TStandardDictionary<K,V>.ForEach( const Enumerate: TEnumeratePair<K,V> );
var
idx: nativeuint;
begin
if getCount=0 then begin
exit;
end;
for idx := 0 to pred(getCount) do begin
Enumerate(getKeyByIndex(idx),getValueByIndex(idx));
end;
end;
{$endif}
function TStandardDictionary<K,V>.getKeyByIndex( const idx: nativeuint ): K;
begin
{$warnings off} Result := Default(K); {$warnings on}
if idx<getCount then begin
Result := fKeys[idx];
end;
end;
function TStandardDictionary<K,V>.CompareKeys( const KeyA: K; const KeyB: K ): TComparisonResult;
{$ifdef fpc}
var
Glob: TCompareGlobal<K>;
Obj: TCompareOfObject<K>;
Nested: TCompareNested<K>;
{$endif}
begin
{$ifdef fpc}
Result := TComparisonResult.crErrorNotCompared;
if not assigned(fKeyCompare) then begin
exit;
end;
case fKeyCompareType of
rfGlobal: begin
Glob := nil;
Move(fKeyCompare,Glob,sizeof(pointer));
Result := Glob( KeyA, keyB );
end;
rfObject: begin
Obj := nil;
Move(fKeyCompare,Obj,sizeof(pointer));
Result := Obj( KeyA, keyB );
end;
rfNested: begin
Nested := nil;
Move(fKeyCompare,Nested,sizeof(pointer));
Result := Nested( KeyA, keyB );
end;
end;
{$else}
Result := fKeyCompare( KeyA, keyB );
{$endif}
end;
function TStandardDictionary<K,V>.getKeyExists( const key: K ): boolean;
var
idx: nativeuint;
begin
Result := False;
if getCount=0 then begin
exit;
end;
for idx := 0 to pred(getCount) do begin
if CompareKeys(fKeys[idx],key)=crAEqualToB then begin
Result := True;
Exit;
end;
end;
end;
function TStandardDictionary<K,V>.getValueByIndex( const idx: nativeuint ): V;
begin
Result := Default(V);
if idx<getCount then begin
Result := fItems[idx];
end;
end;
procedure TStandardDictionary<K,V>.setValueByIndex( const idx: nativeuint; const value: V );
begin
fItems[idx] := value;
end;
function TStandardDictionary<K,V>.getValueByKey( const key: K ): V;
var
idx: nativeuint;
begin
Result := Default(V);
if getCount=0 then begin
exit;
end;
for idx := 0 to pred(getCount) do begin
if CompareKeys(fKeys[idx],key)=crAEqualToB then begin
Result := fItems[idx];
Exit;
end;
end;
end;
function TStandardDictionary<K,V>.OrderedRemoveItem( const idx: nativeuint ): boolean;
var
idy: nativeuint;
begin
Result := False; // unless..
if fCount=0 then begin
exit;
end;
if idx<pred(fCount) then begin
for idy := idx to pred(pred(fCount)) do begin
fItems[idy] := fItems[succ(idy)];
fKeys[idy] := fKeys[succ(idy)];
end;
fItems[pred(fCount)] := Default(V);
fKeys[pred(fCount)] := Default(K);
dec(fCount);
Result := True;
end else if idx=pred(fCount) then begin
//- Item is last on list, no need to move-down items above it.
fItems[idx] := Default(V);
fKeys[idx] := Default(K);
dec(fCount);
Result := True;
end;
end;
function TStandardDictionary<K,V>.UnorderedRemoveItem( const idx: nativeuint ): boolean;
begin
Result := False; // unless..
if fCount=0 then begin
exit;
end;
if idx<pred(fCount) then begin
//- Move last item into place of that being removed.
fItems[idx] := fItems[pred(fCount)];
fKeys[idx] := fKeys[pred(fCount)];
//- Clear last item
fItems[pred(fCount)] := Default(V);
{$warnings off} fKeys[pred(fCount)] := Default(K); {$warnings on}
dec(fCount);
Result := True;
end else if idx=pred(fCount) then begin
//- if idx=fCount then simply remove the top item and decrement
fItems[idx] := Default(V);
{$warnings off} fKeys[idx] := Default(K); {$warnings on}
dec(fCount);
Result := True;
end;
end;
procedure TStandardDictionary<K,V>.PruneCapacity;
var
Blocks: nativeuint;
Remainder: nativeuint;
TargetSize: nativeuint;
begin
Blocks := fCount div fGranularity;
Remainder := fCount - Blocks;
if Remainder>0 then begin
inc(Blocks);
end;
TargetSize := Blocks*fGranularity;
//- Total number of required blocks has been determined.
if fCapacity>TargetSize then begin
fCapacity := TargetSize;
SetLength( fItems, fCapacity );
SetLength( fKeys, fCapacity );
end;
end;
procedure TStandardDictionary<K,V>.removeByIndex( const idx: nativeuint );
begin
// If the list is ordered, perform slow removal, else fast removal
if fOrdered then begin
OrderedRemoveItem( idx );
end else begin
UnorderedRemoveItem( idx );
end;
// If the list is pruning memory (to save memory space), do the prune.
if fPruned then begin
PruneCapacity;
end;
end;
procedure TStandardDictionary<K,V>.Clear;
begin
fCount := 0;
if fPruned then begin
fCapacity := 0;
SetLength( fKeys, fCapacity );
SetLength( fItems, fCapacity );
end;
end;
procedure TStandardDictionary<K,V>.setValueByKey( const key: K; const value: V );
var
idx: nativeuint;
begin
if getCount>0 then begin //- Craig! Don't change this!
for idx := pred(getCount) downto 0 do begin
if CompareKeys(fKeys[idx],key)=crAEqualToB then begin
fItems[idx] := value;
exit;
end;
end;
end;
//- If we made it here, add the item.
if (fCount=fCapacity) then begin
fCapacity := fCapacity + fGranularity;
SetLength(fKeys,fCapacity);
SetLength(fItems,fCapacity);
end;
fKeys[fCount] := key;
fItems[fCount] := value;
inc(fCount);
end;
function TStandardDictionary<K,V>.getAsReadOnly: IReadOnlyDictionary<K,V>;
begin
Result := Self as IReadOnlyDictionary<K,V>;
end;
end.
|
unit MIRIAMForm;
{ SimThyr Project }
{ A numerical simulator of thyrotropic feedback control }
{ Version 4.0.2 (Merlion) }
{ (c) J. W. Dietrich, 1994 - 2020 }
{ (c) Ludwig Maximilian University of Munich 1995 - 2002 }
{ (c) Ruhr University of Bochum 2005 - 2020 }
{ This unit provides an editor for MIRIAM-compliant model annotation }
{ Source code released under the BSD License }
{ See http://simthyr.sourceforge.net for details }
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ExtCtrls, EditBtn, LCLIntf, DateUtils, StrUtils, EnvironmentInfo,
SimThyrTypes, SimThyrResources, SimThyrServices, ScenarioHandler;
type
{ TAnnotationForm }
TAnnotationForm = class(TForm)
StandardButton: TButton;
CreatedTimeEdit: TEdit;
CommentsMemo: TMemo;
Image1: TImage;
mibbiLogo: TImage;
MIASELogo: TImage;
ModelCommentLabel: TLabel;
ModifiedTimeEdit: TEdit;
ModelTermsCombo: TComboBox;
MIRIAMLogo: TImage;
ModelTermsLabel: TLabel;
BottomPanel: TPanel;
ReferenceLabel: TLabel;
ReferenceEdit: TEdit;
ModelNameLabel: TLabel;
ModelNameEdit: TEdit;
ModifiedLabel: TLabel;
CreatorsMemo: TMemo;
CreatorsLabel: TLabel;
CreatedDateEdit: TDateEdit;
CreatedLabel: TLabel;
ModifiedDateEdit: TDateEdit;
SpeciesLabel: TLabel;
SpeciesCombo: TComboBox;
OKButton: TButton;
ScrollBox1: TScrollBox;
TitleLabel: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Image1Click(Sender: TObject);
procedure mibbiLogoClick(Sender: TObject);
procedure MIASELogoClick(Sender: TObject);
procedure MIRIAMLogoClick(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure StandardButtonClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
procedure ShowDatesAndTimes(theModel: TModel);
procedure ShowAnnotation(theModel: TModel);
end;
var
AnnotationForm: TAnnotationForm;
implementation
uses
ShowAboutModel;
{$R *.lfm}
{ TAnnotationForm }
procedure TAnnotationForm.OKButtonClick(Sender: TObject);
var
TimeCreated, TimeModified: TDateTime;
theHour, theMinute, theSecond: integer;
ConvError: boolean;
begin
ConvError := false;
gActiveModel.Name := ModelNameEdit.Text;
gActiveModel.Reference := ReferenceEdit.Text;
gActiveModel.Species := SpeciesCombo.Text;
gActiveModel.Creators := CreatorsMemo.Lines.Text;
gActiveModel.Created := CreatedDateEdit.Date;
if not tryStrToInt(ExtractDelimited(1, CreatedTimeEdit.Text, [':', '.']), theHour) then
begin
bell;
ConvError := true;
theHour := 0;
end;
if not tryStrToInt(ExtractDelimited(2, CreatedTimeEdit.Text, [':', '.']), theMinute) then
begin
bell;
ConvError := true;
theMinute := 0;
end;
if not tryStrToInt(ExtractDelimited(3, CreatedTimeEdit.Text, [':', '.']), theSecond) then
begin
bell;
ConvError := true;
theSecond := 0;
end;
TimeCreated := EncodeDateTime(1900, 1, 1, theHour, theMinute, theSecond, 0);
ReplaceTime(gActiveModel.Created, TimeCreated);
gActiveModel.LastModified := ModifiedDateEdit.Date;
if not tryStrToInt(ExtractDelimited(1, ModifiedTimeEdit.Text, [':', '.']), theHour) then
begin
bell;
ConvError := true;
theHour := 0;
end;
if not tryStrToInt(ExtractDelimited(2, ModifiedTimeEdit.Text, [':', '.']), theMinute) then
begin
bell;
ConvError := true;
theMinute := 0;
end;
if not tryStrToInt(ExtractDelimited(3, ModifiedTimeEdit.Text, [':', '.']), theSecond) then
begin
bell;
ConvError := true;
theSecond := 0;
end;
TimeModified := EncodeDateTime(1900, 1, 1, theHour, theMinute, theSecond, 0);
ReplaceTime(gActiveModel.LastModified, TimeModified);
gActiveModel.Terms := ModelTermsCombo.Text;
gActiveModel.Comments := CommentsMemo.Lines.Text;
if ConvError then
ShowDatesAndTimes(gActiveModel)
else
Close;
end;
procedure TAnnotationForm.StandardButtonClick(Sender: TObject);
var
tempModel: TModel;
begin
tempModel := emptyModel;
ShowAnnotation(tempModel);
end;
procedure TAnnotationForm.ShowDatesAndTimes(theModel: TModel);
begin
CreatedDateEdit.Date := theModel.Created;
CreatedTimeEdit.Text := TimeToStr(theModel.Created);
ModifiedDateEdit.Date := theModel.LastModified;
ModifiedTimeEdit.Text := TimeToStr(theModel.LastModified);
end;
procedure TAnnotationForm.ShowAnnotation(theModel: TModel);
begin
ModelNameEdit.Text := theModel.Name;
ReferenceEdit.Text := theModel.Reference;
SpeciesCombo.Text := theModel.Species;
CreatorsMemo.Lines.Text := theModel.Creators;
ShowDatesAndTimes(theModel);
ModelTermsCombo.Text := theModel.Terms;
CommentsMemo.Lines.Text := theModel.Comments;
end;
procedure TAnnotationForm.FormShow(Sender: TObject);
begin
FormPaint(Sender);
ShowAnnotation(gActiveModel);
end;
procedure TAnnotationForm.Image1Click(Sender: TObject);
begin
AboutModelForm.Show;
end;
procedure TAnnotationForm.mibbiLogoClick(Sender: TObject);
begin
OpenURL(MIBBI_URL);
end;
procedure TAnnotationForm.MIASELogoClick(Sender: TObject);
begin
OpenURL(MIASE_URL);
end;
procedure TAnnotationForm.FormCreate(Sender: TObject);
begin
if YosemiteORNewer then
begin
StandardButton.Height := 22;
OKButton.Height := 22;
end;
end;
procedure TAnnotationForm.FormPaint(Sender: TObject);
begin
if DarkTheme then
begin
Color := BACKCOLOUR;
BottomPanel.Color := BACKCOLOUR;
end
else
begin
Color := clWhite;
BottomPanel.Color := clWhite;
end
end;
procedure TAnnotationForm.MIRIAMLogoClick(Sender: TObject);
begin
OpenURL(MIRIAM_URL);
end;
end.
|
unit EnviaEmail;
interface
uses AcbrMail;
type
TEnviaEmail = class
private
FAcbrMail :TACBrMail;
public
procedure addAnexo(pCaminhoAnexo :String);
procedure Enviar;
public
constructor Create(pDestinatario, pAssunto, pTexto :String);
destructor Destroy;override;
end;
implementation
uses uModulo, System.SysUtils;
{ TEnviaEmail }
procedure TEnviaEmail.addAnexo(pCaminhoAnexo: String);
begin
FAcbrMail.AddAttachment(TFileName( pCaminhoAnexo ));
end;
constructor TEnviaEmail.Create(pDestinatario, pAssunto, pTexto: String);
begin
if not assigned(dm.Empresa.ConfiguracoesEmail) then
raise Exception.Create('Não foi possível enviar e-mail, pois não há configurações de e-mail cadastradas');
FAcbrMail := TACBrMail.Create(nil);
FAcbrMail.Clear;
FAcbrMail.Host := dm.Empresa.ConfiguracoesEmail.smtp_host;
FAcbrMail.Port := dm.Empresa.ConfiguracoesEmail.smtp_port;
FAcbrMail.Username := dm.Empresa.ConfiguracoesEmail.smtp_user;
FAcbrMail.Password := dm.Empresa.ConfiguracoesEmail.smtp_password;
FAcbrMail.FromName := dm.Empresa.razao;
FAcbrMail.From := dm.Empresa.ConfiguracoesEmail.smtp_user;
FAcbrMail.IsHTML := false;
FAcbrMail.AddAddress(pDestinatario);
FAcbrMail.Subject := pAssunto;
FAcbrMail.Body.Text := pTexto;
FAcbrMail.AltBody.Text := FAcbrMail.Body.Text;
end;
destructor TEnviaEmail.Destroy;
begin
if assigned(FAcbrMail) then
FreeAndNil(FAcbrMail);
inherited;
end;
procedure TEnviaEmail.Enviar;
begin
FAcbrMail.Send;
end;
end.
|
{******************************************************************************}
{ }
{ Indy (Internet Direct) - Internet Protocols Simplified }
{ }
{ https://www.indyproject.org/ }
{ https://gitter.im/IndySockets/Indy }
{ }
{******************************************************************************}
{ }
{ This file is part of the Indy (Internet Direct) project, and is offered }
{ under the dual-licensing agreement described on the Indy website. }
{ (https://www.indyproject.org/license/) }
{ }
{ Copyright: }
{ (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. }
{ }
{******************************************************************************}
{ }
{ Originally written by: Fabian S. Biehn }
{ fbiehn@aagon.com (German & English) }
{ }
{ Contributers: }
{ Here could be your name }
{ }
{******************************************************************************}
// This File is auto generated!
// Any change to this file should be made in the
// corresponding unit in the folder "intermediate"!
// Generation date: 23.07.2021 14:35:33
unit IdOpenSSLHeaders_idea;
interface
// Headers for OpenSSL 1.1.1
// idea.h
{$i IdCompilerDefines.inc}
uses
IdCTypes,
IdGlobal,
IdOpenSSLConsts;
const
// Added '_CONST' to avoid name clashes
IDEA_ENCRYPT_CONST = 1;
// Added '_CONST' to avoid name clashes
IDEA_DECRYPT_CONST = 0;
IDEA_BLOCK = 8;
IDEA_KEY_LENGTH = 16;
type
IDEA_INT = type TIdC_INT;
idea_key_st = record
data: array[0..8, 0..5] of IDEA_INT;
end;
IDEA_KEY_SCHEDULE = idea_key_st;
PIDEA_KEY_SCHEDULE = ^IDEA_KEY_SCHEDULE;
function IDEA_options: PIdAnsiChar cdecl; external CLibCrypto;
procedure IDEA_ecb_encrypt(const in_: PByte; out_: PByte; ks: PIDEA_KEY_SCHEDULE) cdecl; external CLibCrypto;
procedure IDEA_set_encrypt_key(const key: PByte; ks: PIDEA_KEY_SCHEDULE) cdecl; external CLibCrypto;
procedure IDEA_set_decrypt_key(ek: PIDEA_KEY_SCHEDULE; dk: PIDEA_KEY_SCHEDULE) cdecl; external CLibCrypto;
procedure IDEA_cbc_encrypt(const in_: PByte; out_: PByte; length: TIdC_LONG; ks: PIDEA_KEY_SCHEDULE; iv: PByte; enc: TIdC_INT) cdecl; external CLibCrypto;
procedure IDEA_cfb64_encrypt(const in_: PByte; out_: PByte; length: TIdC_LONG; ks: PIDEA_KEY_SCHEDULE; iv: PByte; num: PIdC_INT; enc: TIdC_INT) cdecl; external CLibCrypto;
procedure IDEA_ofb64_encrypt(const in_: PByte; out_: PByte; length: TIdC_LONG; ks: PIDEA_KEY_SCHEDULE; iv: PByte; num: PIdC_INT) cdecl; external CLibCrypto;
procedure IDEA_encrypt(in_: PIdC_LONG; ks: PIDEA_KEY_SCHEDULE) cdecl; external CLibCrypto;
implementation
end.
|
unit ACG_MBS_TYPES_DINAMIC;
interface
uses
Classes, sysUtils,math, StdCtrls, Grids,
mcsConstantesTiposRutinas,mcsConstantesRutinas,
mcsRutinas,mcsTMicroEjecucion,
ACG_MBS_TYPES;
const
N_CTBIF2_JMP2=0; N_ETIQ_BIF2=1; N_CTBIF1_JMP1=2; N_ETIQ_BIF1=3;
NREC_RX=4; NFILA=5; NPROG=6; NSOL_A=7; NSOL_B=8; NSOL_R=9; NREC_TX=10;
N_ETIQ_JMP1=11; N_DJNZ_BIF1=12; N_ETIQ_JMP2=13; N_DJNZ_BIF2=14;
const
CODIGO_NINGUNA_TECLA_PRESIONADA=99;
POBLACION_MAXIMA=100000;//10000;//100000;//90000;//80000;
NUMERO_DE_PAREJAS_MAXIMO = 400;//1000;//500;//400;
VALOR_MINIMO_CONDICION = -51;
VALOR_MAXIMO_CONDICION = 255;
VALOR_ALEATORIO_MINIMO_PESO = 1;
VALOR_ALEATORIO_MAXIMO_PESO = 5;
NUMERO_GRANDE_SMALLINT = 32767;{Numero mas grande SmallInt}
NUMERO_EVALUACIONES_SIN_MEJORA = 100000;{Numero de valuaciones sin mejora}
NUMERO_MAXIMO_DE_DEMES = 10;
TAMANO_ARREGLO_PARA_SEGMENTOS = 20;{La cantidad de segmentos debe ser menor o igual}
var
NUMERO_DE_REPRESENTANTES_DIN:Integer =2;//1;// 2;// 4;// 2;//3;//2;
APLICACION_ACTIVADA:Boolean=True;
NUMERO_DE_SEGMENTOS_EN_CC:Integer=10;
TAMANO_POBLACION_DIN:Integer=200;//100 valor anterior
TAMANO_MINIMO_DE_SECUENCIA_DIN:Integer=2;//3;//3;//2;//4; 31 AGOSTO 2020
TAMANO_MAXIMO_DE_SECUENCIA_DIN:Integer=4;//4;//5;//4//8; 31 AGOSTO 2020
NUMERO_MAXIMO_DE_EVALUACIONES:Integer;
PROBABILIDAD_EN_SELECCION_DE_PADRES:Double = 0.4;//0.5;//0.6;// 0.4;//0.1;// 0.4;
PROBABILIDAD_DE_MUTACION_DIN:Integer = 30;//100;// 30;
PROBABILIDAD_DE_CRUZAMIENTO:Double = 0.3;
PROBABILIDAD_INTERCAMBIO_DE_COLAS_EN_CROSSOVER:Integer = 30;
REGISTRO_DE_SALIDA_BYTE_BAJO:string = 'R0';
type
matrizDiagramasDeTiempo = array of vectorValoresSalidaB;
matrizValoresDePartesProgramaDIN = array of vectorValoresSalida64;
Tseq = array of vectorInstruccion;
arregloEntero=array of Integer;
type
estructuraVIDin = record
// w:Real;
viA,viB,viR0, viPx:Byte;
end;
estructuraControlDin = record
// w:Real;
wint:Smallint;
cond:Smallint;
iIni:Integer;
iFin:Integer;
end;
Tcontrol = array of estructuraControlDin;
estructuraTransferDin = record
// w:Real;
tipo:byte;
iDes:integer;
rDes:byte;
iFue:integer;
rFue:byte;
inme:Byte;{valor inmediato en recuperacion CAMBIO 2016}
end;
Ttransfer = array of estructuraTransferDin;
// RDatosSeq = record
// s:Integer;{Tamaño}
// f:vectorParaPartesF;{Adecuacion}
// fsumaesc:Integer;{Entero menor de la Suma de elementos de f multiplicado por un valor}
// fsuma:Integer;{Entero menor de la suma de elementos de f}
// e:Integer;{Número de instrucción del primer error en dt}
// u:Integer;{Número de instrucción ultimo en dt}
// p:Integer;{Procedencia p=0 - cuantica; p=1 - multiobjetivo}
// end;
RDatosSeq = record
s:Integer;{Tamaño}
f:vectorParaPartesF;{Adecuacion}
fsumaesc:Integer;{Entero menor de la Suma de elementos de f multiplicado por un valor}
fsuma:Integer;{Entero menor de la suma de elementos de f}
e:Integer;{Número de instrucción del primer error en dt}
ie:Integer;
iei:vectorParaPartesF;{indices de extremo izquierdo}
u:Integer;{Indice ultimo maximo en dt}
m:Integer;{Indice ultimo minimo en dt}
p:Integer;{Procedencia p=0 - cuantica; p=1 - multiobjetivo}
end;
TdimCC=array[0..TAMANO_ARREGLO_PARA_SEGMENTOS-1] of integer;
tipoSolucionDin=record
dimCC:TdimCC;
// VISol:estructuraVIDin;
SeqSol:Tseq;
rdsSol:RDatosSeq;
ConSol:Tcontrol;
TransSol:Ttransfer;
// fSol:vectorParaPartesF;
nPSol:vectorParaPartes;{Se usa en PKIP}
nISol:vectorParaPartes;{Se usa en PKIP}
LCDSol:rLCD;
diferencia:Integer;
end;
var
mvrDin:matrizValoresDePartesProgramaDIN;
SolDin:tipoSolucionDin;
dtsObjetivo:matrizDiagramasDeTiempo;
function RandomM(Nmax,m:integer):arregloEntero;
function RandomConPesosLineales(n:Integer):Integer;
procedure indicesDePadres(Nmax,m:Integer;var a,b:arregloEntero);
function IndiceEnSegmento(n,LongitudSegmento1:Integer):Integer;
procedure indicesDePadresEnSegmentos(longSeg1,longSeg2,m:Integer;var a,b,sa,sb:arregloEntero);
function calcularAdecuacionDT(var rdt:rLCD):vectorParaPartesF;
function calcularAdecuacionDTextenso(var rdt:rLCD):vectorParaPartesF;
procedure MatrizProgramaAMemo_DIN_conOC(var memo:TMemo;var s:tipoSolucionDin);
procedure MatrizProgramaAMemo_DIN(var memo:TMemo;var s:tipoSolucionDin;var nie:integer);
procedure valoresInicialesEnMatrizMVR_DIN(s:Integer);
procedure MostrarLocalizacionDeBitsDin(var memo:TMemo;var s:tipoSolucionDin);
procedure SecuenciaAMemo_PKIP_DIN(var memo:TMemo;var s:tipoSolucionDin;var nie:Integer);
procedure SecuenciaAMemo_PKIP_DIN_conOC(var memo:TMemo;var s:tipoSolucionDin);
procedure SecuenciaMenorAStringGrid(var mProg:Tseq;var mControl:Tcontrol;var SG:TStringGrid);
procedure SecuenciaDinamicaAStringGrid(var sol: tipoSolucionDin;var SG:TStringGrid);
procedure stringGridAmemo_PKIP_DIN(var SG:TStringGrid;var Memo:TMemo);
procedure PrimerasInstruccionesEnRich_LCD(var Memo:TMemo;var nig,nec:Integer);
function TransferConPesosYcondicionAleatorios:estructuraTransferDin;
function controlConPesosYcondicionAleatorios:estructuraControlDin;
function controlConPesosAleatoriosCondicionLineal:estructuraControlDin;
function LinealRandom(n : Integer): Integer;
function ExponencialRandom(N:Integer): Integer;
function QubicRandom: Double;
procedure mostrarControlDin(var Memo:TMemo;var x:Tcontrol);
function hallarUltimaInstruccionEnTcontrol(var x:Tcontrol):Integer;
function obtenerAdecuacionConInstruccionSalida(f:vectorParaPartesF;nI:vectorParaPartes):vectorParaPartesF;
function obtenerAdecuacionConTamano(f:vectorParaPartesF;
var mControl:Tcontrol):vectorParaPartesF;
function obtenerAdecuacionConTiempoMaximoDeEjecucion(f:vectorParaPartesF;
var mControl:Tcontrol):vectorParaPartesF;
function obtenerAdecuacionConTiempoMaximoDeEjecucionSCT(f:vectorParaPartesF;
var mControl:Tcontrol;var mTransfer:Ttransfer):vectorParaPartesF;
function obtenerAdecuacionConTiempoMaximoDeEjecucionST(f:vectorParaPartesF;
var mProg:Tseq;var mTransfer:Ttransfer):vectorParaPartesF;
function obtenerAdecuacionConTiempoMaximoDeEjecucionS(f:vectorParaPartesF;
var mProg:Tseq):vectorParaPartesF;
function obtenerAdecuacionGAconInstruccionSalida(f:vectorParaPartesF;nI:vectorParaPartes):vectorParaPartesF;
function cumpleCondicionDin(numCondicion:integer):boolean;
procedure EquipararSecuenciaYcontrol(var x:Tseq;var y:Tcontrol);
procedure mostrarCadenasDT(var memo:TMemo;var xdts:matrizDiagramasDeTiempo);
procedure mostrarMatrizDiagramasDeTiempo_DIN(var Memo:TMemo;var x:mrLCD);
procedure mutarEliminando(var seq:Tseq);
procedure mutarInsertando(var seq:Tseq);
procedure mutarReemplazando(var seq:Tseq);
procedure mutarAdicionando(var seq:Tseq);
procedure mutarDuplicando(var seq:Tseq);
procedure convertirPesosARangos(var x:Tcontrol);
implementation
uses
mcsAVR;
procedure SecuenciaDinamicaAStringGrid(var sol: tipoSolucionDin;var SG:TStringGrid);
procedure ponerEnSG(col:Integer;fil:Integer;s:string);
var
sAux:string;
begin
sAux:=SG.cells[col,fil];
if sAux='' then
begin
if (col=N_ETIQ_BIF1)or(col=N_ETIQ_BIF2)or(col=N_ETIQ_JMP2)or(col=N_ETIQ_JMP1) then
begin
SG.cells[col,fil]:=s+':';
end
else
begin
SG.cells[col,fil]:=s;
end;
end
else
begin
if (col=N_ETIQ_BIF1)or(col=N_ETIQ_BIF2)or(col=N_ETIQ_JMP2)or(col=N_ETIQ_JMP1) then
begin
SG.cells[col,fil]:=sAux+';'+s+':';
end
else
begin
SG.cells[col,fil]:=sAux+';'+s;
end;
end;
end;
var
j,t:Integer;
linea:string;
OCcadena:string;
CadenaMnemonico:cadena10;
fila:Integer;
vi:vectorInstruccion;
begin
fila:=1;//Con fila:=0 se pierde la primera instrucción (2016)
SG.rowCount:=fila+1;
case CBII of
PKIP_CC,CONV_CC:begin // WFS
t:=vpnMaximo(sol.nISol);
end;
LCD_CC:begin // WFS OJO
t:=sol.LCDSol.nUltimaInstDeDT;
end;
end;
for j:=0 to t do
begin
linea:='';
vi:=sol.SeqSol[j];
OCcadena:=vectorInstruccionAVRaCadenaASM(vi);
eliminarEspaciosLaterales(OCcadena);
CadenaMnemonico:=extraerPrimeraPalabra(OCcadena);
linea:=linea+CadenaMnemonico+' ';
linea:=linea+OCcadena;//+' '+cDir;
SG.rowCount:=fila+1;
SG.cells[NFILA,fila]:=IntToStr(j);
ponerEnSG(NPROG,fila,linea);
Inc(fila);
end;
SG.rowCount:=fila+1;
end;
procedure convertirPesosARangos(var x:Tcontrol);
var
i,t,inicio,fin:Integer;
begin
t:=Length(x);
if t=0 then Exit;
inicio:=0;
for i:=0 to t-1 do
begin
fin:=inicio+x[i].wint-1;
x[i].iIni:=inicio;
x[i].iFin:=fin;
inicio:=fin+1;
end;
end;
procedure mutarEliminando(var seq:Tseq);
var
i,j,s:Integer;
a:Tseq;
p:Real;
begin
s:=Length(seq);
if s=0 then Exit;
p:=Random;
i:=Floor(p*(s-1));
SetLength(a,s-1);
for j:=0 to s-1 do
begin
if j<i then a[j]:=seq[j];
if j>i then a[j-1]:=seq[j];
end;
SetLength(seq,s-1);
seq:=Copy(a);
end;
procedure mutarInsertando(var seq:Tseq);
var
i,j,s:Integer;
a:Tseq;
p:Real;
begin
s:=Length(seq);
if s=0 then Exit;
p:=Random;
i:=Floor(p*(s-1));
SetLength(a,s+1);
for j:=0 to s do
begin
if j<i then a[j]:=seq[j];
if j=i then a[j]:=instruccionAleatoria;
if j>i then a[j]:=seq[j-1];
end;
SetLength(seq,s+1);
seq:=Copy(a);
end;
procedure mutarDuplicando(var seq:Tseq);
var
i,j,s:Integer;
a:Tseq;
p:Real;
begin
s:=Length(seq);
if s=0 then Exit;
p:=Random;
i:=Floor(p*(s-1));
SetLength(a,s+1);
for j:=0 to s do
begin
if j<i then a[j]:=seq[j];
// if j=i then a[j]:=instruccionAleatoria;
if j>i then a[j]:=seq[j-1];
end;
if i=0 then
begin
a[i]:=instruccionAleatoria;
end
else
begin
a[i]:=seq[i-1];
end;
SetLength(seq,s+1);
seq:=Copy(a);
end;
procedure mutarReemplazando(var seq:Tseq);
var
i,s:Integer;
p:Real;
begin
s:=Length(seq);
if s=0 then Exit;
p:=Random;
i:=Floor(p*(s-1));
seq[i]:=instruccionAleatoria;
end;
procedure mutarAdicionando(var seq:Tseq);
var
s:Integer;
begin
s:=Length(seq);
s:=s+1;
SetLength(seq,s);
seq[s-1]:=instruccionAleatoria;
end;
procedure mostrarMatrizDiagramasDeTiempo_DIN(var Memo:TMemo;var x:mrLCD);
var
i,j:integer;
linea:cadena100;
begin
for i:=0 to NUMERO_DE_CADENAS_DE_SALIDA-1 do
begin
// Memo.Lines.add('Target Time Diagram:');
linea:=IntToStr(i)+' ';
for j:=0 to NUMERO_DE_VALORES_EN_CADENA_DE_SALIDA-1 do
begin
linea:=linea+numCad(dtsObjetivo[i,j],4);
end;
Memo.Lines.add(linea);
// Memo.Lines.add('Time Diagram:');
linea:=IntToStr(i)+' ';
for j:=0 to NUMERO_DE_VALORES_EN_CADENA_DE_SALIDA-1 do
begin
linea:=linea+numCad(x[i].dt[j],4);
end;
Memo.Lines.add(linea);
linea:='';
for j:=0 to NUMERO_DE_VALORES_EN_CADENA_DE_SALIDA-1 do
begin
linea:=linea+numCad(x[i].nI[j],4);
end;
Memo.Lines.add(linea);
// Memo.Lines.add('nIntervalo:'+inttostr(x[i].nIntervalo)+
// ' nTiempo:'+inttostr(x[i].nTiempo)+
// ' nInstrUltimoCambio:'+inttostr(x[i].nInstruccionUltimoCambio)+
// ' nUltimaInstruccionDT:'+inttostr(x[i].nUltimaInstDeDT));
Memo.Lines.Add('------------------------------------------------------------------------');
end;
Memo.Lines.add(FloatToStr(fmocc));
Memo.Lines.Add('------------------------------------------------------------------------');
end;
procedure mostrarCadenasDT(var memo:TMemo;var xdts:matrizDiagramasDeTiempo);
var
i,j:Integer;
linea:string;
begin
for i:=0 to NUMERO_DE_CADENAS_DE_SALIDA-1 do
begin
linea:='';
for j:=0 to NUMERO_DE_VALORES_EN_CADENA_DE_SALIDA-1 do
begin
linea:=linea+numCad(xdts[i,j],4);
end;
Memo.Lines.add(linea);
end;
end;
procedure hallarIFinMasCercano(n:Integer;var y:Tcontrol;var fin,indice:Integer);
var
i:Integer;
begin
for i:=0 to Length(y)-1 do
begin
if y[i].iFin>=n then
begin
fin:=y[i].iFin;
indice:=i;
Exit;
end;
end;
fin:=-1;
indice:=-1;
end;
procedure EquipararSecuenciaYcontrol(var x:Tseq;var y:Tcontrol);
var
tx,ty,uity,i,fin,indice:Integer;
begin
tx:=Length(x);
ty:=Length(y);
uity:=y[ty-1].iFin;
if uity=tx-1 then Exit;
if tx-1<uity then
begin
{Buscar iFin mayor mas cercano a ultima instruccion de x}
hallarIFinMasCercano(tx-1,y,fin,indice);
SetLength(x,fin+1);
{Completar x con instrucciones NOP}
for i:=tx to fin do
begin
x[i]:=instruccionNOP;
end;
{Eliminar filas superiores en y}
SetLength(y,indice+1);
Exit;
end;
if tx-1>uity then
begin
{Eliminar filas superiores en x}
SetLength(x,uity+1);
Exit;
end;
end;
function BitsIguales(direccion:integer;numeroBit,valorBit:Byte):boolean;
var
bleido:byte;
begin
case direccion of
direccionP0:bleido:=microEje.pEMIC.APINS[0] and microEje.pEMIC.AreaSFR[direccionP0];
direccionP1:bleido:=microEje.pEMIC.APINS[1] and microEje.pEMIC.AreaSFR[direccionP1];
direccionP2:bleido:=microEje.pEMIC.APINS[2] and microEje.pEMIC.AreaSFR[direccionP2];
direccionP3:bleido:=microEje.pEMIC.APINS[3] and microEje.pEMIC.AreaSFR[direccionP3];
else
bleido:=microEje.pEMIC.AreaSFR[direccion];
end;
if (bleido shr numeroBit)and 1=valorBit then
begin
Result:=TRUE;
end
else
begin
Result:=FALSE;
end;
end;
function cumpleCondicionDin(numCondicion:integer):boolean;
var
bleido,bleido2:byte;
num:integer;
begin
case numCondicion of
0..7:
begin // $20:begin { JB BIT ADDR,CODE ADDR }
Result:=BitsIguales(direccionACC,numCondicion,1);
exit;
end;
8..15:
begin // $30:begin { JNB BIT ADDR,CODE ADDR }
Result:=BitsIguales(direccionACC,numCondicion-8,0);
exit;
end;
16:
begin // $60:begin { JZ CODE ADDR }
bleido:=microEje.pEMIC.AreaSFR[direccionACC];
if bleido=0 then Result:=TRUE else Result:=FALSE;
exit;
end;
17:
begin // $70:begin { JNZ CODE ADDR }
bleido:=microEje.pEMIC.AreaSFR[direccionACC];
if bleido<>0 then Result:=TRUE else Result:=FALSE;
exit;
end;
18:
begin // $40:begin { JC CODE ADDR }
Result:=BitsIguales(direccionPSW,7,1);
exit;
end;
19:
begin // $50:begin { JNC CODE ADDR }
Result:=BitsIguales(direccionPSW,7,0);
exit;
end;
20..27:
begin // $20:begin { JB BIT ADDR,CODE ADDR }
Result:=BitsIguales(direccionB,numCondicion-20,1);
exit;
end;
28..35:
begin // $30:begin { JNB BIT ADDR,CODE ADDR }
Result:=BitsIguales(direccionB,numCondicion-28,0);
exit;
end;
36..43:
begin // $20:begin { JB BIT ADDR,CODE ADDR }
if PUERTO_USADO_P1_O_P2=1 then
begin
Result:=BitsIguales(direccionP1,numCondicion-36,1);
exit;
end;
if PUERTO_USADO_P1_O_P2=2 then
begin
Result:=BitsIguales(direccionP2,numCondicion-36,1);
exit;
end;
end;
44..51:
begin // $30:begin { JNB BIT ADDR,CODE ADDR }
if PUERTO_USADO_P1_O_P2=1 then
begin
Result:=BitsIguales(direccionP1,numCondicion-44,0);
exit;
end;
if PUERTO_USADO_P1_O_P2=2 then
begin
Result:=BitsIguales(direccionP2,numCondicion-44,0);
exit;
end;
end;
end;
Result:=FALSE;
end;
function obtenerAdecuacionConTiempoMaximoDeEjecucionS(f:vectorParaPartesF;
var mProg:Tseq):vectorParaPartesF;
var
i,nProg,tamano:integer;
begin
nProg:=Length(mProg);
if nProg=0 then
begin
Result:=f;
Exit;
end;
tamano:=0;
for i:=0 to NUMERO_DE_PARTES_DE_SALIDA - 1 do
begin
Result[i] :=f[i]-(0.0001)*(nProg);
end;
end;
function obtenerAdecuacionConTiempoMaximoDeEjecucionST(f:vectorParaPartesF;
var mProg:Tseq;var mTransfer:Ttransfer):vectorParaPartesF;
var
i,nProg,nTransfer,tamano:integer;
begin
nProg:=Length(mProg);
nTransfer:=Length(mTransfer);
if nProg=0 then
begin
Result:=f;
Exit;
end;
tamano:=0;
for i:=0 to NUMERO_DE_PARTES_DE_SALIDA - 1 do
begin
Result[i] :=f[i]-(0.0001)*(nProg+nTransfer);
end;
end;
function obtenerAdecuacionConTiempoMaximoDeEjecucionSCT(f:vectorParaPartesF;
var mControl:Tcontrol;var mTransfer:Ttransfer):vectorParaPartesF;
var
i,nControl,nTransfer,tamano:integer;
begin
nControl:=Length(mControl);
nTransfer:=Length(mTransfer);
if nControl=0 then
begin
Result:=f;
Exit;
end;
tamano:=0;
for i:=0 to nControl-1 do
begin
if mControl[i].iFin >=0 then
begin
case mControl[i].cond of
VALOR_MINIMO_CONDICION..0:begin
tamano:=tamano+(mControl[i].iFin-mControl[i].iIni+1)+1;
end;
1:begin
tamano:=tamano+(mControl[i].iFin-mControl[i].iIni+1);
end;
2..VALOR_MAXIMO_CONDICION:begin
tamano:=tamano+
((mControl[i].iFin-mControl[i].iIni+1+1)*(mControl[i].cond))+1
end;
end;
end;
end;
for i:=0 to NUMERO_DE_PARTES_DE_SALIDA - 1 do
begin
// Result[i] :=f[i]+(1/(tamano+1));
// Result[i] :=f[i]+(0.5/(tamano+1));
// Result[i] :=f[i]+(2/(tamano+1));
// Result[i] :=f[i]+(1/(tamano+nTransfer+1));
Result[i] :=f[i]-(0.0001)*(tamano+nTransfer);
end;
end;
function obtenerAdecuacionConTiempoMaximoDeEjecucion(f:vectorParaPartesF;
var mControl:Tcontrol):vectorParaPartesF;
var
i,nControl,tamano:integer;
begin
nControl:=Length(mControl);
if nControl=0 then
begin
Result:=f;
Exit;
end;
tamano:=0;
for i:=0 to nControl-1 do
begin
if mControl[i].iFin >=0 then
begin
case mControl[i].cond of
VALOR_MINIMO_CONDICION..0:begin
tamano:=tamano+(mControl[i].iFin-mControl[i].iIni+1)+1;
end;
1:begin
tamano:=tamano+(mControl[i].iFin-mControl[i].iIni+1);
end;
2..VALOR_MAXIMO_CONDICION:begin
tamano:=tamano+
((mControl[i].iFin-mControl[i].iIni+1+1)*(mControl[i].cond))+1
end;
end;
end;
end;
for i:=0 to NUMERO_DE_PARTES_DE_SALIDA - 1 do
begin
// Result[i] :=f[i]+(1/(tamano+1));
// Result[i] :=f[i]+(0.5/(tamano+1));
// Result[i] :=f[i]+(2/(tamano+1));
Result[i] :=f[i]-(0.001)*(tamano);
end;
end;
function obtenerAdecuacionConTamano(f:vectorParaPartesF;
var mControl:Tcontrol):vectorParaPartesF;
var
i,nControl,tamano:integer;
begin
nControl:=Length(mControl);
if nControl=0 then
begin
Result:=f;
Exit;
end;
tamano:=0;
for i:=0 to nControl-1 do
begin
if mControl[i].iFin >=0 then
begin
case mControl[i].cond of
VALOR_MINIMO_CONDICION..0:begin
tamano:=tamano+(mControl[i].iFin-mControl[i].iIni+1)+1;
end;
1:begin
tamano:=tamano+(mControl[i].iFin-mControl[i].iIni+1);
end;
2..VALOR_MAXIMO_CONDICION:begin
tamano:=tamano+(mControl[i].iFin-mControl[i].iIni+1)+2
end;
end;
end;
end;
for i:=0 to NUMERO_DE_PARTES_DE_SALIDA - 1 do
begin
Result[i] :=f[i]+(1/(tamano+1));
end;
end;
function obtenerAdecuacionGAconInstruccionSalida(f:vectorParaPartesF;nI:vectorParaPartes):vectorParaPartesF;
var
i,n:integer;
begin
n:=vpnMaximo(nI);
for i:=0 to NUMERO_DE_PARTES_DE_SALIDA - 1 do
begin
Result[i] :=f[i]+(1/(n+1));
end;
end;
function obtenerAdecuacionConInstruccionSalida(f:vectorParaPartesF;nI:vectorParaPartes):vectorParaPartesF;
var
i:integer;
begin
for i:=0 to NUMERO_DE_PARTES_DE_SALIDA - 1 do
begin
Result[i] :=f[i]+(1/(nI[i]+1));
// Result[i] :=f[i]+(2/(nI[i]+1));
end;
end;
function hallarUltimaInstruccionEnTcontrol(var x:Tcontrol):Integer;
var
i,m,n:Integer;
begin
m:=Length(x);
if m>0 then
begin
for i:=m-1 downto 0 do
begin
if x[i].iFin>=0 then
begin
Result:= x[i].iFin;
Exit;
end;
end;
Result:=-1;
end
else
begin
Result:=-1;
end;
end;
procedure mostrarControlDin(var Memo:TMemo;var x:Tcontrol);
var
j:integer;
linea:cadena100;
begin
Memo.Lines.add('LEVEL-1 FLOW CONTROL OPERATIONS:');
Memo.Lines.add('No START END COND WEIGHT Description');
for j:=0 to Length(x)-1 do
begin
linea:=numCad(j,2)+' ';
linea:=linea+numCad(x[j].iIni,6);
linea:=linea+numCad(x[j].iFin,6);
linea:=linea+numCad(x[j].cond,6);
linea:=linea+' '+IntToStr(x[j].wint)+' ';
case x[j].cond of
1:linea:=linea+' Single execution';
2..VALOR_MAXIMO_CONDICION:linea:=linea+' Loop';
VALOR_MINIMO_CONDICION..0:linea:=linea+' Conditional jump';
else
linea:=linea+' Unknown Operation';
end;
Memo.Lines.add(linea);
end;
end;
function TransferConPesosYcondicionAleatorios:estructuraTransferDin;
var
x:estructuraTransferDin;
begin
x.tipo:=random(CANTIDAD_DE_TIPOS_TRANSFERENCIA);
x.inme:=random(VALOR_INMEDIATO_MAXIMOMASUNO);//Valor inmediato
x.rDes:=Random(NUMERO_DE_REGISTROS);
x.rFue:=Random(NUMERO_DE_REGISTROS);;
x.iDes:=random(2*TAMANO_MINIMO_DE_SECUENCIA_DIN -2)+2;
x.iFue:=random(integer(x.iDes-1));
Result:=x;
end;
function controlConPesosYcondicionAleatorios:estructuraControlDin;
var
x:estructuraControlDin;
n:Integer;
begin
x.wint:=VALOR_ALEATORIO_MINIMO_PESO+
Random(VALOR_ALEATORIO_MAXIMO_PESO-VALOR_ALEATORIO_MINIMO_PESO+1);
// x.cond:=Random(VALOR_MAXIMO_CONDICION-VALOR_MINIMO_CONDICION+1)+VALOR_MINIMO_CONDICION;
n:=Random(300); {Igual probabilidad}
if n<100 then
begin {Salto condicional}
x.cond:=(-1)*Random((-1)*VALOR_MINIMO_CONDICION+1)
end
else
begin
if n<200 then
begin {Bucle}
x.cond:=Random(VALOR_MAXIMO_CONDICION+1);
end
else
begin {Ejecucion unica}
x.cond:=1;
end;
end;
Result:=x;
end;
function controlConPesosAleatoriosCondicionLineal:estructuraControlDin;
var
x:estructuraControlDin;
begin
x.wint:=VALOR_ALEATORIO_MINIMO_PESO+
Random(VALOR_ALEATORIO_MAXIMO_PESO-VALOR_ALEATORIO_MINIMO_PESO+1);
// x.w:=Random;
x.cond:=1;
Result:=x;
end;
procedure PrimerasInstruccionesEnRich_LCD(var Memo:TMemo;var nig,nec:Integer);
begin
Memo.Lines.add(';-----------------------');Inc(nec);
Memo.Lines.add('; LCD');Inc(nec);
Memo.Lines.add('; inicialization');Inc(nec);
Memo.Lines.add('; program');Inc(nec);
Memo.Lines.add(';-----------------------');Inc(nec);
Memo.Lines.add(' '+'MOV A,#0');Inc(nig);
Memo.Lines.add(' '+'MOV B,A');Inc(nig);
Memo.Lines.add(' '+'MOV R0,A');Inc(nig);
Memo.Lines.add(' '+'MOV P1,#0FFH');Inc(nig);
Memo.Lines.add(' '+'MOV PSW,#0');Inc(nig);
Memo.Lines.add(';START OF THE');Inc(nec);
Memo.Lines.add(';GENERATED PROGRAM');Inc(nec);
end;
procedure stringGridAmemo_PKIP_DIN(var SG:TStringGrid;var Memo:TMemo);
procedure separarCadenas(x:string;var c:tipoCadenasSeparadas);
var
i:Integer;
contador:Integer;
xCola:string;
posSeparador:byte;
tamano:integer;
begin
contador:=0;
tamano:=length(x);
if tamano=0 then
begin
c[0]:='FINALBLOQUE';
exit;
end;
while tamano>0 do
begin
posSeparador:=pos(';',x);
if posSeparador>0 then
begin
c[contador]:=copy(x,1,posSeparador-1);
Inc(contador);
xCola:=copy(x,posSeparador+1,tamano-posSeparador);
end
else
begin
c[contador]:=x;
Inc(contador);
xCola:='';
end;
x:=xCola;
tamano:=length(x);
end;
c[contador]:='FINALBLOQUE';
end;
var
i,j,k,m:integer;
sLinea:string;
c:tipoCadenasSeparadas;
begin
m:=0;// 2020
case CBII of
LCD_GP,PKIP_GP:begin
m:=1;{solo debe ser mayor que 0}
end;
PKIP_SC_GP:begin
m:=1;
end;
end;
if (m>=0) then
begin
for i:=0 to SG.rowCount do
begin
for j:=0 to SG.ColCount do
begin
sLinea:=SG.cells[j,i];
if (sLinea<>'')and(j<>NFILA) then
begin
separarCadenas(sLinea,c);
k:=0;
while c[k]<>'FINALBLOQUE' do
begin
if (j=N_ETIQ_BIF1)or(j=N_ETIQ_BIF2)or(j=N_ETIQ_JMP2)or(j=N_ETIQ_JMP1) then
begin
Memo.Lines.add(c[k]);
end
else
begin
Memo.Lines.add(' '+c[k]);
//n:=Pos('PORT',instruccionS);
if Pos('PORT',c[k])>0 then
begin
Memo.Lines.Add(' CALL DELAY');
end;
end;
Inc(k);
end;
end;
end;
end;
end;
// Memo.Lines.add('; End of the');
// Memo.Lines.add('; evolved program.');
end;
procedure SecuenciaMenorAStringGrid(var mProg:Tseq;var mControl:Tcontrol;var SG:TStringGrid);
procedure ponerEnSG(col:Integer;fil:Integer;s:string);
var
sAux:string;
begin
sAux:=SG.cells[col,fil];
if sAux='' then
begin
if (col=N_ETIQ_BIF1)or(col=N_ETIQ_BIF2)or(col=N_ETIQ_JMP2)or(col=N_ETIQ_JMP1) then
begin
SG.cells[col,fil]:=s+':';
end
else
begin
// SG.cells[col,fil]:=' '+s;
SG.cells[col,fil]:=s;
end;
end
else
begin
if (col=N_ETIQ_BIF1)or(col=N_ETIQ_BIF2)or(col=N_ETIQ_JMP2)or(col=N_ETIQ_JMP1) then
begin
SG.cells[col,fil]:=sAux+';'+s+':';
end
else
begin
// SG.cells[col,fil]:=sAux+';'+' '+s;
SG.cells[col,fil]:=sAux+';'+s;
end;
end;
end;
var
j,ts,ui:Integer;
linea:string;
OCcadena:string;
CadenaMnemonico:cadena10;
fila:Integer;
begin
fila:=1;//Con fila:=0 se pierde la primera instrucción (2016)
SG.rowCount:=fila+1;
ts:=Length(mProg);
ui:=hallarUltimaInstruccionEnTcontrol(mControl);
if ui<0 then Exit;
for j:=0 to ui do
begin
linea:='';
OCcadena:=vectorInstruccionAcadenaASM(mProg[j],0);
eliminarEspaciosLaterales(OCcadena);
CadenaMnemonico:=extraerPrimeraPalabra(OCcadena);
linea:=linea+CadenaMnemonico+' ';
linea:=linea+OCcadena;//+' '+cDir;
SG.rowCount:=fila+1;
SG.cells[NFILA,fila]:=IntToStr(j);
ponerEnSG(NPROG,fila,linea);
Inc(fila);
end;
SG.rowCount:=fila+1;
end;
procedure MostrarLocalizacionDeBitsDin(var Memo:TMemo;var s:tipoSolucionDin);
var
cProg:string;
nR,nBR:vectorParaPartes;
i:Integer;
linea:string;
begin
for i:=0 to NUMERO_DE_PARTES_DE_SALIDA - 1 do
begin
nR[i]:=s.nPSol[i] div 8;
nBR[i]:=s.nPSol[i] mod 8;
end;
linea:='BIT LOCATION: ';
for i:=NUMERO_DE_PARTES_DE_SALIDA - 1 downto 0 do
begin
linea:=linea+'Bit'+intToStr(i)+' ';
end;
Memo.Lines.Add(linea);
Memo.Lines.Add('Register: '+cadenaDeVectorParaPartes(nR,True));
Memo.Lines.Add('Bit in Register: '+cadenaDeVectorParaPartes(nBR,False));
Memo.Lines.Add('Number of Instr: '+cadenaDeVectorParaPartes(s.nISol,False));
cProg:=numFCad(sumarElementosVectorParaPartesF(s.rdsSol.f),6);
Memo.Lines.Add('--------------------------------------------------------------');
Memo.Lines.Add('FITNESS: '+cadenaDeVectorParaPartesF(s.rdsSol.f));
Memo.Lines.Add('TOTAL FITNESS:'+cProg);
end;
procedure valoresInicialesEnMatrizMVR_DIN(s:Integer);
var
i,k:integer;
begin
SetLength(mvrDin,s);
for i:=0 to s-1 do
begin
for k:=0 to NUMERO_DE_CADENAS_DE_SALIDA-1 do
begin
mvrDin[i][k]:=0;
end;
end;
end;
procedure SecuenciaAMemo_PKIP_DIN(var memo:TMemo;var s:tipoSolucionDin;var nie:Integer);
var
j,t:Integer;
linea:string;
begin
// Memo.Lines.Add('INSTRUCTION SEQUENCE: ');
// Memo.Lines.Add(' No OpCODE MNEMONIC');
// t:=Length(s.progSol);
// t:=s.LCDSol.nUltimaInstDeDT;
// for j:=0 to t-1 do
t:=Length(s.SeqSol);
nie:=nie+t;
for j:=0 to t-1 do
begin
linea:=' '+vectorInstruccionAcadenaASM(s.SeqSol[j],0);
Memo.Lines.Add(linea);
end;
end;
procedure SecuenciaAMemo_PKIP_DIN_conOC(var memo:TMemo;var s:tipoSolucionDin);
var
j,t:Integer;
linea:string;
begin
t:=Length(s.SeqSol);
for j:=0 to t-1 do
begin
linea:=' ';
if j<10 then linea:=linea+' ';
if j<100 then linea:=linea+' ';
linea:=linea+IntToStr(j)+' ';{Pone Numero de Fila}
linea:=linea+' '+vectorInstruccionAVRaCadenaASM(s.SeqSol[j]);
Memo.Lines.Add(linea);
end;
end;
procedure MatrizProgramaAMemo_DIN_conOC(var memo:TMemo;var s:tipoSolucionDin);
var
j,t,n:Integer;
linea:string;
instruccionS:string;
begin
t:=s.rdsSol.u+1;
for j:=0 to t-1 do
begin
instruccionS:=vectorInstruccionAVRaCadenaASM(s.SeqSol[j]);
linea:=' '+instruccionS;
Memo.Lines.Add(linea);
n:=Pos('PORT',instruccionS);
if n>0 then
begin
Memo.Lines.Add(' CALL DELAY');
end;
end;
end;
procedure MatrizProgramaAMemo_DIN(var memo:TMemo;var s:tipoSolucionDin;var nie:integer);
var
j,t:Integer;
linea:string;
begin
// t:=s.LCDSol.nUltimaInstDeDT;
t:=s.rdsSol.u;
nie:=nie+t+1;
// for j:=0 to t-1 do
for j:=0 to t do
begin
linea:=' '+vectorInstruccionAcadenaASM(s.SeqSol[j],0);
Memo.Lines.Add(linea);
end;
end;
function calcularAdecuacionDT(var rdt:rLCD):vectorParaPartesF;
var
i,j:Integer;
f:vectorParaPartesF;
a,g,b:Byte;
bb:SmallInt;
begin
anularVectorParaPartesF(f);
for j:=0 to NUMERO_DE_CADENAS_DE_SALIDA-1 do {PRUEBA}
begin
a:=dtObjetivo[j];
bb:=rdt.dt[j];
if bb>=0 then
begin
b:=Byte(bb);
for i:=0 to 7 do
begin
g:=byte((not(((a shr i)and 1)xor((b shr i)and 1)))and 1);
if g=1 then
begin
f[i]:=f[i]+(NUMERO_DE_CADENAS_DE_SALIDA-j);// 2020 se activa
// f[i]:=f[i]+2*(NUMERO_DE_CADENAS_DE_SALIDA-j);// 2020 se activa
end;
end;
end;
end;
Result:=f;
end;
function calcularAdecuacionDTNuevo(var rdt:rLCD):vectorParaPartesF;
var
i,j:Integer;
f:vectorParaPartesF;
a,g,b:Byte;
bb:SmallInt;
sigueIgual:Boolean;
begin
anularVectorParaPartesF(f);
sigueIgual:=True;
for j:=0 to NUMERO_DE_VALORES_EN_CADENA_DE_SALIDA-1 do
begin
a:=dtObjetivo[j];
bb:=rdt.dt[j];
if bb<>a then sigueIgual:=False;
if bb>=0 then {Si bb=-1 no se cuenta}
begin
b:=Byte(bb);
for i:=0 to 7 do
begin
g:=byte((not(((a shr i)and 1)xor((b shr i)and 1)))and 1);
if g=1 then
begin
if sigueIgual then
begin
f[i]:=f[i]+(NUMERO_DE_VALORES_EN_CADENA_DE_SALIDA-j);
// f[i]:=f[i]+2*(NUMERO_DE_VALORES_EN_CADENA_DE_SALIDA-j);
end
else
begin
f[i]:=f[i]+1.0;
end;
end;
end;
end;
end;
Result:=f;
end;
function calcularAdecuacionDTextenso(var rdt:rLCD):vectorParaPartesF;
var
i,j:Integer;
f:vectorParaPartesF;
a,g,b:Byte;
bb:SmallInt;
begin
anularVectorParaPartesF(f);
for j:=0 to NUMERO_DE_CADENAS_DE_SALIDA-1 do {PRUEBA}
begin
a:=dtObjetivo[j];
bb:=rdt.dt[j];
if bb>=0 then
begin
b:=Byte(bb);
for i:=0 to 7 do
begin
g:=byte((not(((a shr i)and 1)xor((b shr i)and 1)))and 1);
if g=1 then
begin
// f[i]:=f[i]+(NUMERO_DE_CADENAS_DE_SALIDA-j);
// f[i]:=f[i]+1.0;
// f[j]:=f[j]+1.0;
f[j]:=f[j]+(NUMERO_DE_CADENAS_DE_SALIDA-j);
end;
end;
end;
end;
Result:=f;
end;
function IndiceEnSegmento(n,LongitudSegmento1:Integer):Integer;
begin
if n<LongitudSegmento1 then
begin
Result:=n;
end
else
begin
Result:=n-LongitudSegmento1;
end;
end;
function RandomConPesosLineales(n:Integer):Integer;
{Devuelve numero aleatorio entre 0 y n-1 con probabilidades linealmente variables,
0 tiene la mayor probabilidad n-1 la menor}
var
tope,m,i:Integer;
begin
tope:=(n*(n+1)) div 2;
m:=Random(tope);
for i:=0 to n do
begin
if (i*(i+1) div 2) > m then
begin
Result:=(n-1)-(i-1);
Exit;
end;
end;
end;
function QubicRandom: Double;
var
a:Double;
begin
a:=Random;
Result := (1-a)*(1-a)*(1-a);
end;
function LinealRandom(n : Integer): Integer;
begin
// Result := (-Ln(1.0 - Random) / Lambda);
Result := Floor((1-n)* Random + n);
end;
function ExponencialRandom(N:Integer): Integer;
var
logar,ln000001:Double;
begin
// Result := (-Ln(1.0 - Random) / Lambda);
ln000001:=Ln(0.000001);
logar:= (N+1)*(Ln(1.0 - Random + 0.000001)/ln000001);
Result:=Trunc(abs(logar));
// Result := (-Ln((1.0 - Random)/lambda) / Lambda);
end;
procedure indicesDePadres(Nmax,m:Integer;var a,b:arregloEntero);
{Devuelve m pares a[i], b[i] (a[i]<>b[i]) menores a Nmax}
var
i:Integer;
begin
SetLength(a,m);
SetLength(b,m);
if Nmax<=1 then Exit;
for i:= 0 to m - 1 do
begin
a[i]:=RandomConPesosLineales(Nmax);
repeat
b[i]:=RandomConPesosLineales(Nmax);
until b[i]<>a[i];
end;
end;
procedure indicesDePadresEnSegmentos(longSeg1,longSeg2,m:Integer;var a,b,sa,sb:arregloEntero);
{longSeg1-tamaño P1t, longSeg2-tamaño P2t; m-cantidad de parejas
Devuelve m pares a[i], b[i].
a[i]-Indice en P1t (sa[i]=1) o en P2t (sa[i]=2)
b[i]-Indice en P1t (sb[i]=1) o en P2t (sb[i]=2) }
var
i,Nmax:Integer;
begin
SetLength(a,m);
SetLength(b,m);
SetLength(sa,m);
SetLength(sb,m);
{Indices en un solo segmento}
Nmax:=longSeg1+longSeg2;
if Nmax<=1 then Exit;
for i:= 0 to m - 1 do
begin
// a[i]:=RandomConPesosLineales(Nmax);
a[i]:=Trunc(Nmax*QubicRandom);
repeat
// b[i]:=RandomConPesosLineales(Nmax);
b[i]:=Trunc(Nmax*QubicRandom);
until b[i]<>a[i];
end;
{Indices en dos segmentos}
for i:= 0 to m - 1 do
begin
if a[i]<longSeg1 then
begin
sa[i]:=1;
end
else
begin
a[i]:=a[i]-longSeg1;
sa[i]:=2;
end;
if b[i]<longSeg1 then
begin
sb[i]:=1;
end
else
begin
b[i]:=b[i]-longSeg1;
sb[i]:=2;
end;
end;
end;
function RandomM(Nmax,m:integer):arregloEntero;
{Devuelve arreglo con m números aleatorios diferentes menores a Nmax}
var
i,j,aux:Integer;
a:arregloEntero;
hay:Boolean;
begin
SetLength(a,m);
a[0]:=Random(Nmax);
for i:= 1 to m - 1 do
begin
hay:=False;
repeat
aux:=Random(Nmax);
for j:=0 to i-1 do
begin
if aux=a[j] then
begin
hay:=True;
Break;
end;
end;
until not(hay);
a[i]:=aux;
end;
RandomM:=Copy(a);
end;
end.
|
unit SG_Edit;
interface
uses
stdctrls;
procedure validarDatoIngresado(edit:TEdit;descripcionEdit:string);
function esDigito(caracter:char):boolean;
procedure validarDatoNumerico(edit:TEdit;descripcionEdit:string);
procedure validarDatoNumericoEntero(edit:TEdit;descripcionEdit:string);
procedure validarDatoNumericoConDecimales(edit:TEdit;descripcionEdit:string);
implementation
uses
sysutils;
procedure validarDatoIngresado(edit:TEdit;descripcionEdit:string);
begin
if edit.Text='' then
raise Exception.Create('El parametro '+descripcionEdit+' es obligatorio');
end;
function esDigito(caracter:char):boolean;
begin
Result:=
(caracter = '0') or
(caracter = '1') or
(caracter = '2') or
(caracter = '3') or
(caracter = '4') or
(caracter = '5') or
(caracter = '6') or
(caracter = '7') or
(caracter = '8') or
(caracter = '9');
end;
procedure validarDatoNumerico(edit:TEdit;descripcionEdit:string);
var
longitud,
i:integer;
begin
if edit.Text = '' then
exit;
longitud:=length(edit.Text);
for i:=1 to longitud do
if not esDigito(edit.Text[i]) then
raise Exception.Create('El parametro '+descripcionEdit+' solo acepta '+
'caracteres numericos');
end;
procedure validarDatoNumericoEntero(edit:TEdit;descripcionEdit:string);
begin
if edit.Text = '' then
exit;
try
StrToInt(edit.Text);
except
on EConvertError do
raise Exception.Create('El parametro '+descripcionEdit+' solo acepta '+
'valores numericos');
end;
end;
procedure validarDatoNumericoConDecimales(edit:TEdit;descripcionEdit:string);
begin
if edit.Text = '' then
exit;
try
StrToFloat(edit.Text);
except
on EConvertError do
raise Exception.Create('El parametro '+descripcionEdit+' solo acepta '+
'valores numéricos decimales');
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ Copyright(c) 2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.FontGlyphs.Android;
interface
uses
System.Types, System.Classes, System.SysUtils, System.UITypes, System.UIConsts, System.Generics.Collections,
FMX.Types, FMX.Surfaces, FMX.FontGlyphs, FMX.PixelFormats,
Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge;
{$SCOPEDENUMS ON}
type
TAndroidFontGlyphManager = class(TFontGlyphManager)
private
FPaint: JPaint;
//Current metrics
FSpacing: Single;
FTop: Single;
FTopInt: Integer;
FAscent: Single;
FDescent: Single;
FBottom: Single;
FBottomInt: Integer;
FLeading: Single;
FLeadingInt: Integer;
protected
procedure LoadResource; override;
procedure FreeResource; override;
function DoGetGlyph(const Char: UCS4Char; const Settings: TFontGlyphSettings): TFontGlyph; override;
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses
System.Math, System.Character,
Androidapi.Bitmap,
FMX.Graphics;
{ TAndroidFontGlyphManager }
constructor TAndroidFontGlyphManager.Create;
begin
inherited Create;
FPaint := TJPaint.Create;
end;
destructor TAndroidFontGlyphManager.Destroy;
begin
FPaint := nil;
inherited;
end;
procedure TAndroidFontGlyphManager.LoadResource;
const
BoldAndItalic = [TFontStyle.fsBold, TFontStyle.fsItalic];
var
TypefaceFlag: Integer;
Typeface: JTypeface;
FamilyName: JString;
Metrics: JPaint_FontMetrics;
MetricsInt: JPaint_FontMetricsInt;
begin
FPaint.setAntiAlias(True);
FPaint.setTextSize(CurrentSettings.Size * CurrentSettings.Scale);
FPaint.setARGB(255, 255, 255, 255);
FPaint.setUnderlineText(TFontStyle.fsUnderline in CurrentSettings.Style);
FPaint.setStrikeThruText(TFontStyle.fsStrikeOut in CurrentSettings.Style);
if TOSVersion.Check(4, 0) then
FPaint.setHinting(TJPaint.JavaClass.HINTING_ON);
//Font
try
FamilyName := StringToJString(CurrentSettings.Family);
if (BoldAndItalic * CurrentSettings.Style) = BoldAndItalic then
TypefaceFlag := TJTypeface.JavaClass.BOLD_ITALIC
else
if TFontStyle.fsBold in CurrentSettings.Style then
TypefaceFlag := TJTypeface.JavaClass.BOLD
else
if TFontStyle.fsItalic in CurrentSettings.Style then
TypefaceFlag := TJTypeface.JavaClass.ITALIC
else
TypefaceFlag := TJTypeface.JavaClass.NORMAL;
Typeface := TJTypeface.JavaClass.create(FamilyName, TypefaceFlag);
FPaint.setTypeface(Typeface);
try
Metrics := FPaint.getFontMetrics;
MetricsInt := FPaint.getFontMetricsInt;
//
FSpacing := FPaint.getFontMetrics(Metrics);
FTop := Metrics.top;
FTopInt := MetricsInt.top;
FAscent := Metrics.ascent;
FDescent := Metrics.descent;
FBottom := Metrics.bottom;
FBottomInt := MetricsInt.bottom;
FLeading := Metrics.leading;
FLeadingInt := MetricsInt.leading;
// SysDebug(FloatToStr(CurrentSettings.Size) + ':' + FloatToStr(CurrentSettings.Scale));
// Log.d(Format('Top=(%d %f) Bottom=(%d %f) Leading=(%d %f) FAscent=(%d %f)', [FTopInt, FTop, FBottomInt, FBottom, FLeadingInt, FLeading, MetricsInt.ascent, FAscent]));
finally
Metrics := nil;
MetricsInt := nil;
end;
finally
FamilyName := nil;
Typeface := nil;
end;
end;
procedure TAndroidFontGlyphManager.FreeResource;
begin
if Assigned(FPaint) then
FPaint.reset;
end;
function TAndroidFontGlyphManager.DoGetGlyph(const Char: UCS4Char; const Settings: TFontGlyphSettings): TFontGlyph;
var
Text: JString;
Bitmap: JBitmap;
Canvas: JCanvas;
GlyphRect: TRect;
C, I, J, Width, Height: Integer;
Advance: Single;
Bounds: JRect;
GlyphStyle: TFontGlyphStyles;
PixelBuffer: Pointer;
Data: PIntegerArray;
Path: JPath;
PathMeasure: JPathMeasure;
PathLength: Single;
Coords: TJavaArray<Single>;
StartPoint, LastPoint, Point: TPointF;
NewContour, HasStartPoint: Boolean;
begin
try
Text := StringToJString(System.Char.ConvertFromUtf32(Char));
Advance := FPaint.measureText(Text);
// SysDebug(Format('%s %f', [System.Char.ConvertFromUtf32(Char), Advance]));
Height := Abs(FTopInt) + Abs(FBottomInt) + 2;
Width := Ceil(Abs(Advance)) + 2;
try
Bitmap := TJBitmap.JavaClass.createBitmap(Width, Height, TJBitmap_Config.JavaClass.ARGB_8888);
try
Bounds := TJRect.Create;
FPaint.getTextBounds(Text, 0, Text.length, Bounds);
// Log.d(Format('Bounds=(%d %d %d %d) %d %d ', [Bounds.left, Bounds.top, Bounds.right, Bounds.bottom, Bounds.width, Bounds.height]));
try
Canvas := TJCanvas.JavaClass.init(Bitmap);
Canvas.drawText(Text, 0, -Trunc(FAscent), FPaint);
finally
Canvas := nil;
end;
GlyphStyle := [];
if ((FAscent = 0) and (FDescent = 0)) or not HasGlyph(Char) then
GlyphStyle := [TFontGlyphStyle.NoGlyph];
if TFontGlyphSetting.gsPath in Settings then
GlyphStyle := GlyphStyle + [TFontGlyphStyle.HasPath];
Result := TFontGlyph.Create(TPoint.Create(Bounds.left, Abs(FTopInt - Bounds.top)),
Advance, Abs(FTopInt) + Abs(FBottomInt) + Abs(FLeadingInt), GlyphStyle);
if (TFontGlyphSetting.gsBitmap in Settings) and
(HasGlyph(Char) or ((FAscent <> 0) or (FDescent <> 0))) and
(AndroidBitmap_lockPixels(TJNIResolver.GetJNIEnv, (Bitmap as ILocalObject).GetObjectID, @PixelBuffer) = 0) then
begin
Data := PIntegerArray(PixelBuffer);
GlyphRect.Left := Bounds.left;
GlyphRect.Right := Bounds.Right;
GlyphRect.Top := Abs(Trunc(FAscent) - Bounds.top);
GlyphRect.Bottom := Abs(Trunc(FAscent) - Bounds.bottom);
// Log.d(Format('GlyphRect=(%d %d %d %d) %d %d', [GlyphRect.Left, GlyphRect.Top, GlyphRect.Right, GlyphRect.Bottom, GlyphRect.Width, GlyphRect.Height]));
if (GlyphRect.Width > 0) or (GlyphRect.Height > 0) then
begin
Result.Bitmap.SetSize(GlyphRect.Width + 1, GlyphRect.Height + 1, TPixelFormat.pfA8R8G8B8);
if TFontGlyphSetting.gsPremultipliedAlpha in Settings then
begin
for I := GlyphRect.Top to GlyphRect.Bottom do
Move(Data[I * Width + Max(GlyphRect.Left, 0)],
Result.Bitmap.GetPixelAddr(0, I - GlyphRect.Top)^, Result.Bitmap.Pitch);
end
else
for I := GlyphRect.Top to GlyphRect.Bottom - 1 do
for J := GlyphRect.Left to GlyphRect.Right - 1 do
begin
C := Data[I * Width + J];
if C <> 0 then
begin
C := ((C shr 16) and $FF + (C shr 8) and $FF + (C and $FF)) div 3;
Result.Bitmap.Pixels[J - GlyphRect.Left, I - GlyphRect.Top] := MakeColor($FF, $FF, $FF, C);
end
end;
end;
AndroidBitmap_unlockPixels(TJNIResolver.GetJNIEnv, (Bitmap as ILocalObject).GetObjectID);
end;
//Path
if TFontGlyphSetting.gsPath in Settings then
try
Path := TJPath.Create;
FPaint.getTextPath(Text, 0, Text.length, Result.Origin.X, Result.Origin.Y, Path);
PathMeasure := TJPathMeasure.Create;
PathMeasure.setPath(Path, False);
Coords := TJavaArray<Single>.Create(2);
if PathMeasure.getLength > 0 then
repeat
PathLength := PathMeasure.getLength;
NewContour := True;
HasStartPoint := False;
I := 0;
while I < PathLength do
begin
if PathMeasure.getPosTan(I, Coords, nil) then
begin
Point := PointF(Coords[0], Coords[1]);
if NewContour then
begin
Result.Path.MoveTo(Point);
NewContour := False;
HasStartPoint := False;
end
else
if Point <> LastPoint then
begin
if HasStartPoint and (LastPoint <> StartPoint) then
if not SameValue(((Point.Y - StartPoint.Y) / (Point.X - StartPoint.X)), ((Point.Y - LastPoint.Y) / (Point.X - LastPoint.X)), Epsilon) then
begin
Result.Path.LineTo(Point);
HasStartPoint := False;
end
else
else
Result.Path.LineTo(Point);
end;
LastPoint := Point;
if not HasStartPoint then
begin
StartPoint := Point;
HasStartPoint := True;
end;
end;
Inc(I);
end;
if Result.Path.Count > 0 then
Result.Path.ClosePath;
until not PathMeasure.nextContour;
Point := Result.Path.GetBounds.TopLeft;
Result.Path.Translate(-Point.X + Result.Origin.X, -Point.Y + Result.Origin.Y);
finally
FreeAndNil(Coords);
Path := nil;
PathMeasure := nil;
end;
finally
Bounds := nil;
end;
finally
Bitmap.recycle;
Bitmap := nil;
end;
finally
Text := nil;
end;
end;
end.
|
unit DentalDataFeeders;
interface
uses
DentalIntf, DB, pFIBDataSet, pFIBDatabase, uCommonDefinitions, Classes,
WideStrings, Pfibquery;
type
omStates = (omCreating, omIdle);
TOnDestroyTransaction = procedure of object;
TOnGetOwnerID = procedure (var AID: IDentifier) of object;
TOnSetOwnerID = TOnGetOwnerID;
ICompoPartDataFeederBridge = interface(IInterface)
['{8A3CDD5A-89B6-4EA9-BB94-44994ACDFD6A}']
procedure SetGeneralTransaction(const Value: TpFIBTransaction);
function GetGeneralTransaction: TpFIBTransaction;
property GeneralTransaction: TpFIBTransaction read GetGeneralTransaction write SetGeneralTransaction;
end;
ICompoPartDataFeeder = interface(IInterface)
['{93A34536-0A5A-4110-94FB-FCEC33AF7FF4}']
procedure CompoOpenEdit(var Aid: IDentifier; AProps: IProperties);
procedure CompoOpenView(var Aid: IDentifier; AProps: IProperties);
procedure CompoReadProps(var Aid: IDentifier; AProps: IProperties);
procedure CompoSave(var Aid: IDentifier; AProps: IProperties);
procedure CompoDelete(Aid: IDentifier; AProps: IProperties);
procedure SetOnGetOwnerID(const Value: TOnGetOwnerID);
function GetOnGetOwnerID: TOnGetOwnerID;
property OnGetOwnerID: TOnGetOwnerID read GetOnGetOwnerID write SetOnGetOwnerID;
procedure SetOnSetOwnerID(const Value: TOnSetOwnerID);
function GetOnSetOwnerID: TOnSetOwnerID;
property OnSetOwnerID: TOnSetOwnerID read GetOnSetOwnerID write SetOnSetOwnerID;
end;
ICompoExposedDataFeeder = interface(IInterface)
['{0E2E47F7-EA42-4A13-8139-1986DB331850}']
function GetDataFeeder: IDataFeeder;
property DataFeeder: IDataFeeder read GetDataFeeder;
end;
TBaseDataFeeder = class(TInterfacedObject, IDataFeeder)
private
procedure OnDestroyTransactionNative;
protected
FState: omStates;
Fds: TpFIBDataSet;
Ftr: TpFIBTransaction;
FDbEventName: string;
FOnDestroyTransaction: TOnDestroyTransaction;
procedure OnCreateTransaction; virtual;
procedure DoOnDestroyTransaction; virtual;
protected
{IDataFeeder}
procedure ProcessDbEvent(EventName: string); virtual;
procedure Init; virtual;
function GetListSource: TDataSet; virtual;
public
{ class methods }
constructor Create;
destructor Destroy; override;
end;
TListedDataFeeder = class(TBaseDataFeeder, IListDataFeeder)
private
FOnChangedCurrentID: TOnChangedCurrentID;
procedure OnAfterScroll(DataSet: TDataSet);
procedure DoChangeCurrentID;
{function GetRecordID: IDentifier;}
protected
FIdField: string;
function GetCurrentID: IDentifier;
procedure SetCurrentID(Value: IDentifier);
function GetOnChangedCurrentID: TOnChangedCurrentID;
procedure SetOnChangedCurrentID(Value: TOnChangedCurrentID);
protected
{ IDataFeeder }
function GetListSource: TDataSet; override;
{ IListDataFeeder }
property CurrentID: IDentifier read GetCurrentID write SetCurrentID;
property OnChangedCurrentID: TOnChangedCurrentID read GetOnChangedCurrentID write SetOnChangedCurrentID;
procedure PostInit;
public
{ class methods }
constructor Create;
destructor Destroy; override;
end;
TRWDataFeeder = class(TBaseDataFeeder, IObjectDataFeeder)
protected
procedure RestartTrans(const params: string); virtual;
procedure SoftCommit; virtual;
procedure SoftRollback; virtual;
procedure HardCommit; virtual;
procedure HardRollback; virtual;
procedure StartTransaction; virtual;
procedure InternalOpenEdit(var Aid: IDentifier; AProps: IProperties); virtual; abstract;
procedure InternalOpenView(var Aid: IDentifier; AProps: IProperties); virtual; abstract;
procedure InternalReadProps(var Aid: IDentifier; AProps: IProperties); virtual; abstract;
procedure InternalSave(var Aid: IDentifier; AProps: IProperties); virtual; abstract;
procedure InternalDelete(Aid: IDentifier; AProps: IProperties); virtual; abstract;
protected
function Read(var Aid: IDentifier; AProps: IProperties; AOpenState: TOpenState; var AEditViewState: TEditViewState): dbopState;
function Save(var Aid: IDentifier; AProps: IProperties): dbopState;
function Delete(Aid: IDentifier; AProps: IProperties): dbopState;
end;
TCompoPartDataFeederRW = class(TRWDataFeeder, ICompoPartDataFeeder)
protected
FOnGetOwnerID: TOnGetOwnerID;
FOnSetOwnerID: TOnSetOwnerID;
procedure SetOnGetOwnerID(const Value: TOnGetOwnerID);
function GetOnGetOwnerID: TOnGetOwnerID;
procedure SetOnSetOwnerID(const Value: TOnSetOwnerID);
function GetOnSetOwnerID: TOnSetOwnerID;
procedure DoOnSetOwnerID(var AID: IDentifier);
procedure DoOnGetOwnerID(var AID: IDentifier);
protected
procedure CompoOpenEdit(var Aid: IDentifier; AProps: IProperties); virtual;
procedure CompoOpenView(var Aid: IDentifier; AProps: IProperties); virtual;
procedure CompoReadProps(var Aid: IDentifier; AProps: IProperties); virtual;
procedure CompoSave(var Aid: IDentifier; AProps: IProperties); virtual;
procedure CompoDelete(Aid: IDentifier; AProps: IProperties); virtual;
property OnSetOwnerID: TOnSetOwnerID read GetOnSetOwnerID write SetOnSetOwnerID;
property OnGetOwnerID: TOnGetOwnerID read GetOnGetOwnerID write SetOnGetOwnerID;
end;
TCompositeDataFeeder = class(TRWDataFeeder, ICompositeDataFeeder)
private
FDFList: TInterfaceList;
protected
function GetDataFeeder(Idx: integer): IDataFeeder;
function GetDataFeederCount: integer;
procedure InternalOpenEdit(var Aid: IDentifier; AProps: IProperties); override;
procedure InternalOpenView(var Aid: IDentifier; AProps: IProperties); override;
procedure InternalReadProps(var Aid: IDentifier; AProps: IProperties); override;
procedure InternalSave(var Aid: IDentifier; AProps: IProperties); override;
procedure InternalDelete(Aid: IDentifier; AProps: IProperties); override;
protected
property DataFeeders[Idx: integer]: IDataFeeder read GetDataFeeder;
function RegisterDataFeeder(DF: IDataFeeder): integer;
property DataFeederCount: integer read GetDataFeederCount;
public
constructor Create;
destructor Destroy; override;
end;
TMasterDrivenDataFeeder = class(TListedDataFeeder, IMasterDrivenDataFeeder)
protected
FMasterID: IDentifier;
FForceSetMasterID: boolean;
function GetMasterID: IDentifier;
procedure SetMasterID(Value: IDentifier); virtual;
procedure ReassignParams; virtual;
procedure RecreateListSource;
protected
{ IMasterDrivenDataFeeder }
property MasterID: IDentifier read GetMasterID write SetMasterID;
public
{ class methods }
constructor Create;
destructor Destroy; override;
end;
TdstrPair = class(TObject)
public
ds: TpFIBDataSet;
tr: TpFIBTransaction;
constructor Create;
destructor Destroy; override;
end;
TqtrPair = class(TObject)
public
q: TpFIBQuery;
tr: TpFIBTransaction;
constructor Create;
destructor Destroy; override;
end;
implementation
uses
uDB, SysUtils, Variants, Dialogs, Fib, IB_ErrorCodes, uErrorLog, PFibProps, FIBDataSet;
{ TBaseDataFeeder }
constructor TBaseDataFeeder.Create;
begin
inherited;
FState := omCreating;
Fds := dbmDental.CreateDS;
FOnDestroyTransaction := OnDestroyTransactionNative;
OnCreateTransaction;
Fds.Transaction := Ftr;
Fds.UpdateTransaction := Ftr;
end;
destructor TBaseDataFeeder.Destroy;
begin
dbmDental.CloseDS(Fds);
// if Assigned(Fds) then
// FreeAndNil(Fds);
DoOnDestroyTransaction;
inherited;
end;
procedure TBaseDataFeeder.DoOnDestroyTransaction;
begin
if Assigned(FOnDestroyTransaction) then
FOnDestroyTransaction;
end;
function TBaseDataFeeder.GetListSource: TDataSet;
begin
Result := Fds;
end;
procedure TBaseDataFeeder.Init;
begin
FState := omIdle;
end;
procedure TBaseDataFeeder.OnCreateTransaction;
begin
Ftr := dbmDental.CreateTr(trSingleLockTrans);
end;
procedure TBaseDataFeeder.OnDestroyTransactionNative;
begin
if Assigned(Ftr) then
begin
if Ftr.InTransaction then
Ftr.Rollback;
dbmDental.CloseTR(Ftr);
// FreeAndNil(Ftr);
end;
end;
procedure TBaseDataFeeder.ProcessDbEvent(EventName: string);
begin
if AnsiCompareText(EventName, FDbEventName)=0 then
begin
Fds.DisableControls;
try
Fds.DisableScrollEvents;
try
if (Fds.CacheModelOptions.CacheModelKind=cmkStandard)
and (Fds.AutoUpdateOptions.KeyFields<>'')
then
Fds.ReopenLocate(Fds.AutoUpdateOptions.KeyFields)
else
Fds.FullRefresh;
if Assigned(Fds.AfterScroll) then
Fds.AfterScroll(Fds);
finally
Fds.EnableScrollEvents;
end;
finally
Fds.EnableControls;
end;
end;
end;
{ TListedDataFeeder }
constructor TListedDataFeeder.Create;
begin
inherited;
Fds.AfterScroll := OnAfterScroll;
end;
destructor TListedDataFeeder.Destroy;
begin
inherited;
end;
procedure TListedDataFeeder.DoChangeCurrentID;
begin
if Assigned(FOnChangedCurrentID) then
FOnChangedCurrentID(CurrentID);
end;
function TListedDataFeeder.GetCurrentID: IDentifier;
begin
if Fds.Active then
begin
if not VarIsNull(Fds.FieldByName(FIdField).Value) then
Result := Fds.FieldByName(FIdField).Value
else
Result := UndefiniteID;
end
else
Result := UndefiniteID;
end;
function TListedDataFeeder.GetListSource: TDataSet;
begin
Result := Fds;
end;
function TListedDataFeeder.GetOnChangedCurrentID: TOnChangedCurrentID;
begin
Result := FOnChangedCurrentID;
end;
(*
function TListedDataFeeder.GetRecordID: IDentifier;
begin
if Fds.Active then begin
if not VarIsNull(Fds.FieldByName(FIdField).Value) then
Result := Fds.FieldByName(FIdField).Value
else
Result := UndefiniteID;
end else
Result := UndefiniteID;
end;
*)
procedure TListedDataFeeder.OnAfterScroll(DataSet: TDataSet);
begin
DoChangeCurrentID;
end;
procedure TListedDataFeeder.PostInit;
begin
if Assigned(Fds.AfterScroll) then
Fds.AfterScroll(Fds);
end;
procedure TListedDataFeeder.SetCurrentID(Value: IDentifier);
begin
if FState<>omCreating then
Fds.Locate(FIdField, Value, []);
end;
procedure TListedDataFeeder.SetOnChangedCurrentID(
Value: TOnChangedCurrentID);
begin
FOnChangedCurrentID := Value;
end;
{ TRWDataFeeder }
function TRWDataFeeder.Delete(Aid: IDentifier; AProps: IProperties): dbopState;
begin
Result := dbopUndef;
try
StartTransaction;
try
InternalDelete(Aid, AProps);
HardCommit;
Result := dbopSucc;
except
on E:Exception do
begin
if Fds.State in [dsEdit, dsInsert] then
Fds.Cancel;
HardRollback;
ErrorLog.AddToLog(E.Message);
raise;
end;
end;
except
on E:EFIBInterBaseError do
begin
case E.IBErrorCode of
isc_lock_conflict:
Result := dbopLocked;
end;
end;
on E:Exception do
Result := dbopFailed;
end;
end;
procedure TRWDataFeeder.HardCommit;
begin
Ftr.Commit;
end;
procedure TRWDataFeeder.HardRollback;
begin
Ftr.Rollback;
end;
function TRWDataFeeder.Read(var Aid: IDentifier; AProps: IProperties;
AOpenState: TOpenState; var AEditViewState: TEditViewState): dbopState;
begin
Result := dbopUndef;
try
if AOpenState in [osEditOnly, osEditOrView] then
begin
try
RestartTrans(trSingleLockTrans);
InternalOpenEdit(Aid, AProps);
AEditViewState := evsEdit;
except
on E:EFIBInterBaseError do
begin
case E.IBErrorCode of
isc_lock_conflict:
if AOpenState=osEditOrView then
begin
RestartTrans(trSingleNoLockTrans);
InternalOpenView(Aid, AProps);
AEditViewState := evsView;
end
else
Result := dbopLocked; (* 1 *)
end;
end;
on E:Exception do
raise;
end;
end
else
begin
RestartTrans(trSingleNoLockTrans);
InternalOpenView(Aid, AProps);
AEditViewState := evsView;
end;
if Result<>dbopLocked then // если не попадали в точку (* 1 *)
begin
InternalReadProps(Aid, AProps);
Result := dbopSucc;
end;
except
on E:EFIBInterBaseError do
begin
case E.IBErrorCode of
isc_lock_conflict:
Result := dbopLocked;
end;
end;
on E:Exception do
begin
ErrorLog.AddToLog(E.Message);
Result := dbopFailed;
end;
end;
end;
procedure TRWDataFeeder.RestartTrans(const params: string);
begin
if Fds.UpdateTransaction.Active then
Fds.UpdateTransaction.Rollback;
Fds.UpdateTransaction.TRParams.CommaText := params;
Fds.UpdateTransaction.StartTransaction;
end;
function TRWDataFeeder.Save(var Aid: IDentifier;
AProps: IProperties): dbopState;
begin
Result := dbopUndef;
try
try
InternalSave(Aid, AProps);
SoftCommit;
Result := dbopSucc;
except
on E:Exception do
begin
if Fds.State in [dsEdit, dsInsert] then
Fds.Cancel;
SoftRollback;
ErrorLog.AddToLog(E.Message);
raise;
end;
end;
except
on E:EFIBInterBaseError do
begin
case E.IBErrorCode of
isc_lock_conflict:
Result := dbopLocked;
end;
end;
on E:Exception do
Result := dbopFailed;
end;
end;
procedure TRWDataFeeder.SoftCommit;
begin
Fds.UpdateTransaction.CommitRetaining;
end;
procedure TRWDataFeeder.SoftRollback;
begin
Fds.UpdateTransaction.RollbackRetaining;
end;
procedure TRWDataFeeder.StartTransaction;
begin
Ftr.StartTransaction;
end;
{ TMasterDrivenDataFeeder }
constructor TMasterDrivenDataFeeder.Create;
begin
inherited;
FMasterID := UndefiniteID;
FForceSetMasterID := False;
end;
destructor TMasterDrivenDataFeeder.Destroy;
begin
inherited;
end;
function TMasterDrivenDataFeeder.GetMasterID: IDentifier;
begin
Result := FMasterID;
end;
procedure TMasterDrivenDataFeeder.ReassignParams;
begin
Fds.ParamByName('MasterID').Value := FMasterID;
end;
procedure TMasterDrivenDataFeeder.RecreateListSource;
begin
Fds.DisableControls;
try
Fds.DisableScrollEvents;
try
Fds.Close;
ReassignParams;
Fds.Open;
// Такое поведение Scroll'а нужно потому что
// AfterScroll не происходит при пустом DataSet.
// А так - произойдёт в любом случае.
if Assigned(Fds.AfterScroll) then
Fds.AfterScroll(Fds);
finally
Fds.EnableScrollEvents;
end;
finally
Fds.EnableControls;
end;
end;
procedure TMasterDrivenDataFeeder.SetMasterID(Value: IDentifier);
begin
if FState<>omCreating then
if (FMasterID<>Value) or FForceSetMasterID then
begin
FMasterID := Value;
RecreateListSource;
end;
end;
{ TCompositeDataFeeder }
constructor TCompositeDataFeeder.Create;
begin
inherited;
FDFList := TInterfaceList.Create;
end;
destructor TCompositeDataFeeder.Destroy;
begin
if Assigned(FDFList) then
FreeAndNil(FDFList);
inherited;
end;
function TCompositeDataFeeder.GetDataFeeder(Idx: integer): IDataFeeder;
begin
Result := FDFList.Items[Idx] as IDataFeeder;
end;
function TCompositeDataFeeder.GetDataFeederCount: integer;
begin
Result := FDFList.Count;
end;
procedure TCompositeDataFeeder.InternalDelete(Aid: IDentifier; AProps: IProperties);
var
i: integer;
begin
for i:=0 to FDFList.Count-1 do
(FDFList.Items[i] as ICompoPartDataFeeder).CompoDelete(Aid, AProps);
end;
procedure TCompositeDataFeeder.InternalOpenEdit(var Aid: IDentifier; AProps: IProperties);
var
i: integer;
begin
for i:=0 to FDFList.Count-1 do
(FDFList.Items[i] as ICompoPartDataFeeder).CompoOpenEdit(Aid, AProps);
end;
procedure TCompositeDataFeeder.InternalOpenView(var Aid: IDentifier; AProps: IProperties);
var
i: integer;
begin
for i:=0 to FDFList.Count-1 do
(FDFList.Items[i] as ICompoPartDataFeeder).CompoOpenView(Aid, AProps);
end;
procedure TCompositeDataFeeder.InternalReadProps(var Aid: IDentifier; AProps: IProperties);
var
i: integer;
begin
for i:=0 to FDFList.Count-1 do
(FDFList.Items[i] as ICompoPartDataFeeder).CompoReadProps(Aid, AProps);
end;
procedure TCompositeDataFeeder.InternalSave(var Aid: IDentifier;
AProps: IProperties);
var
i: integer;
begin
for i:=0 to FDFList.Count-1 do
(FDFList.Items[i] as ICompoPartDataFeeder).CompoSave(Aid, AProps);
end;
function TCompositeDataFeeder.RegisterDataFeeder(DF: IDataFeeder): integer;
begin
Result := FDFList.Add(DF);
end;
{ TCompoPartDataFeederRW }
procedure TCompoPartDataFeederRW.CompoDelete(Aid: IDentifier; AProps: IProperties);
var
intID: IDentifier;
begin
intID := Aid;
DoOnGetOwnerID(intID);
InternalDelete(intID, AProps);
DoOnSetOwnerID(intID);
end;
procedure TCompoPartDataFeederRW.CompoOpenEdit(var Aid: IDentifier; AProps: IProperties);
var
intID: IDentifier;
begin
intID := Aid;
DoOnGetOwnerID(intID);
InternalOpenEdit(intID, AProps);
DoOnSetOwnerID(intID);
end;
procedure TCompoPartDataFeederRW.CompoOpenView(var Aid: IDentifier; AProps: IProperties);
var
intID: IDentifier;
begin
intID := Aid;
DoOnGetOwnerID(intID);
InternalOpenView(intID, AProps);
DoOnSetOwnerID(intID);
end;
procedure TCompoPartDataFeederRW.CompoReadProps(var Aid: IDentifier; AProps: IProperties);
var
intID: IDentifier;
begin
intID := Aid;
DoOnGetOwnerID(intID);
InternalReadProps(intID, AProps);
DoOnSetOwnerID(intID);
end;
procedure TCompoPartDataFeederRW.CompoSave(var Aid: IDentifier; AProps: IProperties);
var
intID: IDentifier;
begin
intID := Aid;
DoOnGetOwnerID(intID);
InternalSave(intID, AProps);
DoOnSetOwnerID(intID);
end;
procedure TCompoPartDataFeederRW.DoOnGetOwnerID(var AID: IDentifier);
begin
if Assigned(FOnGetOwnerID) then
FOnGetOwnerID(AID);
end;
procedure TCompoPartDataFeederRW.DoOnSetOwnerID(var AID: IDentifier);
begin
if Assigned(FOnSetOwnerID) then
FOnSetOwnerID(AID);
end;
function TCompoPartDataFeederRW.GetOnGetOwnerID: TOnGetOwnerID;
begin
Result := FOnGetOwnerID;
end;
function TCompoPartDataFeederRW.GetOnSetOwnerID: TOnSetOwnerID;
begin
Result := FOnSetOwnerID;
end;
procedure TCompoPartDataFeederRW.SetOnGetOwnerID(const Value: TOnGetOwnerID);
begin
FOnGetOwnerID := Value;
end;
procedure TCompoPartDataFeederRW.SetOnSetOwnerID(const Value: TOnSetOwnerID);
begin
FOnSetOwnerID := Value;
end;
{ TdstrPair }
constructor TdstrPair.Create;
begin
inherited;
tr := dbmDental.CreateTr;
tr.StartTransaction;
ds := dbmDental.CreateDS;
ds.Transaction := tr;
ds.UpdateTransaction := tr;
end;
destructor TdstrPair.Destroy;
begin
if Assigned(ds) then
dbmDental.CloseDS(ds);
if Assigned(tr) then
dbmDental.CloseTr(tr);
inherited;
end;
{ TqtrPair }
constructor TqtrPair.Create;
begin
inherited;
tr := dbmDental.CreateTr;
tr.StartTransaction;
q := dbmDental.CreateQuery;
q.Transaction := tr;
end;
destructor TqtrPair.Destroy;
begin
if Assigned(q) then
dbmDental.CloseQ(q);
if Assigned(tr) then
dbmDental.CloseTr(tr);
inherited;
end;
end.
|
unit unfrInstrumentos;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TfrInstrumentos = class(TForm)
Label1: TLabel;
txtInstrumento: TEdit;
GroupBox1: TGroupBox;
Label2: TLabel;
mmoReuniaoJovensMenores: TMemo;
Label3: TLabel;
mmoCultoOficial: TMemo;
Label4: TLabel;
mmoOficializacao: TMemo;
Button1: TButton;
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frInstrumentos: TfrInstrumentos;
implementation
uses
unGlobal, unSQLS, undmBase, DB;
{$R *.dfm}
procedure TfrInstrumentos.FormShow(Sender: TObject);
begin
txtInstrumento.Text := '';
mmoReuniaoJovensMenores.Text := '';
mmoCultoOficial.Text := '';
mmoOficializacao.Text := '';
if self.Tag <> 0 then
begin
// Busca os dados do Ancião
dmBase.qrEmp.SQL.Text := SQL_SELECT_INSTRUMENT_BY_ID;
dmBase.qrEmp.Params[0].AsInteger := self.Tag;
dmBase.qrEmp.Open;
if not dmBase.qrEmp.IsEmpty then
begin
txtInstrumento.Text := dmBase.qrEmp.fieldbyname('name').AsString;
mmoReuniaoJovensMenores.Text := dmBase.qrEmp.fieldbyname('metodo_rjm').AsString;
mmoCultoOficial.Text := dmBase.qrEmp.fieldbyname('metodo_culto_oficial').AsString;
mmoOficializacao.Text := dmBase.qrEmp.fieldbyname('metodo_oficializacao').AsString;
end;
end;
end;
procedure TfrInstrumentos.Button1Click(Sender: TObject);
begin
// ---------------------------
// Validações
// ---------------------------
if txtInstrumento.Text = '' then
begin
Application.MessageBox('Por favor, digite o nome do instrumento.', PChar(Application.title), MB_OK + MB_ICONSTOP);
exit;
end;
if mmoReuniaoJovensMenores.Text = '' then
begin
Application.MessageBox('Por favor, preencha a sugestão de método para reunião de jovens e menores.', PChar(Application.title), MB_OK + MB_ICONSTOP);
mmoReuniaoJovensMenores.SetFocus();
exit;
end;
if mmoCultoOficial.Text = '' then
begin
Application.MessageBox('Por favor, preencha a sugestão de método para culto oficial.', PChar(Application.title), MB_OK + MB_ICONSTOP);
mmoCultoOficial.SetFocus();
exit;
end;
if mmoOficializacao.Text = '' then
begin
Application.MessageBox('Por favor, preencha a sugestão de método para oficialização.', PChar(Application.title), MB_OK + MB_ICONSTOP);
mmoOficializacao.SetFocus();
exit;
end;
// ---------------------------
// Grava/ Atualiza o registro no banco de dados
// ---------------------------
if self.Tag = 0 then
begin
dmBase.qrEmp.SQL.Text := SQL_INSERT_INSTRUMENT;
dmBase.qrEmp.Params[0].AsString := txtInstrumento.Text;
if mmoReuniaoJovensMenores.Text <> '' then dmBase.qrEmp.Params[1].AsString := mmoReuniaoJovensMenores.Text;
if mmoCultoOficial.Text <> '' then dmBase.qrEmp.Params[2].AsString := mmoCultoOficial.Text;
if mmoOficializacao.Text <> '' then dmBase.qrEmp.Params[3].AsString := mmoOficializacao.Text;
dmBase.qrEmp.ExecSQL;
end
else
begin
dmBase.qrEmp.SQL.Text := SQL_UPDATE_INSTRUMENT;
dmBase.qrEmp.Params[0].AsString := txtInstrumento.Text;
if mmoReuniaoJovensMenores.Text <> '' then dmBase.qrEmp.Params[1].AsString := mmoReuniaoJovensMenores.Text;
if mmoCultoOficial.Text <> '' then dmBase.qrEmp.Params[2].AsString := mmoCultoOficial.Text;
if mmoOficializacao.Text <> '' then dmBase.qrEmp.Params[3].AsString := mmoOficializacao.Text;
dmBase.qrEmp.Params[4].AsInteger := self.Tag;
dmBase.qrEmp.ExecSQL;
end;
//Application.MessageBox('Sucesso', PChar(Application.Title), MB_OK + MB_ICONINFORMATION);
Close();
end;
procedure TfrInstrumentos.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
IF Key = Vk_Escape then Close;
end;
end.
|
unit uLoginDao;
interface
uses uConexao,SysUtils,ZAbstractConnection, ZConnection, DB, ZAbstractRODataset,
ZAbstractDataset, ZDataset, uLoginModel;
type
TLoginDAO = class
private
FConn:TConexao;
public
constructor Create;
destructor Destroy; override;
function Logar(LoginModel:TLoginModel):Boolean;
end;
implementation
{ TLogin }
constructor TLoginDAO.Create;
begin
FConn := TConexao.Create;
end;
destructor TLoginDAO.Destroy;
begin
FreeAndNil(FConn);
inherited;
end;
function TLoginDAO.Logar(LoginModel:TLoginModel): Boolean;
var
Qry:TZQuery;
begin
Qry := FConn.CriaQuery;
try
Qry.Close;
Qry.SQL.Clear;
Qry.SQL.Add('select * from login where login = :log and senha = :pass');
Qry.ParamByName('log').AsString := LoginModel.Login;
Qry.ParamByName('pass').AsString := LoginModel.Senha;
Qry.Open;
Result := (Qry.RecordCount > 0);
finally
FreeAndNil(qry);
end;
end;
end.
|
unit qtxcomponent;
interface
uses
W3System;
type
(* Exception classes *)
EQTXException = Class(Exception);
EQTXNotImplemented = Class(EQTXException);
TQTXExceptionClass = Class of EQTXException;
(* Forward declarations *)
TQTXErrorObject = Class;
TQTXPersistent = Class;
TQTXComponent = Class;
TQTXHtmlElement = Class;
TQTXDelegate = Class;
TQTXControl = Class;
(* Standard datatype mapping *)
TDateTime = Float;
Real = Float;
Double = Float;
Extended = Float;
TColor = Integer;
THandle = Variant;
IQTXError = Interface
// function getUseException:Boolean;
// procedure setUseException(aValue:Boolean);
procedure setLastError(aValue:String);
function getLastError:String;
function getExceptionType:TQTXExceptionClass;
procedure clearLastError;
end;
IQTXPersistent = interface
function queryID: String;
function queryContent:Boolean;
function readContent:String;
procedure writeContent(aData:String);
end;
IQTXComponent = interface
function getChildCount:Integer;
function getChild(index:Integer):TQTXComponent;
function insertChild(const aInstance:TQTXComponent):Integer;
procedure removeChild(const aInstance:TQTXComponent);
Function indexOf(const aInstance:TQTXComponent):Integer;
function objectOf(aName:String):TQTXComponent;
end;
IQTXAttributeAccess = interface
function getAttribute(aName:String):variant;
procedure setAttribute(aName:String;aValue:Variant);
end;
IQTXHtmlElement = interface
function queryAttached:Boolean;
function getElementType:String;
procedure makeHandle;
procedure destroyHandle;
procedure attachTo(const aParent:TQTXHtmlElement);
Procedure detachFrom;
end;
IQTXParentContainer = interface
Procedure childInserted(aChild:TQTXHtmlElement);
Procedure childRemoved(aChild:TQTXHtmlElement);
end;
TQTXErrorObject = Class(TObject,IQTXError)
private
FLastError: String;
FUseException:Boolean;
protected
(* IMPLEMENTS:: IQTXError *)
procedure setLastError(aValue:String);
function getUseException:Boolean;
procedure setUseException(aValue:Boolean);
function getLastError:String;
function getExceptionType:TQTXExceptionClass;
procedure clearLastError;
(* Aux formated variation of setLastError *)
procedure setLastErrorF(aValue:String;
const aItems:Array of const);
Property UseException:Boolean read getUseException
write setUseException;
End;
TQTXPersistent = Class(TQTXErrorObject,IQTXPersistent)
protected
(* IMPLEMENTS:: IQTXPersistent *)
function QueryID: String;
function QueryContent:Boolean;
function ReadContent:String;
procedure WriteContent(aData:String);
public
Procedure Assign(aSource:TQTXPersistent);overload;
Procedure Assign(aSource:IQTXPersistent);overload;
end;
TQTXHtmlElement = Class(TQTXPersistent,IQTXHtmlElement,IQTXAttributeAccess)
private
FHandle: THandle;
FParent: TQTXHtmlElement;
protected
(* IMPLEMENTS:: IQTXHtmlElement *)
function queryAttached:Boolean;virtual;
function getElementType:String;virtual;
procedure makeHandle;virtual;
procedure destroyHandle;virtual;
procedure AttachTo(const aParent:TQTXHtmlElement);
Procedure DetachFrom;
(* IMPLEMENTS:: IQTXAttributeAccess *)
function getAttribute(aName:String):variant;
procedure setAttribute(aName:String;aValue:Variant);
protected
Procedure AfterCreateHandle;virtual;
Procedure BeforeDestroyHandle;virtual;
public
Property Handle:THandle read FHandle;
property Parent:TQTXHtmlElement read FParent;
end;
TQTXComponentState = set of (csCreating,csLoading,csDestroying);
TQTXComponent = Class(TQTXPersistent,IQTXParentContainer)
private
FChildren: Array of TQTXHtmlElement;
FState: TQTXComponentState;
FParent: TQTXComponent;
protected
Procedure ChildInserted(aChild:TQTXHtmlElement);
Procedure ChildRemoved(aChild:TQTXHtmlElement);
function getChildCount:Integer;
function getChild(index:Integer):TQTXHtmlElement;
public
Property ComponentState: TQTXComponentState read FState;
Property Parent:TQTXComponent read FParent;
Constructor Create(AOwner:TQTXComponent);virtual;
Destructor Destroy;Override;
end;
TQTXDelegateHandler = procedure (eventObj:TQTXDelegate);
TQTXDelegate = Class(TQTXPersistent)
private
FName: String;
FParent: TQTXControl;
FHandler: TQTXDelegateHandler;
protected
procedure Dispatch;
public
Property Parent:TQTXControl read FParent;
Property EventName:String read FName;
Property OnExecute:TQTXDelegateHandler
read FHandler write FHandler;
Constructor Create(AOwner:TQTXControl);virtual;
end;
TQTXDelegates = Class(TQTXPersistent)
private
FParent: TQTXControl;
FDelegates: Array of TQTXDelegate;
public
Property Count:Integer read ( FDelegates.Count );
Property Item[index:Integer]:TQTXDelegate
read ( FDelegates[index] );
function Add:TQTXDelegate;virtual;
Constructor Create(AOwner:TQTXControl);
Destructor Destroy;Override;
end;
TQTXControl = Class(TQTXComponent)
private
FDelegates: TQTXDelegates;
protected
protected
procedure Resize;virtual;
Procedure Paint;virtual;
public
Property Delegates:TQTXDelegates read FDelegates;
Property Child[index:Integer]:TQTXHtmlElement
read ( getChild(index) );
Property ChildCount:Integer read getChildCount;
Procedure Invalidate;
Constructor Create(AOwner:TQTXControl);override;
Destructor Destroy;Override;
End;
implementation
const
CNT_QTX_NODATA = '';
resourcestring
CNT_QTX_NOTIMPLEMENTED = 'Method not implemented error';
CNT_QTX_FailedCreateElement = 'Failed to create HTML element: %s';
//############################################################################
// TQTXControl
//############################################################################
Constructor TQTXControl.Create(AOwner:TQTXControl);
Begin
inherited Create(AOwner);
FDelegates:=TQTXDelegates.Create(self);
end;
Destructor TQTXControl.Destroy;
Begin
FDelegates.free;
inherited;
end;
Procedure TQTXControl.Invalidate;
Begin
(* if not (csDestroying in ComponentState) then
TQTXRuntime.delayedDispatch( procedure ()
Begin
Paint;
end,
50); *)
end;
procedure TQTXControl.Resize;
begin
end;
Procedure TQTXControl.Paint;
Begin
end;
//############################################################################
// TQTXDelegates
//############################################################################
Constructor TQTXDelegates.Create(AOwner:TQTXControl);
Begin
inherited Create;
FParent:=AOwner;
end;
Destructor TQTXDelegates.Destroy;
var
x: Integer;
Begin
if FDelegates.Count>0 then
begin
for x:=FDelegates.low to FDelegates.high do
FDelegates[x].free;
end;
inherited;
end;
function TQTXDelegates.Add:TQTXDelegate;
begin
result:=TQTXDelegate.Create(FParent);
FDelegates.add(result);
end;
//############################################################################
// TQTXDelegate
//############################################################################
Constructor TQTXDelegate.Create(AOwner:TQTXControl);
Begin
inherited Create;
FParent:=AOwner;
end;
procedure TQTXDelegate.Dispatch;
Begin
if assigned(FHandler) then
FHandler(self);
end;
//############################################################################
// TQTXComponent
//############################################################################
Constructor TQTXComponent.Create(AOwner:TQTXComponent);
Begin
inherited Create;
FParent:=AOwner;
end;
Destructor TQTXComponent.Destroy;
var
x: Integer;
Begin
include(FState,csDestroying);
if FChildren.Count>0 then
begin
try
for x:=FChildren.low to FChildren.high do
FChildren[x].free;
finally
FChildren.clear;
end;
end;
inherited;
end;
Procedure TQTXComponent.ChildInserted(aChild:TQTXHtmlElement);
begin
if assigned(aChild) then
begin
if FChildren.indexOf(aChild)<0 then
begin
FChildren.add(aChild);
end;
end;
end;
Procedure TQTXComponent.ChildRemoved(aChild:TQTXHtmlElement);
var
mIndex: Integer;
begin
if not (csDestroying in ComponentState) then
Begin
if assigned(aChild) then
begin
mIndex:=FChildren.indexOf(aChild);
if mIndex>=0 then
FChildren.delete(mIndex,1);
end;
end;
end;
function TQTXComponent.getChildCount:Integer;
begin
result:=FChildren.Count;
end;
function TQTXComponent.getChild(index:Integer):TQTXHtmlElement;
begin
result:=FChildren[index];
end;
//############################################################################
// TQTXHtmlElement
//############################################################################
function TQTXHtmlElement.getAttribute(aName:String):variant;
Begin
result:=null;
end;
procedure TQTXHtmlElement.setAttribute(aName:String;aValue:Variant);
Begin
end;
function TQTXHtmlElement.getElementType:String;
Begin
result:='div';
end;
procedure TQTXHtmlElement.makeHandle;
var
mRef: THandle;
mObj: String;
begin
try
try
mObj:=getElementType;
asm
@mRef = document.createElement(@mObj);
end;
except
on e: exception do
setLastErrorF(CNT_QTX_FailedCreateElement,[e.message]);
end;
FHandle:=mRef;
finally
AfterCreateHandle;
end;
end;
procedure TQTXHtmlElement.destroyHandle;
begin
if (FHandle) then
begin
try
BeforeDestroyHandle;
if queryAttached then
DetachFrom;
//if (FHandle.parentNode) then
//FHandle.parentNode.removeChild(FHandle);
finally
FHandle:=null;
FParent:=NIL;
end;
end;
end;
Procedure TQTXHtmlElement.AfterCreateHandle;
begin
end;
Procedure TQTXHtmlElement.BeforeDestroyHandle;
Begin
end;
function TQTXHtmlElement.queryAttached:Boolean;
Begin
if (FHandle) then
result:=(FHandle.parentNode);
end;
procedure TQTXHtmlElement.AttachTo(const aParent:TQTXHtmlElement);
var
mAccess: IQTXParentContainer;
begin
if (FHandle) then
Begin
(* Detach if already attached to an element *)
if (FHandle.parentNode) then
detachFrom;
(* set new parent object *)
FParent:=aParent;
(* attach to new parent handle *)
if FParent<>NIl then
FHandle.parentNode := aParent.Handle;
mAccess:=(aParent as IQTXParentContainer);
if mAccess<>NIL then
mAccess.ChildInserted(self);
end;
end;
Procedure TQTXHtmlElement.DetachFrom;
var
mAccess: IQTXParentContainer;
Begin
if (FHandle) then
Begin
if (FHandle.parentNode) then
FHandle.parentNode.removeChild(FHandle);
if assigned(FParent) then
begin
mAccess:=(FParent as IQTXParentContainer);
if mAccess<>NIL then
mAccess.ChildRemoved(self);
end;
FParent:=NIL;
end;
end;
//############################################################################
// TQTXPersistent
//############################################################################
Procedure TQTXPersistent.Assign(aSource:TQTXPersistent);
Begin
if assigned(aSource) then
Begin
if aSource.QueryContent then
WriteContent(aSource.ReadContent) else
WriteContent(CNT_QTX_NODATA);
end else
WriteContent(CNT_QTX_NODATA);
end;
Procedure TQTXPersistent.Assign(aSource:IQTXPersistent);
Begin
if assigned(aSource) then
begin
if aSource.QueryContent then
writeContent(aSource.ReadContent) else
writeContent(CNT_QTX_NODATA);
end else
WriteContent(CNT_QTX_NODATA);
end;
function TQTXPersistent.QueryID:String;
Begin
result:=className;
end;
function TQTXPersistent.QueryContent:Boolean;
begin
result:=False;
end;
function TQTXPersistent.ReadContent:String;
begin
result:=CNT_QTX_NODATA;
setLastError(CNT_QTX_NOTIMPLEMENTED);
end;
procedure TQTXPersistent.WriteContent(aData:String);
begin
end;
//############################################################################
// TQTXErrorObject
//############################################################################
function TQTXErrorObject.getUseException:Boolean;
Begin
result:=FUseException;
end;
procedure TQTXErrorObject.setUseException(aValue:Boolean);
Begin
FUseException:=aValue;
end;
function TQTXErrorObject.getExceptionType:TQTXExceptionClass;
Begin
result:=EQTXException;
end;
procedure TQTXErrorObject.setLastError(aValue:String);
begin
FLastError:=trim(aValue);
if getUseException then
raise getExceptionType.Create(FLastError);
end;
procedure TQTXErrorObject.setLastErrorF(aValue:String;
const aItems:Array of const);
begin
setLastError(Format(aValue,aItems));
end;
function TQTXErrorObject.getLastError:String;
Begin
result:=FLastError;
end;
procedure TQTXErrorObject.clearLastError;
Begin
FLastError:='';
end;
end.
|
{
Treat the challenging_spell_learning.esp as a dynamic patch file which can be updated based on all loaded mods.
Just run this script and magic happens.
Tomes updated will be listed in the Messages tab with ---------------------------------------- prefixed to make spotting errors easier.
}
unit CSL_Patch_Update;
// Find the challenging_spell_learning.esp file in the loaded plugins list and return its index
function IndexOfValidatedTIM(): integer;
var
CSL: integer;
j: integer;
i: integer;
f: IInterface;
g: IInterface;
begin
for CSL := FileCount - 1 downto 0 do
if GetFileName(FileByIndex(CSL)) = 'Transmundane.esp' then break;
if CSL = 0 then
raise Exception.Create('Transmundane.esp must be loaded!');
for j := FileCount - 1 downto CSL + 1 do begin
f := FileByIndex(j);
g := GroupBySignature(f, 'BOOK');
if not Assigned(g) then continue;
for i := ElementCount(g) - 1 downto 0 do
if Assigned(ElementByPath(ElementByIndex(g, i), 'DATA\Spell')) then
raise Exception.Create('Transmundane.esp must load after other plugins containing spell tomes!');
end;
Result := CSL;
end;
// Remove existing books from patch and then insert all spell tomes found in the other plugins
procedure AddTomesToPatch(CSLfile: IInterface; CSLindex: integer);
var
j: integer;
i: integer;
f: IInterface;
g: IInterface;
e: IInterface;
begin
//if Assigned(GroupBySignature(CSLfile, 'BOOK')) then
// RemoveNode(GroupBySignature(CSLfile, 'BOOK'));
for j := CSLindex - 1 downto 0 do begin
f := FileByIndex(j);
g := GroupBySignature(f, 'BOOK');
if not Assigned(g) then continue;
for i := ElementCount(g) - 1 downto 0 do begin
e := ElementByIndex(g, i);
if Assigned(ElementByPath(e, 'DATA\Spell')) then begin
AddRequiredElementMasters(e, CSLfile, False);
wbCopyElementToFile(e, CSLfile, False, True);
end;
end;
end;
end;
// Find a usable spell description from the spell or one of its magic effects.
function FindSpellDescription(spell: IInterface): string;
var
i: integer;
best: string;
d: string;
e: IInterface;
mag: string;
dur: string;
begin
best := GetEditValue(ElementByPath(spell, 'DESC')); // use the spell's description if it exists
if best = '' then begin // otherwise search through the spell effects for a good desription
e := ElementByPath(spell, 'Effects');
for i := ElementCount(e) - 1 downto 0 do begin
mag := GetNativeValue(ElementByPath(ElementByIndex(e,i), 'EFIT\Magnitude'));
dur := GetNativeValue(ElementByPath(ElementByIndex(e,i), 'EFIT\Duration'));
d := GetEditValue(ElementByPath(WinningOverride(LinksTo(ElementByPath(ElementByIndex(e,i), 'EFID'))), 'DNAM'));
d := StringReplace(d, '<mag>', mag, [rfReplaceAll, rfIgnoreCase]);
d := StringReplace(d, '<dur>', dur, [rfReplaceAll, rfIgnoreCase]);
if (d <> '') and (d <> ' ') then
best := d;
end;
end;
best := StringReplace(best, '<', '', [rfReplaceAll, rfIgnoreCase]);
best := StringReplace(best, '>', '', [rfReplaceAll, rfIgnoreCase]);
if best = '' then
AddMessage('No spell description found for ' + Name(spell));
Result := best;
end;
// Find the list of scripts in a VMAD record.
function FindScripts(VMAD: IInterface): IInterface;
begin
if Assigned(ElementByPath(VMAD, 'Scripts')) then // different paths for different versions of xEdit!
Result := ElementByPath(VMAD, 'Scripts')
else
Result := ElementByPath(VMAD, 'Data\Scripts');
end;
// Find the CSL script in the VMAD record.
function FindLearningScript(VMAD: IInterface): IInterface;
var
i: integer;
scripts: IInterface;
begin
scripts := FindScripts(VMAD);
for i := ElementCount(scripts) - 1 downto 0 do
if GetEditValue(ElementByPath(ElementByIndex(scripts,i), 'scriptName')) = 'csl_sparks_script' then
Result := ElementByIndex(scripts, i);
end;
// Find the LearnedSpell property in the script.
function FindSpellProperty(script: IInterface): IInterface;
var
i: integer;
begin
script := ElementByPath(script, 'Properties');
for i := ElementCount(script) - 1 downto 0 do
if GetEditValue(ElementByPath(ElementByIndex(script,i), 'propertyName')) = 'LearnedSpell' then
Result := ElementByPath(ElementByIndex(script,i), 'Value\Object Union\Object v2\FormID');
end;
// Copy the CLS script into the spell tome then move the spell to the LearnedSpell property and clear the Teaches Spell flag on the tome.
procedure TransferSpellToLearningScript(e, spell, VMAD: IInterface);
var
i: integer;
learningScript: IInterface;
prop: IInterface;
begin
// Copy just the spell learning script or the entire VMAD record
if ElementExists(e, 'VMAD') then begin
AddMessage('Pre-existing script on spell tome ' + Name(e) + ' attempting to copy learning script.');
learningScript := FindLearningScript(ElementByPath(e, 'VMAD'));
if not Assigned(learningScript) then
ElementAssign(FindScripts(ElementByPath(e, 'VMAD')), HighInteger, FindLearningScript(VMAD), False);
end
else begin
Add(e, 'VMAD', true);
ElementAssign(ElementByPath(e, 'VMAD'), LowInteger, VMAD, False); // copy entire VMAD record
end
// Find and fill the LearnedSpell property with the actual spell entry
learningScript := FindLearningScript(ElementByPath(e, 'VMAD'));
if not Assigned(learningScript) then begin AddMessage('Missing csl_sparks_script for ' + Name(e)); Exit; end;
prop := FindSpellProperty(learningScript);
if not Assigned(prop) then begin AddMessage('Missing critical LearnedSpell property for ' + Name(e)); Exit; end;
SetEditValue(prop, Name(spell));
// Clear the Teaches Spell flag and Spell/Skill fields for the new scripted spell tome
SetNativeValue(ElementByPath(e, 'DATA\Flags'), 0);
SetEditValue(ElementByPath(e, 'DATA\Skill'), 'None');
end;
// Main function (in Finalize because it needs to run after "Process" to avoid UI errors).
function Finalize: integer;
var
i: integer;
e: IInterface;
desc: string;
spell: IInterface;
CSLindex: integer;
CSLfile: IInterface;
VMAD: IInterface;
BOOKS: IInterface;
begin
// Find the patch file and its place in the load order
CSLindex := IndexOfValidatedTIM();
CSLfile := FileByIndex(CSLindex);
// Find the script element that needs to be copied into each spell tome
VMAD := ElementByPath(ElementByIndex(GroupBySignature(CSLfile, 'MISC'),0), 'VMAD');
if not Assigned(VMAD) then
raise Exception.Create('Can not locate the script holder script information!');
// Remove existing books from patch then add spell tomes from all plugins lower in load order.
AddTomesToPatch(CSLfile, CSLIndex);
// Now update all of the added spell tomes
BOOKS := GroupBySignature(CSLfile, 'BOOK');
for i := ElementCount(BOOKS) - 1 downto 0 do begin
e := ElementByIndex(BOOKS, i);
AddMessage('----------------------------------------' + Name(e));
// Get the spell the tome teaches and assign it to the script property
spell := LinksTo(ElementByPath(e, 'DATA\Spell'));
if not Assigned(spell) then begin AddMessage('No spell associated with tome ' + Name(e)); continue; end; // Should not be possible!
TransferSpellToLearningScript(e, spell, VMAD);
// Copy the spell information into an additional page of the spell tome (preserving any existing text for spell mods that already had interesting text)
SetEditValue(ElementByPath(e, 'DESC'), GetEditValue(ElementByPath(e, 'DESC')) + ' [pagebreak] <font face''$HandwrittenFont''><font size=''30''><p align=''center''>' + GetEditValue(ElementByPath(spell, 'FULL')));
// Now use the spell description (possibly from its effects) to fill the tome description and add that to the tome text as well.
desc := FindSpellDescription(spell);
SetEditValue(ElementByPath(e, 'CNAM'), desc);
SetEditValue(ElementByPath(e, 'DESC'), GetEditValue(ElementByPath(e, 'DESC')) + '<font size=''20''><p><p align=''left''>' + desc);
// Some books have all zeros for object bounds, so set those to the book default
if (GetEditValue(ElementByPath(e, 'OBND\X1')) = '0') and (GetEditValue(ElementByPath(e, 'OBND\X2')) = '0') then
ElementAssign(ElementByPath(e, 'OBND'), LowInteger, ElementByPath(ElementByIndex(GroupBySignature(CSLfile, 'MISC'),0), 'OBND'), False);
end;
// A little housekeeping
SortMasters(CSLfile);
CleanMasters(CSLfile);
RemoveFilter; // force interface to collapse records to avoid a UI error
end;
end.
|
unit AT.Vcl.DX.SpreadSheet.ActionsStrs;
interface
resourcestring
sATdxSpreadSheetActionNumberGeneralCaption = 'General';
sATdxSpreadSheetActionNumberGeneralHint = 'General|No specific format';
sATdxSpreadSheetActionNumberNumberCaption = 'Number';
sATdxSpreadSheetActionNumberNumberHint = 'Number';
sATdxSpreadSheetActionNumberCurrencyCaption = 'Currency';
sATdxSpreadSheetActionNumberCurrencyHint = 'Currency';
sATdxSpreadSheetActionNumberAccountingCaption = 'Accounting';
sATdxSpreadSheetActionNumberAccountingHint = 'Accounting';
sATdxSpreadSheetActionNumberDateCaption = 'Date';
sATdxSpreadSheetActionNumberDateHint = 'Date';
sATdxSpreadSheetActionNumberTimeCaption = 'Time';
sATdxSpreadSheetActionNumberTimeHint = 'Time';
sATdxSpreadSheetActionNumberPercentCaption = 'Percentage';
sATdxSpreadSheetActionNumberPercentHint = 'Percentage';
sATdxSpreadSheetActionNumberFractionCaption = 'Fraction';
sATdxSpreadSheetActionNumberFractionHint = 'Fraction';
sATdxSpreadSheetActionNumberScientificCaption = 'Scientific';
sATdxSpreadSheetActionNumberScientificHint = 'Scientific';
sATdxSpreadSheetActionNumberTextCaption = 'Text';
sATdxSpreadSheetActionNumberTextHint = 'Text';
sATdxSpreadSheetActionNumberDialogCaption = 'Number Format';
sATdxSpreadSheetActionNumberDialogHint = 'Number Format';
sATdxSpreadSheetActionAlignDialogCaption = 'Alignment Settings';
sATdxSpreadSheetActionAlignDialogHint = 'Alignment Settings';
sATdxSpreadSheetActionFontDialogCaption = 'Font Settings';
sATdxSpreadSheetActionFontDialogHint = 'Font Settings';
sATdxSpreadSheetActionFillDialogCaption = 'Fill Settings';
sATdxSpreadSheetActionFillDialogHint = 'Fill Settings';
sATdxSpreadSheetActionCellProtectDialogCaption = 'Cell Protection';
sATdxSpreadSheetActionCellProtectDialogHint = 'Cell Protection';
sATdxSpreadSheetActionInsertCellsCaption = 'Insert Cells...';
sATdxSpreadSheetActionInsertCellsHint = 'Insert Cells';
sATdxSpreadSheetActionDeleteCellsCaption = 'Delete Cells...';
sATdxSpreadSheetActionDeleteCellsHint = 'Delete Cells';
sATdxSpreadSheetActionLockCellsCaption = 'Lock Cell';
sATdxSpreadSheetActionLockCellsHint = 'Lock Cell';
sATdxSpreadSheetActionProtectSheetCaption = 'Protect Sheet';
sATdxSpreadSheetActionProtectWorkbookCaption = 'Protect Workbook';
sATdxSpreadSheetActionUnprotectSheetCaption = 'Unprotect Sheet';
sATdxSpreadSheetActionUnprotectWorkbookCaption = 'Unprotect Workbook';
sATdxSpreadSheetActionClearCommentsCaption = 'Clear Comments';
sATdxSpreadSheetActionClearCommentsHint = 'Clear Comments';
sATdxSpreadSheetActionSelectAllCaption = 'Select All';
sATdxSpreadSheetActionSelectAllHint = 'Select All';
sATdxSpreadSheetActionSelectNoneCaption = 'Select None';
sATdxSpreadSheetActionSelectNoneHint = 'Select None';
sATdxSpreadSheetActionInsertFunctionCaption = 'Insert Function';
sATdxSpreadSheetActionInsertFunctionHint = 'Insert Function';
sATdxSpreadSheetActionPasteSpecialCaption = 'Paste Special';
sATdxSpreadSheetActionPasteSpecialHint = 'Paste Special';
sATdxSpreadSheetActionRenameSheetCaption = 'Rename Sheet';
sATdxSpreadSheetActionRenameSheetHint = 'Rename Sheet';
sATdxSpreadSheetActionInsertTextBoxCaption = 'New Text Box';
sATdxSpreadSheetActionInsertTextBoxHint = 'New Text Box';
sATdxSpreadSheetActionEditTextBoxCaption = 'Edit Text Box';
sATdxSpreadSheetActionEditTextBoxHint = 'Edit Text Box';
sATdxSpreadSheetActionInsertShapeCaption = 'New Shape';
sATdxSpreadSheetActionInsertShapeHint = 'New Shape';
sATdxSpreadSheetActionEditShapeCaption = 'Edit Shape';
sATdxSpreadSheetActionEditShapeHint = 'Edit Shape';
sATdxSpreadSheetActionInsertPictureCaption = 'New Picture';
sATdxSpreadSheetActionInsertPictureHint = 'New Picture';
sATdxSpreadSheetActionEditPictureCaption = 'Edit Picture';
sATdxSpreadSheetActionEditPictureHint = 'Edit Picture';
sATdxSpreadSheetActionGridlinesPrintCaption = 'Print';
sATdxSpreadSheetActionGridlinesPrintHint = 'Print Grid Lines';
sATdxSpreadSheetActionGridlinesViewCaption = 'View';
sATdxSpreadSheetActionGridlinesViewHint = 'View Grid Lines';
sATdxSpreadSheetActionHeadingsPrintCaption = 'Print';
sATdxSpreadSheetActionHeadingsPrintHint = 'Print Headings';
sATdxSpreadSheetActionHeadingsViewCaption = 'View';
sATdxSpreadSheetActionHeadingsViewHint = 'View Headings';
sATdxSpreadSheetActionShowFormulasCaption = 'Show Formulas';
sATdxSpreadSheetActionShowFormulasHint = 'Show Formulas';
sATdxSpreadSheetActionAutoCalcCaption = 'Automatic Calculation';
sATdxSpreadSheetActionAutoCalcHint = 'Automatic Calculation';
sATdxSpreadSheetActionCalcStatusCaption = 'Calculating';
sATdxSpreadSheetActionCalcStatusHint = 'Calculating';
sATdxSpreadSheetActionCalcNowCaption = 'Calculate Now';
sATdxSpreadSheetActionCalcNowHint = 'Calculate Now';
sATdxtActionInsertTextBox = 'Insert Text Box';
sATdxtActionEditTextBox = 'Edit Text Box';
sATdxtActionInsertShape = 'Insert Shape';
sATdxtActionEditShape = 'Edit Shape';
sATdxtActionInsertPicture = 'Insert Picture';
sATdxtActionEditPicture = 'Edit Picture';
sATdxActionInsertPictureDlgCaption = 'Insert Picture';
implementation
end.
|
unit uTestWriteRead;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, umap, umodbus, fpcunit, testregistry, Windows;
type
{ TTestWriteRead }
TTestWriteRead= class(TTestCase)
published
procedure TestUInt8h;
procedure TestUInt8hMin;
procedure TestUInt8hMax;
procedure TestUInt8l;
procedure TestUInt8lMin;
procedure TestUInt8lMax;
procedure TestUInt16;
procedure TestUInt16Min;
procedure TestUInt16Max;
procedure TestUInt32;
procedure TestUInt32Min;
procedure TestUInt32Max;
procedure TestSInt16;
procedure TestSInt16Min;
procedure TestSInt16Max;
procedure TestSInt32;
procedure TestSInt32Min;
procedure TestSInt32Max;
procedure TestSInt16_;
procedure TestSInt32_;
procedure TestFloat;
procedure TestMulti10;
procedure TestMulti100;
procedure TestMulti1000;
procedure TestMulti10000;
procedure TestMulti100000;
procedure TestMulti10_;
procedure TestMulti100_;
procedure TestMulti1000_;
procedure TestMulti10000_;
procedure TestMulti100000_;
end;
implementation
var
Controller: IController;
Map: IMap;
{ TTestWriteRead }
procedure TTestWriteRead.TestUInt8h;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: Byte = $12;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: Byte;
begin
Writeln('------------ UInt8h ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue shl 8, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint8h(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt8hMin;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: Byte = $0;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: Byte;
begin
Writeln('------------ UInt8hMin ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue shl 8, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint8h(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt8hMax;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: Byte = $FF;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: Byte;
begin
Writeln('------------ UInt8hMax ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue shl 8, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint8h(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt8l;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: Byte = $34;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: Byte;
begin
Writeln('------------ UInt8l ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint8l(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt8lMin;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: Byte = $0;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: Byte;
begin
Writeln('------------ UInt8lMin ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint8l(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt8lMax;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: Byte = $FF;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: Byte;
begin
Writeln('------------ UInt8lMax ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint8l(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt16;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: Word = $1234;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: Word;
begin
Writeln('------------ UInt16 ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint16(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt16Min;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: Word = $0;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: Word;
begin
Writeln('------------ UInt16Min ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint16(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt16Max;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: Word = $FFFF;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: Word;
begin
Writeln('------------ UInt16Max ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint16(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt32;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: DWord = $12345678;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: DWord;
begin
Writeln('------------ UInt32 ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint32(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt32Min;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: DWord = $0;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: DWord;
begin
Writeln('------------ UInt32Min ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint32(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestUInt32Max;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: DWord = $FFFFFFFF;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: DWord;
begin
Writeln('------------ UInt32Max ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadUint32(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestSInt16;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: SmallInt = $1234;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: SmallInt;
begin
Writeln('------------ SInt16 ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt16(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestSInt16_;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: SmallInt = $D678;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: SmallInt;
begin
Writeln('------------ SInt16_ -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt16(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Format('Value %d', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestSInt16Min;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: SmallInt = -32768;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: SmallInt;
begin
Writeln('------------ SInt16Min ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt16(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestSInt16Max;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 1;
TestValue: SmallInt = 32767;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: SmallInt;
begin
Writeln('------------ SInt16Max ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt16(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestSInt32;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: LongInt = $12345678;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: LongInt;
begin
Writeln('------------ SInt32 ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestSInt32_;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: LongInt = $8044812D;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: LongInt;
begin
Writeln('------------ SInt32_ -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Format('Value %d', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestSInt32Min;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: LongInt = -2147483648;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: LongInt;
begin
Writeln('------------ SInt32Min ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestSInt32Max;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: LongInt = 2147483647;
FormatStr = 'Value: 0x%x';
var
Frame: IFrame;
ReturnValue: LongInt;
begin
Writeln('------------ SInt32Max ------------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, TestValue, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format(FormatStr, [TestValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format(FormatStr, [ReturnValue]));
Writeln(Format('Value %d', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestFloat;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = 3.1415266;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ Float -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(TestValue), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %.5f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadFloat(TTypeTable.ttHolding, OffSet);
Writeln('READ');
Writeln(Format('Value %.5f', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestMulti10;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = 123.4;
Multipler: DWord = 10;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ SInt32 / 10 -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(Round(TestValue * Multipler)), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet, Multipler);
Writeln('READ');
Writeln(Format('Value %f', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestMulti100;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = 123.45;
Multipler: DWord = 100;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ SInt32 / 100 -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(Round(TestValue * Multipler)), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet, Multipler);
Writeln('READ');
Writeln(Format('Value %f', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestMulti1000;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = 123.456;
Multipler: DWord = 1000;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ SInt32 / 1000 -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(Round(TestValue * Multipler)), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %.3f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet, Multipler);
Writeln('READ');
Writeln(Format('Value %.3f', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestMulti10000;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = 123.4567;
Multipler: DWord = 10000;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ SInt32 / 10000 -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(Round(TestValue * Multipler)), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %.4f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet, Multipler);
Writeln('READ');
Writeln(Format('Value %.4f', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestMulti100000;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = 123.45678;
Multipler: DWord = 100000;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ SInt32 / 100000 -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(Round(TestValue * Multipler)), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %.5f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet, Multipler);
Writeln('READ');
Writeln(Format('Value %.5f', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestMulti10_;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = -123.4;
Multipler: DWord = 10;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ SInt32_ / 10 -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(Round(TestValue * Multipler)), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet, Multipler);
Writeln('READ');
Writeln(Format('Value %f', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestMulti100_;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = -123.45;
Multipler: DWord = 100;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ SInt32_ / 100 -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(Round(TestValue * Multipler)), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet, Multipler);
Writeln('READ');
Writeln(Format('Value %f', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestMulti1000_;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = -123.456;
Multipler: DWord = 1000;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ SInt32_ / 1000 -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(Round(TestValue * Multipler)), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %.3f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet, Multipler);
Writeln('READ');
Writeln(Format('Value %.3f', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestMulti10000_;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = -123.4567;
Multipler: DWord = 10000;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ SInt32_ / 10000 -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(Round(TestValue * Multipler)), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %.4f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet, Multipler);
Writeln('READ');
Writeln(Format('Value %.4f', [ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
procedure TTestWriteRead.TestMulti100000_;
const
OffSet: Word = 0;
SlaveId: Byte = 1;
RegCount: Word = 2;
TestValue: Single = -123.45678;
Multipler: DWord = 100000;
var
Frame: IFrame;
ReturnValue: Single;
begin
Writeln('------------ SInt32_ / 100000 -----------');
Frame := WriteMultiple(SlaveId, OffSet, RegCount, DWord(Round(TestValue * Multipler)), 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Writeln('WRITE');
Writeln(Format('Value %.5f', [TestValue]));
Writeln(Utf8Decode(Frame.ToString));
Frame := ReadHolding(SlaveId, OffSet, RegCount, 300);
AssertTrue(Controller.InQueue(Frame));
AssertTrue(Frame.Responded);
Map.WriteData(OffSet, Frame.ResponsePdu);
ReturnValue := Map.ReadSUInt32(TTypeTable.ttHolding, OffSet, Multipler);
Writeln('READ');
Writeln(Format('Value %.5f', [ReturnValue]));
Writeln(Format('Value %.*f', [4, ReturnValue]));
Writeln(Utf8Decode(Frame.ToString));
AssertEquals(TestValue, ReTurnValue);
end;
initialization
SetConsoleCp(1251);
SetConsoleOutputCP(1251);
// Controller := GetRtuBuilder.GetController('COM3', 19200, 2, 0, 8, 30);
Controller := GetTcpBuilder.GetController('192.168.0.166', 502);
Controller.Open;
Map := GetMap;
RegisterTest(TTestWriteRead);
end.
|
unit Dragon;
{$mode objfpc}{$H+}
interface
uses
Classes, DragonHeatshield, DragonPressurizedCapsule, DragonThrusters,
DragonTrunk, MassInfo, SizeInfo, SysUtils, VolumeInfo, BaseModel;
type
{ IBaseDragon }
IBaseDragon = interface(IBaseModel) ['{B25B729F-DAA4-4ECD-8F2F-7297EDA11B28}']
function GetActive: Boolean;
function GetCrewCapacity: Byte;
function GetDescription: string;
function GetDiameter: ISizeInfo;
function GetDryMassKilograms: Double;
function GetDryMassPounds: Double;
function GetFirstFlight: TDateTime;
function GetFlickrImages: TStringList;
function GetHeatShield: IDragonHeatshield;
function GetHeightWithTrunk: ISizeInfo;
function GetId: string;
function GetLaunchPayloadMass: IMassInfo;
function GetLaunchPayloadVolume: IVolumeInfo;
function GetName: string;
function GetOrbitDurationYears: LongWord;
function GetPressurizedCapsule: IDragonPressurizedCapsule;
function GetReturnPayloadMass: IMassInfo;
function GetReturnPayloadVolume: IVolumeInfo;
function GetSidewallAngleDegress: LongWord;
function GetThrusters: IDragonThrustersList;
function GetTrunk: IDragonTrunk;
function GetTypeInfo: string;
function GetWikipedia: string;
procedure SetActive(AValue: Boolean);
procedure SetCrewCapacity(AValue: Byte);
procedure SetDescription(AValue: string);
procedure SetDiameter(AValue: ISizeInfo);
procedure SetDryMassKilograms(AValue: Double);
procedure SetDryMassPounds(AValue: Double);
procedure SetFirstFlight(AValue: TDateTime);
procedure SetFlickrImages(AValue: TStringList);
procedure SetHeatShield(AValue: IDragonHeatshield);
procedure SetHeightWithTrunk(AValue: ISizeInfo);
procedure SetId(AValue: string);
procedure SetLaunchPayloadMass(AValue: IMassInfo);
procedure SetLaunchPayloadVolume(AValue: IVolumeInfo);
procedure SetName(AValue: string);
procedure SetOrbitDurationYears(AValue: LongWord);
procedure SetPressurizedCapsule(AValue: IDragonPressurizedCapsule);
procedure SetReturnPayloadMass(AValue: IMassInfo);
procedure SetReturnPayloadVolume(AValue: IVolumeInfo);
procedure SetSidewallAngleDegress(AValue: LongWord);
procedure SetThrusters(AValue: IDragonThrustersList);
procedure SetTrunk(AValue: IDragonTrunk);
procedure SetTypeInfo(AValue: string);
procedure SetWikipedia(AValue: string);
end;
{ IDragon }
IDragon = interface(IBaseDragon) ['{EEEAFF17-37AF-49EB-A43A-59C92343C4E0}']
property Active: Boolean read GetActive write SetActive;
property CrewCapacity: Byte read GetCrewCapacity write SetCrewCapacity;
property Description: string read GetDescription write SetDescription;
property Diameter: ISizeInfo read GetDiameter write SetDiameter; // need to define sizeinfo object
property DryMassKilograms: Double read GetDryMassKilograms write SetDryMassKilograms;
property DryMassPounds: Double read GetDryMassPounds write SetDryMassPounds;
property FirstFlight: TDateTime read GetFirstFlight write SetFirstFlight;
property FlickrImages: TStringList read GetFlickrImages write SetFlickrImages;
property HeatShield: IDragonHeatshield read GetHeatShield write SetHeatShield;
property HeightWithTrunk: ISizeInfo read GetHeightWithTrunk write SetHeightWithTrunk;
property Id: string read GetId write SetId;
property LaunchPayloadMass: IMassInfo read GetLaunchPayloadMass write SetLaunchPayloadMass;
property LaunchPayloadVolume: IVolumeInfo read GetLaunchPayloadVolume write SetLaunchPayloadVolume;
property Name: string read GetName write SetName;
property OrbitDurationYears: LongWord read GetOrbitDurationYears write SetOrbitDurationYears;
property PressurizedCapsule: IDragonPressurizedCapsule read GetPressurizedCapsule write SetPressurizedCapsule;
property ReturnPayloadMass: IMassInfo read GetReturnPayloadMass write SetReturnPayloadMass;
property ReturnPayloadVolume: IVolumeInfo read GetReturnPayloadVolume write SetReturnPayloadVolume;
property SidewallAngleDegress: LongWord read GetSidewallAngleDegress write SetSidewallAngleDegress;
property Thrusters: IDragonThrustersList read GetThrusters write SetThrusters;
property Trunk: IDragonTrunk read GetTrunk write SetTrunk;
property TypeInfo: string read GetTypeInfo write SetTypeInfo; // Type is a reserved word in pascal
property Wikipedia: string read GetWikipedia write SetWikipedia;
end;
{ IDragonList }
IDragonList = interface(IBaseModelList) ['{D4C2474C-5CCF-4C67-BB86-3F3B3F15A91F}']
end;
{ TDragonEnumerator }
TDragonEnumerator = class(TBaseModelEnumerator)
function GetCurrent: IDragon;
property Current : IDragon read GetCurrent;
end;
function NewDragon: IDragon;
function NewDragonList: IDragonList;
operator enumerator(AList: IDragonList): TDragonEnumerator;
implementation
uses
Variants, JSON_Helper;
type
{ TDragon }
TDragon = class(TBaseModel, IDragon)
private
FActive: Boolean;
FCrewCapacity: Byte;
FDescription: string;
FDiameter: ISizeInfo;
FDryMassKilograms: Double;
FDryMassPounds: Double;
FFirstFlight: TDateTime;
FFlickrImages: TStringList;
FHeatShield: IDragonHeatshield;
FHeightWithTrunk: ISizeInfo;
FId: string;
FLaunchPayloadMass: IMassInfo;
FLaunchPayloadVolume: IVolumeInfo;
FName: string;
FOrbitDurationYears: LongWord;
FPressurizedCapsule: IDragonPressurizedCapsule;
FReturnPayloadMass: IMassInfo;
FReturnPayloadVolume: IVolumeInfo;
FSidewallAngleDegress: LongWord;
FThrusters: IDragonThrustersList;
FTrunk: IDragonTrunk;
FTypeInfo: string;
FWikipedia: string;
private
function GetActive: Boolean;
function GetCrewCapacity: Byte;
function GetDescription: string;
function GetDiameter: ISizeInfo;
function GetDryMassKilograms: Double;
function GetDryMassPounds: Double;
function GetFirstFlight: TDateTime;
function GetFlickrImages: TStringList;
function GetHeatShield: IDragonHeatshield;
function GetHeightWithTrunk: ISizeInfo;
function GetId: string;
function GetLaunchPayloadMass: IMassInfo;
function GetLaunchPayloadVolume: IVolumeInfo;
function GetName: string;
function GetOrbitDurationYears: LongWord;
function GetPressurizedCapsule: IDragonPressurizedCapsule;
function GetReturnPayloadMass: IMassInfo;
function GetReturnPayloadVolume: IVolumeInfo;
function GetSidewallAngleDegress: LongWord;
function GetThrusters: IDragonThrustersList;
function GetTrunk: IDragonTrunk;
function GetTypeInfo: string;
function GetWikipedia: string;
private
procedure SetActive(AValue: Boolean);
procedure SetActive(AValue: Variant);
procedure SetCrewCapacity(AValue: Byte);
procedure SetCrewCapacity(AValue: Variant);
procedure SetDescription(AValue: string);
procedure SetDescription(AValue: Variant);
procedure SetDiameter(AValue: ISizeInfo);
procedure SetDryMassKilograms(AValue: Double);
procedure SetDryMassKilograms(AValue: Variant);
procedure SetDryMassPounds(AValue: Double);
procedure SetDryMassPounds(AValue: Variant);
procedure SetFirstFlight(AValue: TDateTime);
procedure SetFirstFlight(AValue: string);
procedure SetFirstFlight(AValue: Variant);
procedure SetFlickrImages(AValue: TStringList);
procedure SetHeatShield(AValue: IDragonHeatshield);
procedure SetHeightWithTrunk(AValue: ISizeInfo);
procedure SetId(AValue: string);
procedure SetId(AValue: Variant);
procedure SetLaunchPayloadMass(AValue: IMassInfo);
procedure SetLaunchPayloadVolume(AValue: IVolumeInfo);
procedure SetName(AValue: string);
procedure SetName(AValue: Variant);
procedure SetOrbitDurationYears(AValue: LongWord);
procedure SetOrbitDurationYears(AValue: Variant);
procedure SetPressurizedCapsule(AValue: IDragonPressurizedCapsule);
procedure SetReturnPayloadMass(AValue: IMassInfo);
procedure SetReturnPayloadVolume(AValue: IVolumeInfo);
procedure SetSidewallAngleDegress(AValue: LongWord);
procedure SetSidewallAngleDegress(AValue: Variant);
procedure SetThrusters(AValue: IDragonThrustersList);
procedure SetTrunk(AValue: IDragonTrunk);
procedure SetTypeInfo(AValue: string);
procedure SetTypeInfo(AValue: Variant);
procedure SetWikipedia(AValue: string);
procedure SetWikipedia(AValue: Variant);
public
procedure BuildSubObjects(const JSONData: IJSONData); override;
constructor Create;
destructor Destroy; override;
function ToString: string; override;
published
property active: Variant write SetActive;
property crew_capacity: Variant write SetCrewCapacity;
property description: Variant write SetDescription;
property dry_mass_kilograms: Variant write SetDryMassKilograms;
property dry_mass_pounds: Variant write SetDryMassPounds;
property first_flight: Variant write SetFirstFlight;
property flickr_images: TStringList read GetFlickrImages write SetFlickrImages;
property id: Variant write SetId;
property name: Variant write SetName;
property orbit_duration_years: Variant write SetOrbitDurationYears;
property sidewall_angle_degress: Variant write SetSidewallAngleDegress;
property wikipedia: Variant write SetWikipedia;
end;
{ TDragonList }
TDragonList = class(TBaseModelList, IDragonList)
function NewItem: IBaseModel; override;
end;
function NewDragon: IDragon;
begin
Result := TDragon.Create;
Result.FlickrImages := TStringList.Create;
end;
function NewDragonList: IDragonList;
begin
Result := TDragonList.Create;
end;
operator enumerator(AList: IDragonList): TDragonEnumerator;
begin
Result := TDragonEnumerator.Create;
Result.FList := AList;
end;
{ TDragonEnumerator }
function TDragonEnumerator.GetCurrent: IDragon;
begin
Result := FCurrent as IDragon;
end;
function TDragonList.NewItem: IBaseModel;
begin
Result := NewDragon;
end;
{ TDragon }
function TDragon.GetActive: Boolean;
begin
Result := FActive;
end;
function TDragon.GetCrewCapacity: Byte;
begin
Result := FCrewCapacity;
end;
function TDragon.GetDescription: string;
begin
Result := FDescription;
end;
function TDragon.GetDiameter: ISizeInfo;
begin
Result := FDiameter;
end;
function TDragon.GetDryMassKilograms: Double;
begin
Result := FDryMassKilograms;
end;
function TDragon.GetDryMassPounds: Double;
begin
Result := FDryMassPounds;
end;
function TDragon.GetFirstFlight: TDateTime;
begin
Result := FFirstFlight;
end;
function TDragon.GetFlickrImages: TStringList;
begin
Result := FFlickrImages;
end;
function TDragon.GetHeatShield: IDragonHeatshield;
begin
Result := FHeatShield;
end;
function TDragon.GetHeightWithTrunk: ISizeInfo;
begin
Result := FHeightWithTrunk;
end;
function TDragon.GetId: string;
begin
Result := FId;
end;
function TDragon.GetLaunchPayloadMass: IMassInfo;
begin
Result := FLaunchPayloadMass;
end;
function TDragon.GetLaunchPayloadVolume: IVolumeInfo;
begin
Result := FLaunchPayloadVolume;
end;
function TDragon.GetName: string;
begin
Result := FName;
end;
function TDragon.GetOrbitDurationYears: LongWord;
begin
Result := FOrbitDurationYears;
end;
function TDragon.GetPressurizedCapsule: IDragonPressurizedCapsule;
begin
Result := FPressurizedCapsule;
end;
function TDragon.GetReturnPayloadMass: IMassInfo;
begin
Result := FReturnPayloadMass;
end;
function TDragon.GetReturnPayloadVolume: IVolumeInfo;
begin
Result := FReturnPayloadVolume;
end;
function TDragon.GetSidewallAngleDegress: LongWord;
begin
Result := FSidewallAngleDegress;
end;
function TDragon.GetThrusters: IDragonThrustersList;
begin
Result := FThrusters;
end;
function TDragon.GetTrunk: IDragonTrunk;
begin
Result := FTrunk;
end;
function TDragon.GetTypeInfo: string;
begin
Result := FTypeInfo;
end;
function TDragon.GetWikipedia: string;
begin
Result := FWikipedia;
end;
procedure TDragon.SetActive(AValue: Boolean);
begin
FActive := AValue;
end;
procedure TDragon.SetActive(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FActive := False;
end else if VarIsBool(AValue) then
FActive := AValue;
end;
procedure TDragon.SetCrewCapacity(AValue: Byte);
begin
FCrewCapacity := AValue;
end;
procedure TDragon.SetCrewCapacity(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FCrewCapacity := -0;
end else if VarIsNumeric(AValue) then
FCrewCapacity := AValue;
end;
procedure TDragon.SetDescription(AValue: string);
begin
FDescription := AValue;
end;
procedure TDragon.SetDescription(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FDescription := '';
end else if VarIsStr(AValue) then
FDescription := AValue;
end;
procedure TDragon.SetDiameter(AValue: ISizeInfo);
begin
FDiameter := AValue;
end;
procedure TDragon.SetDryMassKilograms(AValue: Double);
begin
FDryMassKilograms := AValue;
end;
procedure TDragon.SetDryMassKilograms(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FDryMassKilograms := -0;
end else if VarIsNumeric(AValue) then
FDryMassKilograms := AValue;
end;
procedure TDragon.SetDryMassPounds(AValue: Double);
begin
FDryMassPounds := AValue;
end;
procedure TDragon.SetDryMassPounds(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FDryMassPounds := -0;
end else if VarIsNumeric(AValue) then
FDryMassPounds := AValue;
end;
procedure TDragon.SetFirstFlight(AValue: TDateTime);
begin
FFirstFlight := AValue;
end;
procedure TDragon.SetFirstFlight(AValue: string);
begin
try
FormatSettings.DateSeparator := '-';
FormatSettings.ShortDateFormat := 'y/m/d';
FFirstFlight := StrToDate(AValue);
finally
FormatSettings := DefaultFormatSettings;
end;
end;
procedure TDragon.SetFirstFlight(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FFirstFlight := MinDateTime;
end else if VarIsStr(AValue) then
SetFirstFlight(VarToStr(AValue));
end;
procedure TDragon.SetFlickrImages(AValue: TStringList);
begin
FFlickrImages := AValue;
end;
procedure TDragon.SetHeatShield(AValue: IDragonHeatshield);
begin
FHeatShield := AValue;
end;
procedure TDragon.SetHeightWithTrunk(AValue: ISizeInfo);
begin
FHeightWithTrunk := AValue;
end;
procedure TDragon.SetId(AValue: string);
begin
FId := AValue;
end;
procedure TDragon.SetId(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FId := '';
end else if VarIsStr(AValue) then
FId := AValue;
end;
procedure TDragon.SetLaunchPayloadMass(AValue: IMassInfo);
begin
FLaunchPayloadMass := AValue;
end;
procedure TDragon.SetLaunchPayloadVolume(AValue: IVolumeInfo);
begin
FLaunchPayloadVolume := AValue;
end;
procedure TDragon.SetName(AValue: string);
begin
FName := AValue;
end;
procedure TDragon.SetName(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FName := '';
end else if VarIsStr(AValue) then
FName := AValue;
end;
procedure TDragon.SetOrbitDurationYears(AValue: LongWord);
begin
FOrbitDurationYears := AValue;
end;
procedure TDragon.SetOrbitDurationYears(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FOrbitDurationYears := -0;
end else if VarIsNumeric(AValue) then
FOrbitDurationYears := AValue;
end;
procedure TDragon.SetPressurizedCapsule(AValue: IDragonPressurizedCapsule);
begin
FPressurizedCapsule := AValue;
end;
procedure TDragon.SetReturnPayloadMass(AValue: IMassInfo);
begin
FReturnPayloadMass := AValue;
end;
procedure TDragon.SetReturnPayloadVolume(AValue: IVolumeInfo);
begin
FReturnPayloadVolume := AValue;
end;
procedure TDragon.SetSidewallAngleDegress(AValue: LongWord);
begin
FSidewallAngleDegress := AValue;
end;
procedure TDragon.SetSidewallAngleDegress(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FSidewallAngleDegress := -0;
end else if VarIsNumeric(AValue) then
FSidewallAngleDegress := AValue;
end;
procedure TDragon.SetThrusters(AValue: IDragonThrustersList);
begin
FThrusters := AValue;
end;
procedure TDragon.SetTrunk(AValue: IDragonTrunk);
begin
FTrunk := AValue;
end;
procedure TDragon.SetTypeInfo(AValue: string);
begin
FTypeInfo := AValue;
end;
procedure TDragon.SetTypeInfo(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FTypeInfo := '';
end else if VarIsStr(AValue) then
FTypeInfo := AValue;
end;
procedure TDragon.SetWikipedia(AValue: string);
begin
FWikipedia := AValue;
end;
procedure TDragon.SetWikipedia(AValue: Variant);
begin
if VarIsNull(AValue) then begin
FWikipedia := '';
end else if VarIsStr(AValue) then
FWikipedia := AValue;
end;
procedure TDragon.BuildSubObjects(const JSONData: IJSONData);
var
SubJSONData: IJSONData;
Diameter: ISizeInfo;
HeatShield: IDragonHeatShield;
HeightWithTrunk: ISizeInfo;
LaunchPayloadMass: IMassInfo;
LaunchPayloadVolume: IVolumeInfo;
PressurizedCapsule: IDragonPressurizedCapsule;
ReturnPayloadMass: IMassInfo;
ReturnPayloadVolume: IVolumeInfo;
Thrusters: IDragonThrustersList;
Trunk: IDragonTrunk;
begin
inherited BuildSubObjects(JSONData);
SubJSONData := JSONData.GetPath('diameter');
Diameter := NewSizeInfo;
JSONToModel(SubJSONData.GetJSONData, Diameter);
Self.FDiameter := Diameter;
SubJSONData := JSONData.GetPath('heat_shield');
HeatShield := NewDragonHeatShield;
JSONToModel(SubJSONData.GetJSONData, HeatShield);
Self.FHeatShield := HeatShield;
SubJSONData := JSONData.GetPath('height_w_trunk');
HeightWithTrunk := NewSizeInfo;
JSONToModel(SubJSONData.GetJSONData, HeightWithTrunk);
Self.FHeightWithTrunk := HeightWithTrunk;
SubJSONData := JSONData.GetPath('launch_payload_mass');
LaunchPayloadMass := NewMassInfo;
JSONToModel(SubJSONData.GetJSONData, LaunchPayloadMass);
Self.FLaunchPayloadMass := LaunchPayloadMass;
SubJSONData := JSONData.GetPath('launch_payload_vol');
LaunchPayloadVolume := NewVolumeInfo;
JSONToModel(SubJSONData.GetJSONData, LaunchPayloadVolume);
Self.FLaunchPayloadVolume := LaunchPayloadVolume;
SubJSONData := JSONData.GetPath('pressurized_capsule');
PressurizedCapsule := NewDragonPressurizedCapsule;
JSONToModel(SubJSONData.GetJSONData, PressurizedCapsule);
Self.FPressurizedCapsule := PressurizedCapsule;
SubJSONData := JSONData.GetPath('return_payload_mass');
ReturnPayloadMass := NewMassInfo;
JSONToModel(SubJSONData.GetJSONData, ReturnPayloadMass);
Self.FReturnPayloadMass := ReturnPayloadMass;
SubJSONData := JSONData.GetPath('return_payload_vol');
ReturnPayloadVolume := NewVolumeInfo;
JSONToModel(SubJSONData.GetJSONData, ReturnPayloadVolume);
Self.FReturnPayloadVolume := ReturnPayloadVolume;
SubJSONData := JSONData.GetPath('thrusters');
Thrusters := NewDragonThrustersList;
JSONToModel(SubJSONData.GetJSONData, Thrusters);
Self.FThrusters := Thrusters;
SubJSONData := JSONData.GetPath('trunk');
Trunk := NewDragonTrunk;
JSONToModel(SubJSONData.GetJSONData, Trunk);
Self.FTrunk := Trunk;
Self.FTypeInfo := JSONData.GetPath('type').GetJSONData;
end;
constructor TDragon.Create;
begin
inherited Create;
FFlickrImages := TStringList.Create;
FFlickrImages.SkipLastLineBreak := True;
end;
destructor TDragon.Destroy;
begin
FreeAndNil(FFlickrImages);
inherited Destroy;
end;
function TDragon.ToString: string;
begin
Result := Format(''
+ 'Active: %s' + LineEnding
+ 'Crew Capacity: %u' + LineEnding
+ 'Description: %s' + LineEnding
+ 'Diameter: %s' + LineEnding
+ 'Dry Mass(kg): %f' + LineEnding
+ 'Dry Mass(lbs): %f' + LineEnding
+ 'First Flight: %s' + LineEnding
+ 'Flickr Images: [' + LineEnding + ' %s' + ' ]' + LineEnding
+ 'Heat Shield: %s' + LineEnding
+ 'Height with Trunk: %s' + LineEnding
+ 'ID: %s' + LineEnding
+ 'Launch Payload Mass: %s' + LineEnding
+ 'Launch Payload Volume: %s' + LineEnding
+ 'Name: %s' + LineEnding
+ 'Orbit Duration Years: %u' + LineEnding
+ 'Pressurized Capsule: %s' + LineEnding
+ 'Return Payload Mass: %s' + LineEnding
+ 'Return Payload Volume: %s' + LineEnding
+ 'Sidewall Angle Degrees: %u' + LineEnding
+ 'Thrusters: [' + LineEnding + ' %s' + LineEnding + ' ]' + LineEnding
+ 'Trunk: [' + LineEnding + ' %s' + LineEnding + ' ]' + LineEnding
+ 'Type: %s' + LineEnding
+ 'Wikipedia: %s'
, [
BoolToStr(GetActive, True),
GetCrewCapacity,
GetDescription,
GetDiameter.ToString,
GetDryMassKilograms,
GetDryMassPounds,
DateToStr(GetFirstFlight),
StringReplace(
GetFlickrImages.Text, LineEnding, LineEnding + ' ', [rfReplaceAll]),
GetHeatShield.ToString,
GetHeightWithTrunk.ToString,
GetId,
GetLaunchPayloadMass.ToString,
GetLaunchPayloadVolume.ToString,
GetName,
GetOrbitDurationYears,
GetPressurizedCapsule.ToString,
GetReturnPayloadMass.ToString,
GetReturnPayloadVolume.ToString,
GetSidewallAngleDegress,
StringReplace(
GetThrusters.ToString(LineEnding + ',' + LineEnding), LineEnding, LineEnding + ' ', [rfReplaceAll]),
StringReplace(
GetTrunk.ToString, LineEnding, LineEnding + ' ', [rfReplaceAll]),
GetTypeInfo,
GetWikipedia
]);
end;
end.
|
{==============================================================================]
Author: Jarl K. Holta
Project: ObjectWalk
Project URL: https://github.com/WarPie/ObjectWalk
License: GNU LGPL (https://www.gnu.org/licenses/lgpl-3.0.en.html)
[==============================================================================}
type
EMinimapObject = (
mmLadder, mmTree, mmDeadTree, mmPalmTree, mmFlax, mmBoulder, mmHenge,
mmCactus, mmMaple, mmRock, mmRed
);
MMObjDef = record
Colors:TIntegerArray;
Tol: Int32;
SplitX, SplitY: Int32;
AvgNumOfPoints, AvgTol: Int32;
end;
const
MINIMAP_POLYGON: TPointArray = [
[571,77], [571,67], [575,54], [581,43], [587,35], [598,25], [609,18],
[628,11], [645,10], [658,11], [671,15], [683,22], [692,29], [702,40],
[709,50], [713,63], [713,65], [713,82], [708,105],[702,115],[670,135],
[660,145],[658,151],[651,158],[633,158],[628,154],[625,151],[623,145],
[613,135],[601,128],[584,117],[578,110],[573,96]
];
(*
Filters points so you only end up with points actually on the minimap..
This works unlike the broken one in SRL/SRL #BlameOlly
Note: It's slow.. so, don't use it in any high performance methods.
*)
procedure TMinimap.FilterPointsFix(var TPA:TPointArray); static;
var
tmp:TPointArray;
i,c:Int32;
begin
SetLength(tmp, Length(TPA));
for i:=0 to High(TPA) do
if srl.PointInPoly(TPA[i], MINIMAP_POLYGON) then
tmp[Inc(c)-1] := TPA[i];
TPA := tmp;
SetLength(TPA, c);
end;
//inspired by function in ObjectDTM (by euph..)
function TMinimap.FindObjEx(Obj:MMObjDef; Bounds:TBox; OnMinimapCheck:Boolean=True): TPointArray;
var
i,avgN,lo,hi,color: Int32;
TPA,TmpRes: TPointArray;
ATPA: T2DPointArray;
mid: TPoint;
begin
SetLength(ATPA, Length(Obj.Colors));
for i:=0 to High(Obj.Colors) do
FindColorsTolerance(ATPA[i], Obj.Colors[i], Bounds.x1, Bounds.y1, Bounds.x2, Bounds.y2, Obj.Tol);
avgN := Obj.AvgNumOfPoints;
for i:=0 to High(ATPA) do
for TPA in ClusterTPAEx(ATPA[i], Obj.SplitX, Obj.SplitY) do
begin
if not InRange(Length(TPA), avgN - Obj.AvgTol, avgN + Obj.AvgTol) then
Continue;
mid := MiddleTPA(TPA);
if (not OnMinimapCheck) or srl.PointInPoly(mid, MINIMAP_POLYGON) then
TmpRes += mid;
end;
//clearning duplicates and neighbouring points by simply merging them into 1
for TPA in ClusterTPA(TmpRes, 2) do Result += MiddleTPA(TPA);
end;
function TMinimap.FindObj(Obj: MMObjDef): TPointArray;
begin // MM area
Result := FindObjEx(Obj, [570,9,714,159]);
end;
function UniqueColors(colors:TIntegerArray; Tolerance:Int32=5): TIntegerArray;
var
i,j:Int32;
similar:Boolean;
begin
for i:=0 to High(colors) do
begin
for j:=i+1 to High(colors) do
if similar := SimilarColors(colors[i],colors[j], tolerance) then
Break;
if not similar then
Result += colors[i];
end;
end;
(*
Based on a function in ObjectDTM (by euph..)
The object definitions might not work properly, this is a rough sketch.
The colors comment is what I've used to calibrate tolerances.
The more colors we add the lower tolerance we can use, the more the merrier, up to a point.
*)
var
MMObjRecords: array [EMinimapObject] of MMObjDef;
begin
{colors: 1717603,1783655,6976,6993,865128}
with MMObjRecords[mmLadder] do
begin
Colors := [928084];
Tol := 30;
SplitX := 2; SplitY := 2;
AvgNumOfPoints := 32; AvgTol := 19;
end;
with MMObjRecords[mmTree] do
begin
Colors := UniqueColors([1258044,7983,602944,271914,1391694,140343,2310221,933949]);
Tol := 18; //stem
SplitX := 2; SplitY := 2;
AvgNumOfPoints := 7; AvgTol := 6;
end;
with MMObjRecords[mmDeadTree] do
begin
Colors := UniqueColors([2346,1188400,2305857,6452,1387330,267550]);
Tol := 20;
SplitX := 2; SplitY := 2;
AvgNumOfPoints := 20; AvgTol := 8;
end;
with MMObjRecords[mmPalmTree] do
begin
Colors := UniqueColors([1384586,3445,137352,2633365,463487]);
Tol := 20;
SplitX := 1; SplitY := 1;
AvgNumOfPoints := 4; AvgTol := 3;
end;
with MMObjRecords[mmFlax] do
begin
Colors := [9398872];
Tol := 1; //not tweaked
SplitX := 2; SplitY := 2;
AvgNumOfPoints := 6; AvgTol := 3;
end;
//3757702, 1920118, 3890578
with MMObjRecords[mmBoulder] do
begin
Colors := [2905476];
Tol := 30; //partially tweaked
SplitX := 1; SplitY := 1;
AvgNumOfPoints := 37; AvgTol := 18;
end;
with MMObjRecords[mmHenge] do
begin
Colors := [4409670];
Tol := 1; //not tweaked
SplitX := 1; SplitY := 1;
AvgNumOfPoints := 9; AvgTol := 6;
end;
//5013585
with MMObjRecords[mmCactus] do
begin
Colors := [5013585];
Tol := 30;
SplitX := 1; SplitY := 1;
AvgNumOfPoints := 80; AvgTol := 50;
end;
with MMObjRecords[mmMaple] do
begin
Colors := [999524];
Tol := 1; //not tweaked
SplitX := 1; SplitY := 1;
AvgNumOfPoints := 17; AvgTol := 5;
end;
{colors: 5923680,7429746,7365990,4869977,7365990}
with MMObjRecords[mmRock] do
begin
Colors := UniqueColors([5923680,7429746,7365990,4869977,7365990,3884104]);
Tol := 20;
SplitX := 1; SplitY := 1;
AvgNumOfPoints := 34; AvgTol := 18;
end;
with MMObjRecords[mmRed] do
begin
Colors := [240];
Tol := 22;
SplitX := 1; SplitY := 1;
AvgNumOfPoints := 8; AvgTol := 6;
end;
end;
|
{*******************************************************************************
This file is part of the Open Chemera Library.
This work is public domain (see README.TXT).
********************************************************************************
Author: Ludwig Krippahl
Date: 1.6.2011
Purpose:
Line grids for 3D shape representation, and computing surface and core regions
NOTE: unlike original BiGGER implementation, linegrid segments are aligned
with the Z coordinate, for a more intuitive [X,Y,Z] indexation of the matrix.
Requirements:
Revisions:
To do:
*******************************************************************************}
unit linegrids;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, basetypes, geomutils, geomhash,dateutils;
type
TLineSegment=array [0..1] of Integer; //start, end of segment
TGridLine=array of TLineSegment; //disjunt segments sorted from lower to high
TLineArray=array of TGridLine;
TGridPlane=array of array of TGridLine;
TGridShape=record
Grid:TGridPlane;
NonEmpty:TLineArray; //X oriented array of non-empty gridlines
CellCounts:array of array of Integer;
//CellsBelowMiddle,CellsAboveMiddle:array of array of Integer;
//tested, and does not improve performance because when core splits domain there
//is already too much overlap for more pruning with cellcounts
TotalCount:Integer;
ZMax:Integer;
end;
//For domain representation
TDomainBlock=record
//values for domain cuboid hull
ProbeEndX,ProbeEndY,ProbeEndZ,TargetEndX,TargetEndY,TargetEndZ:Integer;
XOffset,YOffset,ZOffset:Integer;
DomainEndX,DomainEndY,DomainEndZ:Integer;
end;
TDomainGrid=record
Block:TDomainBlock;
Shape:TGridShape; //full domain
end;
{ TDockingGrid }
//grids associated with a structure. Includes base, core and surface
TDockingGrid=class
protected
//atomic coordinates are shifted so that min-rad-FSurfThickness==0
FCoords,FCoreCutCoords:TCoords;
FRads,FCoreCutRads:TFloats;
FResolution:TFloat;
FTransVec:TCoord;
//translation vector for adjusting coordinates
//from coords to grid: add
//from grid to coords: subtract
FBase,FSurf,FCore:TGridShape;
procedure SetSurfCoreLine(X,Y:Integer;var Neighs,Surfs,Cores:TIntegers);
procedure SetLineVals(Line:TGridLine;var ValArray:TIntegers;Val:Integer);
procedure UpdateNeighbours(Line:TGridLine;var Neighs:TIntegers;Mult:Integer);
procedure ResetBaseLines(X,Y:Integer;var Neighs,Surfs,Cores:TIntegers);
//recomputes neighbour counts and resets surf and core vals to zero
procedure BaseLineIncY(X:Integer; var Y:Integer;var Neighs,Surfs,Cores:TIntegers);
//incrementally changes Y to next value and updates
//neighbour surf and core vals.
procedure BuildBaseGrid(gzlPrints:Integer); //translates structure and creates FBase
procedure BuildSurfCoreGrids; //builds from Base grid
public
property Base:TGridShape read FBase;
property Core:TGridShape read FCore;
property Surf:TGridShape read FSurf;
property Resolution:TFloat read FResolution;
property TransVec:TCoord read FTransVec;
constructor Create(AResolution:TFloat);
procedure BuildFromSpheres(gzlPrints:Integer;Coords:TCoords;Rads:TFloats;
CoreCuts:TCoords=nil;CoreCutRads:TFloats=nil);
end;
TDockingGrids=array of TDockingGrid;
function Intersect(const Line1,Line2:TGridLine):TGridLine;overload;
procedure Intersect(var Line:TGridLine; const NewMin,NewMax:Integer);
procedure DisplaceLine(var Line:TGridLine;Displacement:Integer);
{ function IntegersToGrid(const Ints: TIntegers; TGridSize:Integer;const Threshold:Integer=0; Limit1:Integer=-1;
Limit2: Integer=-1; Limit3: Integer=-1): TGridPlane; }
function IntegersToLine(const Ints:TIntegers;const Threshold:Integer=0;
Limit1:Integer=-1;Limit2:Integer=-1):TGridLine;overload;
procedure SetIntegersLine(const Line:TGridLine;var Ints:TIntegers; Val:Integer);
procedure ComputeShapeStats(var Shape:TGridShape);
function CountSegments(const Grid:TGridPlane):Integer;
function CountCells(const Grid:TGridPlane):Integer;overload;
function CountCells(const Line:TGridLine):Integer;overload;
function CountCellsBetween(const Line:TGridLine;const MinZ,MaxZ:Integer):Integer;
procedure GetLineExtremes(const Line:TGridLine; out LineMin,LineMax:Integer);
function NewLine(Ix1,Ix2:Integer):TGridLine;
implementation
function Intersect(const Line1, Line2: TGridLine): TGridLine;
var
ix,ni1,ni2:Integer;
i1,i2,ll1,ll2:Integer;
top,bot:Integer;
begin
SetLength(Result,Length(Line1)+Length(Line2));
ix:=0;
i1:=0;
i2:=0;
ll1:=Length(Line1);
ll2:=Length(Line2);
while (i1<ll1) and (i2<ll2) do
begin
top:=Min(Line1[i1,1],Line2[i2,1]);
bot:=Max(Line1[i1,0],Line2[i2,0]);
if top>=bot then
begin
Result[ix,0]:=bot;
Result[ix,1]:=top;
Inc(ix);
end;
if Line1[i1,1]>=Line2[i2,1] then ni2:=i2+1 else ni2:=i2;
if Line1[i1,1]<=Line2[i2,1] then ni1:=i1+1 else ni1:=i1;
i1:=ni1;
i2:=ni2;
end;
SetLength(Result,ix);
end;
procedure Intersect(var Line: TGridLine; const NewMin, NewMax: Integer);
var
f,lastvalid:Integer;
begin
lastvalid:=-1;
for f:=0 to High(Line) do
begin
if (Line[f,1]>=NewMin) and (Line[f,0]<=NewMax) then
//line segment is inside new interval
begin
Line[f,0]:=Max(NewMin,Line[f,0]);
Line[f,1]:=Min(NewMax,Line[f,1]);
Inc(lastvalid);
if lastvalid<f then
Line[lastvalid]:=Line[f];
end
end;
SetLength(Line,lastvalid+1);
end;
procedure DisplaceLine(var Line: TGridLine; Displacement: Integer);
var f:Integer;
begin
for f:=0 to High(Line) do
begin
Line[f,0]:=Line[f,0]+Displacement;
Line[f,1]:=Line[f,1]+Displacement;
end;
end;
function IntegersToLine(const Ints: TIntegers; const Threshold:Integer; Limit1:Integer;
Limit2: Integer): TGridLine;
var
f,curr:Integer;
isin:Boolean;
begin
if Limit1<0 then Limit1:=0;
if Limit2<0 then Limit2:=High(Ints);
SetLength(Result,Limit2-Limit1+1);
curr:=-1;
isin:=False;
//threshold = 0
for f:=Limit1 to Limit2 do
begin
if (Ints[f] <> 0) or (Ints[f] <> 1) then
begin
Ints[f]:=0;
end;
if Ints[f]>Threshold then
begin
if not isin then
begin
isin:=True;
Inc(curr);
Result[curr,0]:=f;
end;
end
else if isin then
begin
Result[curr,1]:=f-1;
isin:=False;
end;
end;
if isin then Result[curr,1]:=Limit2;
SetLength(Result,curr+1);
end;
procedure SetIntegersLine(const Line: TGridLine; var Ints: TIntegers;
Val: Integer);
var f,ff:Integer;
begin
for f:=0 to High(Line) do
for ff:=Line[f,0] to Line[f,1] do
Ints[ff]:=Val;
end;
procedure ComputeShapeStats(var Shape: TGridShape);
var
x,y:Integer;
tmpline:TIntegers;
begin
with Shape do
begin
SetLength(NonEmpty,Length(Grid));
SetLength(CellCounts,Length(Grid),Length(Grid[0]));
//SetLength(CellsBelowMiddle,Length(Grid),Length(Grid[0]));
//SetLength(CellsAboveMiddle,Length(Grid),Length(Grid[0]));
ZMax:=0;
TotalCount:=0;
for x:=0 to High(Grid) do
begin
tmpline:=FilledInts(Length(Grid[0]),0);
for y:=0 to High(Grid[0]) do
if Grid[x,y]<>nil then
begin
tmpline[y]:=1;
if ZMax<Grid[x,y,High(Grid[x,y]),1] then
ZMax:=Grid[x,y,High(Grid[x,y]),1];
CellCounts[x,y]:=CountCells(Grid[x,y]);
TotalCount:=TotalCount+CellCounts[x,y];
//CellsBelowMiddle[x,y]:=CountCellsBetween(Grid[x,y],0,ZMax div 2);
//CellsAboveMiddle[x,y]:=CountCellsBetween(Grid[x,y],ZMax div 2,ZMax);
end;
NonEmpty[x]:=IntegersToLine(tmpline,0);
end;
end;
end;
function CountSegments(const Grid:TGridPlane):Integer;
var x,y:Integer;
begin
Result:=0;
for x:=0 to High(Grid) do
for y:=0 to High(Grid[x]) do
Result:=Result+Length(Grid[x,y]);
end;
function CountCells(const Grid:TGridPlane):Integer;
var x,y,z:Integer;
begin
Result:=0;
for x:=0 to High(Grid) do
for y:=0 to High(Grid[x]) do
for z:=0 to High(Grid[x,y]) do
Result:=Result+Grid[x,y,z,1]-Grid[x,y,z,0]+1;
end;
function CountCells(const Line: TGridLine): Integer;
var z:Integer;
begin
Result:=0;
for z:=0 to High(Line) do
Result:=Result+Line[z,1]-Line[z,0]+1;
end;
function CountCellsBetween(const Line: TGridLine; const MinZ, MaxZ: Integer
): Integer;
var z:Integer;
begin
Result:=0;
for z:=0 to High(Line) do
if (Line[z,0]<=MaxZ) and (Line[z,1]>=MinZ) then
Result:=Result+Min(MaxZ,Line[z,1])-Max(Line[z,0],MinZ)+1;
end;
procedure GetLineExtremes(const Line: TGridLine; out LineMin, LineMax: Integer);
begin
if Line=nil then
begin
LineMin:=-1;
LineMax:=-2;
end
else
begin
LineMin:=Line[0,0];
LineMax:=Line[High(Line),1];
end;
end;
function NewLine(Ix1, Ix2: Integer): TGridLine;
begin
SetLength(Result,1);
Result[0,0]:=Ix1;
Result[0,1]:=Ix2;
end;
{ TDockingGrid }
procedure TDockingGrid.SetSurfCoreLine(X, Y: Integer; var Neighs, Surfs,
Cores: TIntegers);
var z,zz:Integer;
begin
for z:=0 to High(FBase.Grid[X,Y]) do
for zz:=FBase.Grid[X,Y,z,0] to FBase.Grid[X,Y,z,1] do
if Neighs[zz]>=27 then
Cores[zz]:=1
else Surfs[zz]:=1;
FCore.Grid[X,Y]:=IntegersToLine(Cores);
FSurf.Grid[X,Y]:=IntegersToLine(Surfs);
end;
procedure TDockingGrid.SetLineVals(Line: TGridLine; var ValArray: TIntegers;
Val: Integer);
var z,zz:Integer;
begin
for z:=0 to High(Line) do
for zz:=Line[z,0] to Line[z,1] do
ValArray[zz]:=Val;
end;
procedure TDockingGrid.UpdateNeighbours(Line: TGridLine; var Neighs: TIntegers;
Mult: Integer);
var z,zz,bot,top:Integer;
begin
for z:=0 to High(Line) do
begin
bot:=Line[z,0];
top:=Line[z,1];
Neighs[bot-1]:=Neighs[bot-1]+Mult;
Neighs[top+1]:=Neighs[top+1]+Mult;
Neighs[bot]:=Neighs[bot]+Mult;
if bot<top then
begin
Neighs[bot]:=Neighs[bot]+Mult;
Neighs[top]:=Neighs[top]+2*Mult;
end;
for zz:=bot+1 to top-1 do
Neighs[zz]:=Neighs[zz]+3*Mult;
end;
end;
procedure TDockingGrid.ResetBaseLines(X, Y: Integer; var Neighs, Surfs,
Cores: TIntegers);
var f,g:Integer;
begin
for f:=0 to High(Neighs) do
begin
Neighs[f]:=0;
Surfs[f]:=0;
Cores[f]:=0;
end;
for f:=X-1 to X+1 do
for g:=Y-1 to Y+1 do
with FBase do
UpdateNeighbours(Grid[f,g],Neighs,1);
end;
procedure TDockingGrid.BaseLineIncY(X: Integer; var Y: Integer; var Neighs,
Surfs, Cores: TIntegers);
begin
UpdateNeighbours(FBase.Grid[X-1,Y-1],Neighs,-1);
UpdateNeighbours(FBase.Grid[X,Y-1],Neighs,-1);
UpdateNeighbours(FBase.Grid[X+1,Y-1],Neighs,-1);
SetLineVals(FBase.Grid[X,Y],Surfs,0);
SetLineVals(FBase.Grid[X,Y],Cores,0);
Inc(Y);
UpdateNeighbours(FBase.Grid[X-1,Y+1],Neighs,1);
UpdateNeighbours(FBase.Grid[X,Y+1],Neighs,1);
UpdateNeighbours(FBase.Grid[X+1,Y+1],Neighs,1);
end;
function getNeededMemoryInBytes(zlineElems:Integer; fpointsNR:Integer):Double;
var
nSegments:Integer;
begin
nSegments:=zlineElems*zlineElems*zlineElems;
Result:= 4 *fpointsNR +
+ 4 * nSegments+
+ 4 * 3 * nSegments+
+ 4 * 3 * nSegments * fpointsNR+
+ 4 * nSegments * fpointsNR+
+ nSegments*fpointsNR;
end;
procedure TDockingGrid.BuildBaseGrid(gzlPrints:Integer);
var
hash:TGeomHasher;
halfres,maxrad:TFloat;
top:TCoord;
xyzpoint:TCoord;
x,y,z,i,j,k,index,step,limitS,limitE:Integer;
nrPartitions,gridSizeP,nRowsP,nSegsP:Integer;
restGridSizeP,restRows,nSegs,nRemSegments:Integer;
sFCoords,FCoordsRem:TCoords;
fRadsRem,fRadsS:TFloats;
totalNeededMemory, totalFreeMemory:Double;
zline:TIntegers;
zlineExtended,zlineS,zlineRem:TIntegers;
remaining:Boolean;
startGZL,stopGZL:TDateTime;
begin
//Adjust coordinates
maxrad:=Max(Max(FRads),FResolution);
//Translate and size guaranteeing one layer of empty grid cells
FTransVec:=Min(FCoords);
FTransVec:=Add(Simmetric(FTransVec),maxrad+FResolution);
FCoords:=Add(FTransvec,FCoords);
top:=Add(Max(FCoords),maxrad+1.5*FResolution);
SetLength(FBase.Grid,Round(top[0]/FResolution),Round(top[1]/FResolution));
SetLength(zline,Round(top[2]/FResolution));
FBase.ZMax:=High(zline);
hash:=TGeomHasher.Create(FCoords,maxrad,Round(top[0]/FResolution),Round(top[1]/FResolution),Round(top[2]/FResolution),FRads,true);
halfres:=0.5*FResolution;
startGZL:=Now;
//{$DEFINE GETZLINE}
{$IFDEF GETZLINE}
//zline array
SetLength(zlineExtended,Length(zline)*(High(FBase.Grid[0])+1)*(High(FBase.Grid) + 1));
step:=length(zline);
// ===================Solução Marrow====================
getZline(zlineExtended, FResolution, FCoords
, FRads, Length(zline),(High(FBase.Grid[0])+1),(High(FBase.Grid) + 1), Length(FCoords));
//Zline apos o kernel são os 0s e 1s para a grelha toda em vez de uma só linha
limitS:=0;
limitE :=FBase.ZMax;
for x:=0 to High(FBase.Grid) do
begin
for y:=0 to High(FBase.Grid[x]) do
begin
FBase.Grid[x,y]:=IntegersToLine(zlineExtended,0,limitS,limitE);
limitS+=step;
limitE+=step;
end
end;
{$ELSE}
// ===================Solução original====================
for x:=0 to High(FBase.Grid) do
begin
xyzpoint[0]:=x*FResolution+halfres;
for y:=0 to High(FBase.Grid[x]) do
begin
xyzpoint[1]:=y*FResolution+halfres;
for z:=0 to High(zline) do
begin
xyzpoint[2]:=z*FResolution+halfres;
if hash.IsInnerPoint(xyzpoint) then
zline[z]:=1
else zline[z]:=0;
end;
FBase.Grid[x,y]:=IntegersToLine(zline);
end;
end;
{$ENDIF}
//WriteLn(hash.getLoopCount()/(Length(zlineExtended)), ' average atoms used');
//hash.ResetAtomCounter();
// PRINT PARA DETERMINAR O TEMPO DE EXECUCAO DESTE TROÇO EM ESPECIFICO
// PARA CADA ROTACAO
stopGZL:=Now;
if gzlPrints <= 1 then
begin
WriteLn('total segments ', Length(zline)*(High(FBase.Grid[0])+1)*(High(FBase.Grid) + 1));
WriteLn('total atoms ', Length(FCoords));
WriteLn(FormatDateTime('hh.nn.ss.zzz', stopGZL-startGZL), ' GZL ms');
end;
hash.Free;
end;
procedure TDockingGrid.BuildSurfCoreGrids;
var
x,y:Integer;
neighs,surfs,cores:TIntegers;
begin
SetLength(FCore.Grid,Length(FBase.Grid),Length(FBase.Grid[0]));
SetLength(FSurf.Grid,Length(FBase.Grid),Length(FBase.Grid[0]));
SetLength(neighs,FBase.ZMax+1);
SetLength(surfs,FBase.ZMax+1);
SetLength(cores,FBase.ZMax+1);
for x:=1 to High(FBase.Grid)-1 do
begin
y:=1;
ResetBaseLines(x,y,neighs,surfs,cores);
repeat
SetSurfCoreLine(x,y,neighs,surfs,cores);
BaseLineIncY(x,y,neighs,surfs,cores);
until y>=High(FBase.Grid[x])-1;
SetSurfCoreLine(x,y,neighs,surfs,cores);
end;
end;
constructor TDockingGrid.Create(AResolution:TFLoat);
begin
inherited Create;
FTransVec:=NullVector;
FResolution:=AResolution;
end;
procedure TDockingGrid.BuildFromSpheres(gzlPrints:Integer; Coords: TCoords; Rads: TFloats;
CoreCuts: TCoords; CoreCutRads: TFloats);
begin
Assert(Length(Coords)=Length(Rads),'Coordinates and radius values do not match');
FCoords:=Copy(Coords,0,Length(Coords));
FRads:=Copy(Rads,0,Length(Rads));
FCoreCutCoords:=Copy(CoreCuts,0,Length(CoreCuts));
FCoreCutRads:=Copy(CoreCutRads,0,Length(CoreCutRads));
BuildBaseGrid(gzlPrints);
BuildSurfCoreGrids;
ComputeShapeStats(FSurf);
ComputeShapeStats(FCore);
FCoords:=nil;
FRads:=nil;
FCoreCutCoords:=nil;
FCoreCutRads:=nil;
end;
end.
{ totalNeededMemory := getNeededMemoryInBytes(length(zline),length(FCoords));
totalFreeMemory := getTotalDeviceFreeMem();
nSegs:=length(zline)*length(zline)*length(zline);
nrPartitions := trunc(totalNeededMemory/totalFreeMemory);
if nrPartitions > 0 then
begin
remaining := round(Dmod(totalNeededMemory,totalFreeMemory)) <> 0;
if nrPartitions = 1 then
begin
nrPartitions := nrPartitions +1;
end;
gridSizeP := trunc(exp((1/3)*ln(length(zline) div nrPartitions)));
nSegsP := gridSizeP*gridSizeP*gridSizeP;
SetLength(zlineS,nSegsP);
if (nrPartitions = 2) and remaining then
begin
for i := 0 to nrPartitions -1 do
begin
zlineS:=Copy(zlineExtended,i*nSegsP,Length(zlineS));
getZline(zlineS,FResolution,FCoords,FRads,gridSizeP,length(FCoords));
zlineExtended:=Copy(zlineS,i*nSegsP,Length(zlineS));
end
end
else
begin
for i := 0 to nrPartitions do
begin
zlineS:=Copy(zlineExtended,i*nSegsP,Length(zlineS));
getZline(zlineS,FResolution,FCoords,FRads,gridSizeP,length(FCoords));
zlineExtended:=Copy(zlineS,i*nSegsP,Length(zlineS));
end
end;
if remaining then
begin
// A last call to getZline with the remaining unprocessed zline elements
restGridSizeP := trunc(exp((1/3)*ln(nSegs-nrPartitions*nSegsP)));
nRemSegments := restGridSizeP*restGridSizeP*restGridSizeP;
SetLength(zlineRem,nRemSegments);
zlineRem:= Copy(zlineExtended,restGridSizeP,Length(zlineRem));
getZline(zlineRem,FResolution,FCoords,FRads,restGridSizeP,Length(FCoords));
zlineExtended:= Copy(zlineRem,(nrPartitions*nSegsP)-1,Length(zlineRem));
end
end
else}
|
unit ArrayManager;
{$mode objfpc}{$H+}
interface
uses Classes;
type
{ TArrayManager }
TArrayManager = class(TObject)
protected
FOwner1: TObject;
function GetItem(index: Integer): TObject; virtual;
function GetOwner: TObject; virtual;
procedure SetOwner(AValue: TObject);
private
Items1: array of TObject;
FPosition: Integer;
function GetCount: Integer;
function GetEof: boolean;
public
property Position: Integer read FPosition write FPosition;
property Owner: TObject read GetOwner write SetOwner;
procedure Clear; virtual;
property Count: Integer read GetCount;
property Item[index: Integer]: TObject read GetItem;
property EOF: boolean read GetEof;
function Add(AObject: TObject): TObject; virtual;
function GetItemIndex(AObject: TObject): Integer;
function Extract(AObject: TObject): TObject; virtual;
procedure Assign(ASource: TObject); virtual;
function Current(): TObject; virtual;
function Next(): TObject; virtual;
procedure Reset();
function Prev(): TObject; virtual;
constructor Create(AOwner: TObject); virtual;
destructor Destroy; virtual;
end;
implementation
{ TRCArrayManager }
function TArrayManager.GetCount: Integer;
begin
Result := Length(Items1);
end;
function TArrayManager.GetEof: boolean;
begin
Result := Position >= Count;
end;
procedure TArrayManager.SetOwner(AValue: TObject);
begin
FOwner1 := AValue;
end;
function TArrayManager.GetOwner: TObject;
begin
Result := FOwner1;
end;
function TArrayManager.GetItem(index: Integer): TObject;
begin
Result := Items1[index];
end;
procedure TArrayManager.Clear;
begin
Position := -1;
SetLength(Items1, 0);
end;
function TArrayManager.Add(AObject: TObject): TObject;
var
AIndex1: Integer;
begin
AIndex1 := GetItemIndex(AObject);
if AIndex1 = -1 then
begin
SetLength(Items1, Count + 1);
Items1[Count - 1] := AObject;
Result := Items1[Count - 1];
end
else
Result := AObject;
end;
function TArrayManager.GetItemIndex(AObject: TObject): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to Count - 1 do
if Item[i] = AObject then
begin
Result := i;
break;
end;
end;
function TArrayManager.Extract(AObject: TObject): TObject;
var
i, j, c: Integer;
begin
i := GetItemIndex(AObject);
c := 0;
Result := nil;
if (i <> -1) then
begin
for j := 0 to Count - 1 do
begin
Items1[j] := Items1[c];
if j <> i then
Inc(c);
end;
SetLength(Items1, c);
Result := AObject;
end;
end;
procedure TArrayManager.Assign(ASource: TObject);
begin
raise TExceptionClass.Create('Assign method not implemented');
end;
function TArrayManager.Current: TObject;
begin
if (Position = -1) then
if (Count > 0) then
Result := GetItem(0)
else
Result := nil
else
Result := GetItem(Position)
end;
function TArrayManager.Next: TObject;
begin
Result := nil;
if Count > 0 then
begin
Inc(FPosition);
if Position < Count then
Result := GetItem(Position);
end;
end;
procedure TArrayManager.Reset;
begin
Position := -1;
end;
function TArrayManager.Prev: TObject;
begin
Result := nil;
end;
constructor TArrayManager.Create(AOwner: TObject);
begin
FOwner1 := AOwner;
Clear;
end;
destructor TArrayManager.Destroy;
begin
Clear;
end;
end.
|
unit UListUsers;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, Buttons, StdCtrls, ExtCtrls, Grids, UGrid;
Type
TOneUser = Class
public
Name: String;
Subname: string;
Family: string;
ShortName: string;
Login: string;
Password: string;
Procedure WriteToStream(F: tStream);
Procedure ReadFromStream(F: tStream);
Procedure Assign(User: TOneUser);
Constructor Create;
Destructor Destroy;
end;
TListUsers = Class
public
Count: integer;
Users: array of TOneUser;
Procedure WriteToFile(FileName: String);
Procedure ReadFromFile(FileName: string);
Procedure Clear;
function Add: integer;
Procedure Delete(Login: string);
function UserExists(Login, Password: string): boolean;
Constructor Create;
Destructor Destroy;
end;
var
ListUsers: TListUsers;
UPos: integer;
implementation
uses umain, ucommon, umyfiles;
function MyEncodeString(Step: integer; Src: String): string;
var
i: integer;
begin
result := '';
for i := 0 to length(Src) do
result := result + chr(ord(Src[i]) - Step);
end;
function MyDecodeString(Step: integer; out Src: String): string;
var
i: integer;
begin
result := '';
for i := 0 to length(Src) do
result := result + chr(ord(Src[i]) + Step);
end;
Constructor TOneUser.Create;
begin
Name := '';
Subname := '';
Family := '';
ShortName := '';
Login := '';
Password := '';
end;
Destructor TOneUser.Destroy;
begin
FreeMem(@Name);
FreeMem(@Subname);
FreeMem(@Family);
FreeMem(@ShortName);
FreeMem(@Login);
FreeMem(@Password);
end;
Procedure TOneUser.WriteToStream(F: tStream);
begin
WriteBufferStr(F, MyEncodeString(StepCoding, Name));
WriteBufferStr(F, MyEncodeString(StepCoding, Subname));
WriteBufferStr(F, MyEncodeString(StepCoding, Family));
WriteBufferStr(F, MyEncodeString(StepCoding, ShortName));
WriteBufferStr(F, MyEncodeString(StepCoding, Login));
WriteBufferStr(F, MyEncodeString(StepCoding, Password));
end;
Procedure TOneUser.ReadFromStream(F: tStream);
var
s: string;
begin
ReadBufferStr(F, s);
Name := MyDecodeString(StepCoding, s);
ReadBufferStr(F, Subname);
Subname := MyDecodeString(StepCoding, s);
ReadBufferStr(F, Family);
Family := MyDecodeString(StepCoding, s);
ReadBufferStr(F, ShortName);
ShortName := MyDecodeString(StepCoding, s);
ReadBufferStr(F, Login);
Login := MyDecodeString(StepCoding, s);
ReadBufferStr(F, Password);
Password := MyDecodeString(StepCoding, s);
end;
Procedure TOneUser.Assign(User: TOneUser);
begin
Name := User.Name;
Subname := User.Subname;
Family := User.Family;
ShortName := User.ShortName;
Login := User.Login;
Password := User.Password;
end;
Constructor TListUsers.Create;
begin
Count := 0;
end;
Destructor TListUsers.Destroy;
var
i: integer;
begin
Clear;
FreeMem(@Count);
FreeMem(@Users);
end;
Procedure TListUsers.Clear;
var
i: integer;
begin
for i := Count - 1 to 0 do
Users[i].FreeInstance;
Count := 0;
Setlength(Users, Count);
end;
function TListUsers.UserExists(Login, Password: string): boolean;
var
i: integer;
begin
result := false;
for i := 0 to Count - 1 do
begin
if (trim(Users[i].Login) = trim(Login)) and
(trim(Users[i].Password) = trim(Password)) then
begin
result := true;
exit;
end;
end;
end;
Procedure TListUsers.WriteToFile(FileName: String);
var
Stream: TFileStream;
i: integer;
renm: string;
begin
try
if FileExists(FileName) then
begin
renm := ExtractFilePath(FileName) + 'Temp.Save';
RenameFile(FileName, renm);
DeleteFile(renm);
end;
Stream := TFileStream.Create(FileName, fmCreate or fmShareDenyNone);
try
Stream.WriteBuffer(Count, SizeOf(integer));
for i := 0 to Count - 1 do
Users[i].WriteToStream(Stream);
finally
FreeAndNil(Stream);
end;
except
end;
end;
Procedure TListUsers.ReadFromFile(FileName: string);
var
Stream: TFileStream;
i, apos, cnt: integer;
begin
if not FileExists(FileName) then
exit;
Stream := TFileStream.Create(FileName, fmOpenReadWrite or fmShareDenyNone);
try
Stream.ReadBuffer(cnt, SizeOf(integer));
Clear;
for i := 0 to cnt - 1 do
begin
apos := Add;
Users[apos].ReadFromStream(Stream);
end;
finally
FreeAndNil(Stream);
end;
end;
function TListUsers.Add: integer;
begin
Count := Count + 1;
Setlength(Users, Count);
Users[Count - 1] := TOneUser.Create;
// Users[Count-1].Name := User.Name;
// Users[Count-1].Subname := User.Subname;
// Users[Count-1].Family := User.Family;
// Users[Count-1].ShortName := User.Subname;
// Users[Count-1].Login := User.Login;
// Users[Count-1].Password := User.Password;
result := Count - 1;
end;
Procedure TListUsers.Delete(Login: string);
var
i, apos: integer;
begin
for i := 0 to Count - 1 do
begin
if trim(Users[i].Login) = trim(Login) then
begin
apos := i;
break;
end;
end;
if apos < Count - 1 then
for i := apos to Count - 1 do
Users[apos] := Users[apos + 1];
Count := Count - 1;
Setlength(Users, Count);
end;
initialization
ListUsers := TListUsers.Create;
UPos := ListUsers.Add;
ListUsers.Users[UPos].Name := 'Demo';
ListUsers.Users[UPos].Subname := '';
ListUsers.Users[UPos].Family := '';
ListUsers.Users[UPos].ShortName := 'Demo';
ListUsers.Users[UPos].Login := 'Demo';
ListUsers.Users[UPos].Password := 'Demo';
UPos := ListUsers.Add;
ListUsers.Users[UPos].Name := 'Павел';
ListUsers.Users[UPos].Subname := 'Алексеевич';
ListUsers.Users[UPos].Family := 'Завьялов';
ListUsers.Users[UPos].ShortName := 'Supervisor';
ListUsers.Users[UPos].Login := 'sv';
ListUsers.Users[UPos].Password := '_cyt;yfz_';
finalization
ListUsers.Clear;
ListUsers.FreeInstance;
end.
|
unit Providers.Main;
interface
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, VCL.Wait, Vcl.StdCtrls;
type
TFrmMain = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
procedure TFrmMain.Button1Click(Sender: TObject);
var
Waiting: TWait;
begin
Waiting := TWait.Create('Wait...');
Waiting.Start(
procedure
var
I: Integer;
begin
Waiting.ProgressBar.SetMax(100);
for I := 1 to 100 do
begin
Waiting.SetContent('Wait... ' + I.ToString + ' of 100').ProgressBar.Step();
Sleep(100); // Your code here!!!
end;
end);
end;
procedure TFrmMain.Button2Click(Sender: TObject);
begin
TWait.Create('Wait...').Start(
procedure
begin
Sleep(1500); // Your code here!!!
end);
end;
end.
|
{*****************************************************************************
* The contents of this file are used with permission, subject to
* the Mozilla Public License Version 1.1 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
*****************************************************************************
*
* This file was created by Mason Wheeler. He can be reached for support at
* tech.turbu-rpg.com.
*****************************************************************************}
unit rsCodegen;
interface
uses
Classes, RTTI, Generics.Collections,
rsDefs, rsDefsBackend;
type
IrsOptimizer = interface
procedure Process(proc: TProcSymbol);
end;
TrsMethodFlattener = class(TInterfacedObject, IrsOptimizer)
private
procedure Process(proc: TProcSymbol);
end;
TrsCodegen = class
private
FJumpTable: TDictionary<string, integer>;
FUnresolvedJumpTable: TList<TPair<string, integer>>;
FConstTable: TStringList;
FLocals: TStringList;
FCurrent: TrsScriptUnit;
FCurrentUnit: TUnitSymbol;
FFreeReg: integer;
FTempReg: integer;
FTempList: TList<integer>;
FTempQueue: TQueue<integer>;
FTryStack: TStack<TPair<TSyntaxKind, integer>>;
FUnresStack: TStack<TPair<string, TReferenceType>>;
FDebug: boolean;
FCurrentLine: integer;
function NextReg(temp: integer = 0): integer;
procedure Write(const opcode: TrsAsmInstruction);
procedure WriteOp(opcode: TrsOpcode; left: integer = 0; right: integer = 0);
function UnresolvedJump(const name: string): integer;
function ResolveJump(const name: string): integer;
function Eval(value: TTypedSyntax): integer;
function WriteBinCalc(value: TBinOpSyntax): TrsAsmInstruction;
function WriteIntBinCalc(value: TBinOpSyntax): TrsAsmInstruction;
procedure ProcessProc(proc: TProcSymbol);
function WriteConst(value: TValueSyntax): TrsAsmInstruction;
function WriteUnCalc(value: TUnOpSyntax): TrsAsmInstruction;
function WriteBoolCalc(value: TBoolOpSyntax): TrsAsmInstruction;
function WriteVariable(value: TVariableSyntax): TrsAsmInstruction;
function WriteCall(value: TCallSyntax): TrsAsmInstruction;
function WriteElem(value: TElemSyntax): TrsAsmInstruction;
procedure WriteJump(value: TJumpSyntax);
procedure WriteAssign(value: TAssignmentSyntax);
procedure AssignLValue(lValue: TTypedSyntax; rValue: integer);
procedure AssignElem(lValue: TElemSyntax; rValue: integer);
procedure AssignDot(lValue: TDotSyntax; rValue: integer);
procedure AssignProp(selfVal, rValue: integer; prop: TVariableSyntax);
procedure AssignArrayProp(lValue: TArrayPropSyntax; rValue: integer);
{ procedure AssignField(lValue: TFieldSyntax; rValue: integer);
procedure AssignProp(lValue: TPropSyntax; rValue: integer); }
procedure WriteTryBlock(opcode: TrsOpcode; opType: TSyntaxKind);
procedure CloseTryBlock(kind: TSyntaxKind; const ret: string);
function VariableIndex(sym: TVarSymbol): integer;
procedure WriteTryCallBlock(syntax: TTryCallSyntax);
procedure WriteRaise(syntax: TRaiseSyntax);
function WriteDotChain(value: TDotSyntax): TrsAsmInstruction;
function WriteClassRef(value: TTypeRefSyntax): TrsAsmInstruction;
function WriteCast(value: TCastSyntax): TrsAsmInstruction;
function ClassIndex(sym: TClassTypeSymbol): integer;
function CreateProcInfo(proc: TProcSymbol; start: integer; ext, standalone: boolean): TrsProcInfo;
procedure CreateUnitClass(&unit: TUnitSymbol);
procedure ResolveJumps;
procedure ChangeLeftValue(index, value: integer);
procedure ChangeRightValue(index, value: integer);
function ResolveCall(const name: string; position: integer): integer;
procedure ResolveUnitLocalCalls(&unit: TUnitSymbol);
procedure SetupUnitGlobals(&unit: TUnitSymbol; rsu: TrsScriptUnit);
procedure SetupUnitProperties(&unit: TUnitSymbol; rsu: TrsScriptUnit);
procedure SetupLocals(proc: TProcSymbol);
procedure SetupUnitExternalClasses(&unit: TUnitSymbol; rsu: TrsScriptUnit);
procedure PopUnres;
function ShortCircuitEval(value: TBoolOpSyntax): TrsAsmInstruction;
procedure AssignConst(lvalue: TVariableSyntax; rvalue: TValueSyntax);
procedure AssignSelfBinOp(lvalue: TVariableSyntax; rvalue: TBinOpSyntax);
procedure PushParam(param: TTypedSyntax);
function WriteArrayPropRead(value: TArrayPropSyntax): TrsAsmInstruction;
function WritePropertyValue(symbol: TPropSymbol;
sem: integer): TrsAsmInstruction;
function SerializeArray(const value: TValue): string;
function SerializeConstant(value: TValueSyntax): string;
procedure AssignmentPeephole(start: integer);
procedure LoadSR(l: integer);
procedure ChangeLeft(index, value: integer);
procedure ChangeLastOp(value: TrsOpcode);
public
constructor Create;
destructor Destroy; override;
function Process(&unit: TUnitSymbol): TrsScriptUnit;
property constants: TStringList read FConstTable;
end;
implementation
uses
Windows, Math,
SysUtils, StrUtils, TypInfo,
rsEnex, rsImport,
vmtBuilder, newClass;
{ TrsMethodFlattener }
procedure TrsMethodFlattener.Process(proc: TProcSymbol);
var
block: TSyntaxList;
i, j: integer;
sub: TBlockSyntax;
begin
block := proc.syntax.children;
i := 0;
while i < block.Count do
begin
if block[i].kind = skBlock then
begin
sub := TBlockSyntax(block[i]);
for j := sub.children.count - 1 downto 0 do
block.Insert(i + 1, sub.children[j]);
TSyntaxList(sub.children).OwnsObjects := false;
assert(block[i] = sub);
block.Delete(i);
end
else inc(i);
end;
end;
{ TrsCodegen }
constructor TrsCodegen.Create;
begin
FJumpTable := TDictionary<string, integer>.Create;
FTryStack := TStack<TPair<TSyntaxKind, integer>>.Create;
FConstTable := TStringList.Create;
FConstTable.AddObject('False', TypeInfo(boolean));
FConstTable.AddObject('True', TypeInfo(boolean));
FLocals := TStringList.Create;
FUnresolvedJumpTable := TList<TPair<string, integer>>.Create;
FUnresStack := TStack<TPair<string, TReferenceType>>.Create;
FTempList := TList<integer>.Create;
FTempQueue := TQueue<integer>.Create;
end;
destructor TrsCodegen.Destroy;
begin
FTempQueue.Free;
FTempList.Free;
FJumpTable.Free;
FUnresStack.Free;
FUnresolvedJumpTable.Free;
FTryStack.Free;
FLocals.Free;
inherited;
end;
procedure TrsCodegen.Write(const opcode: TrsAsmInstruction);
begin
assert(opcode.op in [low(TrsOpcode)..High(TrsOpcode)]);
FCurrent.Text.Add(opcode);
FCurrent.OpcodeMap.Add(FCurrentLine);
end;
procedure TrsCodegen.WriteOp(opcode: TrsOpcode; left, right: integer);
var
op: TrsAsmInstruction;
begin
op.op := opcode;
op.left := left;
op.right := right;
write(op);
end;
function TrsCodegen.SerializeArray(const value: TValue): string;
var
sl: TStringList;
i: integer;
begin
sl := TStringList.Create;
try
for i := 0 to value.GetArrayLength - 1 do
sl.add(value.GetArrayElement(i).ToString);
result := '[' + sl.CommaText + ']';
finally
sl.free;
end;
end;
function TrsCodegen.WriteConst(value: TValueSyntax): TrsAsmInstruction;
begin
result.left := NextReg(value.sem);
if value.value.Kind = tkInteger then
begin
result.op := OP_MOVI;
result.right := value.value.AsInteger;
end
else begin
result.op := OP_MOVC;
if value.value.TypeInfo = TypeInfo(boolean) then
begin
result.op := OP_MOVB;
result.right := ord(value.value.AsBoolean);
end
else result.right := FConstTable.AddObject(SerializeConstant(value), pointer(value.value.TypeInfo))
end;
end;
function TrsCodegen.WriteIntBinCalc(value: TBinOpSyntax): TrsAsmInstruction;
const OPCODES: array[TBinOpKind] of TrsOpcode =
(OP_INC, OP_DEC, OP_MULI, OP_DIVI, OP_NOP, OP_MODI, OP_ANDI, OP_ORI, OP_XORI, OP_SHLI, OP_SHRI, OP_NOP);
var
left, new: integer;
begin
left := Eval(value.left);
if left = -1 then
popUnres;
if left > FLocals.Count then
result.left := left
else begin
new := NextReg(value.sem);
WriteOp(OP_MOV, new, left);
result.left := new;
end;
result.right := (value.right as TValueSyntax).value.AsInteger;
result.op := OPCODES[value.op];
assert(result.op <> OP_NOP);
end;
function TrsCodegen.WriteBinCalc(value: TBinOpSyntax): TrsAsmInstruction;
const OPCODES: array[TBinOpKind] of TrsOpcode =
(OP_ADD, OP_SUB, OP_MUL, OP_DIV, OP_FDIV, OP_MOD, OP_AND, OP_OR, OP_XOR, OP_SHL, OP_SHR, OP_AS);
var
left, new: integer;
begin
if not (value.op in [opDivide, opAs]) and (value.right.kind = skValue)
and (TValueSyntax(value.right).value.Kind = tkInteger)
and (value.left.&type.TypeInfo.Kind = tkInteger) then
Exit(WriteIntBinCalc(value));
result.right := Eval(value.right);
left := Eval(value.left);
if left = -1 then
popUnres;
if left > FLocals.Count then
result.left := left
else begin
new := NextReg(value.sem);
WriteOp(OP_MOV, new, left);
result.left := new;
end;
if result.right = -1 then
popUnres;
result.op := OPCODES[value.op];
if (result.op = OP_ADD) and (value.left.&type.TypeInfo.Kind in [tkUString, tkWString, tkWChar]) then
result.op := OP_SCAT;
end;
function TrsCodegen.WriteUnCalc(value: TUnOpSyntax): TrsAsmInstruction;
const OPCODES: array[TUnOpKind] of TrsOpcode = (OP_NEG, OP_NOT, OP_INC, OP_DEC, OP_EXIS);
begin
if value.op in [opNeg, opNot] then
begin
result.right := Eval(value.sub);
if (value.op = opNot) and (result.right = 0) then
result.left := 0
else result.left := NextReg(value.sem);
end
else begin
result.left := Eval(value.sub);
result.right := 1;
end;
result.op := OPCODES[value.op];
end;
function TrsCodegen.ShortCircuitEval(value: TBoolOpSyntax): TrsAsmInstruction;
var
location: integer;
begin
assert(value.op in [opBoolAnd, opBoolOr]);
result.left := 0;
result.op := OP_NOP;
location := FCurrent.Text.Count;
if value.op = opBoolAnd then
WriteOp(OP_FJMP, -1)
else WriteOp(OP_TJMP, -1);
Eval(value.right);
ChangeLeftValue(location, FCurrent.Text.Count - location);
end;
function TrsCodegen.WriteBoolCalc(value: TBoolOpSyntax): TrsAsmInstruction;
const
OPCODES: array[TBoolOpKind] of TrsOpcode =
(OP_GTE, OP_LTE, OP_GT, OP_LT, OP_EQ, OP_NEQ, OP_IN, OP_IS, OP_NOP, OP_NOP, OP_XORB);
OPCODES_I: array[opGreaterEqual..opNotEqual] of TrsOpcode =
(OP_GTEI, OP_LTEI, OP_GTI, OP_LTI, OP_EQI, OP_NEQI);
begin
result.left := Eval(value.left);
//special-case opimization
if (value.op in [opGreaterEqual..opNotEqual]) and (value.right.kind = skValue)
and (TValueSyntax(value.right).value.Kind = tkInteger) then
begin
result.right := TValueSyntax(value.right).value.AsInteger;
result.op := OPCODES_I[value.op];
end
else if value.op in [opBoolAnd, opBoolOr] then
result := ShortCircuitEval(value)
else begin
result.right := Eval(value.right);
result.op := OPCODES[value.op];
if (result.left = 0) and (value.op in [opEquals, opNotEqual]) then
begin
inc(result.op, ord(OP_EQB) - ord(OP_EQ));
if FCurrent.Text.Last.op = OP_MOVB then
ChangeLastOp(OP_MOVC);
end;
end;
end;
function MakeArrayPropGetter(const value: string): string;
begin
result := StringReplace(value, '.', '.Get*', []);
end;
function TrsCodegen.WritePropertyValue(symbol: TPropSymbol; sem: integer): TrsAsmInstruction;
var
typ: TTypeSymbol;
isArray: boolean;
refType: TReferenceType;
begin
typ := symbol.&Type;
isArray := AnsiStartsStr('ARRAYOF*', typ.name);
if isArray then
result.op := OP_MVAP
else result.op := OP_MOVP;
result.left := NextReg(sem);
result.right := -1;
if isArray then
FCurrent.Unresolved.Add(TUnresolvedReference.Create(MakeArrayPropGetter(symbol.fullName), FCurrent.Text.Count, rtArrayProp))
else FCurrent.Unresolved.Add(TUnresolvedReference.Create(symbol.fullName, FCurrent.Text.Count, rtProp));
end;
function TrsCodegen.WriteVariable(value: TVariableSyntax): TrsAsmInstruction;
begin
if value.symbol is TFieldSymbol then
begin
result.op := OP_MOVF;
result.left := NextReg(value.sem);
result.right := TFieldSymbol(value.symbol).index;
end
else if value.symbol is TPropSymbol then
result := WritePropertyValue(TPropSymbol(value.symbol), value.sem)
else if value.&type = BooleanType then
begin
result.op := OP_MOV;
result.left := 0;
result.right := VariableIndex(value.symbol);
end
else begin
result.op := OP_NOP;
result.left := VariableIndex(value.symbol);
end
end;
function TrsCodegen.UnresolvedJump(const name: string): integer;
begin
result := -1;
FUnresolvedJumpTable.Add(TPair<string, integer>.Create(name, FCurrent.Text.Count));
end;
function TrsCodegen.ResolveJump(const name: string): integer;
begin
if FJumpTable.TryGetValue(name, result) then
result := result - FCurrent.Text.Count
else result := UnresolvedJump(name);
end;
function TrsCodegen.ResolveCall(const name: string; position: integer): integer;
var
table: TUnresList;
begin
if FCurrent.Routines.ContainsKey(name) then
result := FCurrent.Routines[name].index - position
else begin
result := -1;
if AnsiStartsText(FCurrent.namedot, name) then
table := FCurrent.UnresolvedCalls
else table := FCurrent.Unresolved;
table.Add(TUnresolvedReference.Create(name, position, rtCall));
end;
end;
function TrsCodegen.SerializeConstant(value: TValueSyntax): string;
begin
if value.value.Kind in [tkArray, tkDynArray] then
result := SerializeArray(value.value)
else result := value.value.ToString;
end;
procedure TrsCodegen.PushParam(param: TTypedSyntax);
var
left: integer;
last: TrsAsmInstruction;
begin
if param.kind = skValue then
begin
if TValueSyntax(param).value.Kind = tkInteger then
WriteOp(OP_PSHI, TValueSyntax(param).value.AsInteger)
else if TValueSyntax(param).value.TypeInfo = TypeInfo(boolean) then
WriteOp(OP_PSHC, ord(TValueSyntax(param).value.AsBoolean))
else WriteOp(OP_PSHC, FConstTable.AddObject(serializeConstant(TValueSyntax(param)), pointer(TValueSyntax(param).value.TypeInfo)));
end
else begin
left := Eval(param);
if left = -1 then
PopUnres;
last := FCurrent.Text.Last;
if last.op = OP_CALL then
begin
FCurrent.Text.Delete(FCurrent.Text.Count - 1);
WriteOp(OP_PCAL, last.left, last.right);
end
else WriteOp(OP_PUSH, left);
end;
end;
function TrsCodegen.WriteCall(value: TCallSyntax): TrsAsmInstruction;
var
param: TTypedSyntax;
left: Integer;
begin
WriteOp(OP_LIST, value.params.Count);
for param in value.params do
PushParam(param);
if assigned(value.SelfSymbol) then
begin
left := Eval(value.SelfSymbol);
if left = -1 then
PopUnres;
LoadSR(left);
end;
result.op := OP_CALL;
result.right := ResolveCall(value.proc.fullName, FCurrent.Text.Count);
if assigned(value.proc.&Type) then
begin
if value.proc.&type = BooleanType then
result.left := 0
else result.left := NextReg(value.sem);
end
else result.left := -1;
end;
procedure TrsCodegen.PopUnres;
var
pair: TPair<string, TReferenceType>;
ref: TUnresolvedReference;
begin
pair := FUnresStack.Pop;
ref := TUnresolvedReference.Create(pair.Key, FCurrent.Text.Count, pair.Value);
assert(pair.Value <> rtCall);
FCurrent.Unresolved.Add(ref);
end;
function TrsCodegen.WriteElem(value: TElemSyntax): TrsAsmInstruction;
var
left: integer;
begin
result.left := NextReg(value.sem);
result.right := Eval(value.Right);
result.op := OP_ELEM;
if result.right = -1 then
popUnres;
left := Eval(value.Left);
if left = -1 then
popUnres;
WriteOp(OP_ARYL, left);
end;
function TrsCodegen.WriteDotChain(value: TDotSyntax): TrsAsmInstruction;
var
left: integer;
begin
left := Eval(value.Left);
if left = -1 then
popUnres;
LoadSR(left);
result.op := OP_NOP;
result.left := Eval(value.Right);
end;
function TrsCodegen.ClassIndex(sym: TClassTypeSymbol): integer;
begin
assert(false); //TODO: implement this
end;
function TrsCodegen.WriteClassRef(value: TTypeRefSyntax): TrsAsmInstruction;
begin
WriteOp(OP_MCLS, NextReg, ClassIndex(value.&class));
end;
function TrsCodegen.WriteCast(value: TCastSyntax): TrsAsmInstruction;
begin
if (value.Base.&type.TypeInfo.Kind = tkInteger) and (value.&type.TypeInfo.Kind = tkFloat) then
begin
result.op := OP_AITF;
result.left := NextReg(value.sem);
result.right := Eval(value.Base);
end
else raise EParseError.Create('Corrupt parse tree');
end;
function TrsCodegen.WriteArrayPropRead(value: TArrayPropSyntax): TrsAsmInstruction;
var
base: TDotSyntax;
left: integer;
param: TTypedSyntax;
begin
WriteOp(OP_LIST, value.params.Count);
for param in value.params do
PushParam(param);
base := value.base;
left := Eval(base.Left);
if left = -1 then
popUnres;
LoadSR(left);
result.op := OP_MVAP;
result.left := NextReg(value.sem);
result.right := -1;
FCurrent.Unresolved.Add(TUnresolvedReference.Create(
((Base.Right as TVariableSyntax).Symbol as TPropSymbol).readSpec.fullName,
FCurrent.Text.Count, rtArrayProp));
end;
function TrsCodegen.Eval(value: TTypedSyntax): integer;
var
op: TrsAsmInstruction;
begin
case value.kind of
skValue: op := WriteConst(TValueSyntax(value));
skBinOp: op := WriteBinCalc(TBinOpSyntax(value));
skUnOp: op := WriteUnCalc(TUnOpSyntax(value));
skBoolOp: op := WriteBoolCalc(TBoolOpSyntax(value));
skVariable: op := WriteVariable(TVariableSyntax(value));
skCall: op := WriteCall(TCallSyntax(value));
skElem: op := WriteElem(TElemSyntax(value));
skDot: op := WriteDotChain(TDotSyntax(value));
skType: op := WriteClassRef(TTypeRefSyntax(value));
skCast: op := WriteCast(TCastSyntax(value));
skArrayProp: op := WriteArrayPropRead(TArrayPropSyntax(value));
else raise EParseError.Create('Corrupt parse tree');
end;
if (op.op <> OP_NOP) or FDebug then
write(op);
if value.kind <> skBoolOp then
result := op.left
else result := 0;
end;
procedure TrsCodegen.LoadSR(l: integer);
var
prev: TrsAsmInstruction;
begin
prev := FCurrent.Text.Last;
if (prev.op = OP_MOVP) and (prev.left = l) then
ChangeLastOp(OP_MOVPSR)
else if (prev.op = OP_MVAP) and (prev.left = l) then
ChangeLastOp(OP_MVAPSR)
else writeOp(OP_SRLD, l);
end;
function TrsCodegen.NextReg(temp: integer): integer;
var
reg: integer;
begin
if temp > 0 then
begin
if temp <> FTempReg then
begin
FTempReg := temp;
for reg in FTempList do
FTempQueue.Enqueue(reg);
FTempList.Clear;
end;
if FTempQueue.Count > 0 then
begin
result := FTempQueue.Dequeue;
FTempList.Add(result);
FFreeReg := max(FFreeReg, result);
Exit;
end;
end;
inc(FFreeReg);
result := FFreeReg;
if temp > 0 then
FTempList.Add(result);
end;
procedure TrsCodegen.WriteJump(value: TJumpSyntax);
var
left: integer;
begin
left := ResolveJump(value.name);
if value.conditional then
WriteOp(OP_FJMP, left)
else WriteOp(OP_JUMP, left);
end;
procedure TrsCodegen.AssignElem(lValue: TElemSyntax; rValue: integer);
var
op: TrsAsmInstruction;
begin
WriteOp(OP_ARYL, Eval(lValue.Left));
op.op := OP_EASN;
//minor optimization for a common case
if (lValue.Right.kind = skValue) and (TValueSyntax(lValue.Right).value.Kind = tkInteger) then
begin
op.op := OP_EASC;
op.left := TValueSyntax(lValue.Right).value.AsInteger;
end
else op.left := Eval(lValue.Right);
op.right := rValue;
Write(op);
end;
procedure TrsCodegen.AssignArrayProp(lValue: TArrayPropSyntax; rValue: integer);
var
sr: integer;
param: TTypedSyntax;
begin
WriteOp(OP_LIST, lValue.params.Count);
for param in lValue.params do
PushParam(param);
sr := Eval(lValue.base.left);
if sr = -1 then
PopUnres;
LoadSR(sr);
FCurrent.Unresolved.Add(TUnresolvedReference.Create(((lValue.base.Right as TVariableSyntax).Symbol as TPropSymbol).WriteSpec.fullName, FCurrent.Text.Count, rtArrayProp));
WriteOp(OP_APSN, -1, rValue);
end;
{
procedure TrsCodegen.AssignField(lValue: TFieldSyntax; rValue: integer);
begin
WriteOp(OP_LIST);
WriteOp(OP_PUSH, Eval(lValue.Left));
WriteOp(OP_FASN, Eval(lValue.Right), rValue);
end;
}
procedure TrsCodegen.AssignProp(selfVal, rValue: integer; prop: TVariableSyntax);
var
propSym: TPropSymbol;
begin
LoadSR(selfVal);
propSym := prop.symbol as TPropSymbol;
FCurrent.Unresolved.Add(TUnresolvedReference.Create(propSym.fullName, FCurrent.Text.Count, rtProp));
WriteOp(OP_PASN, -1, rValue);
end;
procedure TrsCodegen.AssignDot(lValue: TDotSyntax; rValue: integer);
var
selfVal: integer;
begin
selfVal := eval(lValue.left);
if selfVal = -1 then
PopUnres;
if lValue.Right.kind = skArrayProp then
AssignArrayProp(TArrayPropSyntax(lValue.Right), rValue)
else case (lValue.right as TVariableSyntax).symbol.kind of
syProp: AssignProp(selfVal, rValue, TVariableSyntax(lValue.right));
// syVariable: AssignField(selfVal, dotVal, rValue);
else assert(false);
end;
end;
procedure TrsCodegen.AssignLValue(lValue: TTypedSyntax; rValue: integer);
var
left: integer;
begin
case lValue.kind of
skVariable:
begin
left := VariableIndex(TVariableSyntax(lValue).symbol);
if left = -1 then
PopUnres;
WriteOp(OP_VASN, left, rValue);
end;
skElem: AssignElem(TElemSyntax(lValue), rValue);
skDot: AssignDot(TDotSyntax(lValue), rValue);
skArrayProp: AssignArrayProp(TArrayPropSyntax(lValue), rValue);
{ skField: AssignField(TFieldSyntax(lValue), rValue);
skProp: AssignProp(TPropSyntax(lValue), rValue); }
else raise EParseError.Create('Corrupt parse tree');
end;
end;
procedure TrsCodegen.AssignConst(lvalue: TVariableSyntax; rvalue: TValueSyntax);
var
left: integer;
begin
left := VariableIndex(lValue.symbol);
if rvalue.value.Kind = tkInteger then
WriteOp(OP_MOVI, left, rValue.value.AsInteger)
else if rValue.value.TypeInfo = TypeInfo(boolean) then
WriteOp(OP_MOVB, left, ord(rValue.value.AsBoolean))
else WriteOp(OP_MOVC, left, FConstTable.AddObject(SerializeConstant(rvalue), pointer(rvalue.value.TypeInfo)));
end;
procedure TrsCodegen.AssignSelfBinOp(lvalue: TVariableSyntax; rvalue: TBinOpSyntax);
const OPCODES: array[TBinOpKind] of TrsOpcode =
(OP_ADD, OP_SUB, OP_MUL, OP_DIV, OP_FDIV, OP_MOD, OP_AND, OP_OR, OP_XOR, OP_SHL, OP_SHR, OP_AS);
var
left, right: integer;
begin
assert(lValue.symbol = TVariableSyntax(rvalue.left).symbol);
right := Eval(rValue.right);
left := Eval(lValue);
WriteOp(OPCODES[rValue.op], left, right);
end;
procedure TrsCodegen.ChangeLastOp(value: TrsOpcode);
var
index: integer;
op: TrsAsmInstruction;
begin
index := FCurrent.text.count - 1;
op := FCurrent.Text[index];
op.op := value;
FCurrent.Text[index] := op;
end;
procedure TrsCodegen.ChangeLeft(index, value: integer);
var
op: TrsAsmInstruction;
begin
op := FCurrent.Text[index];
op.left := value;
FCurrent.Text[index] := op;
end;
procedure TrsCodegen.AssignmentPeephole(start: integer);
var
i, j: integer;
mov, ml, mr: integer;
valid: boolean;
op: TrsAsmInstruction;
begin
mov := -1; ml := -1; mr := -1;
valid := false;
i := start;
while i < FCurrent.Text.Count do
begin
op := FCurrent.Text[i];
if op.op = OP_MOV then
begin
mov := i;
ml := op.left;
mr := op.right;
valid := true;
end
else if valid and (op.op = OP_VASN) and (op.left = mr) and (op.right = ml) then
begin
FCurrent.Text.Delete(mov);
dec(i);
for j := mov to i do
if FCurrent.Text[j].left = ml then
ChangeLeft(j, mr);
FCurrent.text.Delete(i);
dec(i);
valid := false;
if ml = FFreeReg then
dec(FFreeReg);
end
else if valid and not ((op.op in [OP_ADD..OP_SHR, OP_MULI..OP_SHRI]) and (op.left = ml)) then
valid := false;
inc(i);
end;
end;
procedure TrsCodegen.WriteAssign(value: TAssignmentSyntax);
var
current: integer;
begin
// x := 5;
if (value.lvalue.kind = skVariable) and (value.rvalue.kind = skValue) then
AssignConst(TVariableSyntax(value.lValue), TValueSyntax(value.rValue))
//x := x * 5;
else if (value.lvalue.kind = skVariable) and (value.rvalue.kind = skBinOp) and
(TBinOpSyntax(value.rValue).left.kind = skVariable) and
(TVariableSyntax(TBinOpSyntax(value.rValue).left).symbol = TVariableSyntax(value.lValue).symbol) then
AssignSelfBinOp(TVariableSyntax(value.lValue), TBinOpSyntax(value.rValue))
//general case
else begin
current := FCurrent.Text.Count;
AssignLValue(value.lValue, Eval(value.rValue));
AssignmentPeephole(current);
end;
end;
procedure TrsCodegen.WriteTryBlock(opcode: TrsOpcode; opType: TSyntaxKind);
begin
WriteOp(opcode);
FTryStack.Push(TPair<TSyntaxKind, integer>.Create(opType, FCurrent.Text.Count));
end;
procedure TrsCodegen.CloseTryBlock(kind: TSyntaxKind; const ret: string);
var
top: TPair<TSyntaxKind, integer>;
tryOp: TrsAsmInstruction;
begin
top := FTryStack.Pop;
if top.Key <> kind then
raise EParseError.Create('Corrupt parse tree');
tryOp := FCurrent.Text[top.Value];
tryOp.left := FCurrent.Text.Count - top.Value;
FCurrent.Text[top.Value] := tryOp;
WriteOp(OP_CTRY, ResolveJump(ret));
end;
function TrsCodegen.VariableIndex(sym: TVarSymbol): integer;
begin
if assigned(FLocals) then
result := FLocals.IndexOf(UpperCase(sym.name))
else result := -1;
if result = -1 then
FUnresStack.push(TPair<string, TReferenceType>.Create(sym.fullName, rtVar));
end;
procedure TrsCodegen.WriteTryCallBlock(syntax: TTryCallSyntax);
begin
WriteOp(OP_TRYC, ResolveJump(syntax.jump));
WriteOp(OP_JUMP, ResolveJump(syntax.ret));
end;
procedure TrsCodegen.WriteRaise(syntax: TRaiseSyntax);
begin
if syntax.obj = nil then
WriteOp(OP_RAIS)
else WriteOp(OP_RAIS, Eval(syntax.obj));
end;
function TrsCodegen.CreateProcInfo(proc: TProcSymbol; start: integer; ext, standalone: boolean): TrsProcInfo;
var
param: TParamSymbol;
params: TList<IBuffer>;
info: PTypeInfo;
begin
result.index := start;
params := TList<IBuffer>.Create;
try
if assigned(proc.paramList) then
for param in proc.paramList do
params.Add(vmtBuilder.CreateMethodParam(param.flags, param.&Type.TypeInfo, 0, param.name));
if assigned(proc.&type) then
info := proc.&Type.TypeInfo
else info := nil;
result.info := vmtBuilder.CreateMethodInfo(pointer(start), proc.name, ccReg,
info, params.ToArray);
result.isExternal := ext;
result.standalone := standalone;
finally
params.Free;
end;
end;
procedure TrsCodegen.ChangeLeftValue(index, value: integer);
var
op: TrsAsmInstruction;
begin
op := FCurrent.Text[index];
op.left := value;
FCurrent.Text[index] := op;
end;
procedure TrsCodegen.ChangeRightValue(index, value: integer);
var
op: TrsAsmInstruction;
begin
op := FCurrent.Text[index];
op.right:= value;
FCurrent.Text[index] := op;
end;
procedure TrsCodegen.ResolveJumps;
var
pair: TPair<string, integer>;
begin
for pair in FUnresolvedJumpTable do
begin
if not FJumpTable.ContainsKey(pair.Key) then
raise EParseError.CreateFmt('Internal error: Invalid jump "%s"', [pair.key]);
ChangeLeftValue(pair.Value, FJumpTable[pair.Key] - pair.Value);
end;
FUnresolvedJumpTable.Clear;
FJumpTable.Clear;
end;
procedure TrsCodegen.SetupLocals(proc: TProcSymbol);
var
locals: TStringList;
local: string;
i: integer;
begin
FLocals.Clear;
locals := proc.symbolTable.KeysWhereValue(
function(value: TSymbol): boolean
begin
result := value.kind = syVariable
end);
try
for local in locals do
FLocals.Add(local);
finally
locals.Free;
end;
if assigned(proc.paramList) then
for i := 0 to proc.paramList.Count - 1 do
begin
FLocals.Delete(FLocals.IndexOf(proc.paramList[i].name));
FLocals.Insert(i, UpperCase(proc.paramList[i].name));
end;
if assigned(proc.&Type) then
begin
FLocals.Delete(FLocals.IndexOf('RESULT'));
FLocals.Insert(proc.paramList.count, 'RESULT');
end;
FLocals.Insert(0, '');
FTempQueue.Clear;
FTempList.Clear;
end;
procedure TrsCodegen.ProcessProc(proc: TProcSymbol);
var
syntax: TSyntax;
start: integer;
dummy: integer;
begin
SetupLocals(proc);
start := FCurrent.Text.Count;
WriteOp(OP_INIT);
FFreeReg := FLocals.Count;
for syntax in proc.syntax.children do
begin
if FCurrentUnit.LineMap.TryGetValue(syntax, dummy) then
FCurrentLine := dummy;
if syntax is TTypedSyntax then
Eval(TTypedSyntax(syntax))
else case syntax.kind of
skReturn: WriteOp(OP_RET);
skLabel: FJumpTable.Add(TLabelSyntax(syntax).name, FCurrent.Text.Count);
skJump: WriteJump(TJumpSyntax(syntax));
skAssign: WriteAssign(TAssignmentSyntax(syntax));
skTryF: WriteTryBlock(OP_TRYF, skFinally);
skTryE: WriteTryBlock(OP_TRYE, skExcept);
skFinally: CloseTryBlock(skFinally, TFinallySyntax(syntax).ret);
skExcept: CloseTryBlock(skExcept, TExceptSyntax(syntax).ret);
skELoad: WriteOp(OP_EXLD, VariableIndex(TExceptionLoadSyntax(syntax).symbol));
skTryCall: WriteTryCallBlock(TTryCallSyntax(syntax));
skRaise: WriteRaise(TRaiseSyntax(syntax));
else raise EParseError.Create('Corrupt parse tree');
end;
end;
ChangeLeftValue(start, FFreeReg);
ResolveJumps;
assert(FUnresStack.Count = 0);
end;
procedure TrsCodegen.CreateUnitClass(&unit: TUnitSymbol);
var
newClass: TNewClass;
info: TrsProcInfo;
prefix: string;
begin
if &unit.IsExternal then
prefix := 'rsUNITEXT*'
else prefix := 'rsUNIT*';
newClass := TNewClass.Create(TObject, prefix + &unit.name);
FCurrent.&Unit.AddClass(newClass);
for info in FCurrent.Routines.Values do
if info.standalone then
newClass.AddMethod(info.info, 0, 0);
end;
procedure TrsCodegen.ResolveUnitLocalCalls(&unit: TUnitSymbol);
var
i: integer;
left: integer;
table: TUnresList;
ref: TUnresolvedReference;
unitName: string;
begin
table := FCurrent.UnresolvedCalls;
unitName := &unit.name + '.';
for i := table.Count - 1 downto 0 do
begin
ref := table[i];
begin
left := ResolveCall(ref.name, ref.location);
assert(left <> -1);
ChangeRightValue(ref.location, left);
end;
end;
table.Clear;
end;
procedure TrsCodegen.SetupUnitProperties(&unit: TUnitSymbol; rsu: TrsScriptUnit);
var
proplist: TList<TPair<string, TSymbol>>;
pair: TPair<string, TSymbol>;
symbol: TSymbol;
cls: TClassTypeSymbol;
props: TArray<TRttiProperty>;
prop, found: TRttiProperty;
propSym: TPropSymbol;
ctx: TRttiContext;
begin
ctx := TRttiContext.Create;
for symbol in &unit.privates.Values do
if (symbol.kind = syType) and (symbol is TClassTypeSymbol) then
begin
cls := TClassTypeSymbol(symbol);
proplist := cls.GetSymbolTable.Where(
function(name: string; value: TSymbol): boolean
begin result := (value.kind = syProp) end);
props := ctx.GetType(cls.metaclass.ClassInfo).GetDeclaredProperties;
try
for pair in propList do
begin
propSym := TPropSymbol(pair.Value);
if assigned(propSym.paramList) and (propSym.paramList.Count > 0) then
begin
if assigned(propSym.readSpec) then
rsu.ArrayProps.Add(propSym.readSpec.fullName);
if assigned(propSym.writeSpec) then
rsu.ArrayProps.Add(propSym.writeSpec.fullName);
end
else begin
found := nil;
for prop in props do
if AnsiSameText(prop.Name, propSym.name)then
begin
found := prop;
Break;
end;
assert(assigned(found));
rsu.properties.AddObject(propSym.fullName, found);
end;
end;
finally
proplist.Free;
end;
end;
end;
procedure TrsCodegen.SetupUnitGlobals(&unit: TUnitSymbol; rsu: TrsScriptUnit);
var
list: TList<TPair<string, TSymbol>>;
pair: TPair<string, TSymbol>;
begin
list := &unit.privates.Where(
function(name: string; value: TSymbol): boolean
begin
result := value.kind = syVariable
end);
try
for pair in list do
rsu.Globals.AddObject(pair.Value.fullName, pointer(TVarSymbol(pair.Value).&Type.TypeInfo));
finally
list.free;
end;
end;
procedure TrsCodegen.SetupUnitExternalClasses(&unit: TUnitSymbol; rsu: TrsScriptUnit);
var
list: TList<TPair<string, TSymbol>>;
pair: TPair<string, TSymbol>;
begin
list := &unit.privates.Where(
function(name: string; value: TSymbol): boolean
begin
result := (value.kind = syType) and (TTypeSymbol(value) is TExternalClassType)
end);
try
for pair in list do
rsu.ExtClasses.Add(TExternalClassType(pair.Value).metaclass);
finally
list.free;
end;
end;
function TrsCodegen.Process(&unit: TUnitSymbol): TrsScriptUnit;
var
procs: TList<TProcSymbol>;
proc: TProcSymbol;
index: integer;
begin
//OutputDebugString('SAMPLING ON');
result := TrsScriptUnit.Create(&unit.name, &unit.IsExternal);
try
FCurrent := result;
FCurrentUnit := &unit;
index := 0;
procs := &unit.procs;
try
for proc in procs do
begin
if not &unit.IsExternal then
begin
index := FCurrent.Text.Count;
processProc(proc);
end
else inc(index);
FCurrent.Routines.Add(proc.fullName, CreateProcInfo(proc, index, &unit.IsExternal,
proc.parent = &unit));
end;
SetupUnitGlobals(&unit, result);
SetupUnitProperties(&unit, result);
SetupUnitExternalClasses(&unit, result);
if not &unit.IsExternal then
ResolveUnitLocalCalls(&unit);
finally
procs.Free;
end;
CreateUnitClass(&unit);
except
result.Free;
raise;
end;
//OutputDebugString('SAMPLING OFF');
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.DUnitCompatibility;
/// This unit provides basic compatibilty with DUnit Tests (not the framework!).
interface
{$I DUnitX.inc}
uses
{$IFDEF USE_NS}
System.SysUtils,
{$ELSE}
SysUtils,
{$ENDIF}
DUnitX.TestFramework;
type
TTestCase = class
protected
procedure SetUp; virtual;
procedure TearDown; virtual;
function GetName : string;
public
procedure Check(const condition: Boolean; const msg: string = '');deprecated 'Use DUnitX.Assert class';
procedure CheckTrue(const condition: Boolean; const msg: string = '');deprecated 'Use DUnitX.Assert class';
procedure CheckFalse(const condition: Boolean; const msg: string = '');deprecated 'Use DUnitX.Assert class';
procedure CheckEquals(const expected, actual: extended; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckEquals(const expected, actual: extended; const delta: extended; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckEquals(const expected, actual: integer; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckEquals(const expected, actual: Cardinal; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckEquals(const expected, actual: int64; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckEquals(const expected, actual: UnicodeString; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
{$IFNDEF NEXTGEN}
procedure CheckEquals(const expected, actual: AnsiString; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckEquals(const expected, actual: ShortString; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
{$ENDIF}
procedure CheckEqualsString(const expected, actual: string; const msg: string = '');deprecated 'Use DUnitX.Assert class';
{$IFNDEF NEXTGEN}
procedure CheckEquals(const expected, actual: WideString; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckEqualsWideString(const expected, actual: WideString; const msg: string = '');deprecated 'Use DUnitX.Assert class';
{$ENDIF}
procedure CheckEqualsMem(const expected, actual: pointer; const size:longword; const msg : string='');deprecated 'Use DUnitX.Assert class';
procedure CheckEquals(const expected, actual: Boolean; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckEqualsBin(const expected, actual: longword; const msg: string = ''; digits: integer=32);deprecated 'Use DUnitX.Assert class';
procedure CheckEqualsHex(const expected, actual: longword; const msg: string = ''; digits: integer=8);deprecated 'Use DUnitX.Assert class';
procedure CheckNotEquals(const expected, actual: integer; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckNotEquals(const expected, actual: Cardinal; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckNotEquals(const expected, actual: int64; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckNotEquals(const expected: extended; const actual: extended; const delta: extended = 0; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckNotEquals(const expected, actual: string; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckNotEqualsString(const expected, actual: string; const msg: string = '');deprecated 'Use DUnitX.Assert class';
{$IFNDEF NEXTGEN}
procedure CheckNotEquals(const expected, actual: WideString; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckNotEqualsWideString(const expected, actual: WideString; const msg: string = '');deprecated 'Use DUnitX.Assert class';
{$ENDIF}
procedure CheckNotEqualsMem(const expected, actual: pointer; const size:longword; const msg : string='');deprecated 'Use DUnitX.Assert class';
procedure CheckNotEquals(const expected, actual: Boolean; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckNotEqualsBin(const expected, actual: longword; const msg: string = ''; digits: integer=32);deprecated 'Use DUnitX.Assert class';
procedure CheckNotEqualsHex(const expected, actual: longword; const msg: string = ''; digits: integer=8);deprecated 'Use DUnitX.Assert class';
procedure CheckNotNull(const obj :IUnknown; const msg :string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckNull(const obj: IUnknown; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckSame(const expected, actual: IInterface; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckSame(const expected, actual: TObject; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckNotNull(const obj: TObject; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckNull(const obj: TObject; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckException(const AMethod: TTestMethod; const AExceptionClass: ExceptClass; const msg :string = '');deprecated 'Use DUnitX.Assert class';
procedure CheckEquals(const expected, actual: TClass; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckInherits(const expected, actual: TClass; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure CheckIs(const AObject :TObject; const AClass: TClass; const msg: string = ''); overload;deprecated 'Use DUnitX.Assert class';
procedure Status(const msg : string);
//Redirect WriteLn to our loggers.
procedure WriteLn(const msg : string);overload;
procedure WriteLn;overload;
[Setup]
procedure TestSetupMethod;
[TearDown]
procedure TestTeardownMethod;
property Name: string read GetName;
end;
implementation
uses
DUnitX.TestRunner;
//Borrowed from DUnit.
function IntToBin(const value, digits: longword): string;
const
ALL_32_BIT_0 = '00000000000000000000000000000000';
var
counter: integer;
pow: integer;
begin
Result := ALL_32_BIT_0;
SetLength(Result, digits);
pow := 1 shl (digits - 1);
if value <> 0 then
for counter := 0 to digits - 1 do
begin
if (value and (pow shr counter)) <> 0 then
begin
{$IFDEF NEXTGEN}
Result.Remove(counter, 1);
Result.Insert(counter, '1');
{$ELSE}
Result[counter+1] := '1';
{$ENDIF}
end;
end;
end;
procedure TTestCase.Check(const condition: Boolean; const msg: string);
begin
Assert.IsTrue(condition,msg);
end;
procedure TTestCase.CheckTrue(const condition: Boolean; const msg: string);
begin
Assert.IsTrue(condition,msg);
end;
function TTestCase.GetName: string;
begin
result := TDUnitXTestRunner.GetCurrentTestName;
end;
procedure TTestCase.SetUp;
begin
end;
procedure TTestCase.Status(const msg: string);
begin
Self.WriteLn(msg);
end;
procedure TTestCase.TearDown;
begin
end;
procedure TTestCase.TestSetupMethod;
begin
Self.SetUp;
end;
procedure TTestCase.TestTeardownMethod;
begin
Self.TearDown;
end;
procedure TTestCase.WriteLn(const msg: string);
var
runner : ITestRunner;
begin
runner := TDUnitXTestRunner.GetActiveRunner;
if runner <> nil then
runner.Log(TLogLevel.Information,msg)
else
System.Writeln(msg);
end;
procedure TTestCase.WriteLn;
begin
Self.WriteLn('');
end;
procedure TTestCase.CheckFalse(const condition: Boolean; const msg: string);
begin
Assert.IsFalse(condition,msg);
end;
procedure TTestCase.CheckEquals(const expected, actual: extended; const msg: string);
begin
Assert.AreEqual(expected,actual,0,msg);
end;
procedure TTestCase.CheckEquals(const expected, actual: extended; const delta: extended; const msg: string);
begin
Assert.AreEqual(expected,actual,delta,msg);
end;
procedure TTestCase.CheckEquals(const expected, actual: integer; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreEqual<integer>(expected,actual,msg);
{$ELSE}
Assert.IsTrue(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckEquals(const expected, actual: Cardinal; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreEqual<Cardinal>(expected,actual,msg);
{$ELSE}
Assert.IsTrue(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckEquals(const expected, actual: int64; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreEqual<Int64>(expected,actual,msg);
{$ELSE}
Assert.IsTrue(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckEquals(const expected, actual: UnicodeString; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreEqual(expected, actual, msg);
{$ELSE}
Assert.IsTrue(expected = actual, msg);
{$ENDIF}
end;
{$IFNDEF NEXTGEN}
procedure TTestCase.CheckEquals(const expected, actual: AnsiString; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreEqual<AnsiString>(expected,actual,msg);
{$ELSE}
Assert.IsTrue(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckEquals(const expected, actual: ShortString; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreEqual<ShortString>(expected,actual,msg);
{$ELSE}
Assert.IsTrue(expected = actual, msg);
{$ENDIF}
end;
{$ENDIF}
procedure TTestCase.CheckEqualsString(const expected, actual: string; const msg: string);
begin
Assert.AreEqual(expected,actual,true,msg);
end;
{$IFNDEF NEXTGEN}
procedure TTestCase.CheckEquals(const expected, actual: WideString; const msg: string);
begin
Assert.AreEqual(expected,actual,true,msg);
end;
procedure TTestCase.CheckEqualsWideString(const expected, actual: WideString; const msg: string);
begin
Assert.AreEqual(expected,actual,true,msg);
end;
{$ENDIF}
procedure TTestCase.CheckEqualsMem(const expected, actual: pointer; const size:longword; const msg : string = '');
begin
Assert.AreEqualMemory(expected,actual,size,msg);
end;
procedure TTestCase.CheckEquals(const expected, actual: Boolean; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreEqual<Boolean>(expected,actual,msg);
{$ELSE}
Assert.IsTrue(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckEqualsBin(const expected, actual: longword; const msg: string; digits: integer);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreEqual(IntToBin(expected, digits), IntToBin(actual, digits),msg);
{$ELSE}
Assert.IsTrue(IntToBin(expected, digits) = IntToBin(actual, digits), msg);
{$ENDIF}
end;
procedure TTestCase.CheckEqualsHex(const expected, actual: longword; const msg: string; digits: integer);
begin
Assert.AreEqual(IntToHex(expected, digits), IntToHex(actual, digits),true,msg);
end;
procedure TTestCase.CheckNotEquals(const expected, actual: integer; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreNotEqual<integer>(expected,actual,msg);
{$ELSE}
Assert.IsFalse(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckNotEquals(const expected, actual: Cardinal; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreNotEqual<Cardinal>(expected,actual,msg);
{$ELSE}
Assert.IsFalse(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckNotEquals(const expected, actual: int64; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreNotEqual<int64>(expected,actual,msg);
{$ELSE}
Assert.IsFalse(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckNotEquals(const expected: extended; const actual: extended; const delta: extended; const msg: string);
begin
Assert.AreNotEqual(expected,actual,delta,msg);
end;
procedure TTestCase.CheckNotEquals(const expected, actual: string; const msg: string);
begin
Assert.AreNotEqual(expected,actual,true,msg);
end;
procedure TTestCase.CheckNotEqualsString(const expected, actual: string; const msg: string);
begin
Assert.AreNotEqual(expected,actual,true,msg);
end;
{$IFNDEF NEXTGEN}
procedure TTestCase.CheckNotEquals(const expected, actual: WideString; const msg: string);
begin
Assert.AreNotEqual(expected,actual,true,msg);
end;
procedure TTestCase.CheckNotEqualsWideString(const expected, actual: WideString; const msg: string);
begin
Assert.AreNotEqual(expected,actual,true,msg);
end;
{$ENDIF}
procedure TTestCase.CheckNotEqualsMem(const expected, actual: pointer; const size:longword; const msg:string='');
begin
Assert.AreNotEqualMemory(expected,actual,size,msg);
end;
procedure TTestCase.CheckNotEquals(const expected, actual: Boolean; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreNotEqual<boolean>(expected,actual,msg);
{$ELSE}
Assert.IsFalse(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckNotEqualsBin(const expected, actual: longword; const msg: string; digits: integer);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreNotEqual<longword>(expected,actual,msg);
{$ELSE}
Assert.IsTrue(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckNotEqualsHex(const expected, actual: longword; const msg: string; digits: integer);
begin
Assert.AreNotEqual(IntToHex(expected, digits), IntToHex(actual, digits),true,msg);
end;
procedure TTestCase.CheckNotNull(const obj :IUnknown; const msg :string);
begin
Assert.IsNotNull(obj,msg);
end;
procedure TTestCase.CheckNull(const obj: IUnknown; const msg: string);
begin
Assert.IsNull(obj,msg);
end;
procedure TTestCase.CheckSame(const expected, actual: IUnknown; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreEqual<IInterface>(expected,actual,msg);
{$ELSE}
Assert.IsTrue(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckSame(const expected, actual: TObject; const msg: string);
begin
{$IFNDEF DELPHI_XE_DOWN}
Assert.AreEqual<TObject>(expected,actual,msg);
{$ELSE}
Assert.IsTrue(expected = actual, msg);
{$ENDIF}
end;
procedure TTestCase.CheckNotNull(const obj: TObject; const msg: string);
begin
Assert.IsNotNull(obj,msg);
end;
procedure TTestCase.CheckNull(const obj: TObject; const msg: string);
begin
Assert.IsNull(obj,msg);
end;
procedure TTestCase.CheckException(const AMethod: TTestMethod; const AExceptionClass: ExceptClass; const msg :string);
begin
Assert.WillRaise(AMethod,AExceptionClass,msg);
end;
procedure TTestCase.CheckEquals(const expected, actual: TClass; const msg: string);
begin
Assert.AreEqual(expected,actual,msg);
end;
procedure TTestCase.CheckInherits(const expected, actual: TClass; const msg: string);
begin
Assert.InheritsFrom(expected,actual,msg);
end;
procedure TTestCase.CheckIs(const AObject :TObject; const AClass: TClass; const msg: string);
begin
Assert.InheritsFrom(AObject.ClassType,AClass,msg);
end;
end.
|
unit ZUUE;
// ***************************************************************************
// ******** Библиотека классов для работы с MIME UUE кодированием ********
// ********************** (C) Зайцев О.В.,2002 г. ****************************
// ***************************************************************************
interface
uses classes, Sysutils, messages, dialogs, types;
type
// Исключение для ошибок кодирования и декодирования
EUUEError = class(Exception)
end;
// 3-х и 4-х байтные структуры для операций кодирования
TByte3 = packed array[0..2] of byte;
PByte3 = ^TByte3;
TByte4 = packed array[0..3] of byte;
PByte4 = ^TByte4;
// Преобразование 3 байта --> 4 символа по кодировке Base64
Procedure InternalCodeUUE(AByte3 : TByte3; var AByte4 : TByte4);
// Преобразование 4 символа Base64 --> 3 нормальных байта
Procedure InternalDeCodeUUE(AByte4 : TByte4; var AByte3 : TByte3);
// ***** Декодирование строки *****
// Расширенное декодирование - учитывает все возможные некорректности и особенности
Function DeCodeStringUUEEx(AInBuffer : AnsiString) : AnsiString;
// ***** Вычисление размеров буферов *****
// Размер декодированного буфера (это максимальный размер, реальный может быть меньше из-за "=" в хвосте, переводов строки и т.п.)
function UUEDecodedSize(const InputSize: Cardinal): Cardinal;
// Размер закодированного буфера (правильно считается только в случае кодирования без вставки переводов строки)
function UUEEncodedSize(const InputSize: Cardinal): Cardinal;
implementation
function UUEEncodedSize(const InputSize: Cardinal): Cardinal;
begin
Result := (InputSize + 2) div 3 * 4;
end;
function UUEDecodedSize(const InputSize: Cardinal): Cardinal;
begin
Result := (InputSize + 3) div 4 * 3 + (InputSize + 3) div 40;
end;
// Преобразование 3 байта --> 4 символа по кодировке Base64
Procedure InternalCodeUUE(AByte3 : TByte3; var AByte4 : TByte4);
begin
end;
Function DeCodeByteUUE(AIn : byte) : byte;
begin
if AIn =$60 then Result :=0 else
Result := AIn - $20;
end;
// Преобразование 4 символа Base64 --> 3 нормальных байта
Procedure InternalDeCodeUUE(AByte4 : TByte4; var AByte3 : TByte3);
begin
{$R-}
AByte3[2] := DeCodeByteUUE(AByte4[3]) + (DeCodeByteUUE(AByte4[2]) and $3) shl 6;
AByte3[1] := DeCodeByteUUE(AByte4[2]) shr 2 + (DeCodeByteUUE(AByte4[1]) and $0F) shl 4;
AByte3[0] := DeCodeByteUUE(AByte4[1]) shr 4 + (DeCodeByteUUE(AByte4[0]) shl 2);
{$R+}
end;
// Преобразование массива
Function CodeStringBase64(const AInBuffer : AnsiString; CRLFfl : boolean = false) : AnsiString;
begin
// Кодирование пустой строки
if AInBuffer = '' then begin
Result := '';
exit;
end;
// Настройка длинны строки
SetLength(Result, UUEEncodedSize(length(AInBuffer)));
// Кодирование
// CodeBufferBase64(AInBuffer[1], length(AInBuffer), Result[1]);
end;
//
Function DeCodeStringUUEEx(AInBuffer : AnsiString) : AnsiString;
var
Poz, EndPoz, Size,
OutPoz, LineOutPoz : Cardinal;
Byte4 : TByte4;
Byte4dword : dword absolute Byte4;
Byte4Poz : byte;
LineLen : integer;
LineEnd : integer;
i : integer;
begin
{$R-}{$I-}
Result := '';
Poz := pos('begin', AInBuffer);
if Poz = 0 then exit;
// Грубое задание размера буфера
SetLength(Result, UUEDecodedSize(length(AInBuffer)));
// Подготовка адресов и указателей
poz := Cardinal(@AInBuffer[1]) + poz + 5;
OutPoz := Cardinal(@Result[1]);
Size := Length(AInBuffer);
EndPoz := Poz + Size;
Byte4Poz := 0;
// Цикл декодирования
while Poz < EndPoz do begin
// Пропуск всех символов кроме перевода строки
if pbyte(pointer(Poz))^ <> $0D then begin inc(Poz); Continue; end;
inc(Poz); // Пропуск символа 0D
if pbyte(pointer(Poz))^ = $0A then begin
inc(Poz); // Пропуск символа 0A
if Poz < EndPoz then begin
// Это "End" ??
if (pbyte(pointer(Poz))^ in [byte('e'), byte('E')]) and (pbyte(pointer(Poz+1))^ = byte('n')) then break;
// Читаем первый байт - это длинна строки
LineLen := DeCodeByteUUE(pbyte(pointer(Poz))^);
inc(Poz);
if LineLen = 0 then continue;
LineEnd := LineLen div 3 * 4 + Poz;
Byte4Poz := 0;
LineOutPoz := 0;
while LineOutPoz < LineLen do begin
Byte4[Byte4Poz] := pbyte(pointer(Poz))^;
inc(Poz);
inc(Byte4Poz);
if Byte4Poz = 4 then begin
InternalDeCodeUUE(Byte4, PByte3(pointer(OutPoz))^);
inc(OutPoz, 3);
inc(LineOutPoz, 3);
Byte4Poz := 0;
end;
end;
if LineOutPoz > LineLen then
OutPoz := OutPoz - (LineOutPoz - LineLen);
if (Byte4Poz > 0) and (Byte4Poz <> 4) then begin
for i := Byte4Poz to 3 do
Byte4[i] := 0;
InternalDeCodeUUE(Byte4, PByte3(pointer(OutPoz))^);
inc(OutPoz, LineLen mod 3);
Byte4Poz := 0;
end;
end;
end;
end;
SetLength(Result, OutPoz - Cardinal(@Result[1]));
{$R+}{$I+}
end;
end.
|
unit PalUtils;
interface
uses
Windows, SysUtils, Classes, Graphics, RGBHSVUtils, RGBHSLUtils, RGBCIEUtils, RGBCMYKUtils,
HTMLColors;
const
clCustom = $2FFFFFFF;
clTransparent = $3FFFFFFF;
//replaces passed strings with passed value
function ReplaceFlags(s: string; flags: array of string; value: integer): string;
//replaces the appropriate tags with values in a hint format string
function FormatHint(fmt: string; c: TColor): string;
implementation
function ReplaceFlags(s: string; flags: array of string; value: integer): string;
var
i, p: integer;
v: string;
begin
Result := s;
v := IntToStr(value);
for i := 0 to Length(flags) - 1 do
begin
p := Pos(flags[i], Result);
if p > 0 then
begin
Delete(Result, p, Length(flags[i]));
Insert(v, Result, p);
end;
end;
end;
function AnsiReplaceText(const AText, AFromText, AToText: string): string;
begin
Result := StringReplace(AText, AFromText, AToText, [rfReplaceAll, rfIgnoreCase]);
end;
function FormatHint(fmt: string; c: TColor): string;
var
h: string;
begin
h := AnsiReplaceText(fmt, '%hex', ColorToHex(c));
h := AnsiReplaceText(h, '%cieL', IntToStr(Round(GetCIElValue(c))));
h := AnsiReplaceText(h, '%cieA', IntToStr(Round(GetCIEaValue(c))));
h := AnsiReplaceText(h, '%cieB', IntToStr(Round(GetCIEbValue(c))));
h := AnsiReplaceText(h, '%cieX', IntToStr(Round(GetCIExValue(c))));
h := AnsiReplaceText(h, '%cieY', IntToStr(Round(GetCIEyValue(c))));
h := AnsiReplaceText(h, '%cieZ', IntToStr(Round(GetCIEzValue(c))));
h := AnsiReplaceText(h, '%cieC', IntToStr(Round(GetCIEcValue(c))));
h := AnsiReplaceText(h, '%cieH', IntToStr(Round(GetCIEhValue(c))));
h := AnsiReplaceText(h, '%hslH', IntToStr(RGBHSLUtils.GetHValue(c)));
h := AnsiReplaceText(h, '%hslS', IntToStr(RGBHSLUtils.GetSValue(c)));
h := AnsiReplaceText(h, '%hslL', IntToStr(RGBHSLUtils.GetLValue(c)));
h := AnsiReplaceText(h, '%hsvH', IntToStr(RGBHSVUtils.GetHValue(c)));
h := AnsiReplaceText(h, '%hsvS', IntToStr(RGBHSVUtils.GetSValue(c)));
h := AnsiReplaceText(h, '%hsvV', IntToStr(RGBHSVUtils.GetVValue(c)));
h := AnsiReplaceText(h, '%r', IntToStr(GetRValue(c)));
h := AnsiReplaceText(h, '%g', IntToStr(GetGValue(c)));
h := AnsiReplaceText(h, '%b', IntToStr(GetBValue(c)));
h := AnsiReplaceText(h, '%c', IntToStr(GetCValue(c)));
h := AnsiReplaceText(h, '%m', IntToStr(GetMValue(c)));
h := AnsiReplaceText(h, '%y', IntToStr(GetYValue(c)));
h := AnsiReplaceText(h, '%k', IntToStr(GetKValue(c)));
h := AnsiReplaceText(h, '%h', IntToStr(RGBHSLUtils.GetHValue(c)));
h := AnsiReplaceText(h, '%s', IntToStr(RGBHSLUtils.GetSValue(c)));
h := AnsiReplaceText(h, '%l', IntToStr(RGBHSLUtils.GetLValue(c)));
h := AnsiReplaceText(h, '%v', IntToStr(RGBHSVUtils.GetVValue(c)));
Result := h;
end;
end.
|
unit JpegErrors;
interface
const
cstrJVERSION = '6a 7-Feb-96';
cstrJCOPYRIGHT = 'Copyright (C) 1996, Thomas G. Lane';
JMSG_STR_PARM_MAX = 80; // defined in jpeg.pas, copied here
cstrJMSG_NOMESSAGE = 'Bogus message code %d'; (* Must be first entry! *)
(* For maintenance convenience, list is alphabetical by message code name *)
cstrJERR_ARITH_NOTIMPL = 'Sorry, there are legal restrictions on arithmetic coding';
cstrJERR_BAD_ALIGN_TYPE = 'ALIGN_TYPE is wrong, please fix';
cstrJERR_BAD_ALLOC_CHUNK = 'MAX_ALLOC_CHUNK is wrong, please fix';
cstrJERR_BAD_BUFFER_MODE = 'Bogus buffer control mode';
cstrJERR_BAD_COMPONENT_ID = 'Invalid component ID %d in SOS';
cstrJERR_BAD_DCTSIZE = 'IDCT output block size %d not supported';
cstrJERR_BAD_IN_COLORSPACE = 'Bogus input colorspace';
cstrJERR_BAD_J_COLORSPACE = 'Bogus JPEG colorspace';
cstrJERR_BAD_LENGTH = 'Bogus marker length';
cstrJERR_BAD_LIB_VERSION
= 'Wrong JPEG library version: library is %d, caller expects %d';
cstrJERR_BAD_MCU_SIZE = 'Sampling factors too large for interleaved scan';
cstrJERR_BAD_POOL_ID = 'Invalid memory pool code %d';
cstrJERR_BAD_PRECISION = 'Unsupported JPEG data precision %d';
cstrJERR_BAD_PROGRESSION
= 'Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d';
cstrJERR_BAD_PROG_SCRIPT
= 'Invalid progressive parameters at scan script entry %d';
cstrJERR_BAD_SAMPLING = 'Bogus sampling factors';
cstrJERR_BAD_SCAN_SCRIPT = 'Invalid scan script at entry %d';
cstrJERR_BAD_STATE = 'Improper call to JPEG library in state %d';
cstrJERR_BAD_STRUCT_SIZE
= 'JPEG parameter struct mismatch: library thinks size is %u, caller expects %u';
cstrJERR_BAD_VIRTUAL_ACCESS = 'Bogus virtual array access';
cstrJERR_BUFFER_SIZE = 'Buffer passed to JPEG library is too small';
cstrJERR_CANT_SUSPEND = 'Suspension not allowed here';
cstrJERR_CCIR601_NOTIMPL = 'CCIR601 sampling not implemented yet';
cstrJERR_COMPONENT_COUNT = 'Too many color components: %d, max %d';
cstrJERR_CONVERSION_NOTIMPL = 'Unsupported color conversion request';
cstrJERR_DAC_INDEX = 'Bogus DAC index %d';
cstrJERR_DAC_VALUE = 'Bogus DAC value 0x%x';
cstrJERR_DHT_COUNTS = 'Bogus DHT counts';
cstrJERR_DHT_INDEX = 'Bogus DHT index %d';
cstrJERR_DQT_INDEX = 'Bogus DQT index %d';
cstrJERR_EMPTY_IMAGE = 'Empty JPEG image (DNL not supported)';
cstrJERR_EMS_READ = 'Read from EMS failed';
cstrJERR_EMS_WRITE = 'Write to EMS failed';
cstrJERR_EOI_EXPECTED = 'Didn''t expect more than one scan';
cstrJERR_FILE_READ = 'Input file read error';
cstrJERR_FILE_WRITE = 'Output file write error --- out of disk space?';
cstrJERR_FRACT_SAMPLE_NOTIMPL = 'Fractional sampling not implemented yet';
cstrJERR_HUFF_CLEN_OVERFLOW = 'Huffman code size table overflow';
cstrJERR_HUFF_MISSING_CODE = 'Missing Huffman code table entry';
cstrJERR_IMAGE_TOO_BIG = 'Maximum supported image dimension is %u pixels';
cstrJERR_INPUT_EMPTY = 'Empty input file';
cstrJERR_INPUT_EOF = 'Premature end of input file';
cstrJERR_MISMATCHED_QUANT_TABLE
= 'Cannot transcode due to multiple use of quantization table %d';
cstrJERR_MISSING_DATA = 'Scan script does not transmit all data';
cstrJERR_MODE_CHANGE = 'Invalid color quantization mode change';
cstrJERR_NOTIMPL = 'Not implemented yet';
cstrJERR_NOT_COMPILED = 'Requested feature was omitted at compile time';
cstrJERR_NO_BACKING_STORE = 'Backing store not supported';
cstrJERR_NO_HUFF_TABLE = 'Huffman table 0x%02x was not defined';
cstrJERR_NO_IMAGE = 'JPEG datastream contains no image';
cstrJERR_NO_QUANT_TABLE = 'Quantization table 0x%02x was not defined';
cstrJERR_NO_SOI = 'Not a JPEG file: starts with 0x%02x 0x%02x';
cstrJERR_OUT_OF_MEMORY = 'Insufficient memory (case %d)';
cstrJERR_QUANT_COMPONENTS
= 'Cannot quantize more than %d color components';
cstrJERR_QUANT_FEW_COLORS = 'Cannot quantize to fewer than %d colors';
cstrJERR_QUANT_MANY_COLORS = 'Cannot quantize to more than %d colors';
cstrJERR_SOF_DUPLICATE = 'Invalid JPEG file structure: two SOF markers';
cstrJERR_SOF_NO_SOS = 'Invalid JPEG file structure: missing SOS marker';
cstrJERR_SOF_UNSUPPORTED = 'Unsupported JPEG process: SOF type 0x%02x';
cstrJERR_SOI_DUPLICATE = 'Invalid JPEG file structure: two SOI markers';
cstrJERR_SOS_NO_SOF = 'Invalid JPEG file structure: SOS before SOF';
cstrJERR_TFILE_CREATE = 'Failed to create temporary file %s';
cstrJERR_TFILE_READ = 'Read failed on temporary file';
cstrJERR_TFILE_SEEK = 'Seek failed on temporary file';
cstrJERR_TFILE_WRITE
= 'Write failed on temporary file --- out of disk space?';
cstrJERR_TOO_LITTLE_DATA = 'Application transferred too few scanlines';
cstrJERR_UNKNOWN_MARKER = 'Unsupported marker type 0x%02x';
cstrJERR_VIRTUAL_BUG = 'Virtual array controller messed up';
cstrJERR_WIDTH_OVERFLOW = 'Image too wide for this implementation';
cstrJERR_XMS_READ = 'Read from XMS failed';
cstrJERR_XMS_WRITE = 'Write to XMS failed';
cstrJMSG_COPYRIGHT = cstrJCOPYRIGHT;
cstrJMSG_VERSION = cstrJVERSION;
cstrJTRC_16BIT_TABLES
= 'Caution: quantization tables are too coarse for baseline JPEG';
cstrJTRC_ADOBE
= 'Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d';
cstrJTRC_APP0 = 'Unknown APP0 marker (not JFIF), length %u';
cstrJTRC_APP14 = 'Unknown APP14 marker (not Adobe), length %u';
cstrJTRC_DAC = 'Define Arithmetic Table 0x%02x: 0x%02x';
cstrJTRC_DHT = 'Define Huffman Table 0x%02x';
cstrJTRC_DQT = 'Define Quantization Table %d precision %d';
cstrJTRC_DRI = 'Define Restart Interval %u';
cstrJTRC_EMS_CLOSE = 'Freed EMS handle %u';
cstrJTRC_EMS_OPEN = 'Obtained EMS handle %u';
cstrJTRC_EOI = 'End Of Image';
cstrJTRC_HUFFBITS = ' %3d %3d %3d %3d %3d %3d %3d %3d';
cstrJTRC_JFIF = 'JFIF APP0 marker, density %dx%d %d';
cstrJTRC_JFIF_BADTHUMBNAILSIZE
= 'Warning: thumbnail image size does not match data length %u';
cstrJTRC_JFIF_MINOR = 'Unknown JFIF minor revision number %d.%02d';
cstrJTRC_JFIF_THUMBNAIL = ' with %d x %d thumbnail image';
cstrJTRC_MISC_MARKER = 'Skipping marker 0x%02x, length %u';
cstrJTRC_PARMLESS_MARKER = 'Unexpected marker 0x%02x';
cstrJTRC_QUANTVALS = ' %4u %4u %4u %4u %4u %4u %4u %4u';
cstrJTRC_QUANT_3_NCOLORS = 'Quantizing to %d = %d*%d*%d colors';
cstrJTRC_QUANT_NCOLORS = 'Quantizing to %d colors';
cstrJTRC_QUANT_SELECTED = 'Selected %d colors for quantization';
cstrJTRC_RECOVERY_ACTION = 'At marker 0x%02x, recovery action %d';
cstrJTRC_RST = 'RST%d';
cstrJTRC_SMOOTH_NOTIMPL
= 'Smoothing not supported with nonstandard sampling ratios';
cstrJTRC_SOF = 'Start Of Frame 0x%02x: width=%u, height=%u, components=%d';
cstrJTRC_SOF_COMPONENT = ' Component %d: %dhx%dv q=%d';
cstrJTRC_SOI = 'Start of Image';
cstrJTRC_SOS = 'Start Of Scan: %d components';
cstrJTRC_SOS_COMPONENT = ' Component %d: dc=%d ac=%d';
cstrJTRC_SOS_PARAMS = ' Ss=%d, Se=%d, Ah=%d, Al=%d';
cstrJTRC_TFILE_CLOSE = 'Closed temporary file %s';
cstrJTRC_TFILE_OPEN = 'Opened temporary file %s';
cstrJTRC_UNKNOWN_IDS
= 'Unrecognized component IDs %d %d %d, assuming YCbCr';
cstrJTRC_XMS_CLOSE = 'Freed XMS handle %u';
cstrJTRC_XMS_OPEN = 'Obtained XMS handle %u';
cstrJWRN_ADOBE_XFORM = 'Unknown Adobe color transform code %d';
cstrJWRN_BOGUS_PROGRESSION
= 'Inconsistent progression sequence for component %d coefficient %d';
cstrJWRN_EXTRANEOUS_DATA
= 'Corrupt JPEG data: %u extraneous bytes before marker 0x%02x';
cstrJWRN_HIT_MARKER = 'Corrupt JPEG data: premature end of data segment';
cstrJWRN_HUFF_BAD_CODE = 'Corrupt JPEG data: bad Huffman code';
cstrJWRN_JFIF_MAJOR = 'Warning: unknown JFIF revision number %d.%02d';
cstrJWRN_JPEG_EOF = 'Premature end of JPEG file';
cstrJWRN_MUST_RESYNC
= 'Corrupt JPEG data: found marker 0x%02x instead of RST%d';
cstrJWRN_NOT_SEQUENTIAL = 'Invalid SOS parameters for sequential JPEG';
cstrJWRN_TOO_MUCH_DATA = 'Application transferred too many scanlines';
const
cJpegErrors: array[0..119] of string[JMSG_STR_PARM_MAX] =
(
cstrJMSG_NOMESSAGE,
cstrJERR_ARITH_NOTIMPL,
cstrJERR_BAD_ALIGN_TYPE,
cstrJERR_BAD_ALLOC_CHUNK,
cstrJERR_BAD_BUFFER_MODE,
cstrJERR_BAD_COMPONENT_ID,
cstrJERR_BAD_DCTSIZE,
cstrJERR_BAD_IN_COLORSPACE,
cstrJERR_BAD_J_COLORSPACE,
cstrJERR_BAD_LENGTH,
cstrJERR_BAD_LIB_VERSION,
cstrJERR_BAD_MCU_SIZE,
cstrJERR_BAD_POOL_ID,
cstrJERR_BAD_PRECISION,
cstrJERR_BAD_PROGRESSION,
cstrJERR_BAD_PROG_SCRIPT,
cstrJERR_BAD_SAMPLING,
cstrJERR_BAD_SCAN_SCRIPT,
cstrJERR_BAD_STATE,
cstrJERR_BAD_STRUCT_SIZE,
cstrJERR_BAD_VIRTUAL_ACCESS,
cstrJERR_BUFFER_SIZE,
cstrJERR_CANT_SUSPEND,
cstrJERR_CCIR601_NOTIMPL,
cstrJERR_COMPONENT_COUNT,
cstrJERR_CONVERSION_NOTIMPL,
cstrJERR_DAC_INDEX,
cstrJERR_DAC_VALUE,
cstrJERR_DHT_COUNTS,
cstrJERR_DHT_INDEX,
cstrJERR_DQT_INDEX,
cstrJERR_EMPTY_IMAGE,
cstrJERR_EMS_READ,
cstrJERR_EMS_WRITE,
cstrJERR_EOI_EXPECTED,
cstrJERR_FILE_READ,
cstrJERR_FILE_WRITE,
cstrJERR_FRACT_SAMPLE_NOTIMPL,
cstrJERR_HUFF_CLEN_OVERFLOW,
cstrJERR_HUFF_MISSING_CODE,
cstrJERR_IMAGE_TOO_BIG,
cstrJERR_INPUT_EMPTY,
cstrJERR_INPUT_EOF,
cstrJERR_MISMATCHED_QUANT_TABLE,
cstrJERR_MISSING_DATA,
cstrJERR_MODE_CHANGE,
cstrJERR_NOTIMPL,
cstrJERR_NOT_COMPILED,
cstrJERR_NO_BACKING_STORE,
cstrJERR_NO_HUFF_TABLE,
cstrJERR_NO_IMAGE,
cstrJERR_NO_QUANT_TABLE,
cstrJERR_NO_SOI,
cstrJERR_OUT_OF_MEMORY,
cstrJERR_QUANT_COMPONENTS,
cstrJERR_QUANT_FEW_COLORS,
cstrJERR_QUANT_MANY_COLORS,
cstrJERR_SOF_DUPLICATE,
cstrJERR_SOF_NO_SOS,
cstrJERR_SOF_UNSUPPORTED,
cstrJERR_SOI_DUPLICATE,
cstrJERR_SOS_NO_SOF,
cstrJERR_TFILE_CREATE,
cstrJERR_TFILE_READ,
cstrJERR_TFILE_SEEK,
cstrJERR_TFILE_WRITE,
cstrJERR_TOO_LITTLE_DATA,
cstrJERR_UNKNOWN_MARKER,
cstrJERR_VIRTUAL_BUG,
cstrJERR_WIDTH_OVERFLOW,
cstrJERR_XMS_READ,
cstrJERR_XMS_WRITE,
cstrJMSG_COPYRIGHT,
cstrJMSG_VERSION,
cstrJTRC_16BIT_TABLES,
cstrJTRC_ADOBE,
cstrJTRC_APP0,
cstrJTRC_APP14,
cstrJTRC_DAC,
cstrJTRC_DHT,
cstrJTRC_DQT,
cstrJTRC_DRI,
cstrJTRC_EMS_CLOSE,
cstrJTRC_EMS_OPEN,
cstrJTRC_EOI,
cstrJTRC_HUFFBITS,
cstrJTRC_JFIF,
cstrJTRC_JFIF_BADTHUMBNAILSIZE,
cstrJTRC_JFIF_MINOR,
cstrJTRC_JFIF_THUMBNAIL,
cstrJTRC_MISC_MARKER,
cstrJTRC_PARMLESS_MARKER,
cstrJTRC_QUANTVALS,
cstrJTRC_QUANT_3_NCOLORS,
cstrJTRC_QUANT_NCOLORS,
cstrJTRC_QUANT_SELECTED,
cstrJTRC_RECOVERY_ACTION,
cstrJTRC_RST,
cstrJTRC_SMOOTH_NOTIMPL,
cstrJTRC_SOF,
cstrJTRC_SOF_COMPONENT,
cstrJTRC_SOI,
cstrJTRC_SOS,
cstrJTRC_SOS_COMPONENT,
cstrJTRC_SOS_PARAMS,
cstrJTRC_TFILE_CLOSE,
cstrJTRC_TFILE_OPEN,
cstrJTRC_UNKNOWN_IDS,
cstrJTRC_XMS_CLOSE,
cstrJTRC_XMS_OPEN,
cstrJWRN_ADOBE_XFORM,
cstrJWRN_BOGUS_PROGRESSION,
cstrJWRN_EXTRANEOUS_DATA,
cstrJWRN_HIT_MARKER,
cstrJWRN_HUFF_BAD_CODE,
cstrJWRN_JFIF_MAJOR,
cstrJWRN_JPEG_EOF,
cstrJWRN_MUST_RESYNC,
cstrJWRN_NOT_SEQUENTIAL,
cstrJWRN_TOO_MUCH_DATA
);
implementation
end.
|
unit Unit2;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Fileutil, shlobj, registry;
function getDirs(directory : string): TStringList ;
function findAllProfiles() : TStringList;
function URLDecode(url: string): String;
function getCurrentProfile(): string;
procedure setCurrentProfile(profileName: string);
implementation
function findAllProfiles() : TStringList;
var
MyDocs: Array[0..MaxPathLen] of Char;
counter: Integer;
totalItems: Integer;
profileDir: String;
begin
//Create our result
Result := TStringList.create;
//Locate the profile folder
MyDocs := '';
SHGetSpecialFolderPath(0,MyDocs,CSIDL_PERSONAL,false);
profileDir := MyDocs + '\ArmA 2 Other Profiles\';
//Make sure the profile directory exists
if (DirectoryExists(profileDir) = false) then
begin
raise Exception.Create('Cant find profile directory!');
end;
//Get a list of everything in the profile folder
Result := getDirs(profileDir);
//URL Decode all of these names
totalItems := Result.Count;
counter := 0;
while (counter < totalItems) do
begin
Result.strings[counter] := URLDecode(Result.strings[counter]);
counter := counter + 1;
end;
//Return the result
Result := Result;
end;
function getDirs(directory : string): TStringList;
var
item : TSearchRec;
begin
Result := TStringList.create;
try
if FindFirst(IncludeTrailingPathDelimiter(directory) + '*.*', faDirectory, item) < 0 then
Exit
else
repeat
if ((item.Attr and faDirectory <> 0) AND (item.Name <> '.') AND (item.Name <> '..')) then
Result.Add(item.Name) ;
until FindNext(item) <> 0;
finally
SysUtils.FindClose(item) ;
end;
end;
function URLDecode(url: string): String;
begin
url := StringReplace(url, '%20', ' ', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%21', '!', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%23', '#', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%24', '$', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%26', '&', [rfReplaceAll,rfIgnoreCase]);
//url := StringReplace(url, '%27', '', [rfReplaceAll,rfIgnoreCase]); Will implement later Should be '
url := StringReplace(url, '%28', '(', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%29', ')', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%2A', '*', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%2B', '+', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%2C', ',', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%2F', '/', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%3A', ':', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%3B', ';', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%3D', '=', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%3F', '?', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%40', '@', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%5B', '[', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%5D', ']', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%22', '"', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%25', '%', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%2D', '-', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%2E', '.', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%3C', '<', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%3E', '>', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%5C', '\', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%5E', '^', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%5F', '_', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%60', '`', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%7B', '{', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%7C', '|', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%7D', '}', [rfReplaceAll,rfIgnoreCase]);
url := StringReplace(url, '%7E', '~', [rfReplaceAll,rfIgnoreCase]);
Result := url;
end;
function getCurrentProfile(): string;
var
HKCU: TRegistry;
begin
Result := '';
HKCU := TRegistry.Create;
try
HKCU.RootKey := HKEY_CURRENT_USER;
if (HKCU.OpenKeyReadOnly('\SOFTWARE\Bohemia Interactive Studio\ArmA 2 OA')) then
begin
Result := HKCU.ReadString('Player Name');
end;
finally
HKCU.free;
end;
end;
procedure setCurrentProfile(profileName: string);
var
HKCU: TRegistry;
begin
HKCU := TRegistry.Create;
try
if (HKCU.OpenKey('\SOFTWARE\Bohemia Interactive Studio\ArmA 2 OA', true)) then
begin
HKCU.WriteString('Player Name', profileName);
end
else
begin
raise Exception.Create('Could not write new profile!');
end;
finally
HKCU.free;
end;
end;
end.
|
unit DW.Android.Service;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL/Android
System.Android.Service;
type
TLocalServiceConnection = class(System.Android.Service.TLocalServiceConnection)
public
class procedure StartForegroundService(const AServiceName: string); static;
end;
implementation
uses
System.SysUtils,
Androidapi.Helpers, AndroidApi.JNI.GraphicsContentViewText,
DW.Androidapi.JNI.ContextWrapper;
{ TLocalServiceConnection }
class procedure TLocalServiceConnection.StartForegroundService(const AServiceName: string);
var
LIntent: JIntent;
LService: string;
begin
if TOSVersion.Check(8) then
begin
LIntent := TJIntent.Create;
LService := AServiceName;
if not LService.StartsWith('com.embarcadero.services.') then
LService := 'com.embarcadero.services.' + LService;
LIntent.setClassName(TAndroidHelper.Context.getPackageName(), TAndroidHelper.StringToJString(LService));
TJContextWrapper.Wrap(System.JavaContext).startForegroundService(LIntent);
end
else
StartService(AServiceName);
end;
end.
|
unit UFunctionTextGenerator;
interface
uses
Classes, Types;
type
TFuncArg = record
Name: string;
Args: array of TFuncArg;
end;
procedure AddAllCombinationsForFunction(
AFuncArg: TFuncArg; ARootValuesSet: array of string;
ANodeValuesSet: array of string; ALeafValuesSet: array of string;
AStrings: TStrings);
implementation
uses
UBUtils;
function FuncArgToString(AArg: TFuncArg): string;
var
i: integer;
args: string;
begin
Result := AArg.Name;
if Length(AArg.Args) > 0 then begin
args := '';
for i := Low(AArg.Args) to High(AArg.Args) do
args := JoinStrings(args, FuncArgToString(AArg.Args[i]), ', ');
Result := Result + '(' + args + ')';
end;
end;
procedure AddAllCombinationsForFunction(
AFuncArg: TFuncArg; ARootValuesSet: array of string;
ANodeValuesSet: array of string; ALeafValuesSet: array of string;
AStrings: TStrings);
var
i, k: integer;
len: integer;
p: ^string;
begin
if Length(AFuncArg.Args) = 0 then begin
p := @ALeafValuesSet[0];
len := Length(ALeafValuesSet);
end
else if Length(ARootValuesSet) = 0 then begin
p := @ANodeValuesSet[0];
len := Length(ANodeValuesSet);
end
else begin
p := @ARootValuesSet[0];
len := Length(ARootValuesSet);
end;
{ for k := 0 to len do begin
if p[k] = AFuncArg.Name then
AStrings.Add(FuncArgToString(AFuncArg))
else
AStrings.Add(FuncArgToString(AFuncArg));
end;
}
for i := Low(AFuncArg.Args) to High(AFuncArg.Args) do
AddAllCombinationsForFunction(AFuncArg.Args[i], [], [], [], AStrings);
end;
procedure AddAllFuncArgsTreeBranches(AFuncArg: TFuncArg; AStrings: TStrings);
var
i: integer;
begin
AStrings.Add(FuncArgToString(AFuncArg));
for i := Low(AFuncArg.Args) to High(AFuncArg.Args) do
AddAllFuncArgsTreeBranches(AFuncArg.Args[i], AStrings);
end;
end.
|
unit Unit22;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type TCodepageArray = array[$80..$FF] of Char;
function ConvertEncoding(s: string): string;
const
ruscii:TCodepageArray = ('À','Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê',
'Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','×','Ø','Ù','Ú','Û',
'Ü','Ý','Þ','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì',
'í','î','ï',#176,#177,#178,#179,#180,#181,#182,#183,#184,#185,#186,
#187,#188,#189,#190,#191,#192,#193,#194,#195,#196,#197,#198,#199,#200,
#201,#202,#203,#204,#205,#206,#207,#208,#209,#210,#211,#212,#213,#214,
#215,#216,#217,#218,#219,#220,#221,#222,#223,'ð','ñ','ò','ó','ô','õ',
'ö','÷','ø','ù','ú','û','ü','ý','þ','ÿ','¨','¸','Ã','ã','ª','º','²',
'³','¯','¿',#250,#251,#252,#253,#254,#255);
koi8u:TCodepageArray = (#128,#129,#130,#131,#132,#133,#134,#135,#136,
#137,#138,#139,#140,#141,#142,#143,#144,#145,#146,#147,#148,#149,#150,
#151,#152,#153,#154,#155,#156,#157,#158,#159,#160,#161,#162,'¸','º',
#165,'³','¿',#168,#169,#170,#171,#172,#173,#174,#175,#176,#177,#178,
'¨','ª',#181,'²','¯',#184,#185,#186,#187,#188,#189,#190,#191,'þ','à',
'á','ö','ä','å','ô','ã','õ','è','é','ê','ë','ì','í','î','ï','ÿ','ð',
'ñ','ò','ó','æ','â','ü','û','ç','ø','ý','ù','÷','ú','Þ','À','Á','Ö',
'Ä','Å','Ô','Ã','Õ','È','É','Ê','Ë','Ì','Í','Î','Ï','ß','Ð','Ñ','Ò',
'Ó','Æ','Â','Ü','Û','Ç','Ø','Ý','Ù','×','Ú' );
utf8:TCodepageArray = (#128,#129,#130,#131,#132,#133,#134,#135,#136,
#137,#138,#139,#140,#141,#142,#143,#144,#145,#146,#147,#148,#149,#150,
#151,#152,#153,#154,#155,#156,#157,#158,#159,#160,#161,#162,#163,#164,
#165,#166,#167,#168,#169,#170,#171,#172,#173,#174,#175,#176,#177,#178,
#179,#180,#181,#182,#183,#184,#185,#186,#187,#188,#189,#190,#191,#192,
#193,#194,#195,#196,#197,#198,#199,#200,#201,#202,#203,#204,#205,#206,
#207,#208,#209,#210,#211,#212,#213,#214,#215,#216,#217,#218,#219,#220,
#221,#222,#223,#224,#225,#226,#227,#228,#229,#230,#231,#232,#233,#234,
#235,#236,#237,#238,#239,#240,#241,#242,#243,#244,#245,#246,#247,#248,
#249,#250,#251,#252,#253,#254,#255);
iso88595:TCodepageArray = (#128,#129,#130,#131,#132,#133,#134,#135,#136,
#137,#138,#139,#140,#141,#142,#143,#144,#145,#146,#147,#148,#149,#150,
#151,#152,#153,#154,#155,#156,#157,#158,#159,#160,'¨',#162,#163,'ª',
#165,'²','¯',#168,#169,#170,#171,#172,#173,#174,#175,'À','Á','Â','Ã',
'Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô',
'Õ','Ö','×','Ø','Ù','Ú','Û','Ü','Ý','Þ','ß','à','á','â','ã','ä','å',
'æ','ç','è','é','ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô','õ','ö',
'÷','ø','ù','ú','û','ü','ý','þ','ÿ',#240,'¸',#242,#243,'º',#245,'³',
'¿',#248,#249,#250,#251,#252,#253,#254,#255);
implementation
{function ConvertEncoding(sIn: string; sCoding: string): string;
var
iFtd: integer;
begin
Result:='';
for iFtd := 1 to length(sIn) do
result := result + sCoding[ord(sIn[iFtd])];
end;}
function ConvertEncoding(s: string): string;
var i:byte;j:integer;
A:TCodepageArray;
begin
Result:='';
A:=ruscii;
For j:=1 to Length(S) do
if Byte(S[j])>=Low(A) then
For i:=Low(A) to High(A) do
begin
if Byte(S[j])=i then
begin
S[j]:=A[i];
break;
end;
end;
result:=s;
end;
end.
{
var SL:TStringList;i:byte;j:integer;
S:String;
A:TCodepageArray;
begin
SL:=TStringList.Create;
try
SL.LoadFromFile(FileName.Text);
S:=SL.Text;
if CodeTable.ItemIndex=0 then A:=ruscii else
if CodeTable.ItemIndex=1 then A:=koi8u else
if CodeTable.ItemIndex=2 then A:=utf8 else
if CodeTable.ItemIndex=3 then A:=iso88595;
For j:=1 to Length(S) do
if Byte(S[j])>=Low(A) then
For i:=Low(A) to High(A) do
begin
if Byte(S[j])=i then
begin
S[j]:=A[i];
break;
end;
end;
finally
Memo1.Text:=S;
SL.Free;
end;
end; }
|
unit Feature;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls {System.Classes,} ,
TypeList, Vcl.Menus, FilmBase;
type
TfrmFeatures = class(TForm)
edtTitle: TEdit;
edtDirectorLastName: TEdit;
edtDirectorName: TEdit;
edtDirectorMiddleName: TEdit;
edtCountry: TEdit;
edtDuration: TEdit;
edtWords: TEdit;
edtAwards: TEdit;
edtBudget: TEdit;
edtBoxOffice: TEdit;
lblTitel: TLabel;
lblDirectorLastName: TLabel;
lblDirectorName: TLabel;
lblDirectorMiddleName: TLabel;
lblGenre: TLabel;
lblCountry: TLabel;
lblYear: TLabel;
lblDuration: TLabel;
lblWords: TLabel;
lblAwards: TLabel;
lblBudget: TLabel;
lblBoxOffice: TLabel;
lblReady: TLabel;
lblRating: TLabel;
lblDirector: TLabel;
btnCancel: TButton;
btnOK: TButton;
cmbbxGenre: TComboBox;
cmbbxRating: TComboBox;
chbxReady: TCheckBox;
edtYear: TEdit;
PopupMenu1: TPopupMenu;
procedure btnOKClick(Sender: TObject);
function cmbbxGenreChange(Sender: TObject): TGenre;
function cmbbxRatingChange(Sender: TObject): TRating;
procedure chbxReadyClick(Sender: TObject);
procedure edtYearKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure etdCurationKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
function GetGenre(const aItem: TItem): Integer;
function TabGenre(Genre: TGenre): string;
function GetRating(const aItem: TItem): Integer;
end;
procedure ClearFeaturesEdits;
var
frmFeatures: TfrmFeatures;
implementation
{$R *.dfm}
{ Создание формы }
procedure TfrmFeatures.FormCreate(Sender: TObject);
begin
if chbxReady.Checked = True then
cmbbxRating.Enabled := True
else
cmbbxRating.Enabled := False;
end;
{ Очистка эдитов }
procedure ClearFeaturesEdits;
begin
with frmFeatures do
begin
edtTitle.Text := '';
edtDirectorLastName.Text := '';
edtDirectorName.Text := '';
edtDirectorMiddleName.Text := '';
cmbbxGenre.ItemIndex := -1;
edtCountry.Text := '';
edtYear.Text := '';
edtDuration.Text := '';
edtWords.Text := '';
edtAwards.Text := '';
edtBudget.Text := '';
edtBoxOffice.Text := '';
chbxReady.Checked := False;
cmbbxRating.ItemIndex := -1;
end;
end;
{ Нажатие на комбобокс }
procedure TfrmFeatures.chbxReadyClick(Sender: TObject);
begin
if chbxReady.Checked = True then
cmbbxRating.Enabled := True
else
cmbbxRating.Enabled := False;
end;
{ кнопка Отмена }
procedure TfrmFeatures.btnCancelClick(Sender: TObject);
begin
ClearFeaturesEdits;
frmFeatures.Close;
frmFilmBase.btnEdit.Enabled := frmFilmBase.lvFilmTab.ItemIndex <> -1;
frmFilmBase.btnDelete.Enabled := frmFilmBase.lvFilmTab.ItemIndex <> -1;
frmFilmBase.btnReport.Enabled := frmFilmBase.lvFilmTab.ItemIndex <> -1;
end;
{ Кнопка ОК }
procedure TfrmFeatures.btnOKClick(Sender: TObject);
var
Info: TItem;
Index: Integer;
begin
if (edtTitle.Text = '') or (edtDirectorLastName.Text = '') or
(edtDirectorName.Text = '') or (cmbbxGenre.ItemIndex = -1) or
(edtCountry.Text = '') or (edtYear.Text = '') or (edtDuration.Text = '')
then
MessageBox(Handle, PChar('Не все необходимые поля заполнены!'),
PChar('ВНИМАНИЕ!'), MB_ICONWARNING + MB_OK)
else
begin
with Info do
begin
if frmFeatures.Tag = 1 then
Index := List.fICount + 1
else
Index := frmFilmBase.GetSelectIndex + 1;
Title := edtTitle.Text;
Director.LastName := edtDirectorLastName.Text;
Director.Name := edtDirectorName.Text;
Director.MiddleName := edtDirectorMiddleName.Text;
Genre := cmbbxGenreChange(cmbbxGenre);
Country := edtCountry.Text;
Year := StrToInt(edtYear.Text);
Duration := StrToInt(edtDuration.Text);
Words := edtWords.Text;
Awards := edtAwards.Text;
if edtBudget.Text = ' млн. $' then
Budget := ''
else
Budget := edtBudget.Text;
if edtBoxOffice.Text = ' $' then
BoxOffice := ''
else
BoxOffice := edtBoxOffice.Text;
Ready := chbxReady.Checked;
if Info.Ready then
Info.Rating := cmbbxRatingChange(cmbbxRating);
end;
if frmFeatures.Tag = 1 then
List.CreateFilm(Info)
else
begin
Index := frmFilmBase.GetSelectIndex;
List.EditFilm(Info, Index);
end;
frmFilmBase.UpdateTab(List);
List.SaveList(FILE_NAME);
ClearFeaturesEdits;
frmFeatures.Tag := 0;
frmFeatures.Close;
end;
frmFilmBase.btnEdit.Enabled := frmFilmBase.lvFilmTab.ItemIndex <> -1;
frmFilmBase.btnDelete.Enabled := frmFilmBase.lvFilmTab.ItemIndex <> -1;
frmFilmBase.btnReport.Enabled := frmFilmBase.lvFilmTab.ItemIndex <> -1;
end;
{ Определение жанра по значению из ComboBox }
function TfrmFeatures.cmbbxGenreChange(Sender: TObject): TGenre;
begin
case cmbbxGenre.ItemIndex of
0:
Result := Adventure;
1:
Result := GAction;
2:
Result := Comedy;
3:
Result := Detective;
4:
Result := Drama;
5:
Result := Thriller;
6:
Result := Fantasy;
7:
Result := Science_fiction;
8:
Result := Horror;
9:
Result := Historical;
10:
Result := Mystery;
11:
Result := Romance;
12:
Result := Western;
13:
Result := Animation;
14:
Result := Musical;
15:
Result := Satire;
16:
Result := Social;
17:
Result := Other;
end;
end;
{ Определение рейтинга по значению из ComboBox }
function TfrmFeatures.cmbbxRatingChange(Sender: TObject): TRating;
begin
case cmbbxRating.ItemIndex of
0:
Result := 10;
1:
Result := 9;
2:
Result := 8;
3:
Result := 7;
4:
Result := 6;
5:
Result := 5;
6:
Result := 4;
7:
Result := 3;
8:
Result := 2;
9:
Result := 1;
end;
end;
{ Ограничения на эдит года }
procedure TfrmFeatures.edtYearKeyPress(Sender: TObject; var Key: Char);
const
Digits = ['0' .. '9', #8];
begin
if not(Key in Digits) then
Key := #0;
end;
{ ограничение на длительность года }
procedure TfrmFeatures.etdCurationKeyPress(Sender: TObject; var Key: Char);
const
Digits = ['0' .. '9', #8];
begin
if not(Key in Digits) then
Key := #0;
end;
{ Определение значения ComboBox по рейтингу из списка }
function TfrmFeatures.GetGenre(const aItem: TItem): Integer;
begin
case aItem.Genre of
Adventure:
Result := 0;
GAction:
Result := 1;
Comedy:
Result := 2;
Detective:
Result := 3;
Drama:
Result := 4;
Thriller:
Result := 5;
Fantasy:
Result := 6;
Science_fiction:
Result := 7;
Horror:
Result := 8;
Historical:
Result := 9;
Mystery:
Result := 10;
Romance:
Result := 11;
Western:
Result := 12;
Animation:
Result := 13;
Musical:
Result := 14;
Satire:
Result := 15;
Social:
Result := 16;
Other:
Result := 17;
end;
end;
{ Получение жанра из таблицы }
function TfrmFeatures.TabGenre(Genre: TGenre): string;
begin
case Genre of
Adventure:
Result := 'Приключения';
GAction:
Result := 'Экшн';
Comedy:
Result := 'Комедия';
Detective:
Result := 'Детектив';
Drama:
Result := 'Драма';
Thriller:
Result := 'Триллер';
Fantasy:
Result := 'Фантастика';
Science_fiction:
Result := 'Научная фантастика';
Horror:
Result := 'Ужастик';
Historical:
Result := 'Исторический';
Mystery:
Result := 'Мистика';
Romance:
Result := 'Мелодрама';
Western:
Result := 'Вестерн';
Animation:
Result := 'Мультфильм';
Musical:
Result := 'Мьюзикл';
Satire:
Result := 'Сатира';
Social:
Result := 'Социальный';
Other:
Result := 'Другое';
end;
end;
{ Определение значения ComboBox по рейтингу из списка }
function TfrmFeatures.GetRating(const aItem: TItem): Integer;
var
i: Integer;
begin
case aItem.Rating of
10:
Result := 0;
9:
Result := 1;
8:
Result := 2;
7:
Result := 3;
6:
Result := 4;
5:
Result := 5;
4:
Result := 6;
3:
Result := 7;
2:
Result := 8;
1:
Result := 9;
end;
end;
end.
|
{
ID:because3
PROG:fence4
LANG:PASCAL
}
program fence4;
type point=record
x,y:double;
end;
var s:array [0..200] of point;
b:array [1..200] of longint;
e,n,i,total:longint;
f:boolean;
function det(x1,y1,x2,y2:double):double;
begin
exit(x1*y2-x2*y1);
end;
function dot(x1,y1,x2,y2:double):double;
begin
exit(x1*x2+y1*y2);
end;
function cross(a,b,c:point):double;
begin
exit(det(a.x-b.x,a.y-b.y,c.x-b.x,c.y-b.y));
end;
function dotdet(a,b,c:point):double;
begin
exit(dot(a.x-b.x,a.y-b.y,c.x-b.x,c.y-b.y));
end;
function inter(a,b,c,d:point):boolean;
var s1,s2,s3,s4:double;
begin
s1:=cross(a,b,c);
s2:=cross(a,b,d);
s3:=cross(c,d,a);
s4:=cross(c,d,b);
if (s1*s2<0) and (s3*s4<0) then exit(true);
if ((s1=0) and (dotdet(a,b,c)>=0) and (dotdet(b,a,c)>=0)) or ((s2=0) and (dotdet(a,b,d)>=0) and (dotdet(b,a,d)>=0)) then exit(true);
exit(false);
end;
function check(a,b:point):boolean;
var p:point;
j1,j2,j3:boolean;
i:longint;
begin
if f then exit(true);
if sqrt(sqr(a.x-b.x)+sqr(a.y-b.y))<0.000001 then exit(false);
p.x:=(a.x+b.x)/2;p.y:=(a.y+b.y)/2;
j1:=true;j2:=true;j3:=true;
for i:=1 to n do
if i<>e then begin
if inter(s[0],a,s[i],s[i+1]) then begin
if inter(s[0],b,s[i],s[i+1]) then exit(false)
else if inter(s[0],p,s[i],s[i+1]) then j1:=false;
end
else if inter(s[0],b,s[i],s[i+1]) then begin
if inter(s[0],p,s[i],s[i+1]) then j2:=false;
end;
if inter(s[0],p,s[i],s[i+1]) then j3:=false;
end;
if j3 then begin f:=true;exit(true);end;
if j1 then j1:=check(a,p);
if j2 then j2:=check(p,b);
exit(j1 or j2);
end;
BEGIN
assign(input,'fence4.in');
reset(input);
assign(output,'fence4.out');
rewrite(output);
readln(n);
for i:=0 to n do
with s[i] do
readln(x,y);
s[n+1]:=s[1];
close(input);
fillchar(b,sizeof(b),0);
for e:=1 to n do begin
f:=false;
if check(s[e],s[e+1]) then
inc(b[e]);
end;
total:=0;
for i:=1 to n do
inc(total,b[i]);
writeln(total);
for i:=1 to n-2 do
if b[i]>0 then
writeln(s[i].x:0:0,' ',s[i].y:0:0,' ',s[i+1].x:0:0,' ',s[i+1].y:0:0);
if b[n]>0 then
writeln(s[1].x:0:0,' ',s[1].y:0:0,' ',s[n].x:0:0,' ',s[n].y:0:0);
if b[n-1]>0 then
writeln(s[n-1].x:0:0,' ',s[n-1].y:0:0,' ',s[n].x:0:0,' ',s[n].y:0:0);
close(output);
END.
|
unit TadGrapher;
interface
uses FrogObj, Func1D, TadMgr;
type
TTadpoleGrapher = class(TFrogObject)
private
mTadMgr: TTadpoleAlgorithmManager;
mWindowsOpen: Boolean;
public
procedure OpenWindows;
procedure CloseWindows;
procedure GraphField(pE: TEField);
procedure GraphTadpoleSpectrum(pTadSpec: TSpectrum; pERef: TEField);
procedure GraphFFTData(pFFTData: TEField);
procedure RunAlgo(pCutoff, pFloor: double);
function HasTestSpec: Boolean;
procedure Abort;
property WindowsOpen: Boolean read mWindowsOpen write mWindowsOpen;
constructor Create(pTadMgr: TTadpoleAlgorithmManager);
end;
var
gTadGrapher: TTadpoleGrapher;
const
SPACING = 5;
LEFT_SIDE = 10;
FORM_HEIGHT = 210;
FORM_WIDTH = 344;
implementation
uses TadGraph, Forms, FieldGraph, FFTGraph, TadResults, WindowMgr;
constructor TTadpoleGrapher.Create(pTadMgr: TTadpoleAlgorithmManager);
begin
mWindowsOpen := False;
mTadMgr := pTadMgr;
end;
procedure TTadpoleGrapher.OpenWindows;
begin
if mWindowsOpen then Exit;
frmTadGraph := TfrmTadGraph.Create(Application);
frmTadGraph.Left := LEFT_SIDE;
frmTadGraph.Top := 5;
frmTadGraph.Height := FORM_HEIGHT;
frmTadGraph.Width := FORM_WIDTH;
WindowManager.InitializeThisWindow(frmTadGraph);
frmTadResults := TfrmTadResults.CreateWithGrapher(Application, Self);
frmTadResults.Left := frmTadGraph.Left + frmTadGraph.Width + SPACING;
frmTadResults.Top := frmTadGraph.Top;
WindowManager.InitializeThisWindow(frmTadResults);
frmFFTGraph := TfrmFFTGraph.CreateWithGrapher(Application, Self);
frmFFTGraph.Top := frmTadGraph.Top + frmTadGraph.Height + SPACING;
frmFFTGraph.Left := LEFT_SIDE;
frmFFTGraph.Height := FORM_HEIGHT;
frmFFTGraph.Width := FORM_WIDTH*2;
WindowManager.InitializeThisWindow(frmFFTGraph);
frmEGraph := TfrmFieldGraph.Create(Application);
frmEGraph.Caption := 'Temporal Field';
frmEGraph.Top := frmFFTGraph.Top + frmFFTGraph.Height + SPACING;
frmEGraph.Left := LEFT_SIDE;
frmEGraph.Height := FORM_HEIGHT;
frmEGraph.Width := FORM_WIDTH;
WindowManager.InitializeThisWindow(frmEGraph);
frmSpecGraph := TfrmFieldGraph.Create(Application);
frmSpecGraph.Caption := 'Spectral Field';
frmSpecGraph.Chart1.LeftAxis.AutomaticMaximum := True;
frmSpecGraph.Top := frmEGraph.Top;
frmSpecGraph.Left := frmEGraph.Left + frmEGraph.Width + SPACING;
frmSpecGraph.Height := FORM_HEIGHT;
frmSpecGraph.Width := FORM_WIDTH;
frmSpecGraph.Chart1.BottomAxis.Title.Caption := 'Wavelength (nm)';
WindowManager.InitializeThisWindow(frmSpecGraph);
mWindowsOpen := True;
end;
procedure TTadpoleGrapher.CloseWindows;
begin
WindowManager.SaveAsDefaults(frmTadGraph);
frmTadGraph.Free;
frmTadGraph := nil;
WindowManager.SaveAsDefaults(frmFFTGraph);
frmFFTGraph.Free;
frmFFTGraph := nil;
WindowManager.SaveAsDefaults(frmEGraph);
frmEGraph.Free;
frmEGraph := nil;
WindowManager.SaveAsDefaults(frmSpecGraph);
frmSpecGraph.Free;
frmSpecGraph := nil;
WindowManager.SaveAsDefaults(frmTadResults);
//frmTadResults.Free;
//frmTadResults := nil;
mWindowsOpen := False;
// Comment here for demo version - Also in AlgoMgr line 193
mTadMgr.SaveResults;
mTadMgr.Deactivate;
end;
procedure TTadpoleGrapher.Abort;
begin
WindowManager.SaveAsDefaults(frmTadResults);
frmTadResults.Free;
frmTadResults := nil;
CloseWindows;
end;
procedure TTadpoleGrapher.GraphField(pE: TEField);
var
TadResults: TTadResults;
begin
// Pre-cond: pE is in dtFREQ
frmSpecGraph.Clear;
frmSpecGraph.GraphSpectrum(pE, nil, true);
pE.InverseTransform;
frmEGraph.Clear;
frmEGraph.GraphEField(pE, nil, true);
pE.CalculateTimeBandwidthProducts;
TadResults.TempWidth := pE.TemporalFWHM;
TadResults.SpecWidth := pE.SpectralFWHM;
TadResults.AutoWidth := pE.AutocorrelationFWHM;
TadResults.FWHM := pE.FWHM_TBP;
TadResults.RMS := pE.RMS_TBP;
TadResults.TL := pE.SpectralLaplacianTBP;
TadResults.SL := pE.TemporalLaplacianTBP;
frmTadResults.DisplayResults(TadResults);
end;
procedure TTadpoleGrapher.RunAlgo(pCutoff, pFloor: double);
begin
// Dispatching method for events from the FFT form
mTadMgr.RunAlgo(pCutoff, pFloor);
end;
procedure TTadpoleGrapher.GraphTadpoleSpectrum(pTadSpec: TSpectrum; pERef: TEField);
begin
frmTadGraph.GraphTadSpectrum(pTadSpec, pERef);
end;
procedure TTadpoleGrapher.GraphFFTData(pFFTData: TEField);
begin
frmFFTGraph.GraphFFTData(pFFTData);
end;
function TTadpoleGrapher.HasTestSpec: Boolean;
begin
HasTestSpec := mTadMgr.HasTestSpec;
end;
end.
|
unit MainIconUpdate;
// Pinched from Jordan Russell's Inno Setup 4.2.2.2 CompResUpdate.pas
(*
Inno Setup License
==================
Except where otherwise noted, all of the documentation and software included
in the Inno Setup package is copyrighted by Jordan Russell.
Copyright (C) 1997-2004 Jordan Russell. All rights reserved.
This software is provided "as-is," without any express or implied warranty.
In no event shall the author be held liable for any damages arising from the
use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter and redistribute it,
provided that the following conditions are met:
1. All redistributions of source code files must retain all copyright
notices that are currently in place, and this list of conditions without
modification.
2. All redistributions in binary form must retain all occurrences of the
above copyright notice and web site addresses that are currently in
place (for example, in the About boxes).
3. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software to
distribute a product, an acknowledgment in the product documentation
would be appreciated but is not required.
4. Modified versions in source or binary form must be plainly marked as
such, and must not be misrepresented as being the original software.
Jordan Russell
jr-2004 AT jrsoftware.org
http://www.jrsoftware.org/
*)
interface
uses
Windows, SysUtils;
procedure UpdateDelphiExeIcons(const FileName, IcoFileName: String);
implementation
uses Classes;
procedure Error(const Msg: String);
begin
raise Exception.Create('Resource update error: ' + Msg);
end;
procedure ErrorWithLastError(const Msg: String);
begin
Error(Msg + '(' + IntToStr(GetLastError) + ')');
end;
function EnumLangsFunc(hModule: Cardinal; lpType, lpName: PAnsiChar; wLanguage: Word; lParam: Integer): BOOL; stdcall;
begin
PWord(lParam)^ := wLanguage;
Result := False;
end;
function GetResourceLanguage(hModule: Cardinal; lpType, lpName: PAnsiChar; var wLanguage: Word): Boolean;
begin
wLanguage := 0;
EnumResourceLanguages(hModule, lpType, lpName, @EnumLangsFunc, Integer(@wLanguage));
Result := True;
end;
procedure UpdateDelphiExeIcons(const FileName, IcoFileName: String);
type
PIcoItemHeader = ^TIcoItemHeader;
TIcoItemHeader = packed record
Width: Byte;
Height: Byte;
Colors: Byte;
Reserved: Byte;
Planes: Word;
BitCount: Word;
ImageSize: DWORD;
end;
PIcoItem = ^TIcoItem;
TIcoItem = packed record
Header: TIcoItemHeader;
Offset: DWORD;
end;
PIcoHeader = ^TIcoHeader;
TIcoHeader = packed record
Reserved: Word;
Typ: Word;
ItemCount: Word;
Items: array [0..MaxInt shr 4 - 1] of TIcoItem;
end;
PGroupIconDirItem = ^TGroupIconDirItem;
TGroupIconDirItem = packed record
Header: TIcoItemHeader;
Id: Word;
end;
PGroupIconDir = ^TGroupIconDir;
TGroupIconDir = packed record
Reserved: Word;
Typ: Word;
ItemCount: Word;
Items: array [0..MaxInt shr 4 - 1] of TGroupIconDirItem;
end;
function IsValidIcon(P: Pointer; Size: Cardinal): Boolean;
var
ItemCount: Cardinal;
begin
Result := False;
if Size < SizeOf(Word) * 3 then
Exit;
if (PChar(P)[0] = 'M') and (PChar(P)[1] = 'Z') then
Exit;
ItemCount := PIcoHeader(P).ItemCount;
if Size < (SizeOf(Word) * 3) + (ItemCount * SizeOf(TIcoItem)) then
Exit;
P := @PIcoHeader(P).Items;
while ItemCount > 0 do begin
if (PIcoItem(P).Offset + PIcoItem(P).Header.ImageSize < PIcoItem(P).Offset) or
(PIcoItem(P).Offset + PIcoItem(P).Header.ImageSize > Size) then
Exit;
Inc(PIcoItem(P));
Dec(ItemCount);
end;
Result := True;
end;
var
H: THandle;
M: HMODULE;
R: HRSRC;
Res: HGLOBAL;
GroupIconDir, NewGroupIconDir: PGroupIconDir;
I: Integer;
wLanguage: Word;
F : TFileStream;
Ico: PIcoHeader;
N: Cardinal;
NewGroupIconDirSize: LongInt;
begin
if Win32Platform <> VER_PLATFORM_WIN32_NT then begin
// complain if can't be done
// Error('Only supported on Windows NT and above');
// quietly return if can't be done
exit;
end;
Ico := nil;
try
{ Load the icons }
F := TFileStream.Create( IcoFileName, fmOpenRead or fmShareDenyWrite );
try
N := F.Size;
GetMem(Ico, N);
F.ReadBuffer( Ico^, N );
finally
F.Free;
end;
{ Ensure the icon is valid }
if not IsValidIcon(Ico, N) then
Error('Icon file is invalid');
{ Update the resources }
H := BeginUpdateResource(PChar(FileName), False);
if H = 0 then
ErrorWithLastError('BeginUpdateResource failed (1)');
try
M := LoadLibraryEx(PChar(FileName), 0, LOAD_LIBRARY_AS_DATAFILE);
if M = 0 then
ErrorWithLastError('LoadLibraryEx failed (1)');
try
{ Load the 'MAINICON' group icon resource }
R := FindResource(M, 'MAINICON', RT_GROUP_ICON);
if R = 0 then
ErrorWithLastError('FindResource failed (1)');
Res := LoadResource(M, R);
if Res = 0 then
ErrorWithLastError('LoadResource failed (1)');
GroupIconDir := LockResource(Res);
if GroupIconDir = nil then
ErrorWithLastError('LockResource failed (1)');
{ Delete 'MAINICON' }
if not GetResourceLanguage(M, RT_GROUP_ICON, 'MAINICON', wLanguage) then
Error('GetResourceLanguage failed (1)');
if not UpdateResource(H, RT_GROUP_ICON, 'MAINICON', wLanguage, nil, 0) then
ErrorWithLastError('UpdateResource failed (1)');
{ Delete the RT_ICON icon resources that belonged to 'MAINICON' }
for I := 0 to GroupIconDir.ItemCount-1 do begin
if not GetResourceLanguage(M, RT_ICON, MakeIntResource(GroupIconDir.Items[I].Id), wLanguage) then
Error('GetResourceLanguage failed (2)');
if not UpdateResource(H, RT_ICON, MakeIntResource(GroupIconDir.Items[I].Id), wLanguage, nil, 0) then
ErrorWithLastError('UpdateResource failed (2)');
end;
{ Build the new group icon resource }
NewGroupIconDirSize := 3*SizeOf(Word)+Ico.ItemCount*SizeOf(TGroupIconDirItem);
GetMem(NewGroupIconDir, NewGroupIconDirSize);
try
{ Build the new group icon resource }
NewGroupIconDir.Reserved := GroupIconDir.Reserved;
NewGroupIconDir.Typ := GroupIconDir.Typ;
NewGroupIconDir.ItemCount := Ico.ItemCount;
for I := 0 to NewGroupIconDir.ItemCount-1 do begin
NewGroupIconDir.Items[I].Header := Ico.Items[I].Header;
NewGroupIconDir.Items[I].Id := I+1; //assumes that there aren't any icons left
end;
{ Update 'MAINICON' }
for I := 0 to NewGroupIconDir.ItemCount-1 do
if not UpdateResource(H, RT_ICON, MakeIntResource(NewGroupIconDir.Items[I].Id), 1033, Pointer(DWORD(Ico) + Ico.Items[I].Offset), Ico.Items[I].Header.ImageSize) then
ErrorWithLastError('UpdateResource failed (3)');
{ Update the icons }
if not UpdateResource(H, RT_GROUP_ICON, 'MAINICON', 1033, NewGroupIconDir, NewGroupIconDirSize) then
ErrorWithLastError('UpdateResource failed (4)');
finally
FreeMem(NewGroupIconDir);
end;
finally
FreeLibrary(M);
end;
except
EndUpdateResource(H, True); { discard changes }
raise;
end;
if not EndUpdateResource(H, False) then
ErrorWithLastError('EndUpdateResource failed');
finally
FreeMem(Ico);
end;
end;
end.
|
unit MolHero.Utils;
interface
uses
System.UITypes;
// http://en.wikipedia.org/wiki/Chemical_element
const
CHEM_ELEMENTS_COUNT = 118;
/// <summary>
/// Converts chemical element symbol to its atomic number
/// </summary>
/// <param name="symbol">
/// Atomic symbol to convert. Characters case is not important
/// </param>
/// <returns>
/// Returns atomic number of the symbol or "0" if symbol is not recognized
/// </returns>
function ElementSymbolToAtomicNr(const symbol: string): byte;
function AtomicNrToColor(const nr: byte): TAlphaColor;
implementation
uses
System.SysUtils,
System.UIConsts;
function ElementSymbolToAtomicNr(const symbol: string): byte;
var s: string;
begin
s := LowerCase(symbol);
if s = 'h' then Result := 1 else
if s = 'he' then Result := 2 else
if s = 'li' then Result := 3 else
if s = 'be' then Result := 4 else
if s = 'b' then Result := 5 else
if s = 'c' then Result := 6 else
if s = 'n' then Result := 7 else
if s = 'o' then Result := 8 else
if s = 'f' then Result := 9 else
if s = 'ne' then Result := 10 else
if s = 'na' then Result := 11 else
if s = 'mg' then Result := 12 else
if s = 'al' then Result := 13 else
if s = 'si' then Result := 14 else
if s = 'p' then Result := 15 else
if s = 's' then Result := 16 else
if s = 'cl' then Result := 17 else
if s = 'ar' then Result := 18 else
if s = 'k' then Result := 19 else
if s = 'ca' then Result := 20 else
if s = 'sc' then Result := 21 else
if s = 'ti' then Result := 22 else
if s = 'v' then Result := 23 else
if s = 'cr' then Result := 24 else
if s = 'mn' then Result := 25 else
if s = 'fe' then Result := 26 else
if s = 'co' then Result := 27 else
if s = 'ni' then Result := 28 else
if s = 'cu' then Result := 29 else
if s = 'zn' then Result := 30 else
if s = 'ga' then Result := 31 else
if s = 'ge' then Result := 32 else
if s = 'as' then Result := 33 else
if s = 'se' then Result := 34 else
if s = 'br' then Result := 35 else
if s = 'kr' then Result := 36 else
if s = 'rb' then Result := 37 else
if s = 'sr' then Result := 38 else
if s = 'y' then Result := 39 else
if s = 'zr' then Result := 40 else
if s = 'nb' then Result := 41 else
if s = 'mo' then Result := 42 else
if s = 'tc' then Result := 43 else
if s = 'ru' then Result := 44 else
if s = 'rh' then Result := 45 else
if s = 'pd' then Result := 46 else
if s = 'ag' then Result := 47 else
if s = 'cd' then Result := 48 else
if s = 'in' then Result := 49 else
if s = 'sn' then Result := 50 else
if s = 'sb' then Result := 51 else
if s = 'te' then Result := 52 else
if s = 'i' then Result := 53 else
if s = 'xe' then Result := 54 else
if s = 'cs' then Result := 55 else
if s = 'ba' then Result := 56 else
if s = 'la' then Result := 57 else
if s = 'ce' then Result := 58 else
if s = 'pr' then Result := 59 else
if s = 'nd' then Result := 60 else
if s = 'pm' then Result := 61 else
if s = 'sm' then Result := 62 else
if s = 'eu' then Result := 63 else
if s = 'gd' then Result := 64 else
if s = 'tb' then Result := 65 else
if s = 'dy' then Result := 66 else
if s = 'ho' then Result := 67 else
if s = 'er' then Result := 68 else
if s = 'tm' then Result := 69 else
if s = 'yb' then Result := 70 else
if s = 'lu' then Result := 71 else
if s = 'hf' then Result := 72 else
if s = 'ta' then Result := 73 else
if s = 'w' then Result := 74 else
if s = 're' then Result := 75 else
if s = 'os' then Result := 76 else
if s = 'ir' then Result := 77 else
if s = 'pt' then Result := 78 else
if s = 'au' then Result := 79 else
if s = 'hg' then Result := 80 else
if s = 'tl' then Result := 81 else
if s = 'pb' then Result := 82 else
if s = 'bi' then Result := 83 else
if s = 'po' then Result := 84 else
if s = 'at' then Result := 85 else
if s = 'rn' then Result := 86 else
if s = 'fr' then Result := 87 else
if s = 'ra' then Result := 88 else
if s = 'ac' then Result := 89 else
if s = 'th' then Result := 90 else
if s = 'pa' then Result := 91 else
if s = 'u' then Result := 92 else
if s = 'np' then Result := 93 else
if s = 'pu' then Result := 94 else
if s = 'am' then Result := 95 else
if s = 'cm' then Result := 96 else
if s = 'bk' then Result := 97 else
if s = 'cf' then Result := 98 else
if s = 'es' then Result := 99 else
if s = 'fm' then Result := 100 else
if s = 'md' then Result := 101 else
if s = 'no' then Result := 102 else
if s = 'lr' then Result := 103 else
if s = 'rf' then Result := 104 else
if s = 'db' then Result := 105 else
if s = 'sg' then Result := 106 else
if s = 'bh' then Result := 107 else
if s = 'hs' then Result := 108 else
if s = 'mt' then Result := 109 else
if s = 'ds' then Result := 110 else
if s = 'rg' then Result := 111 else
if s = 'cn' then Result := 112 else
if s = 'uut' then Result := 113 else
if s = 'uuq' then Result := 114 else
if s = 'uup' then Result := 115 else
if s = 'uuh' then Result := 116 else
if s = 'uus' then Result := 117 else
if s = 'uuo' then Result := 118 else
Result := 0;
end;
type
TColorRGB = array[0..2] of byte;
const
ATOM_COLOR: array[0..CHEM_ELEMENTS_COUNT-1] of TColorRGB = (
{h} (255,255,255),
{he} (217,255,255),
{li} (204,128,255),
{be} (194,255,0),
{b} (255,181,181),
{c} (144,144,144),
{n} (48,80,248),
{o} (255,13,13),
{f} (144,224,80),
{ne} (179,227,245),
{na} (171,92,242),
{mg} (138,255,0),
{al} (191,166,166),
{si} (240,200,160),
{p} (255,128,0),
{s} (255,255,48),
{cl} (31,240,31),
{ar} (128,209,227),
{k} (143,64,212),
{ca} (61,255,0),
{sc} (230,230,230),
{ti} (191,194,199),
{v} (166,166,171),
{cr} (138,153,199),
{mn} (156,122,199),
{fe} (224,102,51),
{co} (240,144,160),
{ni} (80,208,80),
{cu} (200,128,51),
{zn} (125,128,176),
{ga} (194,143,143),
{ge} (102,143,143),
{as} (189,128,227),
{se} (255,161,0),
{br} (166,41,41),
{kr} (92,184,209),
{rb} (112,46,176),
{sr} (0,255,0),
{y} (148,255,255),
{zr} (148,224,224),
{nb} (115,194,201),
{mo} (84,181,181),
{tc} (59,158,158),
{ru} (36,143,143),
{rh} (10,125,140),
{pd} (0,105,133),
{ag} (192,192,192),
{cd} (255,217,143),
{in} (166,117,115),
{sn} (102,128,128),
{sb} (158,99,181),
{te} (212,122,0),
{i} (148,0,148),
{xe} (66,158,176),
{cs} (87,23,143),
{ba} (0,201,0),
{la} (112,212,255),
{ce} (255,255,199),
{pr} (217,255,199),
{nd} (199,255,199),
{pm} (163,255,199),
{sm} (143,255,199),
{eu} (97,255,199),
{gd} (69,255,199),
{tb} (48,255,199),
{dy} (31,255,199),
{ho} (0,255,156),
{er} (0,230,117),
{tm} (0,212,82),
{yb} (0,191,56),
{lu} (0,171,36),
{hf} (77,194,255),
{ta} (77,166,255),
{w} (33,148,214),
{re} (38,125,171),
{os} (38,102,150),
{ir} (23,84,135),
{pt} (208,208,224),
{au} (255,209,35),
{hg} (184,184,208),
{tl} (166,84,77),
{pb} (87,89,97),
{bi} (158,79,181),
{po} (171,92,0),
{at} (117,79,69),
{rn} (66,130,150),
{fr} (66,0,102),
{ra} (0,125,0),
{ac} (112,171,250),
{th} (0,186,255),
{pa} (0,161,255),
{u} (0,143,255),
{np} (0,128,255),
{pu} (0,107,255),
{am} (84,92,242),
{cm} (120,92,227),
{bk} (138,79,227),
{cf} (161,54,212),
{es} (179,31,212),
{fm} (179,31,186),
{md} (179,13,166),
{no} (189,13,135),
{lr} (199,0,102),
{rf} (204,0,89),
{db} (209,0,79),
{sg} (217,0,69),
{bh} (224,0,56),
{hs} (230,0,46),
{mt} (235,0,38),
{ds} (235,0,38),
{rg} (235,0,38),
{cn} (235,0,38),
{uut} (235,0,38),
{uuq} (235,0,38),
{uup} (235,0,38),
{uuh} (235,0,38),
{uus} (235,0,38),
{uuo} (235,0,38)
);
function ColorRGBToAlphaColor(c: TColorRGB): TAlphaColor;
begin
Result := MakeColor(c[0], c[1], c[2]);
end;
function AtomicNrToColor(const nr: byte): TAlphaColor;
begin
if (nr < 1) or (nr > 118) then
Result := MakeColor(255,255,255) // unknown atom type
else
Result := ColorRGBToAlphaColor(ATOM_COLOR[nr-1]);
end;
end.
|
{***************************************************************}
{ Copyright (c) 2013 год . }
{ Тетенев Леонид Петрович, ltetenev@yandex.ru }
{ }
{***************************************************************}
unit CustomSimpleForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CustomForm, PrnDbgeh, Vcl.ExtCtrls, AddActions, Vcl.DBActns, Vcl.ActnList,
Vcl.ComCtrls, DBGridEhGrouping, ToolCtrlsEh, Data.DB, FIBDataSet, pFIBDataSet, GridsEh, DBGridEh;
type
TfrCustomSimpleForm = class(TfrCustomForm)
dbgHost: TDBGridEh;
Q_Host: TpFIBDataSet;
dsHost: TDataSource;
procedure FormActivate(Sender: TObject); override;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Q_HostBeforeOpen(DataSet: TDataSet);
function GetAccessConditionValue: String; virtual;
procedure Q_HostEndScroll(DataSet: TDataSet);
procedure dbgHostEnter(Sender: TObject);
procedure Q_HostBeforeScroll(DataSet: TDataSet);
procedure Q_HostAfterScroll(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
procedure FillHostMenu; virtual; abstract;
class procedure ShowSimpleForm( Act: TAction; DlgIdent: Integer );
end;
implementation
{$R *.dfm}
uses Prima, ClientDM;
{ TfrCustomSimpleForm }
procedure TfrCustomSimpleForm.FormActivate(Sender: TObject);
begin
inherited;
FillHostMenu;
if Q_Host.Active then
Q_Host.Refresh;
end;
procedure TfrCustomSimpleForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
try
DBGridToBase( dbgHost, Self.ClassName, dbgHost.Name );
finally
inherited;
end;
end;
function TfrCustomSimpleForm.GetAccessConditionValue: String;
begin
Result := '';
end;
procedure TfrCustomSimpleForm.Q_HostAfterScroll(DataSet: TDataSet);
begin
inherited;
IsScroll := False;
end;
procedure TfrCustomSimpleForm.Q_HostBeforeOpen(DataSet: TDataSet);
begin
inherited;
if not Q_Host.Transaction.InTransaction then
Q_Host.Transaction.StartTransaction;
end;
procedure TfrCustomSimpleForm.Q_HostBeforeScroll(DataSet: TDataSet);
begin
IsScroll := True;
inherited;
end;
procedure TfrCustomSimpleForm.Q_HostEndScroll(DataSet: TDataSet);
begin
inherited;
DataSetAfterScroll( DataSet );
end;
class procedure TfrCustomSimpleForm.ShowSimpleForm( Act: TAction; DlgIdent: Integer );
begin
With Self.Create( Application ) do begin
try
IsWriteRight := True;
A_Filtr.DlgIdent := DlgIdent;
WindowState := wsMaximized;
ActiveControl := dbgHost;
SetAccessRight( Act.Name );
BaseToDBGrid( dbgHost, Self.ClassName, dbgHost.Name );
Caption := Act.Caption;
FormCaption := Act.Caption;
FormActivate( nil );
if SetAccessRightOfRows( Q_Host, GetAccessConditionValue ) then begin
HostSqlText := Q_Host.SelectSQL.Text;
OpenDataSetOfStartForm;
end;
finally
If not Q_Host.Active then
Close;
end;
end;
end;
procedure TfrCustomSimpleForm.dbgHostEnter(Sender: TObject);
begin
inherited;
DbGridEnter( Sender );
end;
end.
|
unit BaseSystemAdministrationFormController;
interface
uses
unSectionStackedForm,
unSystemAdministrationForm,
AbstractSectionStackedFormController,
AbstractFormController,
SystemAdministrationService,
SectionRecordViewModel,
SectionSetHolder,
SectionStackedFormViewModel,
SystemAdministrationPrivileges,
SystemAdministrationFormViewModelMapperInterface,
BaseSystemAdministrationFormControllerEvents,
FormEvents,
Controls,
EventBus,
Event,
Forms,
SysUtils,
Classes;
type
TBaseSystemAdministrationFormController = class (TAbstractSectionStackedFormController)
protected
FClientIdentity: Variant;
FSystemAdministrationService: ISystemAdministrationService;
FFormViewModelMapper: ISystemAdministrationFormViewModelMapper;
protected
function GetFormClass: TFormClass; override;
protected
function CreateSectionStackedFormViewModel: TSectionStackedFormViewModel; override;
protected
function CreateSectionFormRequestedEventFrom(
SectionRecordViewModel: TSectionRecordViewModel
): TSectionFormRequestedEvent; override;
public
constructor Create(
const ClientIdentity: Variant;
SystemAdministrationService: ISystemAdministrationService;
FormViewModelMapper: ISystemAdministrationFormViewModelMapper;
EventBus: IEventBus
);
end;
implementation
{ TBaseSystemAdministrationFormController }
constructor TBaseSystemAdministrationFormController.Create(
const ClientIdentity: Variant;
SystemAdministrationService: ISystemAdministrationService;
FormViewModelMapper: ISystemAdministrationFormViewModelMapper;
EventBus: IEventBus
);
begin
inherited Create(EventBus);
FClientIdentity := ClientIdentity;
FSystemAdministrationService := SystemAdministrationService;
FFormViewModelMapper := FormViewModelMapper;
end;
function TBaseSystemAdministrationFormController.CreateSectionFormRequestedEventFrom(
SectionRecordViewModel: TSectionRecordViewModel
): TSectionFormRequestedEvent;
begin
Result :=
TSystemAdministrationPrivilegeFormRequestedEvent.Create(
SectionRecordViewModel.Id
);
end;
function TBaseSystemAdministrationFormController.CreateSectionStackedFormViewModel: TSectionStackedFormViewModel;
var SystemAdministrationPrivileges: TSystemAdministrationPrivileges;
begin
SystemAdministrationPrivileges :=
FSystemAdministrationService.GetAllSystemAdministrationPrivileges(FClientIdentity);
try
Result :=
FFormViewModelMapper.MapSystemAdministrationFormViewModelFrom(
SystemAdministrationPrivileges
);
finally
FreeAndNil(SystemAdministrationPrivileges);
end;
end;
function TBaseSystemAdministrationFormController.GetFormClass: TFormClass;
begin
Result := TSystemAdministrationForm;
end;
end.
|
unit Parametros;
interface
uses
ParametrosNFCe,
Empresa;
type
TParametros = class
private
FNFCe :TParametrosNFCe;
FEmpresa: TEmpresa;
function GetEmpresa: TEmpresa;
function GetNFCe: TParametrosNFCe;
private
procedure SetEmpresa(const Value: TEmpresa);
procedure SetNFCe(const Value: TParametrosNFCe);
public
property NFCe :TParametrosNFCe read GetNFCe;
property Empresa :TEmpresa read GetEmpresa;
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses
SysUtils, repositorio, fabricaRepositorio;
{ TParametros }
constructor TParametros.Create;
begin
// FNFCe := TParametrosNFCe.Create;
// FEmpresa := TEmpresa.Create;
end;
destructor TParametros.Destroy;
begin
FreeAndNil(FNFCe);
FreeAndNil(FEmpresa);
inherited;
end;
function TParametros.GetEmpresa: TEmpresa;
var repositorio :TRepositorio;
begin
if not assigned(FEmpresa) then begin
repositorio := TFabricaRepositorio.GetRepositorio(TEmpresa.ClassName);
Fempresa := TEmpresa(repositorio.Get(1));
end;
result := FEmpresa;
end;
function TParametros.GetNFCe: TParametrosNFCe;
var repositorio :TRepositorio;
begin
if not assigned(FNFCe) then begin
repositorio := TFabricaRepositorio.GetRepositorio(TParametrosNFCe.ClassName);
FNFCe := TParametrosNFCe(repositorio.Get(1));
end;
result := FNFCe;
end;
procedure TParametros.SetEmpresa(const Value: TEmpresa);
begin
FEmpresa := Value;
end;
procedure TParametros.SetNFCe(const Value: TParametrosNFCe);
begin
FNFCe := Value;
end;
end.
|
unit PropertyValueEditors;
// Utility unit for the advanced Virtual Treeview demo application which contains the implementation of edit link
// interfaces used in other samples of the demo.
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, VirtualTrees, ExtDlgs, ImgList, Buttons, ExtCtrls, ComCtrls,
Mask, model_config;
type
THandlePropertyValueChanged = reference to procedure
(p: TChangedPropertyValue);
// ----------------------------------------------------------------------------------------------------------------------
// Our own edit link to implement several different node editors.
TPropertyEditLink = class(TInterfacedObject, IVTEditLink)
private
FEdit: TWinControl; // One of the property editor classes.
FTree: TVirtualStringTree; // A back reference to the tree calling.
FNode: PVirtualNode; // The node being edited.
FColumn: integer; // The column of the node being edited.
FConfigData: PConfigData;
FHandlePropertyValueChanged: THandlePropertyValueChanged;
procedure DoPropertyValueChanged;
protected
procedure EditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure EditKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
public
destructor Destroy; override;
function BeginEdit: boolean; stdcall;
function CancelEdit: boolean; stdcall;
function EndEdit: boolean; stdcall;
function GetBounds: TRect; stdcall;
function PrepareEdit(Tree: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex): boolean; stdcall;
procedure ProcessMessage(var Message: TMessage); stdcall;
procedure SetBounds(R: TRect); stdcall;
property OnValueChanged: THandlePropertyValueChanged
write FHandlePropertyValueChanged;
end;
// ----------------------------------------------------------------------------------------------------------------------
type
TPropertyTextKind = (ptkText, ptkHint);
// The following constants provide the property tree with default data.
// ----------------------------------------------------------------------------------------------------------------------
implementation
uses
listports, vclutils;
// ----------------- TPropertyEditLink ----------------------------------------------------------------------------------
// This implementation is used in VST3 to make a connection beween the tree
// and the actual edit window which might be a simple edit, a combobox
// or a memo etc.
destructor TPropertyEditLink.Destroy;
begin
// FEdit.Free; casues issue #357. Fix:
if FEdit.HandleAllocated then
PostMessage(FEdit.Handle, CM_RELEASE, 0, 0);
inherited;
end;
// ----------------------------------------------------------------------------------------------------------------------
procedure TPropertyEditLink.EditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
CanAdvance: boolean;
begin
CanAdvance := true;
case Key of
VK_ESCAPE:
begin
Key := 0; // ESC will be handled in EditKeyUp()
end;
VK_RETURN:
if CanAdvance then
begin
FTree.EndEditNode;
Key := 0;
end;
VK_UP, VK_DOWN:
begin
// Consider special cases before finishing edit mode.
CanAdvance := Shift = [];
if FEdit is TComboBox then
CanAdvance := CanAdvance and not TComboBox(FEdit)
.DroppedDown;
if FEdit is TDateTimePicker then
CanAdvance := CanAdvance and not TDateTimePicker(FEdit)
.DroppedDown;
if CanAdvance then
begin
// Forward the keypress to the tree. It will asynchronously change the focused node.
PostMessage(FTree.Handle, WM_KEYDOWN, Key, 0);
Key := 0;
end;
end;
end;
end;
procedure TPropertyEditLink.EditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_ESCAPE:
begin
FTree.CancelEditNode;
Key := 0;
end; // VK_ESCAPE
end; // case
end;
// ----------------------------------------------------------------------------------------------------------------------
function TPropertyEditLink.BeginEdit: boolean;
begin
Result := true;
FEdit.Show;
FEdit.SetFocus;
end;
// ----------------------------------------------------------------------------------------------------------------------
function TPropertyEditLink.CancelEdit: boolean;
begin
Result := true;
FEdit.Hide;
end;
// ----------------------------------------------------------------------------------------------------------------------
function TPropertyEditLink.EndEdit: boolean;
var
prop: TConfigProperty;
Buffer: array [0 .. 1024] of Char;
S: UnicodeString;
begin
Result := true;
prop := PConfigData(FTree.GetNodeData(FNode)).prop;
if FEdit is TComboBox then
S := TComboBox(FEdit).Text
else if FEdit is TCheckBox then
begin
if (FEdit as TCheckBox).Checked then
S := '1'
else
S := '0';
end
else
begin
GetWindowText(FEdit.Handle, Buffer, 1024);
S := Buffer;
end;
if S <> prop.FValue then
begin
prop.SetStr(S);
DoPropertyValueChanged;
// DataModule1.UpdateConfigPropertyValue(Data.FSectionName, Data.FPropertyName, Data.FValue);
FTree.InvalidateNode(FNode);
FTree.InvalidateNode(FNode.Parent);
end;
FEdit.Hide;
try
FTree.SetFocus;
except
end;
end;
// ----------------------------------------------------------------------------------------------------------------------
function TPropertyEditLink.GetBounds: TRect;
begin
Result := FEdit.BoundsRect;
end;
// ----------------------------------------------------------------------------------------------------------------------
function TPropertyEditLink.PrepareEdit(Tree: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex): boolean;
var
i: integer;
begin
Result := true;
FTree := Tree as TVirtualStringTree;
FNode := Node;
FColumn := Column;
FConfigData := FTree.GetNodeData(FNode);
// determine what edit type actually is needed
FEdit.Free;
FEdit := nil;
if (length(FConfigData.Prop.FList) > 0) or (FConfigData.Prop.ValueType in
[ VtComportName, VtBaud ] ) then
begin
FEdit := TComboBox.Create(nil);
with FEdit as TComboBox do
begin
Visible := False;
Parent := Tree;
Text := FConfigData.Prop.FValue;
if FConfigData.Prop.ValueType = VtComportName then
EnumComPorts(Items)
else if FConfigData.Prop.ValueType = VtBaud then
EnumBaudRates(Items)
else
for i := 0 to length(FConfigData.Prop.FList) - 1 do
Items.Add(FConfigData.Prop.FList[i]);
OnKeyDown := EditKeyDown;
OnKeyUp := EditKeyUp;
style := csDropDown;
ItemHeight := 22;
ItemIndex := Items.IndexOf(FConfigData.Prop.FValue);
end;
end
else if FConfigData.Prop.ValueType = VtString then
begin
FEdit := TEdit.Create(nil);
with FEdit as TEdit do
begin
Visible := False;
Parent := Tree;
Text := FConfigData.Prop.FValue;
OnKeyDown := EditKeyDown;
OnKeyUp := EditKeyUp;
end;
end
else if FConfigData.Prop.ValueType = VtInt then
begin
FEdit := TEdit.Create(nil);
with FEdit as TEdit do
begin
Visible := False;
Parent := Tree;
Text := FConfigData.Prop.FValue;
OnKeyDown := EditKeyDown;
OnKeyUp := EditKeyUp;
end;
end
else if FConfigData.Prop.ValueType = VtFloat then
begin
FEdit := TEdit.Create(nil);
with FEdit as TEdit do
begin
Visible := False;
Parent := Tree;
Text := FConfigData.Prop.FValue;
OnKeyDown := EditKeyDown;
OnKeyUp := EditKeyUp;
end;
end
else if FConfigData.Prop.ValueType = VtBool then
begin
FEdit := TCheckBox.Create(nil);
with FEdit as TCheckBox do
begin
Visible := False;
Parent := Tree;
if FConfigData.Prop.FValue = '0' then
FConfigData.Prop.FValue := '1'
else
FConfigData.Prop.FValue := '0';
Checked := FConfigData.Prop.FValue <> '0';
Caption := '---';
FConfigData.Prop.SetStr(FConfigData.Prop.FValue);
DoPropertyValueChanged;
end;
end
else
Result := False;
end;
// ----------------------------------------------------------------------------------------------------------------------
procedure TPropertyEditLink.ProcessMessage(var Message: TMessage);
begin
FEdit.WindowProc(Message);
end;
// ----------------------------------------------------------------------------------------------------------------------
procedure TPropertyEditLink.SetBounds(R: TRect);
var
Dummy: integer;
begin
// Since we don't want to activate grid extensions in the tree (this would influence how the selection is drawn)
// we have to set the edit's width explicitly to the width of the column.
FTree.Header.Columns.GetColumnBounds(FColumn, Dummy, R.Right);
FEdit.BoundsRect := R;
end;
// ----------------------------------------------------------------------------------------------------------------------
procedure TPropertyEditLink.DoPropertyValueChanged;
var
pc: TChangedPropertyValue;
begin
if (not FConfigData.Prop.HasError) AND Assigned(FHandlePropertyValueChanged) then
begin
pc := TChangedPropertyValue.Create(FConfigData);
FHandlePropertyValueChanged(pc);
pc.Free;
end;
end;
end.
|
{**************************************************************************}
{ }
{ This Source Code Form is subject to the terms of the Mozilla Public }
{ License, v. 2.0. If a copy of the MPL was not distributed with this }
{ file, You can obtain one at http://mozilla.org/MPL/2.0/. }
{ }
{ 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. }
{ }
{ Copyright Eric Grange / Creative IT }
{ }
{**************************************************************************}
unit dwsJITx86;
{$I ../dws.inc}
interface
{
TODO:
- range checking
- check object
}
uses
Classes, SysUtils, Math, {$IFDEF WINDOWS} Windows, {$ENDIF}
dwsExprs, dwsSymbols, dwsErrors, dwsUtils, dwsExprList, dwsXPlatform,
dwsCoreExprs, dwsRelExprs, dwsMagicExprs, dwsConstExprs,
dwsMathFunctions, dwsDataContext, dwsConvExprs, dwsSetOfExprs, dwsMethodExprs,
dwsJIT, dwsJITFixups, dwsJITAllocatorWin, dwsJITx86Intrinsics, dwsVMTOffsets;
type
TRegisterStatus = record
Contains : TObject;
Lock : Integer;
end;
TFixupAlignedTarget = class(TFixupTarget)
public
function GetSize : Integer; override;
procedure Write(output : TWriteOnlyBlockStream); override;
function JumpLocation : Integer; override;
end;
TFixupJump = class(TFixupTargeting)
private
FFlags : TboolFlags;
FLongJump : Boolean;
protected
function NearJump : Boolean;
public
constructor Create(flags : TboolFlags);
function Optimize : TFixupOptimizeAction; override;
function GetSize : Integer; override;
procedure Write(output : TWriteOnlyBlockStream); override;
end;
TFixupPreamble = class(TFixup)
private
FPreserveExec : Boolean;
FTempSpaceOnStack : Integer;
FAllocatedStackSpace : Integer;
public
function GetSize : Integer; override;
procedure Write(output : TWriteOnlyBlockStream); override;
procedure NeedTempSpace(bytes : Integer);
function AllocateStackSpace(bytes : Integer) : Integer;
function NeedEBP : Boolean; inline;
property PreserveExec : Boolean read FPreserveExec write FPreserveExec;
property TempSpaceOnStack : Integer read FTempSpaceOnStack write FTempSpaceOnStack;
property AllocatedStackSpace : Integer read FAllocatedStackSpace write FAllocatedStackSpace;
end;
TFixupPostamble = class(TFixup)
private
FPreamble : TFixupPreamble;
public
constructor Create(preamble : TFixupPreamble);
function GetSize : Integer; override;
procedure Write(output : TWriteOnlyBlockStream); override;
end;
Tx86FixupLogic = class (TFixupLogic)
private
FOptions : TdwsJITOptions;
public
function NewHangingTarget(align : Boolean) : TFixupTarget; override;
property Options : TdwsJITOptions read FOptions write FOptions;
end;
Tx86FixupLogicHelper = class helper for TFixupLogic
function NewJump(flags : TboolFlags) : TFixupJump; overload;
function NewJump(flags : TboolFlags; target : TFixup) : TFixupJump; overload;
function NewJump(target : TFixup) : TFixupJump; overload;
procedure NewConditionalJumps(flagsTrue : TboolFlags; targetTrue, targetFalse : TFixup);
end;
TdwsJITx86 = class (TdwsJIT)
private
FRegs : array [TxmmRegister] of TRegisterStatus;
FXMMIter : TxmmRegister;
FSavedXMM : TxmmRegisters;
FPreamble : TFixupPreamble;
FPostamble : TFixupPostamble;
x86 : Tx86WriteOnlyStream;
FAllocator : TdwsJITAllocatorWin;
FAbsMaskPD : TdwsJITCodeBlock;
FSignMaskPD : TdwsJITCodeBlock;
FBufferBlock : TdwsJITCodeBlock;
FHint32bitSymbol : TObjectsLookup;
FInterpretedJITter : TdwsJITter;
protected
function CreateOutput : TWriteOnlyBlockStream; override;
function CreateFixupLogic : TFixupLogic; override;
procedure StartJIT(expr : TExprBase; exitable : Boolean); override;
procedure EndJIT; override;
procedure EndFloatJIT(resultHandle : Integer); override;
procedure EndIntegerJIT(resultHandle : Integer); override;
public
constructor Create; override;
destructor Destroy; override;
function AllocXMMReg(expr : TExprBase; contains : TObject = nil) : TxmmRegister;
procedure ReleaseXMMReg(reg : TxmmRegister);
function CurrentXMMReg(contains : TObject) : TxmmRegister;
procedure ContainsXMMReg(reg : TxmmRegister; contains : TObject);
procedure ResetXMMReg;
procedure SaveXMMRegs;
procedure RestoreXMMRegs;
function StackAddrOfFloat(expr : TTypedExpr) : Integer;
procedure Hint32Bit(obj : TRefCountedObject);
procedure ClearHint32Bit(obj : TRefCountedObject);
function Is32BitHinted(obj : TRefCountedObject) : Boolean;
property Allocator : TdwsJITAllocatorWin read FAllocator write FAllocator;
property AbsMaskPD : Pointer read FAbsMaskPD.Code;
property SignMaskPD : Pointer read FSignMaskPD.Code;
function CompileFloat(expr : TTypedExpr) : TxmmRegister; inline;
procedure CompileAssignFloat(expr : TTypedExpr; source : TxmmRegister); inline;
procedure CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
function CompiledOutput : TdwsJITCodeBlock; override;
procedure _xmm_reg_expr(op : TxmmOp; dest : TxmmRegister; expr : TTypedExpr);
procedure _comisd_reg_expr(dest : TxmmRegister; expr : TTypedExpr);
function _store_eaxedx : Integer;
procedure _restore_eaxedx(addr : Integer);
procedure _restore_eax(addr : Integer);
procedure _mov_reg_execInstance(reg : TgpRegister);
procedure _DoStep(expr : TExprBase);
procedure _RangeCheck(expr : TExprBase; reg : TgpRegister;
delta, miniInclusive, maxiExclusive : Integer);
end;
TProgramExpr86 = class (TJITTedProgramExpr)
public
procedure EvalNoResult(exec : TdwsExecution); override;
end;
TFloatExpr86 = class (TJITTedFloatExpr)
public
function EvalAsFloat(exec : TdwsExecution) : Double; override;
end;
TIntegerExpr86 = class (TJITTedIntegerExpr)
public
function EvalAsInteger(exec : TdwsExecution) : Int64; override;
end;
TdwsJITter_x86 = class (TdwsJITter)
private
FJIT : TdwsJITx86;
Fx86 : Tx86WriteOnlyStream;
protected
property jit : TdwsJITx86 read FJIT;
property x86 : Tx86WriteOnlyStream read Fx86;
public
constructor Create(jit : TdwsJITx86);
function CompileFloat(expr : TTypedExpr) : Integer; override; final;
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; virtual;
procedure CompileAssignFloat(expr : TTypedExpr; source : Integer); override; final;
procedure DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister); virtual;
function CompileBooleanValue(expr : TTypedExpr) : Integer; override;
procedure CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override; final;
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); virtual;
end;
Tx86ConstFloat = class (TdwsJITter_x86)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
end;
Tx86ConstInt = class (TdwsJITter_x86)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86ConstBoolean = class (TdwsJITter_x86)
function CompileInteger(expr : TTypedExpr) : Integer; override;
function CompileBooleanValue(expr : TTypedExpr) : Integer; override;
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
end;
Tx86InterpretedExpr = class (TdwsJITter_x86)
procedure DoCallEval(expr : TExprBase; vmt : Integer);
procedure CompileStatement(expr : TExprBase); override;
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
procedure DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister); override;
function CompileInteger(expr : TTypedExpr) : Integer; override;
procedure CompileAssignInteger(expr : TTypedExpr; source : Integer); override;
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
function CompileBooleanValue(expr : TTypedExpr) : Integer; override;
end;
Tx86FloatVar = class (TdwsJITter_x86)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
procedure DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister); override;
end;
Tx86IntVar = class (TdwsJITter_x86)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
function CompileInteger(expr : TTypedExpr) : Integer; override;
procedure CompileAssignInteger(expr : TTypedExpr; source : Integer); override;
end;
Tx86BoolVar = class (TdwsJITter_x86)
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
procedure CompileAssignBoolean(expr : TTypedExpr; source : Integer); override;
end;
Tx86ObjectVar = class (TdwsJITter_x86)
function CompileScriptObj(expr : TTypedExpr) : Integer; override;
end;
Tx86RecordVar = class (TdwsJITter_x86)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
procedure DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister); override;
function CompileInteger(expr : TTypedExpr) : Integer; override;
procedure CompileAssignInteger(expr : TTypedExpr; source : Integer); override;
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
end;
Tx86VarParam = class (TdwsJITter_x86)
class procedure CompileAsPVariant(x86 : Tx86WriteOnlyStream; expr : TByRefParamExpr);
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
function CompileInteger(expr : TTypedExpr) : Integer; override;
procedure DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister); override;
procedure CompileAssignInteger(expr : TTypedExpr; source : Integer); override;
end;
Tx86FieldVar = class (Tx86InterpretedExpr)
procedure CompileToData(expr : TFieldVarExpr; dest : TgpRegister);
function CompileInteger(expr : TTypedExpr) : Integer; override;
procedure CompileAssignInteger(expr : TTypedExpr; source : Integer); override;
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
end;
Tx86ArrayBase = class (Tx86InterpretedExpr)
procedure CompileIndexToGPR(indexExpr : TTypedExpr; gpr : TgpRegister; var delta : Integer);
end;
Tx86StaticArray = class (Tx86ArrayBase)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
function CompileInteger(expr : TTypedExpr) : Integer; override;
procedure DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister); override;
end;
Tx86DynamicArrayBase = class (Tx86ArrayBase)
procedure CompileAsData(expr : TTypedExpr);
end;
Tx86DynamicArray = class (Tx86DynamicArrayBase)
procedure CompileAsItemPtr(expr : TDynamicArrayExpr; var delta : Integer);
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
function CompileInteger(expr : TTypedExpr) : Integer; override;
function CompileScriptObj(expr : TTypedExpr) : Integer; override;
end;
Tx86DynamicArraySet = class (Tx86DynamicArrayBase)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86AssignConstToFloatVar = class (Tx86InterpretedExpr)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86AssignConstToIntegerVar = class (Tx86InterpretedExpr)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86AssignConstToBoolVar = class (Tx86InterpretedExpr)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86Assign = class (Tx86InterpretedExpr)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86AssignData = class (Tx86InterpretedExpr)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86OpAssignFloat = class (TdwsJITter_x86)
public
OP : TxmmOp;
constructor Create(jit : TdwsJITx86; op : TxmmOp);
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86Null = class (TdwsJITter_x86)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86BlockExprNoTable = class (TdwsJITter_x86)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86IfThen = class (TdwsJITter_x86)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86IfThenElse = class (TdwsJITter_x86)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86Loop = class (TdwsJITter_x86)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86Repeat = class (Tx86Loop)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86While = class (Tx86Loop)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86ForUpward = class (TdwsJITter_x86)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86Continue = class (TdwsJITter_x86)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86Break = class (TdwsJITter_x86)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86Exit = class (TdwsJITter_x86)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86ExitValue = class (Tx86Exit)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86FloatBinOp = class (TdwsJITter_x86)
public
OP : TxmmOp;
constructor Create(jit : TdwsJITx86; op : TxmmOp);
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
end;
Tx86SqrFloat = class (TdwsJITter_x86)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
function CompileFloatOperand(sqrExpr, operand : TTypedExpr) : TxmmRegister;
end;
Tx86AbsFloat = class (TdwsJITter_x86)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
end;
Tx86NegFloat = class (TdwsJITter_x86)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
end;
Tx86NegInt = class (TdwsJITter_x86)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86AbsInt = class (TdwsJITter_x86)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86NotInt = class (TdwsJITter_x86)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86MultInt = class (TdwsJITter_x86)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86MultIntPow2 = class (TdwsJITter_x86)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86DivInt = class (Tx86InterpretedExpr)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86ModInt = class (Tx86InterpretedExpr)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86IntegerBinOpExpr = class (TdwsJITter_x86)
FOpLow, FOpHigh : TgpOp;
FCommutative : Boolean;
constructor Create(jit : TdwsJITx86;const opLow, opHigh : TgpOP; commutative : Boolean = True);
function CompileInteger(expr : TTypedExpr) : Integer; override;
procedure CompileConstant(expr : TTypedExpr; const val : Int64);
procedure CompileVar(expr : TTypedExpr; const varStackAddr : Integer);
end;
Tx86Shr = class (TdwsJITter_x86)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86Shl = class (TdwsJITter_x86)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86Inc = class (Tx86InterpretedExpr)
procedure DoCompileStatement(v : TIntVarExpr; i : TTypedExpr);
end;
Tx86IncIntVar = class (Tx86Inc)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86IncVarFunc = class (Tx86Inc)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86Dec = class (Tx86InterpretedExpr)
procedure DoCompileStatement(v : TIntVarExpr; i : TTypedExpr);
end;
Tx86DecIntVar = class (Tx86Dec)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86DecVarFunc = class (Tx86Dec)
procedure CompileStatement(expr : TExprBase); override;
end;
Tx86RelOpInt = class (TdwsJITter_x86)
public
FlagsHiPass, FlagsHiFail, FlagsLoPass : TboolFlags;
constructor Create(jit : TdwsJITx86; flagsHiPass, flagsHiFail, flagsLoPass : TboolFlags);
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
end;
Tx86RelEqualInt = class (Tx86RelOpInt)
constructor Create(jit : TdwsJITx86);
end;
Tx86RelNotEqualInt = class (Tx86RelOpInt)
constructor Create(jit : TdwsJITx86);
end;
Tx86RelIntIsZero = class (TdwsJITter_x86)
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
end;
Tx86RelIntIsNotZero = class (Tx86RelIntIsZero)
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
end;
Tx86RelOpFloat = class (TdwsJITter_x86)
public
Flags : TboolFlags;
constructor Create(jit : TdwsJITx86; flags : TboolFlags);
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
end;
Tx86NotExpr = class (TdwsJITter_x86)
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override; final;
end;
Tx86BoolOrExpr = class (TdwsJITter_x86)
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
end;
Tx86BoolAndExpr = class (TdwsJITter_x86)
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
end;
Tx86SetOfExpr = class (TdwsJITter_x86)
procedure NormalizeEnumOperand(setTyp : TSetOfSymbol; operand : TTypedExpr; targetOutOfRange : TFixup);
procedure ComputeFromValueInEAXOffsetInECXMaskInEDX(setTyp : TSetOfSymbol);
end;
Tx86SetOfInExpr = class (Tx86SetOfExpr)
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
end;
Tx86SetOfFunction = class (Tx86SetOfExpr)
procedure CompileStatement(expr : TExprBase); override;
procedure DoByteOp(reg : TgpRegister; offset : Integer; mask : Byte); virtual; abstract;
procedure DoWordOp(dest, src : TgpRegister); virtual; abstract;
end;
Tx86SetOfInclude = class (Tx86SetOfFunction)
procedure DoByteOp(reg : TgpRegister; offset : Integer; mask : Byte); override;
procedure DoWordOp(dest, src : TgpRegister); override;
end;
Tx86SetOfExclude = class (Tx86SetOfFunction)
procedure DoByteOp(reg : TgpRegister; offset : Integer; mask : Byte); override;
procedure DoWordOp(dest, src : TgpRegister); override;
end;
Tx86OrdBool = class (Tx86InterpretedExpr)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86OrdInt = class (Tx86InterpretedExpr)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86ConvIntToFloat = class (TdwsJITter_x86)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
end;
Tx86MagicFunc = class (Tx86InterpretedExpr)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
function CompileInteger(expr : TTypedExpr) : Integer; override;
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
function CompileBooleanValue(expr : TTypedExpr) : Integer; override;
end;
Tx86MagicBoolFunc = class (Tx86MagicFunc)
function CompileInteger(expr : TTypedExpr) : Integer; override;
end;
Tx86DirectCallFunc = class (Tx86InterpretedExpr)
public
AddrPtr : PPointer;
constructor Create(jit : TdwsJITx86; addrPtr : PPointer);
function CompileCall(funcSym : TFuncSymbol; const args : TExprBaseListRec) : Boolean;
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
function CompileInteger(expr : TTypedExpr) : Integer; override;
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
function CompileBooleanValue(expr : TTypedExpr) : Integer; override;
end;
Tx86SqrtFunc = class (Tx86MagicFunc)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
end;
Tx86SqrFloatFunc = class (Tx86SqrFloat)
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
end;
Tx86MinMaxFloatFunc = class (Tx86MagicFunc)
public
OP : TxmmOp;
constructor Create(jit : TdwsJITx86; op : TxmmOp);
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
end;
Tx86RoundFunc = class (Tx86MagicFunc)
function CompileInteger(expr : TTypedExpr) : Integer; override;
function DoCompileFloat(expr : TTypedExpr) : TxmmRegister; override;
end;
Tx86OddFunc = class (Tx86MagicBoolFunc)
procedure DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup); override;
function CompileBooleanValue(expr : TTypedExpr) : Integer; override;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
{$R-}
const
cExecInstanceGPR = gprEDI;
cExecInstanceEBPoffset = 4;
function int64_div(a, b : Int64) : Int64;
begin
Result:=a div b;
end;
function int64_mod(a, b : Int64) : Int64;
begin
Result:=a mod b;
end;
function double_trunc(const v : Double) : Int64;
begin
Result:=Trunc(v);
end;
function double_frac(const v : Double) : Double;
begin
Result:=Frac(v);
end;
function double_exp(const v : Double) : Double;
begin
Result:=Exp(v);
end;
function double_ln(const v : Double) : Double;
{$ifdef WIN32_ASM}
asm
fld v
fldln2
fxch
fyl2x
{$else}
begin
Result:=Ln(v);
{$endif}
end;
function double_log2(const v : Double) : Double;
{$ifdef WIN32_ASM}
asm
fld1
fld v
fyl2x
{$else}
begin
Result:=Log2(v);
{$endif}
end;
function double_log10(const v : Double) : Double;
{$ifdef WIN32_ASM}
asm
fldlg2
fld v
fyl2x
{$else}
begin
Result:=Log10(v);
{$endif}
end;
function double_cos(const v : Double) : Double;
{$ifdef WIN32_ASM}
asm
fld v
fcos
{$else}
begin
Result:=Cos(v);
{$endif}
end;
function double_sin(const v : Double) : Double;
{$ifdef WIN32_ASM}
asm
fld v
fsin
{$else}
begin
Result:=Sin(v);
{$endif}
end;
function double_tan(const v : Double) : Double;
{$ifdef WIN32_ASM}
asm
fld v
fptan
fstp st(0)
{$else}
begin
Result:=Tan(v);
{$endif}
end;
function locPower(const base, exponent: Double) : Double;
begin
Result := Math.power(base, exponent);
end;
var
vAddr_Exp : function (const v : Double) : Double = double_exp;
vAddr_Ln : function (const v : Double) : Double = double_ln;
vAddr_Log2 : function (const v : Double) : Double = double_log2;
vAddr_Log10 : function (const v : Double) : Double = double_log10;
vAddr_Power : function (const base, exponent: Double) : Double = locPower;
vAddr_Trunc : function (const v : Double) : Int64 = double_trunc;
vAddr_Frac : function (const v : Double) : Double = double_frac;
vAddr_div : function (a, b : Int64) : Int64 = int64_div;
vAddr_mod : function (a, b : Int64) : Int64 = int64_mod;
vAddr_IsNaN : function (const v : Double) : Boolean = Math.IsNan;
vAddr_IsInfinite : function (const v : Double) : Boolean = Math.IsInfinite;
vAddr_IsFinite : function (const v : Double) : Boolean = dwsMathFunctions.IsFinite;
vAddr_IsPrime : function (const n : Int64) : Boolean = dwsMathFunctions.IsPrime;
vAddr_Cos : function (const v : Double) : Double = double_cos;
vAddr_Sin : function (const v : Double) : Double = double_sin;
vAddr_Tan : function (const v : Double) : Double = double_tan;
// ------------------
// ------------------ TdwsJITx86 ------------------
// ------------------
// Create
//
constructor TdwsJITx86.Create;
function CreateBytes(const Value: array of Byte): TBytes;
var
vLen: Integer;
begin
vLen := Length(Value);
SetLength(Result, vLen);
if vLen > 0 then
Move(Value[0], Result[0], vLen);
end;
var
vInc: TdwsJITter;
begin
inherited;
FAllocator:=TdwsJITAllocatorWin.Create;
FAbsMaskPD:=FAllocator.Allocate(CreateBytes([$FF, $FF, $FF, $FF, $FF, $FF, $FF, $7F,
$FF, $FF, $FF, $FF, $FF, $FF, $FF, $7F]));
FSignMaskPD:=FAllocator.Allocate(CreateBytes([$00, $00, $00, $00, $00, $00, $00, $80,
$00, $00, $00, $00, $00, $00, $00, $80]));
FBufferBlock:=FAllocator.Allocate(CreateBytes([$66, $66, $66, $90, $66, $66, $66, $90,
$66, $66, $66, $90, $66, $66, $66, $90]));
FHint32bitSymbol:=TObjectsLookup.Create;
JITTedProgramExprClass:=TProgramExpr86;
JITTedFloatExprClass:=TFloatExpr86;
JITTedIntegerExprClass:=TIntegerExpr86;
FInterpretedJITter:=Tx86InterpretedExpr.Create(Self);
RegisterJITter(TConstFloatExpr, Tx86ConstFloat.Create(Self));
RegisterJITter(TConstIntExpr, Tx86ConstInt.Create(Self));
RegisterJITter(TConstBooleanExpr, Tx86ConstBoolean.Create(Self));
RegisterJITter(TFloatVarExpr, Tx86FloatVar.Create(Self));
RegisterJITter(TIntVarExpr, Tx86IntVar.Create(Self));
RegisterJITter(TBoolVarExpr, Tx86BoolVar.Create(Self));
RegisterJITter(TObjectVarExpr, Tx86ObjectVar.Create(Self));
RegisterJITter(TSelfObjectVarExpr, Tx86ObjectVar.Create(Self));
RegisterJITter(TVarParentExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TFieldExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRecordExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRecordVarExpr, Tx86RecordVar.Create(Self));
RegisterJITter(TFieldExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TFieldVarExpr, Tx86FieldVar.Create(Self));
RegisterJITter(TVarParamExpr, Tx86VarParam.Create(Self));
RegisterJITter(TConstParamExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TLazyParamExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TVarParentExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TVarParamParentExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TStaticArrayExpr, Tx86StaticArray.Create(Self));
RegisterJITter(TDynamicArrayExpr, Tx86DynamicArray.Create(Self));
RegisterJITter(TDynamicArrayVarExpr, Tx86DynamicArray.Create(Self));
RegisterJITter(TDynamicArraySetExpr, Tx86DynamicArraySet.Create(Self));
RegisterJITter(TDynamicArraySetVarExpr, Tx86DynamicArraySet.Create(Self));
RegisterJITter(TDynamicArraySetDataExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArrayLengthExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArraySetLengthExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArrayAddExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArrayInsertExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArrayIndexOfExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArrayRemoveExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArrayDeleteExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArrayPopExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArraySwapExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArraySortExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArraySortNaturalStringExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArraySortNaturalIntegerExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArraySortNaturalFloatExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArrayReverseExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TArrayMapExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TOpenArrayLengthExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TNullExpr, Tx86Null.Create(Self));
RegisterJITter(TBlockExpr, Tx86BlockExprNoTable.Create(Self));
RegisterJITter(TBlockExprNoTable, Tx86BlockExprNoTable.Create(Self));
RegisterJITter(TBlockExprNoTable2, Tx86BlockExprNoTable.Create(Self));
RegisterJITter(TBlockExprNoTable3, Tx86BlockExprNoTable.Create(Self));
RegisterJITter(TBlockExprNoTable4, Tx86BlockExprNoTable.Create(Self));
RegisterJITter(TAssignConstToIntegerVarExpr, Tx86AssignConstToIntegerVar.Create(Self));
RegisterJITter(TAssignConstToFloatVarExpr, Tx86AssignConstToFloatVar.Create(Self));
RegisterJITter(TAssignConstToBoolVarExpr, Tx86AssignConstToBoolVar.Create(Self));
RegisterJITter(TAssignConstToStringVarExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAssignExpr, Tx86Assign.Create(Self));
RegisterJITter(TAssignDataExpr, Tx86AssignData.Create(Self));
RegisterJITter(TAssignClassOfExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAssignFuncExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAssignNilToVarExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAssignNilClassToVarExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAssignArrayConstantExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAssignedInstanceExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAssignedMetaClassExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAssignedFuncPtrExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TPlusAssignFloatExpr, Tx86OpAssignFloat.Create(Self, xmm_addsd));
RegisterJITter(TMinusAssignFloatExpr, Tx86OpAssignFloat.Create(Self, xmm_subsd));
RegisterJITter(TMultAssignFloatExpr, Tx86OpAssignFloat.Create(Self, xmm_multsd));
RegisterJITter(TDivideAssignExpr, Tx86OpAssignFloat.Create(Self, xmm_divsd));
RegisterJITter(TStringLengthExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAppendStringVarExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAppendConstStringVarExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TVarStringArraySetExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TPlusAssignIntExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TMinusAssignIntExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TMultAssignIntExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TPlusAssignExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TMinusAssignExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TMultAssignExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TIfThenExpr, Tx86IfThen.Create(Self));
RegisterJITter(TIfThenElseExpr, Tx86IfThenElse.Create(Self));
RegisterJITter(TCaseExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TLoopExpr, Tx86Loop.Create(Self));
RegisterJITter(TRepeatExpr, Tx86Repeat.Create(Self));
RegisterJITter(TWhileExpr, Tx86While.Create(Self));
RegisterJITter(TForUpwardExpr, Tx86ForUpward.Create(Self));
RegisterJITter(TForUpwardStepExpr, Tx86ForUpward.Create(Self));
RegisterJITter(TForDownwardExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TForDownwardStepExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TForCharCodeInStrExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TForCharInStrExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TContinueExpr, Tx86Continue.Create(Self));
RegisterJITter(TBreakExpr, Tx86Break.Create(Self));
RegisterJITter(TExitExpr, Tx86Exit.Create(Self));
RegisterJITter(TExitValueExpr, Tx86ExitValue.Create(Self));
RegisterJITter(TRaiseExpr, FInterpretedJITter.IncRefCount);
// RegisterJITter(TExceptExpr, FInterpretedJITter.IncRefCount);
// RegisterJITter(TFinallyExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAddFloatExpr, Tx86FloatBinOp.Create(Self, xmm_addsd));
RegisterJITter(TSubFloatExpr, Tx86FloatBinOp.Create(Self, xmm_subsd));
RegisterJITter(TMultFloatExpr, Tx86FloatBinOp.Create(Self, xmm_multsd));
RegisterJITter(TSqrFloatExpr, Tx86SqrFloat.Create(Self));
RegisterJITter(TDivideExpr, Tx86FloatBinOp.Create(Self, xmm_divsd));
RegisterJITter(TAbsFloatExpr, Tx86AbsFloat.Create(Self));
RegisterJITter(TNegFloatExpr, Tx86NegFloat.Create(Self));
RegisterJITter(TNegIntExpr, Tx86NegInt.Create(Self));
RegisterJITter(TAbsIntExpr, Tx86AbsInt.Create(Self));
RegisterJITter(TNotIntExpr, Tx86NotInt.Create(Self));
RegisterJITter(TAddIntExpr, Tx86IntegerBinOpExpr.Create(Self, gpOp_add, gpOp_adc));
RegisterJITter(TSubIntExpr, Tx86IntegerBinOpExpr.Create(Self, gpOp_sub, gpOp_sbb, False));
RegisterJITter(TMultIntExpr, Tx86MultInt.Create(Self));
RegisterJITter(TSqrIntExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TDivExpr, Tx86DivInt.Create(Self));
RegisterJITter(TDivConstExpr, Tx86DivInt.Create(Self));
RegisterJITter(TModExpr, Tx86ModInt.Create(Self));
RegisterJITter(TModConstExpr, Tx86ModInt.Create(Self));
RegisterJITter(TMultIntPow2Expr, Tx86MultIntPow2.Create(Self));
RegisterJITter(TIntAndExpr, Tx86IntegerBinOpExpr.Create(Self, gpOp_and, gpOp_and));
RegisterJITter(TIntXorExpr, Tx86IntegerBinOpExpr.Create(Self, gpOp_xor, gpOp_xor));
RegisterJITter(TIntOrExpr, Tx86IntegerBinOpExpr.Create(Self, gpOp_or, gpOp_or));
RegisterJITter(TShrExpr, Tx86Shr.Create(Self));
RegisterJITter(TShlExpr, Tx86Shl.Create(Self));
RegisterJITter(TInOpExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TIncIntVarExpr, Tx86IncIntVar.Create(Self));
RegisterJITter(TDecIntVarExpr, Tx86DecIntVar.Create(Self));
RegisterJITter(TIncVarFuncExpr, Tx86IncVarFunc.Create(Self));
RegisterJITter(TDecVarFuncExpr, Tx86DecVarFunc.Create(Self));
RegisterJITter(TRelEqualIntExpr, Tx86RelEqualInt.Create(Self));
RegisterJITter(TRelNotEqualIntExpr, Tx86RelNotEqualInt.Create(Self));
RegisterJITter(TRelGreaterIntExpr, Tx86RelOpInt.Create(Self, flagsG, flagsL, flagsNBE));
RegisterJITter(TRelGreaterEqualIntExpr, Tx86RelOpInt.Create(Self, flagsG, flagsL, flagsNB));
RegisterJITter(TRelLessIntExpr, Tx86RelOpInt.Create(Self, flagsL, flagsG, flagsB));
RegisterJITter(TRelLessEqualIntExpr, Tx86RelOpInt.Create(Self, flagsL, flagsG, flagsBE));
RegisterJITter(TRelIntIsZeroExpr, Tx86RelIntIsZero.Create(Self));
RegisterJITter(TRelIntIsNotZeroExpr, Tx86RelIntIsNotZero.Create(Self));
RegisterJITter(TRelEqualFloatExpr, Tx86RelOpFloat.Create(Self, flagsE));
RegisterJITter(TRelNotEqualFloatExpr, Tx86RelOpFloat.Create(Self, flagsNE));
RegisterJITter(TRelGreaterFloatExpr, Tx86RelOpFloat.Create(Self, flagsNBE));
RegisterJITter(TRelGreaterEqualFloatExpr, Tx86RelOpFloat.Create(Self, flagsNB));
RegisterJITter(TRelLessFloatExpr, Tx86RelOpFloat.Create(Self, flagsB));
RegisterJITter(TRelLessEqualFloatExpr, Tx86RelOpFloat.Create(Self, flagsBE));
RegisterJITter(TRelEqualStringExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRelNotEqualStringExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRelGreaterStringExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRelGreaterEqualStringExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRelLessStringExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRelLessEqualStringExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRelEqualBoolExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRelNotEqualBoolExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRelEqualMetaExpr, Tx86RelEqualInt.Create(Self));
RegisterJITter(TRelNotEqualMetaExpr, Tx86RelNotEqualInt.Create(Self));
RegisterJITter(TIsOpExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TImplementsIntfOpExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TObjCmpEqualExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TObjCmpNotEqualExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TIntfCmpExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TNotBoolExpr, Tx86NotExpr.Create(Self));
RegisterJITter(TBoolOrExpr, Tx86BoolOrExpr.Create(Self));
RegisterJITter(TBoolAndExpr, Tx86BoolAndExpr.Create(Self));
RegisterJITter(TBoolXorExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TBoolImpliesExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TSetOfInExpr, Tx86SetOfInExpr.Create(Self));
RegisterJITter(TSetOfSmallInExpr, Tx86SetOfInExpr.Create(Self));
RegisterJITter(TSetOfIncludeExpr, Tx86SetOfInclude.Create(Self));
RegisterJITter(TSetOfExcludeExpr, Tx86SetOfExclude.Create(Self));
RegisterJITter(TOrdExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TOrdBoolExpr, Tx86OrdBool.Create(Self));
RegisterJITter(TOrdIntExpr, Tx86OrdInt.Create(Self));
RegisterJITter(TOrdStrExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TSwapExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TAssertExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TDeclaredExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TDefinedExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TConditionalDefinedExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TConvIntToFloatExpr, Tx86ConvIntToFloat.Create(Self));
RegisterJITter(TConvVarToFloatExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TConvVarToIntegerExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TConvOrdToIntegerExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TConstructorStaticExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TConstructorStaticDefaultExpr,FInterpretedJITter.IncRefCount);
RegisterJITter(TConstructorStaticObjExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TConstructorVirtualExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TConstructorVirtualObjExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TMethodStaticExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TMethodVirtualExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TMethodInterfaceExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TMethodInterfaceAnonymousExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TClassMethodStaticExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TClassMethodVirtualExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TRecordMethodExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(THelperMethodExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TFuncPtrExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TFuncExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TFuncSimpleExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TMagicProcedureExpr, FInterpretedJITter.IncRefCount);
RegisterJITter(TMagicFloatFuncExpr, Tx86MagicFunc.Create(Self));
RegisterJITter(TMagicIntFuncExpr, Tx86MagicFunc.Create(Self));
RegisterJITter(TMagicBoolFuncExpr, Tx86MagicFunc.Create(Self));
RegisterJITter(TSqrtFunc, Tx86SqrtFunc.Create(Self));
RegisterJITter(TSqrFloatFunc, Tx86SqrFloatFunc.Create(Self));
RegisterJITter(TMaxFunc, Tx86MinMaxFloatFunc.Create(Self, xmm_maxsd));
RegisterJITter(TMinFunc, Tx86MinMaxFloatFunc.Create(Self, xmm_minsd));
RegisterJITter(TExpFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_Exp));
RegisterJITter(TLnFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_Ln));
RegisterJITter(TLog2Func, Tx86DirectCallFunc.Create(Self, @@vAddr_Log2));
RegisterJITter(TLog10Func, Tx86DirectCallFunc.Create(Self, @@vAddr_Log10));
RegisterJITter(TPowerFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_Power));
RegisterJITter(TRoundFunc, Tx86RoundFunc.Create(Self));
RegisterJITter(TTruncFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_Trunc));
RegisterJITter(TFracFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_Frac));
RegisterJITter(TIsNaNFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_IsNaN));
RegisterJITter(TIsInfiniteFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_IsInfinite));
RegisterJITter(TIsFiniteFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_IsFinite));
RegisterJITter(TIsPrimeFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_IsPrime));
RegisterJITter(TOddFunc, Tx86OddFunc.Create(Self));
RegisterJITter(TCosFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_Cos));
RegisterJITter(TSinFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_Sin));
RegisterJITter(TTanFunc, Tx86DirectCallFunc.Create(Self, @@vAddr_Tan));
end;
// Destroy
//
destructor TdwsJITx86.Destroy;
begin
inherited;
FHint32bitSymbol.Free;
FAllocator.Free;
FSignMaskPD.Free;
FAbsMaskPD.Free;
FBufferBlock.Free;
FInterpretedJITter.Free;
end;
// CreateOutput
//
function TdwsJITx86.CreateOutput : TWriteOnlyBlockStream;
begin
x86:=Tx86WriteOnlyStream.Create;
Result:=x86;
end;
// CreateFixupLogic
//
function TdwsJITx86.CreateFixupLogic : TFixupLogic;
begin
Result:=Tx86FixupLogic.Create;
end;
// AllocXMMReg
//
function TdwsJITx86.AllocXMMReg(expr : TExprBase; contains : TObject = nil) : TxmmRegister;
var
i, avail : TxmmRegister;
begin
avail:=xmmNone;
if contains=nil then
contains:=expr;
for i:=xmm0 to High(TxmmRegister) do begin
if FXMMIter=High(TxmmRegister) then
FXMMIter:=xmm0
else Inc(FXMMIter);
if FRegs[FXMMIter].Contains=nil then begin
FRegs[FXMMIter].Contains:=contains;
FRegs[FXMMIter].Lock:=1;
Exit(FXMMIter);
end else if (avail=xmmNone) and (FRegs[FXMMIter].Lock=0) then
avail:=FXMMIter;
end;
if avail=xmmNone then begin
OutputFailedOn:=expr;
Result:=xmm0;
end else begin
FRegs[avail].Contains:=contains;
FRegs[avail].Lock:=1;
FXMMIter:=avail;
Result:=avail;
end;
end;
// ReleaseXMMReg
//
procedure TdwsJITx86.ReleaseXMMReg(reg : TxmmRegister);
begin
Assert(reg in [xmm0..xmm7]);
if FRegs[reg].Lock>0 then
Dec(FRegs[reg].Lock);
end;
// CurrentXMMReg
//
function TdwsJITx86.CurrentXMMReg(contains : TObject) : TxmmRegister;
var
i : TxmmRegister;
begin
for i:=xmm0 to High(TxmmRegister) do begin
if FRegs[i].Contains=contains then begin
Inc(FRegs[i].Lock);
Exit(i);
end;
end;
Result:=xmmNone;
end;
// ContainsXMMReg
//
procedure TdwsJITx86.ContainsXMMReg(reg : TxmmRegister; contains : TObject);
var
i : TxmmRegister;
begin
for i:=xmm0 to High(FRegs) do begin
if FRegs[i].Contains=contains then begin
if i<>reg then begin
FRegs[i].Contains:=nil;
FRegs[i].Lock:=0;
end;
end;
end;
FRegs[reg].Contains:=contains;
end;
// ResetXMMReg
//
procedure TdwsJITx86.ResetXMMReg;
var
i : TxmmRegister;
begin
FXMMIter:=High(TxmmRegister);
for i:=xmm0 to High(FRegs) do begin
FRegs[i].Contains:=nil;
FRegs[i].Lock:=0;
end;
end;
// SaveXMMRegs
//
procedure TdwsJITx86.SaveXMMRegs;
var
i : TxmmRegister;
n : Integer;
begin
Assert(FSavedXMM=[]);
n:=0;
for i:=xmm0 to High(FRegs) do begin
if FRegs[i].Lock>0 then begin
Include(FSavedXMM, i);
Inc(n);
end;
end;
if n=0 then Exit;
FPreamble.NeedTempSpace(n*SizeOf(Double));
for i:=xmm0 to High(FRegs) do begin
if i in FSavedXMM then begin
Dec(n);
x86._movsd_esp_reg(n*SizeOf(Double), i);
end;
end;
end;
// RestoreXMMRegs
//
procedure TdwsJITx86.RestoreXMMRegs;
var
i : TxmmRegister;
n : Integer;
begin
if FSavedXMM=[] then Exit;
n:=0;
for i:=High(FRegs) downto xmm0 do begin
if i in FSavedXMM then begin
x86._movsd_reg_esp(i, n*SizeOf(Double));
Inc(n);
end else FRegs[i].Contains:=nil;
end;
FSavedXMM:=[];
end;
// StackAddrOfFloat
//
function TdwsJITx86.StackAddrOfFloat(expr : TTypedExpr) : Integer;
begin
if (expr.ClassType=TFloatVarExpr) and (CurrentXMMReg(TFloatVarExpr(expr).DataSym)=xmmNone) then
Result:=TFloatVarExpr(expr).StackAddr
else Result:=-1;
end;
// Hint32Bit
//
procedure TdwsJITx86.Hint32Bit(obj : TRefCountedObject);
begin
FHint32bitSymbol.Add(obj);
end;
// ClearHint32Bit
//
procedure TdwsJITx86.ClearHint32Bit(obj : TRefCountedObject);
begin
FHint32bitSymbol.Extract(obj);
end;
// Is32BitHinted
//
function TdwsJITx86.Is32BitHinted(obj : TRefCountedObject) : Boolean;
begin
Result:=(FHint32bitSymbol.Count>0) and (FHint32bitSymbol.IndexOf(obj)>=0);
end;
// CompileFloat
//
function TdwsJITx86.CompileFloat(expr : TTypedExpr) : TxmmRegister;
begin
Result:=TxmmRegister(inherited CompileFloat(expr));
end;
// CompileAssignFloat
//
procedure TdwsJITx86.CompileAssignFloat(expr : TTypedExpr; source : TxmmRegister);
begin
inherited CompileAssignFloat(expr, Ord(source));
end;
// CompileBoolean
//
procedure TdwsJITx86.CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
begin
inherited CompileBoolean(expr, targetTrue, targetFalse);
end;
// CompiledOutput
//
function TdwsJITx86.CompiledOutput : TdwsJITCodeBlock;
begin
Fixups.FlushFixups(Output.ToBytes, Output);
Result:=Allocator.Allocate(Output.ToBytes);
Result.Steppable:=(jitoDoStep in Options);
end;
// StartJIT
//
procedure TdwsJITx86.StartJIT(expr : TExprBase; exitable : Boolean);
begin
inherited;
ResetXMMReg;
FHint32bitSymbol.Clear;
Fixups.ClearFixups;
(Fixups as Tx86FixupLogic).Options:=Options;
FPreamble:=TFixupPreamble.Create;
Fixups.AddFixup(FPreamble);
FPostamble:=TFixupPostamble.Create(FPreamble);
FPostamble.Logic:=Fixups;
end;
// EndJIT
//
procedure TdwsJITx86.EndJIT;
begin
inherited;
Fixups.AddFixup(FPostamble);
end;
// EndFloatJIT
//
procedure TdwsJITx86.EndFloatJIT(resultHandle : Integer);
begin
FPreamble.NeedTempSpace(SizeOf(Double));
x86._movsd_esp_reg(TxmmRegister(resultHandle));
x86._fld_esp;
inherited;
end;
// EndIntegerJIT
//
procedure TdwsJITx86.EndIntegerJIT(resultHandle : Integer);
begin
inherited;
end;
// _xmm_reg_expr
//
procedure TdwsJITx86._xmm_reg_expr(op : TxmmOp; dest : TxmmRegister; expr : TTypedExpr);
var
addrRight : Integer;
regRight : TxmmRegister;
begin
if expr.ClassType=TConstFloatExpr then begin
x86._xmm_reg_absmem(OP, dest, @TConstFloatExpr(expr).Value);
end else begin
addrRight:=StackAddrOfFloat(expr);
if addrRight>=0 then begin
x86._xmm_reg_execmem(OP, dest, addrRight);
end else begin
regRight:=CompileFloat(expr);
x86._xmm_reg_reg(OP, dest, regRight);
ReleaseXMMReg(regRight);
end;
end;
end;
// _comisd_reg_expr
//
procedure TdwsJITx86._comisd_reg_expr(dest : TxmmRegister; expr : TTypedExpr);
var
addrRight : Integer;
regRight : TxmmRegister;
begin
if expr.ClassType=TConstFloatExpr then begin
x86._comisd_reg_absmem(dest, @TConstFloatExpr(expr).Value);
end else begin
addrRight:=StackAddrOfFloat(expr);
if addrRight>=0 then begin
x86._comisd_reg_execmem(dest, addrRight);
end else begin
regRight:=CompileFloat(expr);
x86._comisd_reg_reg(dest, regRight);
ReleaseXMMReg(regRight);
end;
end;
end;
// _store_eaxedx
//
function TdwsJITx86._store_eaxedx : Integer;
begin
Result:=FPreamble.AllocateStackSpace(SizeOf(Int64));
x86._mov_qword_ptr_reg_eaxedx(gprEBP, Result);
end;
// _restore_eaxedx
//
procedure TdwsJITx86._restore_eaxedx(addr : Integer);
begin
x86._mov_eaxedx_qword_ptr_reg(gprEBP, addr);
end;
// _restore_eax
//
procedure TdwsJITx86._restore_eax(addr : Integer);
begin
x86._mov_reg_dword_ptr_reg(gprEAX, gprEBP, addr);
end;
// _mov_reg_execInstance
//
procedure TdwsJITx86._mov_reg_execInstance(reg : TgpRegister);
begin
FPreamble.PreserveExec:=True;
x86._mov_reg_dword_ptr_reg(reg, gprEBP, cExecInstanceEBPoffset);
end;
// _DoStep
//
var
cPtr_TdwsExecution_DoStep : Pointer = @TdwsExecution.DoStep;
procedure TdwsJITx86._DoStep(expr : TExprBase);
begin
if not (jitoDoStep in Options) then Exit;
_mov_reg_execInstance(gprEAX);
x86._mov_reg_dword(gprEDX, DWORD(expr));
x86._call_absmem(@cPtr_TdwsExecution_DoStep);
ResetXMMReg;
end;
// _RangeCheck
//
var
cPtr_TProgramExpr_RaiseUpperExceeded : Pointer = @TProgramExpr.RaiseUpperExceeded;
cPtr_TProgramExpr_RaiseLowerExceeded : Pointer = @TProgramExpr.RaiseLowerExceeded;
procedure TdwsJITx86._RangeCheck(expr : TExprBase; reg : TgpRegister; delta, miniInclusive, maxiExclusive : Integer);
var
passed, passedMini : TFixupTarget;
begin
delta:=delta-miniInclusive;
maxiExclusive:=maxiExclusive-miniInclusive;
if delta<>0 then
x86._add_reg_int32(reg, delta);
if not (jitoRangeCheck in Options) then Exit;
passed:=Fixups.NewHangingTarget(True);
x86._cmp_reg_int32(reg, maxiExclusive);
Fixups.NewJump(flagsB, passed);
if delta<>0 then
x86._add_reg_int32(reg, -delta);
x86._cmp_reg_int32(reg, miniInclusive);
passedMini:=Fixups.NewHangingTarget(False);
Fixups.NewJump(flagsGE, passedMini);
x86._mov_reg_reg(gprECX, reg);
_mov_reg_execInstance(gprEDX);
x86._mov_reg_dword(gprEAX, DWORD(expr));
x86._call_absmem(@cPtr_TProgramExpr_RaiseLowerExceeded);
Fixups.AddFixup(passedMini);
x86._mov_reg_reg(gprECX, reg);
_mov_reg_execInstance(gprEDX);
x86._mov_reg_dword(gprEAX, DWORD(expr));
x86._call_absmem(@cPtr_TProgramExpr_RaiseUpperExceeded);
Fixups.AddFixup(passed);
end;
// ------------------
// ------------------ TFixupAlignedTarget ------------------
// ------------------
// GetSize
//
function TFixupAlignedTarget.GetSize : Integer;
begin
if TargetCount=0 then begin
Result:=0;
end else begin
Result:=(16-(FixedLocation and $F)) and $F;
if Result>7 then
Result:=0;
// Result:=(4-(FixedLocation and $3)) and $3;
end;
end;
// Write
//
procedure TFixupAlignedTarget.Write(output : TWriteOnlyBlockStream);
begin
(output as Tx86WriteOnlyStream)._nop(GetSize);
end;
// JumpLocation
//
function TFixupAlignedTarget.JumpLocation : Integer;
begin
Result:=FixedLocation+GetSize;
end;
// ------------------
// ------------------ TFixupJump ------------------
// ------------------
// Create
//
constructor TFixupJump.Create(flags : TboolFlags);
begin
inherited Create;
FFlags:=flags;
end;
// Optimize
//
function TFixupJump.Optimize : TFixupOptimizeAction;
begin
if (Next=Target) and (JumpLocation=Next.Location) then begin
Target:=nil;
Result:=foaRemove;
end else Result:=inherited;
end;
// GetSize
//
function TFixupJump.GetSize : Integer;
begin
if (Next=Target) and (Location=Next.Location) then
Result:=0
else if NearJump then
Result:=2
else if FFlags=flagsNone then
Result:=5
else Result:=6;
end;
// NearJump
//
function TFixupJump.NearJump : Boolean;
begin
if FLongJump then
Result:=False
else begin
Result:=(Abs(FixedLocation-Target.JumpLocation)<120);
if (FixedLocation<>0) and (Target.FixedLocation<>0) then
FLongJump:=not Result;
end;
end;
// Write
//
procedure TFixupJump.Write(output : TWriteOnlyBlockStream);
var
offset : Integer;
begin
if (Next=Target) and (Location=Next.Location) then
Exit;
offset:=Target.JumpLocation-FixedLocation;
if NearJump then begin
if FFlags=flagsNone then
output.WriteByte($EB)
else output.WriteByte(Ord(FFlags));
output.WriteByte(Byte(offset-2));
end else begin
if FFlags=flagsNone then begin
output.WriteByte($E9);
output.WriteInt32(offset-5);
end else begin
output.WriteByte($0F);
output.WriteByte(Ord(FFlags)+$10);
output.WriteInt32(offset-6);
end;
end;
end;
// ------------------
// ------------------ TFixupPreamble ------------------
// ------------------
// NeedEBP
//
function TFixupPreamble.NeedEBP : Boolean;
begin
Result:=(AllocatedStackSpace>0) or FPreserveExec;
end;
// GetSize
//
function TFixupPreamble.GetSize : Integer;
begin
Result:=1;
Inc(Result, 3);
if NeedEBP then
Inc(Result, 3);
if TempSpaceOnStack+AllocatedStackSpace>0 then begin
Assert(TempSpaceOnStack<=127);
Inc(Result, 3);
end;
if FPreserveExec then
Inc(Result, 1);
end;
// Write
//
procedure TFixupPreamble.Write(output : TWriteOnlyBlockStream);
var
x86 : Tx86WriteOnlyStream;
begin
x86:=(output as Tx86WriteOnlyStream);
x86._push_reg(cExecMemGPR);
if FPreserveExec then
x86._push_reg(gprEDX);
if NeedEBP then begin
x86._push_reg(gprEBP);
x86._mov_reg_reg(gprEBP, gprESP);
end;
if TempSpaceOnStack+AllocatedStackSpace>0 then
x86._sub_reg_int32(gprESP, TempSpaceOnStack+AllocatedStackSpace);
x86._mov_reg_dword_ptr_reg(cExecMemGPR, gprEDX, cStackMixinBaseDataOffset);
end;
// NeedTempSpace
//
procedure TFixupPreamble.NeedTempSpace(bytes : Integer);
begin
if bytes>TempSpaceOnStack then
TempSpaceOnStack:=bytes;
end;
// AllocateStackSpace
//
function TFixupPreamble.AllocateStackSpace(bytes : Integer) : Integer;
begin
Inc(FAllocatedStackSpace, bytes);
Result:=-AllocatedStackSpace;
end;
// ------------------
// ------------------ TFixupPostamble ------------------
// ------------------
// Create
//
constructor TFixupPostamble.Create(preamble : TFixupPreamble);
begin
inherited Create;
FPreamble:=preamble;
end;
// GetSize
//
function TFixupPostamble.GetSize : Integer;
begin
Result:=0;
if FPreamble.TempSpaceOnStack+FPreamble.AllocatedStackSpace>0 then begin
Assert(FPreamble.TempSpaceOnStack+FPreamble.AllocatedStackSpace<=127);
Inc(Result, 3);
end;
if FPreamble.NeedEBP then
Inc(Result, 1);
if FPreamble.PreserveExec then
Inc(Result, 1);
Inc(Result, 2);
Inc(Result, ($10-(FixedLocation and $F)) and $F);
end;
// Write
//
procedure TFixupPostamble.Write(output : TWriteOnlyBlockStream);
var
x86 : Tx86WriteOnlyStream;
begin
x86:=(output as Tx86WriteOnlyStream);
if FPreamble.TempSpaceOnStack+FPreamble.AllocatedStackSpace>0 then
x86._add_reg_int32(gprESP, FPreamble.TempSpaceOnStack+FPreamble.AllocatedStackSpace);
if FPreamble.NeedEBP then
x86._pop_reg(gprEBP);
if FPreamble.PreserveExec then
x86._pop_reg(gprECX);
x86._pop_reg(cExecMemGPR);
x86._ret;
// pad to multiple of 16 for alignment
x86._nop(($10-(output.Position and $F)) and $F);
end;
// ------------------
// ------------------ Tx86FixupLogic ------------------
// ------------------
// NewHangingTarget
//
function Tx86FixupLogic.NewHangingTarget(align : Boolean) : TFixupTarget;
begin
if align and not (jitoNoBranchAlignment in Options) then
Result:=TFixupAlignedTarget.Create
else Result:=TFixupTarget.Create;
Result.Logic:=Self;
end;
// ------------------
// ------------------ Tx86FixupLogicHelper ------------------
// ------------------
// NewJump
//
function Tx86FixupLogicHelper.NewJump(flags : TboolFlags) : TFixupJump;
begin
Result:=TFixupJump.Create(flags);
AddFixup(Result);
end;
// NewJump
//
function Tx86FixupLogicHelper.NewJump(flags : TboolFlags; target : TFixup) : TFixupJump;
begin
if target<>nil then begin
Result:=NewJump(flags);
Result.Target:=target;
end else Result:=nil;
end;
// NewJump
//
function Tx86FixupLogicHelper.NewJump(target : TFixup) : TFixupJump;
begin
Result:=NewJump(flagsNone, target);
end;
// NewConditionalJumps
//
procedure Tx86FixupLogicHelper.NewConditionalJumps(flagsTrue : TboolFlags; targetTrue, targetFalse : TFixup);
begin
if (targetTrue<>nil) and (targetTrue.Location<>0) then begin
NewJump(flagsTrue, targetTrue);
NewJump(NegateBoolFlags(flagsTrue), targetFalse);
end else begin
NewJump(NegateBoolFlags(flagsTrue), targetFalse);
NewJump(flagsTrue, targetTrue);
end;
end;
// ------------------
// ------------------ TdwsJITter_x86 ------------------
// ------------------
// Create
//
constructor TdwsJITter_x86.Create(jit : TdwsJITx86);
begin
inherited Create(jit);
FJIT:=jit;
Fx86:=jit.x86;
end;
// CompileFloat
//
function TdwsJITter_x86.CompileFloat(expr : TTypedExpr) : Integer;
begin
Result:=Ord(DoCompileFloat(expr));
end;
// DoCompileFloat
//
function TdwsJITter_x86.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
begin
jit.CompileInteger(expr);
jit.FPreamble.NeedTempSpace(SizeOf(Double));
x86._mov_dword_ptr_reg_reg(gprESP, 0, gprEAX);
x86._mov_dword_ptr_reg_reg(gprESP, 4, gprEDX);
x86._fild_esp;
x86._fstp_esp;
Result:=jit.AllocXMMReg(expr);
x86._movsd_reg_esp(Result);
end;
// CompileAssignFloat
//
procedure TdwsJITter_x86.CompileAssignFloat(expr : TTypedExpr; source : Integer);
begin
DoCompileAssignFloat(expr, TxmmRegister(source));
end;
// DoCompileAssignFloat
//
procedure TdwsJITter_x86.DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister);
begin
jit.OutputFailedOn:=expr;
end;
// CompileBooleanValue
//
function TdwsJITter_x86.CompileBooleanValue(expr : TTypedExpr) : Integer;
var
targetTrue, targetFalse, targetDone : TFixupTarget;
begin
targetTrue:=jit.Fixups.NewHangingTarget(False);
targetFalse:=jit.Fixups.NewHangingTarget(False);
targetDone:=jit.Fixups.NewHangingTarget(False);
jit.CompileBoolean(expr, targetTrue, targetFalse);
jit.Fixups.AddFixup(targetFalse);
x86._mov_reg_dword(gprEAX, 0);
jit.Fixups.NewJump(targetDone);
jit.Fixups.AddFixup(targetTrue);
x86._mov_reg_dword(gprEAX, 1);
jit.Fixups.AddFixup(targetDone);
Result:=0;
end;
// CompileBoolean
//
procedure TdwsJITter_x86.CompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
begin
DoCompileBoolean(TBooleanBinOpExpr(expr), targetTrue, targetFalse);
end;
// DoCompileBoolean
//
procedure TdwsJITter_x86.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
begin
jit.OutputFailedOn:=expr;
end;
// ------------------
// ------------------ TProgramExpr86 ------------------
// ------------------
// EvalNoResult
//
procedure TProgramExpr86.EvalNoResult(exec : TdwsExecution);
{$IFDEF CPU64}
asm
jmp [rdi+FCode]
end;
{$ELSE}
asm
jmp [eax+FCode]
end;
{$ENDIF}
// ------------------
// ------------------ TFloatExpr86 ------------------
// ------------------
// EvalAsFloat
//
function TFloatExpr86.EvalAsFloat(exec : TdwsExecution) : Double;
{$IFDEF CPU64}
asm
jmp [rdi+FCode]
end;
{$ELSE}
asm
jmp [eax+FCode]
end;
{$ENDIF}
// ------------------
// ------------------ TIntegerExpr86 ------------------
// ------------------
// EvalAsInteger
//
function TIntegerExpr86.EvalAsInteger(exec : TdwsExecution) : Int64;
{$IFDEF CPU64}
asm
jmp [rdi+FCode]
end;
{$ELSE}
asm
jmp [eax+FCode]
end;
{$ENDIF}
// ------------------
// ------------------ Tx86AssignConstToFloatVar ------------------
// ------------------
// CompileStatement
//
procedure Tx86AssignConstToFloatVar.CompileStatement(expr : TExprBase);
var
e : TAssignConstToFloatVarExpr;
reg : TxmmRegister;
begin
e:=TAssignConstToFloatVarExpr(expr);
reg:=jit.AllocXMMReg(expr);
// check below is necessary as -Nan will be reported equal to zero
if (e.Right=0) and not IsNaN(e.Right) then
x86._xorps_reg_reg(reg, reg)
else x86._movsd_reg_absmem(reg, @e.Right);
jit.CompileAssignFloat(e.Left, reg);
end;
// ------------------
// ------------------ Tx86AssignConstToIntegerVar ------------------
// ------------------
// CompileStatement
//
procedure Tx86AssignConstToIntegerVar.CompileStatement(expr : TExprBase);
var
e : TAssignConstToIntegerVarExpr;
reg : TxmmRegister;
begin
e:=TAssignConstToIntegerVarExpr(expr);
if e.Left.ClassType=TIntVarExpr then begin
reg:=jit.AllocXMMReg(expr);
if e.Right=0 then
x86._xorps_reg_reg(reg, reg)
else x86._movq_reg_absmem(reg, @e.Right);
x86._movq_execmem_reg(TVarExpr(e.Left).StackAddr, reg);
end else inherited;
end;
// ------------------
// ------------------ Tx86AssignConstToBoolVar ------------------
// ------------------
// CompileStatement
//
procedure Tx86AssignConstToBoolVar.CompileStatement(expr : TExprBase);
var
e : TAssignConstToBoolVarExpr;
begin
e:=TAssignConstToBoolVarExpr(expr);
if e.Left.ClassType=TBoolVarExpr then begin
if e.Right then
x86._mov_reg_dword(gprEAX, 1)
else x86._xor_reg_reg(gprEAX, gprEAX);
x86._mov_execmem_reg(TVarExpr(e.Left).StackAddr, 0, gprEAX);
end else inherited;
end;
// ------------------
// ------------------ Tx86Assign ------------------
// ------------------
// CompileStatement
//
procedure Tx86Assign.CompileStatement(expr : TExprBase);
var
e : TAssignExpr;
reg : TxmmRegister;
begin
e:=TAssignExpr(expr);
if jit.IsFloat(e.Left) then
begin
reg:=jit.CompileFloat(e.Right);
jit.CompileAssignFloat(e.Left, reg);
end else if jit.IsInteger(e.Left) then
begin
jit.CompileInteger(e.Right);
jit.CompileAssignInteger(e.Left, 0);
end else if jit.IsBoolean(e.Left) then
begin
jit.CompileBooleanValue(e.Right);
jit.CompileAssignBoolean(e.Left, 0);
end else inherited;
end;
// ------------------
// ------------------ Tx86AssignData ------------------
// ------------------
// CompileStatement
//
procedure Tx86AssignData.CompileStatement(expr : TExprBase);
var
e : TAssignDataExpr;
size : Integer;
begin
e:=TAssignDataExpr(expr);
if e.Right.Typ.UnAliasedType.ClassType=TSetOfSymbol then begin
size:=e.Right.Typ.Size;
if size=1 then begin
jit.CompileInteger(e.Right);
jit.CompileAssignInteger(e.Left, 0);
end else inherited;
end else inherited;
end;
// ------------------
// ------------------ Tx86OpAssignFloat ------------------
// ------------------
// Create
//
constructor Tx86OpAssignFloat.Create(jit : TdwsJITx86; op : TxmmOp);
begin
inherited Create(jit);
Self.OP:=op;
end;
// CompileStatement
//
procedure Tx86OpAssignFloat.CompileStatement(expr : TExprBase);
var
e : TOpAssignExpr;
reg, regRight : TxmmRegister;
jitLeft : TdwsJITter;
delta : Integer;
begin
e:=TOpAssignExpr(expr);
regRight:=jit.CompileFloat(e.Right);
if e.Left is TDynamicArrayExpr then begin
jitLeft:=jit.FindJITter(e.Left.ClassType);
(jitLeft as Tx86DynamicArray).CompileAsItemPtr(TDynamicArrayExpr(e.Left), delta);
reg:=jit.AllocXMMReg(e.Left);
x86._movsd_reg_qword_ptr_indexed(reg, gprEAX, gprECX, 1, delta);
x86._xmm_reg_reg(OP, reg, regRight);
x86._movsd_qword_ptr_indexed_reg(gprEAX, gprECX, 1, delta, reg);
end else begin
reg:=jit.CompileFloat(e.Left);
x86._xmm_reg_reg(OP, reg, regRight);
jit.CompileAssignFloat(e.Left, reg);
end;
if regRight<>reg then
jit.ReleaseXMMReg(regRight);
end;
// ------------------
// ------------------ Tx86Null ------------------
// ------------------
// CompileStatement
//
procedure Tx86Null.CompileStatement(expr : TExprBase);
begin
// nothing
end;
// ------------------
// ------------------ Tx86BlockExprNoTable ------------------
// ------------------
// CompileStatement
//
procedure Tx86BlockExprNoTable.CompileStatement(expr : TExprBase);
var
i : Integer;
subExpr : TExprBase;
begin
for i:=0 to expr.SubExprCount-1 do
begin
if jit.OutputFailedOn<>nil then break;
subExpr:=expr.SubExpr[i];
jit._DoStep(subExpr);
jit.CompileStatement(subExpr);
end;
end;
// ------------------
// ------------------ Tx86IfThen ------------------
// ------------------
// CompileStatement
//
procedure Tx86IfThen.CompileStatement(expr : TExprBase);
var
e : TIfThenExpr;
targetTrue, targetFalse : TFixupTarget;
begin
e:=TIfThenExpr(expr);
targetTrue:=jit.Fixups.NewHangingTarget(False);
targetFalse:=jit.Fixups.NewHangingTarget(False);
jit.CompileBoolean(e.CondExpr, targetTrue, targetFalse);
jit.Fixups.AddFixup(targetTrue);
jit.CompileStatement(e.ThenExpr);
jit.Fixups.AddFixup(targetFalse);
jit.ResetXMMReg;
end;
// ------------------
// ------------------ Tx86IfThenElse ------------------
// ------------------
// CompileStatement
//
procedure Tx86IfThenElse.CompileStatement(expr : TExprBase);
var
e : TIfThenElseExpr;
targetTrue, targetFalse, targetDone : TFixupTarget;
begin
e:=TIfThenElseExpr(expr);
targetTrue:=jit.Fixups.NewHangingTarget(False);
targetFalse:=jit.Fixups.NewHangingTarget(True);
targetDone:=jit.Fixups.NewHangingTarget(False);
jit.CompileBoolean(e.CondExpr, targetTrue, targetFalse);
jit.Fixups.AddFixup(targetTrue);
jit.CompileStatement(e.ThenExpr);
jit.Fixups.NewJump(flagsNone, targetDone);
jit.Fixups.AddFixup(targetFalse);
jit.CompileStatement(e.ElseExpr);
jit.Fixups.AddFixup(targetDone);
jit.ResetXMMReg;
end;
// ------------------
// ------------------ Tx86Loop ------------------
// ------------------
// CompileStatement
//
procedure Tx86Loop.CompileStatement(expr : TExprBase);
var
e : TLoopExpr;
targetLoop, targetExit : TFixupTarget;
begin
e:=TLoopExpr(expr);
jit.ResetXMMReg;
targetLoop:=jit.Fixups.NewTarget(True);
targetExit:=jit.Fixups.NewHangingTarget(False);
jit.EnterLoop(targetLoop, targetExit);
jit._DoStep(e.LoopExpr);
jit.CompileStatement(e.LoopExpr);
jit.Fixups.NewJump(flagsNone, targetLoop);
jit.Fixups.AddFixup(targetExit);
jit.LeaveLoop;
jit.ResetXMMReg;
end;
// ------------------
// ------------------ Tx86Repeat ------------------
// ------------------
// CompileStatement
//
procedure Tx86Repeat.CompileStatement(expr : TExprBase);
var
e : TLoopExpr;
targetLoop, targetExit : TFixupTarget;
begin
e:=TLoopExpr(expr);
jit.ResetXMMReg;
targetLoop:=jit.Fixups.NewTarget(True);
targetExit:=jit.Fixups.NewHangingTarget(False);
jit.EnterLoop(targetLoop, targetExit);
jit._DoStep(e.LoopExpr);
jit.CompileStatement(e.LoopExpr);
jit._DoStep(e.CondExpr);
jit.CompileBoolean(e.CondExpr, targetExit, targetLoop);
jit.Fixups.AddFixup(targetExit);
jit.LeaveLoop;
jit.ResetXMMReg;
end;
// ------------------
// ------------------ Tx86While ------------------
// ------------------
// CompileStatement
//
procedure Tx86While.CompileStatement(expr : TExprBase);
var
e : TLoopExpr;
targetLoop, targetLoopStart, targetExit : TFixupTarget;
begin
e:=TLoopExpr(expr);
jit.ResetXMMReg;
targetLoop:=jit.Fixups.NewTarget(True);
targetLoopStart:=jit.Fixups.NewHangingTarget(False);
targetExit:=jit.Fixups.NewHangingTarget(True);
jit.EnterLoop(targetLoop, targetExit);
jit._DoStep(e.CondExpr);
jit.CompileBoolean(e.CondExpr, targetLoopStart, targetExit);
jit.Fixups.AddFixup(targetLoopStart);
jit._DoStep(e.LoopExpr);
jit.CompileStatement(e.LoopExpr);
jit.Fixups.NewJump(flagsNone, targetLoop);
jit.Fixups.AddFixup(targetExit);
jit.LeaveLoop;
jit.ResetXMMReg;
end;
// ------------------
// ------------------ Tx86ForUpward ------------------
// ------------------
// CompileStatement
//
var
cPtr_TForStepExpr_RaiseForLoopStepShouldBeStrictlyPositive : Pointer = @TForStepExpr.RaiseForLoopStepShouldBeStrictlyPositive;
procedure Tx86ForUpward.CompileStatement(expr : TExprBase);
var
e : TForExpr;
jumpIfHiLower : TFixupJump;
loopStart : TFixupTarget;
loopContinue : TFixupTarget;
loopAfter : TFixupTarget;
stepCheckPassed : TFixupJump;
fromValue, toValue, stepValue : Int64;
toValueIsConstant : Boolean;
toValueIs32bit : Boolean;
toValueOffset : Integer;
stepValueIsConstant : Boolean;
stepValueOffset : Integer;
is32bit : Boolean;
begin
e:=TForExpr(expr);
jit.ResetXMMReg;
toValueIsConstant:=(e.ToExpr is TConstIntExpr);
if toValueIsConstant then begin
toValue:=TConstIntExpr(e.ToExpr).Value;
toValueIs32bit:=(Integer(toValue)=toValue);
end else begin
toValue:=0;
toValueIs32bit:=(e.ToExpr is TArrayLengthExpr)
end;
if e.FromExpr is TConstIntExpr then begin
fromValue:=TConstIntExpr(e.FromExpr).Value;
x86._mov_execmem_imm(e.VarExpr.StackAddr, fromValue);
// TODO: if toValue is dynamic Array Length, could be tagged as 32bit
is32bit:= (fromValue>=0)
and toValueIs32bit
and (Integer(fromValue)=fromValue);
end else begin
jit.CompileInteger(e.FromExpr);
x86._mov_execmem_eaxedx(e.VarExpr.StackAddr);
is32bit:=False;
end;
if not toValueIsConstant then begin
jit.CompileInteger(e.ToExpr);
toValueOffset:=jit._store_eaxedx;
end else toValueOffset:=0;
if e is TForUpwardStepExpr then begin
if TForUpwardStepExpr(e).StepExpr is TConstIntExpr then begin
stepValueIsConstant:=True;
stepValue:=TConstIntExpr(TForUpwardStepExpr(e).StepExpr).Value;
is32bit:=is32bit and (stepValue>=0) and (Integer(stepValue)=stepValue);
stepValueOffset:=0;
end else begin
stepValueIsConstant:=False;
stepValue:=0;
is32bit:=False;
jit.CompileInteger(TForUpwardStepExpr(e).StepExpr);
x86._cmp_reg_int32(gprEDX, 0);
stepCheckPassed:=jit.Fixups.NewJump(flagsGE);
x86._push_reg(gprEDX);
x86._push_reg(gprEAX);
jit._mov_reg_execInstance(gprEDX);
x86._mov_reg_dword(gprEAX, DWORD(expr));
x86._call_absmem(@cPtr_TForStepExpr_RaiseForLoopStepShouldBeStrictlyPositive);
stepCheckPassed.NewTarget(True);
stepValueOffset:=jit._store_eaxedx;
end;
end else begin
stepValueIsConstant:=True;
stepValue:=1;
stepValueOffset:=0;
end;
loopStart:=jit.Fixups.NewTarget(True);
loopContinue:=jit.Fixups.NewHangingTarget(False);
loopAfter:=jit.Fixups.NewHangingTarget(True);
jit.EnterLoop(loopContinue, loopAfter);
if is32bit then begin
jit.Hint32Bit(e.VarExpr.DataSym);
if toValueIsConstant then
x86._cmp_execmem_int32(e.VarExpr.StackAddr, 0, toValue)
else begin
x86._mov_reg_dword_ptr_reg(gprEAX, gprEBP, toValueOffset);
x86._cmp_execmem_reg(e.VarExpr.StackAddr, 0, gprEAX);
end;
jit.Fixups.NewJump(flagsG, loopAfter);
jit._DoStep(e.DoExpr);
jit.CompileStatement(e.DoExpr);
jit.Fixups.AddFixup(loopContinue);
if stepValueIsConstant then
x86._execmem32_inc(e.VarExpr.StackAddr, stepValue)
else begin
jit._restore_eax(stepValueOffset);
x86._add_execmem_reg(e.VarExpr.StackAddr, 0, gprEAX);
end;
jit.Fixups.NewJump(flagsNone, loopStart);
end else begin
if toValueIsConstant then begin
x86._cmp_execmem_int32(e.VarExpr.StackAddr, 4, Integer(toValue shr 32));
jit.Fixups.NewJump(flagsG, loopAfter);
jumpIfHiLower:=jit.Fixups.NewJump(flagsL);
x86._cmp_execmem_int32(e.VarExpr.StackAddr, 0, toValue);
jit.Fixups.NewJump(flagsG, loopAfter);
end else begin
x86._mov_eaxedx_qword_ptr_reg(gprEBP, toValueOffset);
x86._cmp_execmem_reg(e.VarExpr.StackAddr, 4, gprEDX);
jit.Fixups.NewJump(flagsG, loopAfter);
jumpIfHiLower:=jit.Fixups.NewJump(flagsL);
x86._cmp_execmem_reg(e.VarExpr.StackAddr, 0, gprEAX);
jit.Fixups.NewJump(flagsG, loopAfter);
end;
jumpIfHiLower.NewTarget(False);
jit._DoStep(e.DoExpr);
jit.CompileStatement(e.DoExpr);
jit.Fixups.AddFixup(loopContinue);
if stepValueIsConstant then begin
x86._execmem64_inc(e.VarExpr.StackAddr, stepValue);
if stepValue<>1 then
jit.Fixups.NewJump(flagsO, loopAfter);
end else begin
jit._restore_eaxedx(stepValueOffset);
x86._add_execmem_reg(e.VarExpr.StackAddr, 0, gprEAX);
x86._adc_execmem_reg(e.VarExpr.StackAddr, 4, gprEDX);
jit.Fixups.NewJump(flagsO, loopAfter);
end;
jit.Fixups.NewJump(flagsNone, loopStart);
end;
if JIT.LoopContext.Exited then
jit.ResetXMMReg;
jit.LeaveLoop;
jit.Fixups.AddFixup(loopAfter);
if is32bit then
jit.ClearHint32Bit(e.VarExpr.DataSym);
end;
// ------------------
// ------------------ Tx86Continue ------------------
// ------------------
// CompileStatement
//
procedure Tx86Continue.CompileStatement(expr : TExprBase);
begin
if jit.LoopContext<>nil then
jit.Fixups.NewJump(flagsNone, jit.LoopContext.TargetContinue)
else jit.OutputFailedOn:=expr;
end;
// ------------------
// ------------------ Tx86Break ------------------
// ------------------
// CompileStatement
//
procedure Tx86Break.CompileStatement(expr : TExprBase);
begin
if jit.LoopContext<>nil then
jit.Fixups.NewJump(flagsNone, jit.LoopContext.TargetExit)
else jit.OutputFailedOn:=expr;
end;
// ------------------
// ------------------ Tx86Exit ------------------
// ------------------
// CompileStatement
//
procedure Tx86Exit.CompileStatement(expr : TExprBase);
begin
if jit.ExitTarget<>nil then
jit.Fixups.NewJump(flagsNone, jit.ExitTarget)
else jit.OutputFailedOn:=expr;
end;
// ------------------
// ------------------ Tx86ExitValue ------------------
// ------------------
// CompileStatement
//
procedure Tx86ExitValue.CompileStatement(expr : TExprBase);
begin
jit.CompileStatement(TExitValueExpr(expr).AssignExpr);
inherited;
end;
// ------------------
// ------------------ Tx86FloatBinOp ------------------
// ------------------
// Create
//
constructor Tx86FloatBinOp.Create(jit : TdwsJITx86; op : TxmmOp);
begin
inherited Create(jit);
Self.OP:=op;
end;
// CompileFloat
//
function Tx86FloatBinOp.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TFloatBinOpExpr;
begin
e:=TFloatBinOpExpr(expr);
Result:=jit.CompileFloat(e.Left);
jit._xmm_reg_expr(OP, Result, e.Right);
jit.ContainsXMMReg(Result, expr);
end;
// ------------------
// ------------------ Tx86SqrFloat ------------------
// ------------------
// CompileFloat
//
function Tx86SqrFloat.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TSqrFloatExpr;
begin
e:=TSqrFloatExpr(expr);
Result:=CompileFloatOperand(e, e.Expr);
end;
// CompileFloatOperand
//
function Tx86SqrFloat.CompileFloatOperand(sqrExpr, operand : TTypedExpr) : TxmmRegister;
var
reg : TxmmRegister;
begin
reg:=jit.CompileFloat(operand);
if operand.ClassType=TFloatVarExpr then begin
Result:=jit.AllocXMMReg(operand);
x86._movsd_reg_reg(Result, reg);
x86._xmm_reg_reg(xmm_multsd, Result, reg);
jit.ReleaseXMMReg(reg);
end else begin
Result:=reg;
x86._xmm_reg_reg(xmm_multsd, Result, Result);
jit.ContainsXMMReg(Result, sqrExpr);
end;
end;
// ------------------
// ------------------ Tx86AbsFloat ------------------
// ------------------
// DoCompileFloat
//
function Tx86AbsFloat.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TAbsFloatExpr;
begin
e:=TAbsFloatExpr(expr);
Result:=jit.CompileFloat(e.Expr);
// andpd Result, dqword ptr [AbsMask]
x86.WriteBytes([$66, $0F, $54, $05+Ord(Result)*8]);
x86.WritePointer(jit.AbsMaskPD);
jit.ContainsXMMReg(Result, expr);
end;
// ------------------
// ------------------ Tx86NegFloat ------------------
// ------------------
// DoCompileFloat
//
function Tx86NegFloat.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TNegFloatExpr;
begin
e:=TNegFloatExpr(expr);
Result:=jit.CompileFloat(e.Expr);
// xorpd Result, dqword ptr [SignMask]
x86.WriteBytes([$66, $0F, $57, $05+Ord(Result)*8]);
x86.WritePointer(jit.SignMaskPD);
jit.ContainsXMMReg(Result, expr);
end;
// ------------------
// ------------------ Tx86ConstFloat ------------------
// ------------------
// CompileFloat
//
function Tx86ConstFloat.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TConstFloatExpr;
begin
e:=TConstFloatExpr(expr);
Result:=jit.AllocXMMReg(e);
x86._movsd_reg_absmem(Result, @e.Value);
end;
// ------------------
// ------------------ Tx86ConstInt ------------------
// ------------------
// CompileFloat
//
function Tx86ConstInt.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TConstIntExpr;
begin
e:=TConstIntExpr(expr);
if (e.Value>-MaxInt) and (e.Value<MaxInt) then begin
Result:=jit.AllocXMMReg(e, e);
x86._xmm_reg_absmem(xmm_cvtsi2sd, Result, @e.Value);
end else Result:=inherited;
end;
// CompileInteger
//
function Tx86ConstInt.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TConstIntExpr;
begin
e:=TConstIntExpr(expr);
x86._mov_eaxedx_imm(e.Value);
Result:=0;
end;
// ------------------
// ------------------ Tx86ConstBoolean ------------------
// ------------------
// CompileInteger
//
function Tx86ConstBoolean.CompileInteger(expr : TTypedExpr) : Integer;
begin
if TConstBooleanExpr(expr).Value then
x86._mov_eaxedx_imm(1)
else x86._mov_eaxedx_imm(0);
Result:=0;
end;
// CompileBooleanValue
//
function Tx86ConstBoolean.CompileBooleanValue(expr : TTypedExpr) : Integer;
begin
if TConstBooleanExpr(expr).Value then
x86._mov_reg_dword(gprEAX, 1)
else x86._mov_reg_dword(gprEAX, 0);
Result:=0;
end;
// DoCompileBoolean
//
procedure Tx86ConstBoolean.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
begin
if TConstBooleanExpr(expr).Value then
jit.Fixups.NewJump(targetTrue)
else jit.Fixups.NewJump(targetFalse);
end;
// ------------------
// ------------------ Tx86InterpretedExpr ------------------
// ------------------
// DoCallEval
//
procedure Tx86InterpretedExpr.DoCallEval(expr : TExprBase; vmt : Integer);
begin
jit._mov_reg_execInstance(gprEDX);
x86._mov_reg_dword(gprEAX, DWORD(expr));
x86._mov_reg_dword_ptr_reg(gprECX, gprEAX);
x86._call_reg(gprECX, vmt);
if jit.FSavedXMM=[] then
jit.ResetXMMReg;
jit.QueueGreed(expr);
end;
// CompileStatement
//
procedure Tx86InterpretedExpr.CompileStatement(expr : TExprBase);
begin
DoCallEval(expr, vmt_TExprBase_EvalNoResult);
end;
// DoCompileFloat
//
function Tx86InterpretedExpr.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
begin
if jit.IsInteger(expr) then
Exit(inherited DoCompileFloat(expr));
jit.SaveXMMRegs;
DoCallEval(expr, vmt_TExprBase_EvalAsFloat);
jit.RestoreXMMRegs;
jit.FPreamble.NeedTempSpace(SizeOf(Double));
Result:=jit.AllocXMMReg(expr);
x86._fstp_esp;
x86._movsd_reg_esp(Result);
jit.QueueGreed(expr);
end;
// DoCompileAssignFloat
//
procedure Tx86InterpretedExpr.DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister);
begin
jit.ReleaseXMMReg(source);
jit.SaveXMMRegs;
x86._sub_reg_int32(gprESP, SizeOf(Double));
x86._movsd_esp_reg(source);
DoCallEval(expr, vmt_TExprBase_AssignValueAsFloat);
jit.RestoreXMMRegs;
end;
// CompileInteger
//
function Tx86InterpretedExpr.CompileInteger(expr : TTypedExpr) : Integer;
begin
jit.SaveXMMRegs;
DoCallEval(expr, vmt_TExprBase_EvalAsInteger);
jit.RestoreXMMRegs;
jit.QueueGreed(expr);
Result:=0;
end;
// CompileAssignInteger
//
procedure Tx86InterpretedExpr.CompileAssignInteger(expr : TTypedExpr; source : Integer);
begin
jit.SaveXMMRegs;
x86._push_reg(gprEDX);
x86._push_reg(gprEAX);
DoCallEval(expr, vmt_TExprBase_AssignValueAsInteger);
jit.RestoreXMMRegs;
end;
// DoCompileBoolean
//
procedure Tx86InterpretedExpr.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
begin
jit.SaveXMMRegs;
DoCallEval(expr, vmt_TExprBase_EvalAsBoolean);
jit.RestoreXMMRegs;
x86._test_al_al;
jit.Fixups.NewConditionalJumps(flagsNZ, targetTrue, targetFalse);
jit.QueueGreed(expr);
end;
// CompileBooleanValue
//
function Tx86InterpretedExpr.CompileBooleanValue(expr : TTypedExpr) : Integer;
begin
jit.SaveXMMRegs;
DoCallEval(expr, vmt_TExprBase_EvalAsBoolean);
jit.RestoreXMMRegs;
x86._op_reg_int32(gpOp_and, gprEAX, 255);
jit.QueueGreed(expr);
Result:=0;
end;
// ------------------
// ------------------ Tx86FloatVar ------------------
// ------------------
// CompileFloat
//
function Tx86FloatVar.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TFloatVarExpr;
begin
e:=TFloatVarExpr(expr);
Result:=jit.CurrentXMMReg(e.DataSym);
if Result=xmmNone then begin
Result:=jit.AllocXMMReg(e, e.DataSym);
x86._movsd_reg_execmem(Result, e.StackAddr);
end;
end;
// DoCompileAssignFloat
//
procedure Tx86FloatVar.DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister);
var
e : TFloatVarExpr;
begin
e:=TFloatVarExpr(expr);
x86._movsd_execmem_reg(e.StackAddr, source);
jit.ContainsXMMReg(source, e.DataSym);
end;
// ------------------
// ------------------ Tx86IntVar ------------------
// ------------------
// CompileFloat
//
function Tx86IntVar.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TIntVarExpr;
begin
e:=TIntVarExpr(expr);
Result:=jit.AllocXMMReg(e);
if jit.Is32BitHinted(e.DataSym) then begin
x86._xmm_reg_execmem(xmm_cvtsi2sd, Result, e.StackAddr);
end else begin
jit.FPreamble.NeedTempSpace(SizeOf(Double));
x86._fild_execmem(e.StackAddr);
x86._fstp_esp;
x86._movsd_reg_esp(Result);
end;
end;
// CompileInteger
//
function Tx86IntVar.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TIntVarExpr;
begin
e:=TIntVarExpr(expr);
x86._mov_eaxedx_execmem(e.StackAddr);
Result:=0;
end;
// CompileAssignInteger
//
procedure Tx86IntVar.CompileAssignInteger(expr : TTypedExpr; source : Integer);
var
e : TIntVarExpr;
begin
e:=TIntVarExpr(expr);
x86._mov_execmem_eaxedx(e.StackAddr);
end;
// ------------------
// ------------------ Tx86BoolVar ------------------
// ------------------
// DoCompileBoolean
//
procedure Tx86BoolVar.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TBoolVarExpr;
begin
e:=TBoolVarExpr(expr);
x86._cmp_execmem_int32(e.StackAddr, 0, 0);
jit.Fixups.NewJump(flagsNZ, targetTrue);
jit.Fixups.NewJump(targetFalse);
end;
// CompileAssignBoolean
//
procedure Tx86BoolVar.CompileAssignBoolean(expr : TTypedExpr; source : Integer);
var
e : TBoolVarExpr;
begin
e:=TBoolVarExpr(expr);
x86._mov_dword_ptr_reg_reg(cExecMemGPR, StackAddrToOffset(e.StackAddr), gprEAX);
end;
// ------------------
// ------------------ Tx86ObjectVar ------------------
// ------------------
// CompileScriptObj
//
function Tx86ObjectVar.CompileScriptObj(expr : TTypedExpr) : Integer;
begin
Result:=Ord(gprEAX);
x86._mov_reg_execmem(gprEAX, TObjectVarExpr(expr).StackAddr);
end;
// ------------------
// ------------------ Tx86RecordVar ------------------
// ------------------
// CompileFloat
//
function Tx86RecordVar.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TRecordVarExpr;
begin
e:=TRecordVarExpr(expr);
Result:=jit.AllocXMMReg(e);
if jit.IsFloat(e) then begin
x86._movsd_reg_execmem(Result, e.VarPlusMemberOffset);
end else if jit.IsInteger(e) then begin
jit.FPreamble.NeedTempSpace(SizeOf(Double));
x86._fild_execmem(e.VarPlusMemberOffset);
x86._fstp_esp;
x86._movsd_reg_esp(Result);
end else Result:=inherited;
end;
// DoCompileAssignFloat
//
procedure Tx86RecordVar.DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister);
var
e : TRecordVarExpr;
begin
e:=TRecordVarExpr(expr);
if jit.IsFloat(e) then begin
x86._movsd_execmem_reg(e.VarPlusMemberOffset, source);
jit.ReleaseXMMReg(source);
end else inherited;
end;
// CompileInteger
//
function Tx86RecordVar.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TRecordVarExpr;
begin
e:=TRecordVarExpr(expr);
if jit.IsInteger(e) then begin
x86._mov_eaxedx_execmem(e.VarPlusMemberOffset);
Result:=0;
end else Result:=inherited;
end;
// CompileAssignInteger
//
procedure Tx86RecordVar.CompileAssignInteger(expr : TTypedExpr; source : Integer);
var
e : TRecordVarExpr;
begin
e:=TRecordVarExpr(expr);
if jit.IsInteger(e) then begin
x86._mov_execmem_eaxedx(e.VarPlusMemberOffset);
end else inherited;
end;
// DoCompileBoolean
//
procedure Tx86RecordVar.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TRecordVarExpr;
begin
e:=TRecordVarExpr(expr);
if jit.IsBoolean(e) then begin
x86._cmp_execmem_int32(e.VarPlusMemberOffset, 0, 0);
jit.Fixups.NewConditionalJumps(flagsNZ, targetTrue, targetFalse);
end else inherited;
end;
// ------------------
// ------------------ Tx86VarParam ------------------
// ------------------
// CompileAsPVariant
//
class procedure Tx86VarParam.CompileAsPVariant(x86 : Tx86WriteOnlyStream; expr : TByRefParamExpr);
begin
x86._mov_reg_execmem(gprEAX, expr.StackAddr);
x86._xor_reg_reg(gprEDX, gprEDX);
x86._mov_reg_dword_ptr_reg(gprECX, gprEAX);
x86._call_reg(gprECX, vmt_IDataContext_AsPVariant);
end;
// DoCompileFloat
//
function Tx86VarParam.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TVarParamExpr;
begin
e:=TVarParamExpr(expr);
CompileAsPVariant(x86, e);
if jit.IsFloat(e) then begin
Result:=jit.AllocXMMReg(e, e.DataSym);
x86._movsd_reg_qword_ptr_reg(Result, gprEAX, cVariant_DataOffset);
end else Result:=inherited;
end;
// CompileInteger
//
function Tx86VarParam.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TVarParamExpr;
begin
e:=TVarParamExpr(expr);
CompileAsPVariant(x86, e);
if jit.IsInteger(e) then begin
x86._mov_eaxedx_qword_ptr_reg(gprEAX, cVariant_DataOffset);
Result:=0;
end else Result:=inherited;
end;
// DoCompileAssignFloat
//
procedure Tx86VarParam.DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister);
var
e : TVarParamExpr;
begin
e:=TVarParamExpr(expr);
if jit.IsFloat(e) then begin
CompileAsPVariant(x86, e);
x86._movsd_qword_ptr_reg_reg(gprEAX, cVariant_DataOffset, source);
end else inherited;
end;
// CompileAssignInteger
//
procedure Tx86VarParam.CompileAssignInteger(expr : TTypedExpr; source : Integer);
var
e : TVarParamExpr;
addr : Integer;
begin
e:=TVarParamExpr(expr);
if jit.IsInteger(e) then begin
addr:=jit._store_eaxedx;
CompileAsPVariant(x86, e);
x86._mov_reg_reg(gprECX, gprEAX);
jit._restore_eaxedx(addr);
x86._mov_qword_ptr_reg_eaxedx(gprECX, cVariant_DataOffset);
end else inherited;
end;
// ------------------
// ------------------ Tx86FieldVar ------------------
// ------------------
// CompileToData
//
procedure Tx86FieldVar.CompileToData(expr : TFieldVarExpr; dest : TgpRegister);
begin
jit.CompileScriptObj(expr.ObjectExpr);
// TODO check object
x86._mov_reg_dword_ptr_reg(dest, gprEAX, vmt_ScriptObjInstance_IScriptObj_To_FData);
end;
// CompileInteger
//
function Tx86FieldVar.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TFieldVarExpr;
begin
e:=TFieldVarExpr(expr);
CompileToData(e, gprECX);
x86._mov_eaxedx_qword_ptr_reg(gprECX, e.FieldSym.Offset*SizeOf(Variant)+cVariant_DataOffset);
Result:=0;
end;
// CompileAssignInteger
//
procedure Tx86FieldVar.CompileAssignInteger(expr : TTypedExpr; source : Integer);
var
e : TFieldVarExpr;
addr : Integer;
begin
e:=TFieldVarExpr(expr);
addr:=jit.FPreamble.AllocateStackSpace(SizeOf(Int64));
x86._mov_qword_ptr_reg_eaxedx(gprEBP, addr);
CompileToData(e, gprECX);
x86._mov_eaxedx_qword_ptr_reg(gprEBP, addr);
x86._mov_qword_ptr_reg_eaxedx(gprECX, e.FieldSym.Offset*SizeOf(Variant)+cVariant_DataOffset);
end;
// DoCompileBoolean
//
procedure Tx86FieldVar.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TFieldVarExpr;
begin
e:=TFieldVarExpr(expr);
CompileToData(e, gprECX);
x86._mov_reg_dword_ptr_reg(gprEAX, gprECX, e.FieldSym.Offset*SizeOf(Variant)+cVariant_DataOffset);
x86._test_al_al;
jit.Fixups.NewConditionalJumps(flagsNZ, targetTrue, targetFalse);
end;
// ------------------
// ------------------ Tx86ArrayBase ------------------
// ------------------
// CompileIndexToGPR
//
procedure Tx86ArrayBase.CompileIndexToGPR(indexExpr : TTypedExpr; gpr : TgpRegister; var delta : Integer);
var
tempPtrOffset : Integer;
sign : Integer;
begin
delta:=0;
if indexExpr.ClassType=TConstIntExpr then begin
x86._mov_reg_dword(gpr, TConstIntExpr(indexExpr).Value);
end else if indexExpr.ClassType=TIntVarExpr then begin
x86._mov_reg_execmem(gpr, TIntVarExpr(indexExpr).StackAddr);
end else begin
if indexExpr.ClassType=TAddIntExpr then
sign:=1
else if indexExpr.ClassType=TSubIntExpr then
sign:=-1
else sign:=0;
if sign<>0 then begin
if TIntegerBinOpExpr(indexExpr).Right is TConstIntExpr then begin
CompileIndexToGPR(TIntegerBinOpExpr(indexExpr).Left, gpr, delta);
delta:=delta+sign*TConstIntExpr(TIntegerBinOpExpr(indexExpr).Right).Value;
Exit;
end else if TIntegerBinOpExpr(indexExpr).Left is TConstIntExpr then begin
CompileIndexToGPR(TIntegerBinOpExpr(indexExpr).Right, gpr, delta);
delta:=delta+sign*TConstIntExpr(TIntegerBinOpExpr(indexExpr).Left).Value;
Exit;
end;
end;
tempPtrOffset:=jit.FPreamble.AllocateStackSpace(SizeOf(Pointer));
x86._mov_dword_ptr_reg_reg(gprEBP, tempPtrOffset, gprEAX);
jit.CompileInteger(indexExpr);
x86._mov_reg_reg(gpr, gprEAX);
x86._mov_reg_dword_ptr_reg(gprEAX, gprEBP, tempPtrOffset);
end;
end;
// ------------------
// ------------------ Tx86StaticArray ------------------
// ------------------
// DoCompileFloat
//
function Tx86StaticArray.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TStaticArrayExpr;
index, delta : Integer;
begin
e:=TStaticArrayExpr(expr);
if jit.IsFloat(e) then begin
if (e.BaseExpr is TByRefParamExpr) and (e.IndexExpr is TConstIntExpr) then begin
index:=TConstIntExpr(e.IndexExpr).Value-e.LowBound;
Tx86VarParam.CompileAsPVariant(x86, TByRefParamExpr(e.BaseExpr));
x86._mov_reg_dword(gprECX, index*SizeOf(Variant));
Result:=jit.AllocXMMReg(e);
x86._movsd_reg_qword_ptr_indexed(Result, gprEAX, gprECX, 1, cVariant_DataOffset);
end else if e.BaseExpr.ClassType=TVarExpr then begin
if e.IndexExpr is TConstIntExpr then begin
index:=TConstIntExpr(e.IndexExpr).Value-e.LowBound;
Result:=jit.AllocXMMReg(e);
x86._movsd_reg_execmem(Result, TVarExpr(e.BaseExpr).StackAddr+index);
end else begin
CompileIndexToGPR(e.IndexExpr, gprECX, delta);
jit._RangeCheck(e, gprECX, delta, e.LowBound, e.LowBound+e.Count);
Result:=jit.AllocXMMReg(e);
x86._shift_reg_imm(gpShl, gprECX, 4);
x86._movsd_reg_qword_ptr_indexed(Result, cExecMemGPR, gprECX, 1, StackAddrToOffset(TVarExpr(e.BaseExpr).StackAddr));
end;
end else Result:=inherited;
end else Result:=inherited;
end;
// CompileInteger
//
function Tx86StaticArray.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TStaticArrayExpr;
delta : Integer;
begin
e:=TStaticArrayExpr(expr);
if (e.BaseExpr is TConstExpr) then begin
x86._mov_reg_dword(gprEAX, NativeUInt(@TConstExpr(e.BaseExpr).Data[0]));
end else if (e.BaseExpr is TFieldExpr) then begin
jit.CompileScriptObj(TFieldExpr(e.BaseExpr).ObjectExpr);
// TODO object check
x86._mov_reg_dword_ptr_reg(gprEAX, gprEAX, vmt_ScriptObjInstance_IScriptObj_To_FData);
x86._add_reg_int32(gprEAX, TFieldExpr(e.BaseExpr).FieldSym.Offset*SizeOf(Variant));
end else Exit(inherited);
CompileIndexToGPR(e.IndexExpr, gprECX, delta);
jit._RangeCheck(e, gprECX, delta, e.LowBound, e.LowBound+e.Count);
x86._shift_reg_imm(gpShl, gprECX, 4);
x86._mov_reg_dword_ptr_indexed(gprEDX, gprEAX, gprECX, 1, cVariant_DataOffset+4);
x86._mov_reg_dword_ptr_indexed(gprEAX, gprEAX, gprECX, 1, cVariant_DataOffset);
Result:=0;
end;
// DoCompileAssignFloat
//
procedure Tx86StaticArray.DoCompileAssignFloat(expr : TTypedExpr; source : TxmmRegister);
var
e : TStaticArrayExpr;
index : Integer;
begin
e:=TStaticArrayExpr(expr);
if jit.IsFloat(e) then begin
if (e.BaseExpr.ClassType=TVarParamExpr) and (e.IndexExpr is TConstIntExpr) then begin
index:=TConstIntExpr(e.IndexExpr).Value;
Tx86VarParam.CompileAsPVariant(x86, TVarParamExpr(e.BaseExpr));
x86._mov_reg_dword(gprECX, index*SizeOf(Variant));
x86._movsd_qword_ptr_indexed_reg(gprEAX, gprECX, 1, cVariant_DataOffset, source);
end else if (e.BaseExpr.ClassType=TVarExpr) and (e.IndexExpr is TConstIntExpr) then begin
index:=TConstIntExpr(e.IndexExpr).Value;
x86._movsd_execmem_reg(TVarExpr(e.BaseExpr).StackAddr+index, source);
end else inherited;
end else inherited;
end;
// ------------------
// ------------------ Tx86DynamicArrayBase ------------------
// ------------------
// CompileAsData
//
procedure Tx86DynamicArrayBase.CompileAsData(expr : TTypedExpr);
begin
jit.CompileScriptObj(expr);
x86._mov_reg_dword_ptr_reg(gprEAX, gprEAX, vmt_ScriptDynamicArray_IScriptObj_To_FData);
end;
// ------------------
// ------------------ Tx86DynamicArray ------------------
// ------------------
// CompileAsItemPtr
//
procedure Tx86DynamicArray.CompileAsItemPtr(expr : TDynamicArrayExpr; var delta : Integer);
begin
CompileAsData(expr.BaseExpr);
CompileIndexToGPR(expr.IndexExpr, gprECX, delta);
delta:=delta*SizeOf(Variant)*expr.Typ.Size+cVariant_DataOffset;
x86._shift_reg_imm(gpShl, gprECX, 4);
// TODO : range checking
end;
// DoCompileFloat
//
function Tx86DynamicArray.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TDynamicArrayExpr;
delta : Integer;
begin
e:=TDynamicArrayExpr(expr);
if jit.IsFloat(e) then begin
CompileAsItemPtr(e, delta);
Result:=jit.AllocXMMReg(e);
x86._movsd_reg_qword_ptr_indexed(Result, gprEAX, gprECX, 1, delta);
end else Result:=inherited;
end;
// CompileInteger
//
function Tx86DynamicArray.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TDynamicArrayExpr;
delta : Integer;
begin
e:=TDynamicArrayExpr(expr);
CompileAsItemPtr(e, delta);
x86._mov_reg_dword_ptr_indexed(gprEDX, gprEAX, gprECX, 1, delta+4);
x86._mov_reg_dword_ptr_indexed(gprEAX, gprEAX, gprECX, 1, delta);
Result:=0;
end;
// CompileScriptObj
//
function Tx86DynamicArray.CompileScriptObj(expr : TTypedExpr) : Integer;
var
e : TDynamicArrayExpr;
delta : Integer;
begin
e:=TDynamicArrayExpr(expr);
CompileAsItemPtr(e, delta);
Result:=Ord(gprEAX);
x86._mov_reg_dword_ptr_indexed(gprEAX, gprEAX, gprECX, 1, delta);
end;
// ------------------
// ------------------ Tx86DynamicArraySet ------------------
// ------------------
// CompileStatement
//
procedure Tx86DynamicArraySet.CompileStatement(expr : TExprBase);
var
e : TDynamicArraySetExpr;
reg : TxmmRegister;
delta : Integer;
begin
e:=TDynamicArraySetExpr(expr);
if jit.IsFloat(e.ArrayExpr.Typ.Typ) then begin
reg:=jit.CompileFloat(e.ValueExpr);
CompileAsData(e.ArrayExpr);
CompileIndexToGPR(e.IndexExpr, gprECX, delta);
// TODO : range checking
delta:=delta*SizeOf(Variant)+cVariant_DataOffset;
x86._shift_reg_imm(gpShl, gprECX, 4);
x86._movsd_qword_ptr_indexed_reg(gprEAX, gprECX, 1, delta, reg);
end else begin
inherited;
end;
end;
// ------------------
// ------------------ Tx86NegInt ------------------
// ------------------
// CompileInteger
//
function Tx86NegInt.CompileInteger(expr : TTypedExpr) : Integer;
begin
Result:=jit.CompileInteger(TNegIntExpr(expr).Expr);
x86._neg_eaxedx;
end;
// ------------------
// ------------------ Tx86AbsInt ------------------
// ------------------
// CompileInteger
//
function Tx86AbsInt.CompileInteger(expr : TTypedExpr) : Integer;
var
jump : TFixupJump;
begin
Result:=jit.CompileInteger(TNegIntExpr(expr).Expr);
x86._test_reg_reg(gprEDX, gprEDX);
jump:=jit.Fixups.NewJump(flagsNL);
x86._neg_reg(gprEDX);
x86._neg_reg(gprEAX);
x86._sbb_reg_int32(gprEDX, 0);
jump.NewTarget(False);
end;
// ------------------
// ------------------ Tx86NotInt ------------------
// ------------------
// CompileInteger
//
function Tx86NotInt.CompileInteger(expr : TTypedExpr) : Integer;
begin
Result:=jit.CompileInteger(TNotIntExpr(expr).Expr);
x86._not_reg(gprEDX);
x86._not_reg(gprEAX);
end;
// ------------------
// ------------------ Tx86IntegerBinOpExpr ------------------
// ------------------
// Create
//
constructor Tx86IntegerBinOpExpr.Create(jit : TdwsJITx86;const opLow, opHigh : TgpOP;
commutative : Boolean = True);
begin
inherited Create(jit);
FOpLow:=opLow;
FOpHigh:=opHigh;
FCommutative:=commutative;
end;
// CompileInteger
//
function Tx86IntegerBinOpExpr.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TIntegerBinOpExpr;
addr : Integer;
begin
e:=TIntegerBinOpExpr(expr);
if e.Right is TConstIntExpr then
CompileConstant(e.Left, TConstIntExpr(e.Right).Value)
else if FCommutative and (e.Left is TConstIntExpr) then
CompileConstant(e.Right, TConstIntExpr(e.Left).Value)
else if e.Right.ClassType=TIntVarExpr then
CompileVar(e.Left, TIntVarExpr(e.Right).StackAddr)
else if FCommutative and (e.Left.ClassType=TIntVarExpr) then
CompileVar(e.Right, TIntVarExpr(e.Left).StackAddr)
else begin
jit.CompileInteger(e.Right);
addr:=jit._store_eaxedx;
jit.CompileInteger(e.Left);
x86._op_reg_dword_ptr_reg(FOpLow, gprEAX, gprEBP, addr);
x86._op_reg_dword_ptr_reg(FOpHigh, gprEDX, gprEBP, addr+4);
end;
Result:=0;
end;
// CompileConstant
//
procedure Tx86IntegerBinOpExpr.CompileConstant(expr : TTypedExpr; const val : Int64);
begin
jit.CompileInteger(expr);
x86._op_reg_int32(FOpLow, gprEAX, val);
x86._op_reg_int32(FOpHigh, gprEDX, val shr 32);
end;
// CompileVar
//
procedure Tx86IntegerBinOpExpr.CompileVar(expr : TTypedExpr; const varStackAddr : Integer);
var
addr : Integer;
begin
addr:=StackAddrToOffset(varStackAddr);
jit.CompileInteger(expr);
x86._op_reg_dword_ptr_reg(FOpLow, gprEAX, cExecMemGPR, addr);
x86._op_reg_dword_ptr_reg(FOpHigh, gprEDX, cExecMemGPR, addr+4);
end;
// ------------------
// ------------------ Tx86MultInt ------------------
// ------------------
// CompileInteger
//
function Tx86MultInt.CompileInteger(expr : TTypedExpr) : Integer;
procedure CompileOperand(expr : TTypedExpr; var reg : TgpRegister; var addr : Integer);
begin
if expr is TIntVarExpr then begin
reg:=cExecMemGPR;
addr:=StackAddrToOffset(TIntVarExpr(expr).StackAddr);
end else begin
reg:=gprEBP;
jit.CompileInteger(expr);
addr:=jit._store_eaxedx;
end;
end;
var
e : TMultIntExpr;
twomuls, done : TFixupTarget;
leftReg, rightReg : TgpRegister;
leftAddr, rightAddr : Integer;
begin
e:=TMultIntExpr(expr);
CompileOperand(e.Left, leftReg, leftAddr);
CompileOperand(e.Right, rightReg, rightAddr);
// Based on reference code from AMD Athlon Optimization guide
twomuls:=jit.Fixups.NewHangingTarget(True);
done:=jit.Fixups.NewHangingTarget(True);
x86._mov_reg_dword_ptr_reg(gprEDX, leftReg, leftAddr+4); // left_hi
x86._mov_reg_dword_ptr_reg(gprECX, rightReg, rightAddr+4); // right_hi
x86._op_reg_reg(gpOp_or, gprEDX, gprECX); // one operand >= 2^32?
x86._mov_reg_dword_ptr_reg(gprEDX, rightReg, rightAddr); // right_lo
x86._mov_reg_dword_ptr_reg(gprEAX, leftReg, leftAddr); // left_lo
jit.Fixups.NewJump(flagsNZ, twomuls); // yes, need two multiplies
x86._mul_reg(gprEDX); // left_lo * right_lo
jit.Fixups.NewJump(flagsNone, done);
jit.Fixups.AddFixup(twomuls);
x86._imul_reg_dword_ptr_reg(gprEDX, leftReg, leftAddr+4); // p3_lo = left_hi*right_lo
x86._imul_reg_reg(gprECX, gprEAX); // p2_lo = right_hi*left_lo
x86._add_reg_reg(gprECX, gprEDX); // p2_lo + p3_lo
x86._mul_dword_ptr_reg(rightReg, rightAddr); // p1 = left_lo*right_lo
x86._add_reg_reg(gprEDX, gprECX); // p1+p2lo+p3_lo
jit.Fixups.AddFixup(done);
Result:=0;
end;
// ------------------
// ------------------ Tx86MultIntPow2 ------------------
// ------------------
// CompileInteger
//
function Tx86MultIntPow2.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TMultIntPow2Expr;
begin
e:=TMultIntPow2Expr(expr);
Result:=jit.CompileInteger(e.Expr);
x86._shl_eaxedx_imm(e.Shift+1);
end;
// ------------------
// ------------------ Tx86DivInt ------------------
// ------------------
// CompileInteger
//
function Tx86DivInt.CompileInteger(expr : TTypedExpr) : Integer;
procedure DivideByPowerOfTwo(p : Integer);
begin
x86._mov_reg_reg(gprECX, gprEDX);
x86._shift_reg_imm(gpShr, gprECX, 32-p);
x86._add_reg_reg(gprEAX, gprECX);
x86._adc_reg_int32(gprEDX, 0);
x86._sar_eaxedx_imm(p);
end;
var
e : TDivExpr;
d : Int64;
i : Integer;
begin
e:=TDivExpr(expr);
Result:=jit.CompileInteger(e.Left);
if e.Right is TConstIntExpr then begin
d:=TConstIntExpr(e.Right).Value;
if d=1 then begin
Exit;
end;
if d>0 then begin
// is it a power of two?
i:=WhichPowerOfTwo(d);
if (i>0) and (i<=31) then begin
DivideByPowerOfTwo(i);
Exit;
end;
end;
end;
x86._push_reg(gprEDX);
x86._push_reg(gprEAX);
jit.CompileInteger(e.Right);
x86._push_reg(gprEDX);
x86._push_reg(gprEAX);
x86._call_absmem(@@vAddr_div);
end;
// ------------------
// ------------------ Tx86ModInt ------------------
// ------------------
// CompileInteger
//
function Tx86ModInt.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TModExpr;
jumpPositive, jumpDone : TFixupJump;
d : Int64;
begin
e:=TModExpr(expr);
if e.Right is TConstIntExpr then begin
d:=TConstIntExpr(e.Right).Value;
if (d>0) and (WhichPowerOfTwo(d)>=0) then begin
Dec(d);
Result:=jit.CompileInteger(e.Left);
x86._test_reg_reg(gprEDX, gprEDX);
jumpPositive:=jit.Fixups.NewJump(flagsNS);
x86._neg_eaxedx;
if (d shr 32)<>0 then
x86._op_reg_int32(gpOp_and, gprEDX, d shr 32);
x86._op_reg_int32(gpOp_and, gprEAX, d);
x86._neg_eaxedx;
jumpDone:=jit.Fixups.NewJump(flagsNone);
jumpPositive.NewTarget(False);
if (d shr 32)<>0 then
x86._op_reg_int32(gpOp_and, gprEDX, d shr 32);
x86._op_reg_int32(gpOp_and, gprEAX, d);
jumpDone.NewTarget(False);
Exit;
end;
end;
Result:=jit.CompileInteger(e.Left);
x86._push_reg(gprEDX);
x86._push_reg(gprEAX);
jit.CompileInteger(e.Right);
x86._push_reg(gprEDX);
x86._push_reg(gprEAX);
x86._call_absmem(@@vAddr_mod);
end;
// ------------------
// ------------------ Tx86Shr ------------------
// ------------------
// CompileInteger
//
function Tx86Shr.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TShrExpr;
begin
e:=TShrExpr(expr);
if e.Right is TConstIntExpr then begin
Result:=jit.CompileInteger(e.Left);
x86._shr_eaxedx_imm(TConstIntExpr(e.Right).Value);
end else Result:=inherited;
end;
// ------------------
// ------------------ Tx86Shl ------------------
// ------------------
// CompileInteger
//
function Tx86Shl.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TShlExpr;
addr : Integer;
below32, done : TFixupTarget;
begin
e:=TShlExpr(expr);
Result:=jit.CompileInteger(e.Left);
if e.Right is TConstIntExpr then begin
x86._shl_eaxedx_imm(TConstIntExpr(e.Right).Value);
end else begin
if e.Right is TIntVarExpr then begin
x86._mov_reg_execmem(gprECX, TIntVarExpr(e.Right).StackAddr);
end else begin
addr:=jit._store_eaxedx;
jit.CompileInteger(e.Right);
x86._mov_reg_reg(gprECX, gprEAX);
x86._mov_eaxedx_qword_ptr_reg(gprEBP, addr);
end;
x86._op_reg_int32(gpOp_and, gprECX, 63);
below32:=jit.Fixups.NewHangingTarget(False);
done:=jit.Fixups.NewHangingTarget(False);
x86._cmp_reg_int32(gprECX, 32);
jit.Fixups.NewJump(flagsB, below32);
x86._mov_reg_reg(gprEDX, gprEAX);
x86._mov_reg_dword(gprEAX, 0);
x86._shift_reg_cl(gpShl, gprEDX);
jit.Fixups.NewJump(done);
jit.Fixups.AddFixup(below32);
x86._shl_eaxedx_cl;
jit.Fixups.AddFixup(done);
end;
end;
// ------------------
// ------------------ Tx86Inc ------------------
// ------------------
// DoCompileStatement
//
procedure Tx86Inc.DoCompileStatement(v : TIntVarExpr; i : TTypedExpr);
begin
if i is TConstIntExpr then begin
x86._execmem64_inc(v.StackAddr, TConstIntExpr(i).Value);
end else begin
jit.CompileInteger(i);
x86._add_execmem_reg(v.StackAddr, 0, gprEAX);
x86._adc_execmem_reg(v.StackAddr, 4, gprEDX);
end;
end;
// ------------------
// ------------------ Tx86IncIntVar ------------------
// ------------------
// CompileStatement
//
procedure Tx86IncIntVar.CompileStatement(expr : TExprBase);
var
e : TIncIntVarExpr;
begin
e:=TIncIntVarExpr(expr);
DoCompileStatement(e.Left as TIntVarExpr, e.Right);;
end;
// ------------------
// ------------------ Tx86IncVarFunc ------------------
// ------------------
// CompileStatement
//
procedure Tx86IncVarFunc.CompileStatement(expr : TExprBase);
var
e : TIncVarFuncExpr;
begin
e:=TIncVarFuncExpr(expr);
if e.Args[0] is TIntVarExpr then
DoCompileStatement(TIntVarExpr(e.Args[0]), e.Args[1] as TTypedExpr)
else inherited;
end;
// ------------------
// ------------------ Tx86Dec ------------------
// ------------------
// DoCompileStatement
//
procedure Tx86Dec.DoCompileStatement(v : TIntVarExpr; i : TTypedExpr);
begin
if i is TConstIntExpr then begin
x86._execmem64_dec(v.StackAddr, TConstIntExpr(i).Value);
end else begin
jit.CompileInteger(i);
x86._sub_execmem_reg(v.StackAddr, 0, gprEAX);
x86._sbb_execmem_reg(v.StackAddr, 4, gprEDX);
end;
end;
// ------------------
// ------------------ Tx86DecIntVar ------------------
// ------------------
// CompileStatement
//
procedure Tx86DecIntVar.CompileStatement(expr : TExprBase);
var
e : TDecIntVarExpr;
begin
e:=TDecIntVarExpr(expr);
DoCompileStatement(e.Left as TIntVarExpr, e.Right);;
end;
// ------------------
// ------------------ Tx86DecVarFunc ------------------
// ------------------
// CompileStatement
//
procedure Tx86DecVarFunc.CompileStatement(expr : TExprBase);
var
e : TDecVarFuncExpr;
begin
e:=TDecVarFuncExpr(expr);
if e.Args[0] is TIntVarExpr then
DoCompileStatement(TIntVarExpr(e.Args[0]), e.Args[1] as TTypedExpr)
else inherited;
end;
// ------------------
// ------------------ Tx86RelOpInt ------------------
// ------------------
// Create
//
constructor Tx86RelOpInt.Create(jit : TdwsJITx86; flagsHiPass, flagsHiFail, flagsLoPass : TboolFlags);
begin
inherited Create(jit);
Self.FlagsHiPass:=flagsHiPass;
Self.FlagsHiFail:=flagsHiFail;
Self.FlagsLoPass:=FlagsLoPass;
end;
// DoCompileBoolean
//
procedure Tx86RelOpInt.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TIntegerRelOpExpr;
addr : Integer;
begin
e:=TIntegerRelOpExpr(expr);
if e.Right is TConstIntExpr then begin
if e.Left is TIntVarExpr then begin
addr:=TIntVarExpr(e.Left).StackAddr;
x86._cmp_execmem_int32(addr, 4, Integer(TConstIntExpr(e.Right).Value shr 32));
if FlagsHiPass<>flagsNone then
jit.Fixups.NewJump(FlagsHiPass, targetTrue);
if FlagsHiFail<>flagsNone then
jit.Fixups.NewJump(FlagsHiFail, targetFalse);
x86._cmp_execmem_int32(addr, 0, Integer(TConstIntExpr(e.Right).Value));
jit.Fixups.NewConditionalJumps(FlagsLoPass, targetTrue, targetFalse);
end else begin
jit.CompileInteger(e.Left);
x86._cmp_reg_int32(gprEDX, TConstIntExpr(e.Right).Value shr 32);
if FlagsHiPass<>flagsNone then
jit.Fixups.NewJump(FlagsHiPass, targetTrue);
if FlagsHiFail<>flagsNone then
jit.Fixups.NewJump(FlagsHiFail, targetFalse);
x86._cmp_reg_int32(gprEAX, TConstIntExpr(e.Right).Value);
jit.Fixups.NewConditionalJumps(FlagsLoPass, targetTrue, targetFalse);
end;
end else if e.Right is TIntVarExpr then begin
jit.CompileInteger(e.Left);
addr:=TIntVarExpr(e.Right).StackAddr;
x86._cmp_reg_execmem(gprEDX, addr, 4);
if FlagsHiPass<>flagsNone then
jit.Fixups.NewJump(FlagsHiPass, targetTrue);
if FlagsHiFail<>flagsNone then
jit.Fixups.NewJump(FlagsHiFail, targetFalse);
x86._cmp_reg_execmem(gprEAX, addr, 0);
jit.Fixups.NewConditionalJumps(FlagsLoPass, targetTrue, targetFalse);
end else begin
jit.CompileInteger(e.Right);
addr:=jit._store_eaxedx;
jit.CompileInteger(e.Left);
x86._cmp_reg_dword_ptr_reg(gprEDX, gprEBP, addr+4);
if FlagsHiPass<>flagsNone then
jit.Fixups.NewJump(FlagsHiPass, targetTrue);
if FlagsHiFail<>flagsNone then
jit.Fixups.NewJump(FlagsHiFail, targetFalse);
x86._cmp_reg_dword_ptr_reg(gprEAX, gprEBP, addr);
jit.Fixups.NewConditionalJumps(FlagsLoPass, targetTrue, targetFalse);
end;
end;
// ------------------
// ------------------ Tx86RelEqualInt ------------------
// ------------------
// Create
//
constructor Tx86RelEqualInt.Create(jit : TdwsJITx86);
begin
inherited Create(jit, flagsNone, flagsNZ, flagsZ);
end;
// ------------------
// ------------------ Tx86RelNotEqualInt ------------------
// ------------------
// Create
//
constructor Tx86RelNotEqualInt.Create(jit : TdwsJITx86);
begin
inherited Create(jit, flagsNZ, flagsNone, flagsNZ);
end;
// ------------------
// ------------------ Tx86RelIntIsZero ------------------
// ------------------
// DoCompileBoolean
//
procedure Tx86RelIntIsZero.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TUnaryOpBoolExpr;
addr : Integer;
begin
e:=TUnaryOpBoolExpr(expr);
if e.Expr is TIntVarExpr then begin
addr:=TIntVarExpr(e.Expr).StackAddr;
x86._cmp_execmem_int32(addr, 0, 0);
jit.Fixups.NewJump(flagsNZ, targetFalse);
x86._cmp_execmem_int32(addr, 4, 0);
jit.Fixups.NewConditionalJumps(flagsZ, targetTrue, targetFalse);
end else begin
jit.CompileInteger(e.Expr);
x86._test_reg_reg(gprEAX, gprEAX);
jit.Fixups.NewJump(flagsNZ, targetFalse);
x86._test_reg_reg(gprEDX, gprEDX);
jit.Fixups.NewConditionalJumps(flagsZ, targetTrue, targetFalse);
end;
end;
// ------------------
// ------------------ Tx86RelIntIsNotZero ------------------
// ------------------
// DoCompileBoolean
//
procedure Tx86RelIntIsNotZero.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
begin
inherited DoCompileBoolean(expr, targetFalse, targetTrue);
end;
// ------------------
// ------------------ Tx86RelOpFloat ------------------
// ------------------
// Create
//
constructor Tx86RelOpFloat.Create(jit : TdwsJITx86; flags : TboolFlags);
begin
inherited Create(jit);
Self.Flags:=flags;
end;
// DoCompileBoolean
//
procedure Tx86RelOpFloat.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TRelGreaterFloatExpr;
regLeft : TxmmRegister;
begin
e:=TRelGreaterFloatExpr(expr);
regLeft:=jit.CompileFloat(e.Left);
jit._comisd_reg_expr(regLeft, e.Right);
jit.Fixups.NewConditionalJumps(Flags, targetTrue, targetFalse);
end;
// ------------------
// ------------------ Tx86NotExpr ------------------
// ------------------
// DoCompileBoolean
//
procedure Tx86NotExpr.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TNotBoolExpr;
begin
e:=TNotBoolExpr(expr);
jit.CompileBoolean(e.Expr, targetFalse, targetTrue);
end;
// ------------------
// ------------------ Tx86BoolOrExpr ------------------
// ------------------
// DoCompileBoolean
//
procedure Tx86BoolOrExpr.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TBooleanBinOpExpr;
targetFirstFalse : TFixupTarget;
begin
e:=TBooleanBinOpExpr(expr);
targetFirstFalse:=jit.Fixups.NewHangingTarget(False);
jit.CompileBoolean(e.Left, targetTrue, targetFirstFalse);
jit.Fixups.AddFixup(targetFirstFalse);
jit.CompileBoolean(e.Right, targetTrue, targetFalse);
end;
// ------------------
// ------------------ Tx86BoolAndExpr ------------------
// ------------------
// JumpSafeCompile
//
procedure Tx86BoolAndExpr.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TBooleanBinOpExpr;
targetFirstTrue : TFixupTarget;
begin
e:=TBooleanBinOpExpr(expr);
targetFirstTrue:=jit.Fixups.NewHangingTarget(False);
jit.CompileBoolean(e.Left, targetFirstTrue, targetFalse);
jit.Fixups.AddFixup(targetFirstTrue);
jit.CompileBoolean(e.Right, targetTrue, targetFalse);
end;
// ------------------
// ------------------ Tx86SetOfExpr ------------------
// ------------------
// NormalizeEnumOperand
//
procedure Tx86SetOfExpr.NormalizeEnumOperand(setTyp : TSetOfSymbol; operand : TTypedExpr;
targetOutOfRange : TFixup);
begin
jit.CompileInteger(operand);
if setTyp.MinValue<>0 then
x86._sub_reg_int32(gprEAX, setTyp.MinValue);
x86._cmp_reg_int32(gprEAX, setTyp.CountValue);
jit.Fixups.NewJump(flagsGE, targetOutOfRange);
end;
// ComputeFromValueInEAXOffsetInECXMaskInEDX
//
procedure Tx86SetOfExpr.ComputeFromValueInEAXOffsetInECXMaskInEDX(setTyp : TSetOfSymbol);
begin
// this is a bit complicated because of the array of Variant layout
// bits are in 64bit packages with 64bit padding and the test is 32bits
x86._mov_reg_reg(gprECX, gprEAX); // ECX: value
x86._op_reg_int32(gpOp_and, gprECX, 31); // ECX: value and 31
x86._mov_reg_dword(gprEDX, 1);
x86._shift_reg_cl(gpShl, gprEDX); // EDX: 32bit mask
x86._shift_reg_imm(gpShr, gprEAX, 5); // EAX: 32bit index
x86._mov_reg_reg(gprECX, gprEAX); // ECX: 32bit index
x86._op_reg_int32(gpOp_and, gprEAX, 1); // EAX; 32bit index in 64bit package
x86._shift_reg_imm(gpShl, gprEAX, 2); // EAX; offset in 64bit package
x86._shift_reg_imm(gpShr, gprECX, 1); // ECX: 64bit index
x86._shift_reg_imm(gpShl, gprECX, 4); // ECX: SizeOf(Variant) offset
x86._add_reg_reg(gprECX, gprEAX); // ECX: offset
end;
// ------------------
// ------------------ Tx86SetOfInExpr ------------------
// ------------------
// DoCompileBoolean
//
procedure Tx86SetOfInExpr.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TSetOfInExpr;
rightVar : TVarExpr;
rightVarOffset : Integer;
v : Integer;
offset : Integer;
byteMask : Byte;
opAddrRegister : TgpRegister;
begin
e:=TSetOfInExpr(expr);
if e.Right is TVarExpr then
rightVar:=TVarExpr(e.Right)
else begin
inherited;
Exit;
end;
rightVarOffset:=StackAddrToOffset(rightVar.StackAddr);
if e.Left is TConstIntExpr then begin
v:=TConstIntExpr(e.Left).Value-e.SetType.MinValue;
if v>=e.SetType.CountValue then begin
jit.Fixups.NewJump(targetFalse);
Exit;
end;
offset:=e.SetType.ValueToByteOffsetMask(v, byteMask);
offset:=(offset and 7)+(offset shr 8)*SizeOf(Variant);
x86._test_dword_ptr_reg_byte(cExecMemGPR, rightVarOffset+offset, byteMask);
jit.Fixups.NewConditionalJumps(flagsNZ, targetTrue, targetFalse);
Exit;
end else begin
NormalizeEnumOperand(e.SetType, e.Left, targetFalse);
if e.SetType.CountValue<=32 then begin
x86._mov_reg_reg(gprECX, gprEAX);
x86._mov_reg_dword(gprEDX, 1);
x86._shift_reg_cl(gpShl, gprEDX);
opAddrRegister:=cExecMemGPR;
end else begin
ComputeFromValueinEAXOffsetInECXMaskInEDX(e.SetType);
x86._add_reg_reg(gprECX, cExecMemGPR);
opAddrRegister:=gprECX;
end;
x86._test_dword_ptr_reg_reg(opAddrRegister, rightVarOffset, gprEDX);
end;
jit.Fixups.NewConditionalJumps(flagsNZ, targetTrue, targetFalse);
end;
// ------------------
// ------------------ Tx86SetOfFunction ------------------
// ------------------
// CompileStatement
//
procedure Tx86SetOfFunction.CompileStatement(expr : TExprBase);
var
e : TSetOfFunctionExpr;
offset : Integer;
varOffset : Integer;
mask : Byte;
targetOutOfRange : TFixupTarget;
begin
e:=TSetOfFunctionExpr(expr);
if e.BaseExpr is TVarExpr then begin
varOffset:=StackAddrToOffset(TVarExpr(e.BaseExpr).StackAddr);
if e.Operand is TConstIntExpr then begin
offset:=e.SetType.ValueToByteOffsetMask(TConstIntExpr(e.Operand).Value, mask);
varOffset:=varOffset+(offset div 8)*SizeOf(Variant)+(offset and 7);
DoByteOp(cExecMemGPR, varOffset, mask);
end else begin
targetOutOfRange:=jit.Fixups.NewHangingTarget(False);
NormalizeEnumOperand(e.SetType, e.Operand, targetOutOfRange);
ComputeFromValueInEAXOffsetInECXMaskInEDX(e.SetType);
x86._add_reg_reg(gprECX, cExecMemGPR);
x86._mov_reg_dword_ptr_reg(gprEAX, gprECX, varOffset);
DoWordOp(gprEAX, gprEDX);
x86._mov_dword_ptr_reg_reg(gprECX, varOffset, gprEAX);
jit.Fixups.AddFixup(targetOutOfRange);
end;
end else inherited;
end;
// ------------------
// ------------------ Tx86SetOfInclude ------------------
// ------------------
// DoByteOp
//
procedure Tx86SetOfInclude.DoByteOp(reg : TgpRegister; offset : Integer; mask : Byte);
begin
x86._or_dword_ptr_reg_byte(cExecMemGPR, offset, mask);
end;
// DoWordOp
//
procedure Tx86SetOfInclude.DoWordOp(dest, src : TgpRegister);
begin
x86._op_reg_reg(gpOp_or, dest, src);
end;
// ------------------
// ------------------ Tx86SetOfExclude ------------------
// ------------------
// DoByteOp
//
procedure Tx86SetOfExclude.DoByteOp(reg : TgpRegister; offset : Integer; mask : Byte);
begin
x86._and_dword_ptr_reg_byte(cExecMemGPR, offset, not mask);
end;
// DoWordOp
//
procedure Tx86SetOfExclude.DoWordOp(dest, src : TgpRegister);
begin
x86._not_reg(src);
x86._op_reg_reg(gpOp_and, dest, src);
end;
// ------------------
// ------------------ Tx86OrdBool ------------------
// ------------------
// CompileInteger
//
function Tx86OrdBool.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TOrdBoolExpr;
begin
e:=TOrdBoolExpr(expr);
Result:=jit.CompileBooleanValue(e.Expr);
x86._mov_reg_dword(gprEDX, 0);
end;
// ------------------
// ------------------ Tx86OrdInt ------------------
// ------------------
// CompileInteger
//
function Tx86OrdInt.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TOrdIntExpr;
begin
e:=TOrdIntExpr(expr);
jit.CompileInteger(e.Expr);
Result:=0;
end;
// ------------------
// ------------------ Tx86ConvIntToFloat ------------------
// ------------------
// DoCompileFloat
//
function Tx86ConvIntToFloat.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
begin
Result:=jit.CompileFloat(TConvIntToFloatExpr(expr).Expr);
end;
// ------------------
// ------------------ Tx86MagicFunc ------------------
// ------------------
// DoCompileFloat
//
function Tx86MagicFunc.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
jitter : TdwsJITter_x86;
e : TMagicFuncExpr;
begin
e:=(expr as TMagicFuncExpr);
jitter:=TdwsJITter_x86(jit.FindJITter(TMagicFuncSymbol(e.FuncSym).InternalFunction.ClassType));
if jitter<>nil then
Result:=jitter.DoCompileFloat(expr)
else Result:=inherited;
end;
// CompileInteger
//
function Tx86MagicFunc.CompileInteger(expr : TTypedExpr) : Integer;
var
jitter : TdwsJITter_x86;
e : TMagicIntFuncExpr;
begin
e:=(expr as TMagicIntFuncExpr);
jitter:=TdwsJITter_x86(jit.FindJITter(TMagicFuncSymbol(e.FuncSym).InternalFunction.ClassType));
if jitter<>nil then
Result:=jitter.CompileInteger(expr)
else Result:=inherited;
end;
// DoCompileBoolean
//
procedure Tx86MagicFunc.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
jitter : TdwsJITter_x86;
e : TMagicFuncExpr;
begin
e:=(expr as TMagicFuncExpr);
jitter:=TdwsJITter_x86(jit.FindJITter(TMagicFuncSymbol(e.FuncSym).InternalFunction.ClassType));
if jitter<>nil then
jitter.DoCompileBoolean(expr, targetTrue, targetFalse)
else inherited;
end;
// CompileBooleanValue
//
function Tx86MagicFunc.CompileBooleanValue(expr : TTypedExpr) : Integer;
var
jitter : TdwsJITter_x86;
e : TMagicFuncExpr;
begin
if ClassType<>Tx86MagicFunc then
Exit(inherited);
e:=(expr as TMagicFuncExpr);
jitter:=TdwsJITter_x86(jit.FindJITter(TMagicFuncSymbol(e.FuncSym).InternalFunction.ClassType));
if jitter<>nil then
Result:=jitter.CompileBooleanValue(expr)
else Result:=inherited;
end;
// ------------------
// ------------------ Tx86MagicBoolFunc ------------------
// ------------------
// CompileInteger
//
function Tx86MagicBoolFunc.CompileInteger(expr : TTypedExpr) : Integer;
begin
Result:=CompileBooleanValue(expr);
x86._mov_reg_dword(gprEDX, 0);
end;
// ------------------
// ------------------ Tx86DirectCallFunc ------------------
// ------------------
// Create
//
constructor Tx86DirectCallFunc.Create(jit : TdwsJITx86; addrPtr : PPointer);
begin
inherited Create(jit);
Self.AddrPtr:=addrPtr;
end;
// CompileCall
//
function Tx86DirectCallFunc.CompileCall(funcSym : TFuncSymbol; const args : TExprBaseListRec) : Boolean;
var
i, stackOffset : Integer;
p : TParamSymbol;
paramReg : array of TxmmRegister;
paramOffset : array of Integer;
begin
Result:=False;
SetLength(paramReg, funcSym.Params.Count);
SetLength(paramOffset, funcSym.Params.Count);
stackOffset:=0;
for i:=0 to funcSym.Params.Count-1 do begin
p:=funcSym.Params[i];
if jit.IsFloat(p.Typ) then begin
paramReg[i]:=jit.CompileFloat(args[i] as TTypedExpr);
Inc(stackOffset, SizeOf(Double));
paramOffset[i]:=stackOffset;
end else Exit;
end;
x86._sub_reg_int32(gprESP, stackOffset);
for i:=0 to High(paramReg) do begin
if paramReg[i]<>xmmNone then
x86._movsd_esp_reg(stackOffset-paramOffset[i], paramReg[i]);
end;
x86._call_absmem(addrPtr);
Result:=True;
end;
// DoCompileFloat
//
function Tx86DirectCallFunc.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TMagicFuncExpr;
begin
e:=TMagicFuncExpr(expr);
if not CompileCall(e.FuncSym, e.Args) then begin
jit.OutputFailedOn:=expr;
Result:=xmm0;
end else if jit.IsFloat(e.FuncSym.Typ) then begin
jit.FPreamble.NeedTempSpace(SizeOf(Double));
x86._fstp_esp;
Result:=jit.AllocXMMReg(expr);
x86._movsd_reg_esp(Result);
end else begin
jit.OutputFailedOn:=expr;
Result:=xmm0;
end;
end;
// CompileInteger
//
function Tx86DirectCallFunc.CompileInteger(expr : TTypedExpr) : Integer;
var
e : TMagicFuncExpr;
begin
e:=TMagicFuncExpr(expr);
if not CompileCall(e.FuncSym, e.Args) then
jit.OutputFailedOn:=expr;
Result:=0;
end;
// DoCompileBoolean
//
procedure Tx86DirectCallFunc.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
var
e : TMagicFuncExpr;
begin
e:=TMagicFuncExpr(expr);
if not CompileCall(e.FuncSym, e.Args) then
jit.OutputFailedOn:=expr;
x86._test_al_al;
jit.Fixups.NewConditionalJumps(flagsNZ, targetTrue, targetFalse);
end;
// CompileBooleanValue
//
function Tx86DirectCallFunc.CompileBooleanValue(expr : TTypedExpr) : Integer;
var
e : TMagicFuncExpr;
begin
e:=TMagicFuncExpr(expr);
if not CompileCall(e.FuncSym, e.Args) then
jit.OutputFailedOn:=expr;
x86._op_reg_int32(gpOp_and, gprEAX, 1);
Result:=0;
end;
// ------------------
// ------------------ Tx86SqrtFunc ------------------
// ------------------
// DoCompileFloat
//
function Tx86SqrtFunc.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
begin
Result:=jit.AllocXMMReg(expr);
jit._xmm_reg_expr(xmm_sqrtsd, Result, TMagicFuncExpr(expr).Args[0] as TTypedExpr);
end;
// ------------------
// ------------------ Tx86SqrFloatFunc ------------------
// ------------------
// DoCompileFloat
//
function Tx86SqrFloatFunc.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
begin
Result:=CompileFloatOperand(expr, TMagicFuncExpr(expr).Args[0] as TTypedExpr);
end;
// ------------------
// ------------------ Tx86MinMaxFloatFunc ------------------
// ------------------
// Create
//
constructor Tx86MinMaxFloatFunc.Create(jit : TdwsJITx86; op : TxmmOp);
begin
inherited Create(jit);
Self.OP:=op;
end;
// DoCompileFloat
//
function Tx86MinMaxFloatFunc.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
e : TMagicFuncExpr;
begin
e:=TMagicFuncExpr(expr);
Result:=jit.CompileFloat(e.Args[0] as TTypedExpr);
jit._xmm_reg_expr(OP, Result, e.Args[1] as TTypedExpr);
jit.ContainsXMMReg(Result, expr);
end;
// ------------------
// ------------------ Tx86RoundFunc ------------------
// ------------------
// CompileInteger
//
function Tx86RoundFunc.CompileInteger(expr : TTypedExpr) : Integer;
var
reg : TxmmRegister;
begin
reg:=jit.CompileFloat(TMagicFuncExpr(expr).Args[0] as TTypedExpr);
jit.FPreamble.NeedTempSpace(SizeOf(Double));
x86._movsd_esp_reg(reg);
jit.ReleaseXMMReg(reg);
x86._fld_esp;
x86._fistp_esp;
x86._mov_eaxedx_qword_ptr_reg(gprESP, 0);
Result:=0;
end;
// DoCompileFloat
//
function Tx86RoundFunc.DoCompileFloat(expr : TTypedExpr) : TxmmRegister;
var
reg : TxmmRegister;
begin
reg:=jit.CompileFloat(TMagicFuncExpr(expr).Args[0] as TTypedExpr);
jit.FPreamble.NeedTempSpace(SizeOf(Double));
x86._movsd_esp_reg(reg);
jit.ReleaseXMMReg(reg);
x86._fld_esp;
x86._fistp_esp;
x86._fild_esp;
x86._fstp_esp;
Result := jit.AllocXMMReg(expr);
x86._movsd_reg_esp(Result);
end;
// ------------------
// ------------------ Tx86OddFunc ------------------
// ------------------
// DoCompileBoolean
//
procedure Tx86OddFunc.DoCompileBoolean(expr : TTypedExpr; targetTrue, targetFalse : TFixup);
begin
jit.CompileInteger(TMagicFuncExpr(expr).Args[0] as TTypedExpr);
x86._test_reg_imm(gprEax, 1);
jit.Fixups.NewConditionalJumps(flagsNZ, targetTrue, targetFalse);
end;
// CompileBooleanValue
//
function Tx86OddFunc.CompileBooleanValue(expr : TTypedExpr) : Integer;
begin
jit.CompileInteger(TMagicFuncExpr(expr).Args[0] as TTypedExpr);
x86._test_reg_imm(gprEAX, 1);
x86._set_al_flags(flagsNZ);
x86._op_reg_int32(gpOp_and, gprEAX, 1);
Result:=0;
end;
end.
|
program ej6;
type
microprocesador = record
marca:string;
linea:string;
nucleos:integer;
velocidad:Real;
tamano: integer
end;
maximos = record
marca1: string;
marca2: string;
max1: integer;
max2: integer;
end;
procedure leer(var micro:microprocesador);
begin
with micro do begin
writeln('Marca: '); readln(marca);
writeln('Linea'); readln(linea);
writeln('Nucleos'); readln(nucleos);
if (nucleos <> 0) then begin
writeln('Velocidad'); readln(velocidad);
writeln('Tamaño'); readln(tamano);
end;
writeln('----------');
end;
end;
{Informar todos los de mas de 2 nucleos y transistores de a lo sumo 22 nm}
procedure nucleoYtamano(micro:microprocesador);
var cumple : boolean;
begin
cumple := ((micro.nucleos > 2) and (micro.tamano <= 22));
if (cumple) then
writeln('El procesador ',micro.marca, ' ', micro.linea, ' tiene mas de 2 nucleos y transistores a lo sumo de 22 nm.');
end;
{Actualizar el contador global con la cantidad de procesadores Intel o AMD multinucleo y > a 2.0 GHz}
procedure actualizarIntelAMD(micro:microprocesador; var contador:integer);
var cumple : boolean;
begin
cumple := ((micro.marca = 'AMD') or (micro.marca = 'Intel')) and (micro.nucleos > 1) and (micro.velocidad >= 2);
if (cumple) then
contador := contador + 1;
end;
{Actualiza las 2 marcas con mayor cantidad de procesadores con transis de 14 nm}
procedure actualizarMax(var max:maximos; micro:microprocesador; contadorCatorceNm:integer);
begin
with max do begin
if (contadorCatorceNm >= max1) then begin
max.marca2 := max.marca1;
max.max2 := max.max1;
max.marca1 := micro.marca;
max.max1 := contadorCatorceNm;
end
else begin
if (contadorCatorceNm >= max2) then begin
max.marca2 := micro.marca;
max.max2 := contadorCatorceNm;
end;
end;
end;
end;
{actualiza el contador de procesadores con 14 nm}
procedure actualizarContadorNm(var contador:integer; tamano:integer);
begin
if (tamano = 14) then
contador := contador + 1;
end;
{inicializo variable de tipo registro de maximos}
procedure initMax(var max:maximos);
begin
with max do begin
marca1 := '';
marca2 := '';
max1 := 0;
max2 := 0;
end;
end;
var
micro : microprocesador;
max : maximos;
contadorIntelAMD : integer;
marca : string;
contadorCatorceNm: integer;
begin
initMax(max);
contadorIntelAMD := 0;
leer(micro);
while(micro.nucleos <> 0) do begin
marca := micro.marca;
contadorCatorceNm := 0;
while ((micro.nucleos <> 0 ) and (marca = micro.marca)) do begin
nucleoYtamano(micro);
actualizarIntelAMD(micro, contadorIntelAMD);
actualizarContadorNm(contadorCatorceNm, micro.tamano);
actualizarMax(max, micro, contadorCatorceNm);
leer(micro);
end;
end;
writeln('La cantidad de procesadores multicore Intel o AMD con velocidades de al menos 2 GHz fue de ', contadorIntelAMD);
writeln('Las dos marcas con mayor cantidad de procesadores de 14 nm fueron ', max.marca1, ' y ', max.marca2);
end.
{
modelo:
- marca
- linea
- nucleos
- velovidad
- tamano
1)Leer informacion de los micros: Se lee de forma consecutiva por marca, finaliza
al ingresa procesador con 0 nucleos, no se procesa (while).
registro:microprocesador
proceso leerDatos(micros:microprocesador);
begin
leer maca, linea, nucleos, velocidad y tamaño.
end
main progm:
leerDatos()
while(nucleo <> 0) do
inicializo variables
2) Informar: marca y linea (2 variables) de procesadores > 2 cores y <= 22 nm
3) Informar: 2 marcas con mayor cantidad de proc de 14 nm.. (2 maximos)
registro: maxCant
marca1
marca2
cant1
cant2
proceso initMax(maximos) marca1: '' marca2: '' max1:1 max2:0
4) Informar: cantidad de procesadores (contador) AMD o Intel (nucleos > 1) and (velocidad >= 2)
contadorIntelAMD:integer
proceso actualizarIntelAMD(micro:microprocesador; var contador:integer);
var
IntelAMD:boolean
begin
with micro do begin
IntelAMD:= (marca = AMD or marca = Intel) and (nucleos > 1) and (velocidad >= 2)
if IntelAMD then
contador := contador + 1
end
}
{Leo un microprocesador
inicializo
} |
unit MRPWinReader;
interface
uses
SysUtils, Classes, ComObj, CommUtils;
type
TWinRecord = packed record
snumber: string;
sname: string;
dqty: Double;
end;
PWinRecord = ^TWinRecord;
TRPWinReader = class
private
FFile: string;
ExcelApp, WorkBook: Variant;
procedure Open;
procedure Log(const str: string);
public
FList: TStringList;
constructor Create(const sfile: string);
destructor Destroy; override;
procedure Clear;
function GetQty(const snumber: string): Double;
end;
implementation
{ TRPWinReader }
constructor TRPWinReader.Create(const sfile: string);
begin
FFile := sfile;
FList := TStringList.Create;
Open;
end;
destructor TRPWinReader.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
procedure TRPWinReader.Clear;
var
i: Integer;
p: PWinRecord;
begin
for i := 0 to FList.Count - 1 do
begin
p := PWinRecord(FList.Objects[i]);
Dispose(p);
end;
FList.Clear;
end;
function TRPWinReader.GetQty(const snumber: string): Double;
var
i: Integer;
p: PWinRecord;
begin
Result := 0;
for i := 0 to FList.Count - 1 do
begin
p := PWinRecord(FList.Objects[i]);
if p^.snumber = snumber then
begin
Result := p^.dqty;
Break;
end;
end;
end;
procedure TRPWinReader.Log(const str: string);
begin
end;
procedure TRPWinReader.Open;
var
iSheetCount, iSheet: Integer;
sSheet: string;
stitle1, stitle2, stitle3: string;
stitle: string;
irow: Integer;
snumber: string;
p: PWinRecord;
begin
Clear;
if not FileExists(FFile) then Exit;
ExcelApp := CreateOleObject('Excel.Application' );
ExcelApp.Visible := False;
ExcelApp.Caption := '应用程序调用 Microsoft Excel';
try
WorkBook := ExcelApp.WorkBooks.Open(FFile);
try
iSheetCount := ExcelApp.Sheets.Count;
for iSheet := 1 to iSheetCount do
begin
if not ExcelApp.Sheets[iSheet].Visible then Continue;
ExcelApp.Sheets[iSheet].Activate;
sSheet := ExcelApp.Sheets[iSheet].Name;
Log(sSheet);
irow := 1;
stitle1 := ExcelApp.Cells[irow, 1].Value;
stitle2 := ExcelApp.Cells[irow, 2].Value;
stitle3 := ExcelApp.Cells[irow, 3].Value;
stitle := stitle1 + stitle2 + stitle3;
if stitle <> '物料编码物料名称数量' then
begin
Log(sSheet +' 外购入库数据');
Continue;
end;
irow := 2;
snumber := ExcelApp.Cells[irow, 1].Value;
while snumber <> '' do
begin
p := New(PWinRecord);
FList.AddObject(snumber, TObject(p));
p^.snumber := snumber;
p^.sname := ExcelApp.Cells[irow, 2].Value;
p^.dqty := ExcelApp.Cells[irow, 3].Value;
irow := irow + 1;
snumber := ExcelApp.Cells[irow, 1].Value;
end;
end;
finally
ExcelApp.ActiveWorkBook.Saved := True; //新加的,设置已经保存
WorkBook.Close;
end;
finally
ExcelApp.Visible := True;
ExcelApp.Quit;
end;
end;
end.
|
program dos_file;
{$IFNDEF HASAMIGA}
{$FATAL This source is compatible with Amiga, AROS and MorphOS only !}
{$ENDIF}
{$MODE OBJFPC}{$H+}{$HINTS ON}
{$UNITPATH ../../../Base/CHelpers}
{$UNITPATH ../../../Base/Trinity}
{
===========================================================================
Project : dos_file
Topic : Reads a file and writes content to another file
Author : The AROS Development Team.
Source : http://www.aros.org/documentation/developers/samplecode/dos_file.c
===========================================================================
This example was originally written in c by The AROS Development Team.
The original examples are available online and published at the AROS
website (http://www.aros.org/documentation/developers/samples.php)
Free Pascal sources were adjusted in order to support the following targets
out of the box:
- Amiga-m68k, AROS-i386 and MorphOS-ppc
In order to accomplish that goal, some use of support units is used that
aids compilation in a more or less uniform way.
Conversion from c to Free Pascal was done by Magorium in 2015.
===========================================================================
Unless otherwise noted, these examples must be considered
copyrighted by their respective owner(s)
===========================================================================
}
{*
DOS read/write example
*}
Uses
Exec, AmigaDOS,
{$IFDEF AMIGA}
trinity,
{$ENDIF}
chelpers;
Var
buffer : packed array[0..100-1] of Char;
function main: integer;
var
infile : BPTR = Default(Bptr);
outfile : BPTR = Default(bptr);
label
cleanup;
begin
if not( SetAndTest (infile, DOSOpen('s:startup-sequence', MODE_OLDFILE))) then
begin
goto cleanup;
end;
if not( SetAndTest (outfile, DOSOpen('ram:startup-copy', MODE_NEWFILE))) then
begin
goto cleanup;
end;
while (FGets(infile, buffer, sizeof(buffer)) <> nil) do
begin
if (FPuts(outfile, @buffer[0]) <> 0) then // FPuts returns 0 on error
begin
writeln('FPuts() returned a non zero value');
goto cleanup;
end
else writeln('FPuts() returned zero');
end;
cleanup:
{*
Some may argue that "goto" is bad programming style,
but for function cleanup it still makes sense.
*}
PrintFault(IoErr(), 'Error'); // Does nothing when error code is 0
if ( infile <> default(BPTR)) then DOSClose(infile);
if (outfile <> default(BPTR)) then DOSClose(outfile);
result := 0;
end;
begin
ExitCode := Main();
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit InitializeableContainerImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
DependencyContainerIntf;
type
(*!------------------------------------------------
* basic abstract IDependencyContainer implementation class
* having capability to manage dependency and initialize services
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*-----------------------------------------------*)
TInitializeableContainer = class(TInterfacedObject, IDependencyContainer)
protected
fActualContainer : IDependencyContainer;
(*!--------------------------------------------------------
* initialize application required services
*---------------------------------------------------------
* @param container dependency container
*---------------------------------------------------------
* Note: child class must provide its implementation
*---------------------------------------------------------*)
procedure initializeServices(const container : IDependencyContainer); virtual; abstract;
public
(*!--------------------------------------------------------
* constructor
*---------------------------------------------------------
* @param container actual dependency container
*---------------------------------------------------------*)
constructor create(const container : IDependencyContainer);
(*!--------------------------------------------------------
* destructor
*---------------------------------------------------------*)
destructor destroy(); override;
property serviceContainer : IDependencyContainer read fActualContainer implements IDependencyContainer;
end;
implementation
(*!--------------------------------------------------------
* constructor
*---------------------------------------------------------
* @param cntr actual dependency container
*---------------------------------------------------------*)
constructor TInitializeableContainer.create(const container : IDependencyContainer);
begin
inherited create();
fActualContainer := container;
initializeServices(fActualContainer);
end;
(*!--------------------------------------------------------
* destructor
*---------------------------------------------------------*)
destructor TInitializeableContainer.destroy();
begin
fActualContainer := nil;
inherited destroy();
end;
end.
|
unit SimThyrPlot;
{ SimThyr Project }
{ A numerical simulator of thyrotropic feedback control }
{ Version 4.0.0 (Merlion) }
{ (c) J. W. Dietrich, 1994 - 2017 }
{ (c) Ludwig Maximilian University of Munich 1995 - 2002 }
{ (c) Ruhr University of Bochum 2005 - 2017 }
{ This unit plots simulated results in time domain }
{ Source code released under the BSD License }
{ See http://simthyr.sourceforge.net for details }
{$mode objfpc}{$H+}{$R+}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
ExtCtrls, StdCtrls, ComCtrls, ColorBox, Buttons, Menus, TAGraph, TATools,
TASeries, TATransformations, DateUtils, Math, Clipbrd, TAIntervalSources,
TADrawerSVG, TADrawUtils, TADrawerCanvas, TAStyles, TANavigation, LCLVersion,
Types, StrUtils,
SimThyrTypes, SimThyrResources, SimThyrServices, HandleNotifier, PlotOptions;
type
{ TValuesPlot }
TValuesPlot = class(TForm)
OptionsSpeedButton1: TSpeedButton;
OptionsSpeedButton2: TSpeedButton;
TSImageList: TImageList;
Chart1: TChart;
Chart2: TChart;
ChartNavPanel1: TChartNavPanel;
ChartNavPanel2: TChartNavPanel;
ChartToolset1: TChartToolset;
ChartToolset1DataPointClickTool1: TDataPointClickTool;
ChartToolset1ZoomDragTool1: TZoomDragTool;
ChartToolset1ZoomMouseWheelTool1: TZoomMouseWheelTool;
ChartToolset2: TChartToolset;
ChartToolset2DataPointClickTool1: TDataPointClickTool;
ChartToolset2PanMouseWheelTool1: TPanMouseWheelTool;
ChartToolset2ZoomDragTool1: TZoomDragTool;
ColorListBox1: TColorListBox;
ColorListBox2: TColorListBox;
ComboBox1: TComboBox;
ComboBox2: TComboBox;
TimeAxisSource: TDateTimeIntervalChartSource;
FullScaleButton2: TSpeedButton;
Divider1: TMenuItem;
CutItem: TMenuItem;
CopyItem: TMenuItem;
DeleteItem: TMenuItem;
PasteItem: TMenuItem;
UndoItem: TMenuItem;
PopupMenu1: TPopupMenu;
Panel1: TPanel;
Panel2: TPanel;
PlotPanel2: TPanel;
PlotPanel1: TPanel;
FullScaleButton1: TSpeedButton;
StatusBar1: TStatusBar;
procedure Chart1Click(Sender: TObject);
procedure Chart2Click(Sender: TObject);
procedure ChartToolset1DataPointClickTool1PointClick(ATool: TChartTool;
APoint: TPoint);
procedure ChartToolset2DataPointClickTool1PointClick(ATool: TChartTool;
APoint: TPoint);
procedure ColorBox1Change(Sender: TObject);
procedure ColorBox2Change(Sender: TObject);
procedure ColorButton1Click(Sender: TObject);
procedure ColorButton1ColorChanged(Sender: TObject);
procedure ColorListBox1Click(Sender: TObject);
procedure ColorListBox2Click(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure ComboBox2Change(Sender: TObject);
procedure CopyItemClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OptionsSpeedButton1Click(Sender: TObject);
procedure OptionsSpeedButton2Click(Sender: TObject);
procedure UpdateTimeAxes;
procedure FormShow(Sender: TObject);
procedure Panel1Click(Sender: TObject);
procedure Panel2Click(Sender: TObject);
procedure PlotPanel2Click(Sender: TObject);
procedure CopyChart;
procedure SaveChart;
procedure PrintChart(Sender: TObject);
procedure FullScaleButton2Click(Sender: TObject);
procedure FullScaleButton1Click(Sender: TObject);
procedure TitleEditChange(Sender: TObject);
private
{ private declarations }
FLine1, Fline2: TLineSeries;
public
{ public declarations }
PlotOptions: TPlotOptions;
end;
var
factor, i0, i1: longint;
graphready, append: boolean;
ValuesPlot: TValuesPlot;
gr_nummer: string[4];
procedure DrawPlot(empty: boolean);
implementation
uses
SimThyrMain;
{ TValuesPlot }
procedure DrawDummyPlots;
{Draws empty plots that are displayed before simulation run}
begin
with ValuesPlot.Fline1 do
begin
ShowLines := True;
ShowPoints := False;
Pointer.Brush.Color := ValuesPlot.ColorListBox1.Selected;
SeriesColor := ValuesPlot.ColorListBox1.Selected;
ValuesPlot.Chart1.AddSeries(ValuesPlot.Fline1);
AddXY(0, 0, '', SeriesColor);
AddXY(10, 0, '', SeriesColor);
end;
with ValuesPlot.Fline2 do
begin
ShowLines := True;
ShowPoints := False;
Pointer.Brush.Color := ValuesPlot.ColorListBox2.Selected;
SeriesColor := ValuesPlot.ColorListBox2.Selected;
ValuesPlot.Chart2.AddSeries(ValuesPlot.Fline2);
AddXY(0, 0, '', SeriesColor);
AddXY(10, 0, '', SeriesColor);
end;
ValuesPlot.Caption := 'Chart View';
append := false;
end;
procedure DrawPlot(empty: boolean);
{Draws plots from simulated values in gResultMatrix}
var
j: integer;
theSecond: real;
begin
if (empty or not append) then begin
if ValuesPlot.Fline1 <> nil then
ValuesPlot.Chart1.Series.Clear;
if ValuesPlot.Fline2 <> nil then
ValuesPlot.Chart2.Series.Clear;
ValuesPlot.Fline1 := TLineSeries.Create(ValuesPlot.Chart1);
ValuesPlot.Fline2 := TLineSeries.Create(ValuesPlot.Chart2);
end;
if (ValuesPlot.FLine1 = nil) or (ValuesPlot.Fline2 = nil) then
begin
ShowMemoryError;
exit;
end;
ValuesPlot.Fline1.BeginUpdate;
ValuesPlot.Fline2.BeginUpdate;
if empty then
DrawDummyPlots
else
begin
with ValuesPlot.Fline1 do
begin
ShowLines := True;
ShowPoints := False;
Pointer.Brush.Color := ValuesPlot.ColorListBox1.Selected;
SeriesColor := ValuesPlot.ColorListBox1.Selected;
ValuesPlot.Chart1.AddSeries(ValuesPlot.Fline1);
for j := nmax_old to length(gResultMatrix) - 1 do
begin
if not isNaN(gResultMatrix[j, ValuesPlot.ComboBox1.ItemIndex + 2]) then
begin
theSecond := gResultMatrix[j, t_pos];
AddXY(theSecond, gResultMatrix[j, ValuesPlot.ComboBox1.ItemIndex + 2] *
gParameterFactor[ValuesPlot.ComboBox1.ItemIndex + 2], '', SeriesColor);
end;
end;
end;
with ValuesPlot.Fline2 do
begin
ShowLines := True;
ShowPoints := False;
Pointer.Brush.Color := ValuesPlot.ColorListBox2.Selected;
SeriesColor := ValuesPlot.ColorListBox2.Selected;
ValuesPlot.Chart2.AddSeries(ValuesPlot.Fline2);
for j := nmax_old to length(gResultMatrix) - 1 do
begin
if not isNaN(gResultMatrix[j, ValuesPlot.ComboBox2.ItemIndex + 2]) then
begin
theSecond := gResultMatrix[j, t_pos];
AddXY(theSecond, gResultMatrix[j, ValuesPlot.ComboBox2.ItemIndex + 2] *
gParameterFactor[ValuesPlot.ComboBox2.ItemIndex + 2], '', SeriesColor);
end;
end;
end;
graphready := True;
ValuesPlot.Caption := PLOT_TITLE;
append := true;
end;
ValuesPlot.Fline1.EndUpdate;
ValuesPlot.Fline2.EndUpdate;
ValuesPlot.Chart1.Invalidate; {forces redrawing in some operating systems}
ValuesPlot.Chart2.Invalidate;
end;
procedure TValuesPlot.PlotPanel2Click(Sender: TObject);
begin
;
end;
procedure TValuesPlot.ComboBox1Change(Sender: TObject);
begin
ValuesPlot.Chart1.LeftAxis.Title.Caption :=
gParameterLabel[ComboBox1.ItemIndex + 2] + ': ' +
gParameterUnit[ComboBox1.ItemIndex + 2];
ColorListBox1.Selected := gDefaultColors[ComboBox1.ItemIndex + 2];
DrawDummyPlots;
nmax_old := 0;
DrawPlot(not graphready);
end;
procedure TValuesPlot.ColorBox1Change(Sender: TObject);
begin
DrawPlot(not graphready);
end;
procedure TValuesPlot.Chart1Click(Sender: TObject);
begin
Chart1.SetFocus;
gSelectedChart := Chart1;
PlotPanel1.Color := clHighlight;
PlotPanel2.Color := clWhite;
end;
procedure TValuesPlot.Chart2Click(Sender: TObject);
begin
Chart2.SetFocus;
gSelectedChart := Chart2;
PlotPanel1.Color := clWhite;
PlotPanel2.Color := clHighlight;
end;
procedure TValuesPlot.ChartToolset1DataPointClickTool1PointClick(
ATool: TChartTool; APoint: TPoint);
var
theTitle, theUnit: String;
x, y: Double;
begin
theTitle := ExtractDelimited(1, Chart1.LeftAxis.Title.Caption, [':']);
theUnit := ExtractDelimited(2, Chart1.LeftAxis.Title.Caption, [':']);
with ATool as TDatapointClickTool do
if (Series is TLineSeries) then
with TLineSeries(Series) do begin
x := GetXValue(PointIndex);
y := GetYValue(PointIndex);
Statusbar1.SimpleText := Format('%s = %f%s', [theTitle, y, theUnit]);
end
else
Statusbar1.SimpleText := '';
end;
procedure TValuesPlot.ChartToolset2DataPointClickTool1PointClick(
ATool: TChartTool; APoint: TPoint);
var
theTitle, theUnit: String;
x, y: Double;
begin
theTitle := ExtractDelimited(1, Chart2.LeftAxis.Title.Caption, [':']);
theUnit := ExtractDelimited(2, Chart2.LeftAxis.Title.Caption, [':']);
with ATool as TDatapointClickTool do
if (Series is TLineSeries) then
with TLineSeries(Series) do begin
x := GetXValue(PointIndex);
y := GetYValue(PointIndex);
Statusbar1.SimpleText := Format('%s = %f%s', [theTitle, y, theUnit]);
end
else
Statusbar1.SimpleText := '';
end;
procedure TValuesPlot.ColorBox2Change(Sender: TObject);
begin
DrawPlot(not graphready);
end;
procedure TValuesPlot.ColorButton1Click(Sender: TObject);
begin
ValuesPlot.Chart1.Title.Font.Color := PlotOptions.titleColor;
ValuesPlot.Chart2.Title.Font.Color := PlotOptions.titleColor;
end;
procedure TValuesPlot.ColorButton1ColorChanged(Sender: TObject);
begin
ValuesPlot.Chart1.Title.Font.Color := PlotOptions.titleColor;
ValuesPlot.Chart2.Title.Font.Color := PlotOptions.titleColor;
end;
procedure TValuesPlot.ColorListBox1Click(Sender: TObject);
begin
DrawDummyPlots;
nmax_old := 0;
DrawPlot(not graphready);
end;
procedure TValuesPlot.ColorListBox2Click(Sender: TObject);
begin
DrawDummyPlots;
nmax_old := 0;
DrawPlot(not graphready);
end;
procedure TValuesPlot.ComboBox2Change(Sender: TObject);
begin
ValuesPlot.Chart2.LeftAxis.Title.Caption :=
gParameterLabel[ComboBox2.ItemIndex + 2] + ': ' +
gParameterUnit[ComboBox2.ItemIndex + 2];
ColorListBox2.Selected := gDefaultColors[ComboBox2.ItemIndex + 2];
DrawDummyPlots;
nmax_old := 0;
DrawPlot(not graphready);
end;
procedure TValuesPlot.FormCreate(Sender: TObject);
{sets default values}
begin
gDefaultColors[0] := clBlack;
gDefaultColors[1] := clBlack;
gDefaultColors[2] := clTeal;
gDefaultColors[3] := clPurple;
gDefaultColors[4] := clRed;
gDefaultColors[5] := clNavy;
gDefaultColors[6] := clBlue;
gDefaultColors[7] := clOlive;
gDefaultColors[8] := clGreen;
gDefaultColors[9] := clMaroon;
ComboBox1.ItemIndex := 2;
ComboBox2.ItemIndex := 4;
ColorListBox1.Selected := gDefaultColors[4];
ColorListBox2.Selected := gDefaultColors[6];
Chart1.Title.Visible := False;
Chart2.Title.Visible := False;
Chart1.LeftAxis.Title.Caption :=
gParameterLabel[ComboBox1.ItemIndex + 2] + ': ' +
gParameterUnit[ComboBox1.ItemIndex + 2];
Chart2.LeftAxis.Title.Caption :=
gParameterLabel[ComboBox2.ItemIndex + 2] + ': ' +
gParameterUnit[ComboBox2.ItemIndex + 2];
DrawPlot(True);
gSelectedChart := nil;
PlotPanel1.Color := clWhite;
PlotPanel2.Color := clWhite;
append := false;
end;
procedure TValuesPlot.OptionsSpeedButton1Click(Sender: TObject);
var
theTitle: PChar;
begin
PlotOptions := PlotOptionsForm.GetPlotOptions;
if PlotOptions.titleString = '' then
begin
Chart1.Title.Visible := false;
end
else begin
theTitle := PChar(PlotOptions.titleString);
Chart1.Title.Text.SetText(theTitle);
Chart1.Title.Visible := true;
Chart1.Title.Font.Color := PlotOptions.titleColor;
end;
end;
procedure TValuesPlot.OptionsSpeedButton2Click(Sender: TObject);
var
theTitle: PChar;
begin
PlotOptions := PlotOptionsForm.GetPlotOptions;
if PlotOptions.titleString = '' then
begin
Chart2.Title.Visible := false;
end
else begin
theTitle := PChar(PlotOptions.titleString);
Chart2.Title.Text.SetText(theTitle);
Chart2.Title.Visible := true;
Chart2.Title.Font.Color := PlotOptions.titleColor;
end;
end;
procedure TValuesPlot.UpdateTimeAxes;
begin
TimeAxisSource.DateTimeFormat := string(gDateTimeFormat);
end;
procedure TValuesPlot.FormShow(Sender: TObject);
begin
UpdateTimeAxes;
end;
procedure TValuesPlot.Panel1Click(Sender: TObject);
begin
gSelectedChart := nil;
PlotPanel1.Color := clWhite;
PlotPanel2.Color := clWhite;
end;
procedure TValuesPlot.Panel2Click(Sender: TObject);
begin
gSelectedChart := nil;
PlotPanel1.Color := clWhite;
PlotPanel2.Color := clWhite;
end;
procedure TValuesPlot.CopyChart;
{$IFDEF UNIX} {selects optimal type of clipboard graphic for respective OS}
var
theImage: TPortableNetworkGraphic;
theWidth, theHeight: integer;
{$ENDIF}
begin
if gSelectedChart = nil then
bell
else
begin
{ gSelectedChart.CopyToClipboardBitmap doesn't work on Mac OS X }
{$IFDEF UNIX}
theImage := TPortableNetworkGraphic.Create;
try
theWidth := gSelectedChart.Width;
theHeight := gSelectedChart.Height;
theImage.Width := theWidth;
theImage.Height := theHeight;
if (lcl_major < 2) and (lcl_minor < 4) then
gSelectedChart.DrawOnCanvas(rect(0, 0, theImage.Width, theImage.Height),
theImage.canvas)
else
gSelectedChart.PaintOnCanvas(theImage.canvas, rect(0, 0, theImage.Width, theImage.Height));
Clipboard.Assign(theImage);
finally
theImage.Free;
end;
{$ELSE}
gSelectedChart.CopyToClipboardBitmap;
{$ENDIF}
end;
end;
procedure TValuesPlot.SaveChart;
var
theFileName: string;
theFilterIndex: integer;
theStream: TFileStream;
theDrawer: IChartDrawer;
begin
if gSelectedChart = nil then
bell
else
begin
theStream := nil;
SimThyrToolbar.SavePictureDialog1.FilterIndex := 2;
if SimThyrToolbar.SavePictureDialog1.Execute then
try
theFileName := SimThyrToolbar.SavePictureDialog1.FileName;
theFilterIndex := SimThyrToolbar.SavePictureDialog1.FilterIndex;
{$IFDEF LCLcarbon} {compensates for a bug in older versions of carbon widgetset}
if (lcl_major < 2) and (lcl_minor < 2) then
theFilterIndex := theFilterIndex + 1;
{$ENDIF}
case theFilterIndex of
2: gSelectedChart.SaveToBitmapFile(theFileName);
3: gSelectedChart.SaveToFile(TPixmap, theFileName);
4: gSelectedChart.SaveToFile(TPortableNetworkGraphic, theFileName);
5: gSelectedChart.SaveToFile(TPortableAnyMapGraphic, theFileName);
6: gSelectedChart.SaveToFile(TJPEGImage, theFileName);
7: gSelectedChart.SaveToFile(TTIFFImage, theFileName);
8: begin
theStream := TFileStream.Create(theFileName, fmCreate);
theDrawer := TSVGDrawer.Create(theStream, true);
theDrawer.DoChartColorToFPColor := @ChartColorSysToFPColor;
with gSelectedChart do
Draw(theDrawer, Rect(0, 0, Width, Height));
end;
otherwise bell;
end;
finally
if theStream <> nil then theStream.Free;
end;
end;
end;
procedure TValuesPlot.CopyItemClick(Sender: TObject);
{copy chart to clipboard}
begin
CopyChart;
end;
procedure TValuesPlot.FormActivate(Sender: TObject);
begin
{Compensation for very small screens:}
if Screen.Width < ValuesPlot.Left + ValuesPlot.Width then
ValuesPlot.Width := Screen.Width - ValuesPlot.Left - 13;
if ValuesPlot.Top < 0 then ValuesPlot.Top := 26;
if ValuesPlot.Left < 0 then ValuesPlot.Left := 13;
SimThyrToolbar.SelectAllMenuItem.Enabled := false;
gLastActiveCustomForm := ValuesPlot;
end;
procedure TValuesPlot.PrintChart(Sender: TObject);
begin
if gSelectedChart = nil then
bell
else
ShowImplementationMessage; {this function is not yet implemented}
end;
procedure TValuesPlot.FullScaleButton2Click(Sender: TObject);
begin
ValuesPlot.Chart2.Extent.UseYMax := False;
ValuesPlot.Chart2.ZoomFull;
end;
procedure TValuesPlot.FullScaleButton1Click(Sender: TObject);
begin
ValuesPlot.Chart1.Extent.UseYMax := False;
ValuesPlot.Chart1.ZoomFull;
end;
procedure TValuesPlot.TitleEditChange(Sender: TObject);
begin
end;
initialization
{$I simthyrplot.lrs}
end.
|
unit Configuration;
interface
uses
Base.Objects;
type
IConfiguration = interface(IFrameworkInterface)
['{E1F8D997-2335-49E5-8958-B66B3408DD7B}']
end;
TConfiguration = class(TFrameworkObject, IConfiguration)
end;
Configurations = class
private
class function GetDir: String;
class function GetName<TInterface: IConfiguration>: String;
class function GetPath<TInterface: IConfiguration>: String;
class procedure ConfirmDir;
public
class function Configured<TInterface: IConfiguration>: Boolean;
class procedure Delete<TInterface: IConfiguration>;
class procedure Load<TInterface: IConfiguration>(var Config: TInterface);
class procedure RegisterConfiguration<TInterface: IConfiguration; TImplementation: class>;
class procedure Save<TInterface: IConfiguration>(const Config: TInterface);
end;
implementation
uses
System.Classes,
System.SysUtils,
Tools.Encryption,
Tools.Path;
{ Configurations }
class function Configurations.Configured<TInterface>: Boolean;
begin
Result := FileExists(GetPath<TInterface>);
end;
class procedure Configurations.ConfirmDir;
var
D: String;
begin
D := GetDir;
if DirectoryExists(D) then
Exit;
CreateDir(D);
Sleep(100);
end;
class procedure Configurations.Delete<TInterface>;
var
Path: String;
begin
Path := GetPath<TInterface>;
if FileExists(Path) then
DeleteFile(Path);
end;
class function Configurations.GetDir: String;
begin
Result := IncludeTrailingPathDelimiter(Paths.GetPath + 'config');
end;
class function Configurations.GetName<TInterface>: String;
begin
Result := Objects.GetGuid<TInterface>().ToString + '.config';
end;
class function Configurations.GetPath<TInterface>: String;
begin
Result := GetDir + GetName<TInterface>;
end;
class procedure Configurations.Load<TInterface>(var Config: TInterface);
var
Content: String;
F: TStrings;
begin
Config := Objects.New<TInterface>('_config');
if not FileExists(GetPath<TInterface>) then
Exit;
Content := EmptyStr;
F := TStringList.Create;
try
F.LoadFromFile(GetPath<TInterface>);
if F.Text.Trim = '' then
Exit;
Content := Trim(F.Text);
finally
F.Free;
F := nil;
end;
if Content = '' then
Exit;
Content := Encryption.Decrypt(Content);
Config := Objects.New<TInterface>('_config', Content);
end;
class procedure Configurations.RegisterConfiguration<TInterface, TImplementation>;
begin
Objects.RegisterType<TInterface, TImplementation>('_config');
end;
class procedure Configurations.Save<TInterface>(const Config: TInterface);
var
Content: String;
F: TStrings;
begin
Content := Trim(Config.Serialize);
if Content = '' then
Exit;
Content := Encryption.Encrypt(Trim(Content));
ConfirmDir;
F := TStringList.Create;
try
F.Add(Content);
F.SaveToFile(GetPath<TInterface>);
finally
F.Free;
F := nil;
end;
end;
end.
|
unit RelayControl;
interface
uses Classes, ConnBase, TextMessage;
type
IRelayControl = interface
function CloseRelays(const relays: string): boolean;
function OpenRelays(const relays: string): boolean;
function OpenAllRelays(): boolean;
function SwitchRelaysOnOff(const relays: string; const tdelay: cardinal = 50): boolean;
function SwitchRelaysOffOn(const relays: string; const tdelay: cardinal = 50): boolean;
function QueryRelays(var relnrs: string): boolean;
function VerifyClosedRelays(const refrelnrs: string): boolean;
end;
TRelayControl = class(TInterfacedObject, IRelayControl, ITextMessengerImpl)
protected
t_curconn: TConnBase;
t_msgrimpl:TTextMessengerImpl;
protected
procedure SetConnection(const conn: TConnBase); virtual;
public
constructor Create();
destructor Destroy; override;
function CloseRelays(const relays: string): boolean; virtual;
function OpenRelays(const relays: string): boolean; virtual;
function OpenAllRelays(): boolean; virtual;
function SwitchRelaysOnOff(const relays: string; const tdelay: cardinal): boolean; virtual;
function SwitchRelaysOffOn(const relays: string; const tdelay: cardinal): boolean; virtual;
function QueryRelays(var relnrs: string): boolean; virtual;
function VerifyClosedRelays(const refrelnrs: string): boolean; virtual;
property CurConnect: TConnBase read t_curconn write SetConnection;
property MessengerService: TTextMessengerImpl read t_msgrimpl implements ITextMessengerImpl;
end;
TRelayHygrosenUsb = class(TRelayControl)
public
//constructor Create();
//destructor Destroy; override;
property CurConnect: TConnBase read t_curconn;
end;
//Every Keithley Pseudocard 7705 has 40 channels and they are nummerized :
//101, 102, ..., 140 for the first pseudo card
//201, 202, ..., 240 for the second pseudo card, and so on
//301-340 for third, 401-440 for forth and 501-540 for fifth card
//here a channel set (index of channel) is defined for all channels which are being mapped from 0 to 199,
//together are 200 channels for 5 cards. Die mapping:
//101, 102, ..., 140, 201, 202, ..., 240, ......, 501, 502, ..., 540
//0, 1, ..., 39, 40, 41, ..., 79, ......, 160, 161, ..., 199
//using channel set it's easy to compare two groups of relays, see in VerifyClosedRelays
TKeithleyChannelIndex = 0..199;
TKeithleyChannelSet = set of TKeithleyChannelIndex;
//a class to control Keithley Pseudocard 7705
TRelayKeithley = class(TRelayControl)
protected
t_cards: TStrings;
protected
procedure UpdateCardInfo();
procedure SetConnection(const conn: TConnBase); override;
function GetCardCount(): integer;
function GetCardName(idx: integer): string;
function ChannelIndexSet(const chnr: string): TKeithleyChannelSet;
function ChannelNumbers(const chset: TKeithleyChannelSet): string;
function ChannelIndexToNumber(const idx: integer): string;
function ChannelNumberToIndex(const chnr: string): integer;
public
constructor Create();
destructor Destroy; override;
function CloseRelays(const relays: string): boolean; override;
function OpenRelays(const relays: string): boolean; override;
function OpenAllRelays(): boolean; override;
function QueryRelays(var relnrs: string): boolean; override;
function VerifyClosedRelays(const refrelnrs: string): boolean; override;
property CardCount: integer read GetCardCount;
property CardName[idx: integer]: string read GetCardName;
end;
implementation
uses SysUtils, GenUtils, StrUtils;
const
C_MULTIMETER_OPT = '*OPT?'; //query which typ of pseudo card and how many cards are installed
C_MULTIMETER_OPEN_ALL = 'ROUT:OPEN:ALL'; //open all relays
C_MULTIMETER_OPEN = 'ROUT:MULT:OPEN (@%s)'; //n relays to open. %s: relay numbers with separator ','
C_MULTIMETER_CLOSE = 'ROUT:MULT:CLOS (@%s)'; //n relays to clase. %s: relay numbers with separator ','
C_MULTIMETER_CLOSE_ASK = 'ROUT:CLOS?'; // geschlossene Relais abfragen
C_PCARD_CHANNEL_MAX = 40; //maximal channels of Pseudocard 7705
C_PCARD_SLOT_MAX = 5; //maximal slots for Pseudocard 7705
procedure TRelayControl.SetConnection(const conn: TConnBase);
begin
t_curconn := conn;
end;
constructor TRelayControl.Create();
begin
inherited Create();
t_msgrimpl := TTextMessengerImpl.Create(ClassName());
end;
destructor TRelayControl.Destroy;
begin
t_msgrimpl.Free();
inherited Destroy();
end;
function TRelayControl.CloseRelays(const relays: string): boolean;
begin
result := false;
if assigned(t_curconn) then begin
result := t_curconn.SendStr(relays);
end;
end;
function TRelayControl.OpenRelays(const relays: string): boolean;
begin
result := false;
if assigned(t_curconn) then begin
result := t_curconn.SendStr(relays);
end;
end;
function TRelayControl.OpenAllRelays(): boolean;
begin
result := false;
end;
function TRelayControl.SwitchRelaysOnOff(const relays: string; const tdelay: cardinal): boolean;
begin
result := CloseRelays(relays);
if result then begin
TGenUtils.Delay(tdelay);
result := OpenRelays(relays);
end;
end;
function TRelayControl.SwitchRelaysOffOn(const relays: string; const tdelay: cardinal): boolean;
begin
result := OpenRelays(relays);
if result then begin
TGenUtils.Delay(tdelay);
result := CloseRelays(relays);
end;
end;
function TRelayControl.QueryRelays(var relnrs: string): boolean;
begin
result := false;
end;
function TRelayControl.VerifyClosedRelays(const refrelnrs: string): boolean;
begin
result := false;
end;
procedure TRelayKeithley.UpdateCardInfo();
var s_recv: string;
begin
t_cards.Clear();
if assigned(t_curconn) then begin
if t_curconn.SendStr(C_MULTIMETER_OPT + Char(13)) then begin
t_curconn.ExpectStr(s_recv, AnsiChar(13), false);
s_recv := trim(s_recv);
if (ExtractStrings([','], [' '], PChar(s_recv), t_cards) > 0) then
t_msgrimpl.AddMessage(format('%d relay cards(%s) are found.', [t_cards.Count, t_cards.DelimitedText]))
else
t_msgrimpl.AddMessage('No relay card is found.', ML_WARNING);
end;
end;
end;
procedure TRelayKeithley.SetConnection(const conn: TConnBase);
begin
inherited SetConnection(conn);
UpdateCardInfo();
end;
function TRelayKeithley.GetCardCount(): integer;
begin
result := t_cards.Count;
end;
function TRelayKeithley.GetCardName(idx: integer): string;
begin
if ((idx >= 0) and (idx < t_cards.Count)) then result := t_cards[idx]
else result := '';
end;
function TRelayKeithley.ChannelIndexSet(const chnr: string): TKeithleyChannelSet;
var t_chnrs: TStrings; i, i_idx: integer;
begin
t_chnrs := TStringList.Create();
result := [];
if (ExtractStrings([','], [' '], PChar(chnr), t_chnrs) > 0) then begin
for i := 0 to t_chnrs.Count - 1 do begin
i_idx := ChannelNumberToIndex(t_chnrs[i]);
if (i_idx >= Low(TKeithleyChannelIndex)) then Include(result, i_idx);
end;
end;
t_chnrs.Free();
end;
function TRelayKeithley.ChannelNumbers(const chset: TKeithleyChannelSet): string;
var i: integer; s_chnr: string;
begin
result := '';
for i := Low(TKeithleyChannelIndex) to High(TKeithleyChannelIndex) do begin
if (i in chset) then begin
s_chnr := ChannelIndexToNumber(i);
if (s_chnr <> '') then result := result + s_chnr + ',';
end;
end;
if EndsText(',', result) then result := LeftStr(result, length(result) - 1);
end;
function TRelayKeithley.ChannelIndexToNumber(const idx: integer): string;
var i_nr: integer;
begin
if ((idx <= Low(TKeithleyChannelIndex)) and (idx >= High(TKeithleyChannelIndex))) then begin
i_nr := (Trunc((idx + 1) / C_PCARD_CHANNEL_MAX) + 1) * 100 + (idx mod C_PCARD_CHANNEL_MAX) + 1;
result := IntToStr(i_nr);
end else result := '';
end;
function TRelayKeithley.ChannelNumberToIndex(const chnr: string): integer;
var i_chnr, i_cardnr: integer;
begin
result := -1;
if TryStrToInt(chnr, i_chnr) then begin
i_cardnr := trunc(i_chnr / 100);
i_chnr := (i_chnr mod 100);
if ((i_cardnr > 0) and (i_cardnr <= t_cards.Count) and (i_chnr <= C_PCARD_CHANNEL_MAX)) then
result := (i_cardnr - 1) * C_PCARD_CHANNEL_MAX + i_chnr - 1;
end;
end;
constructor TRelayKeithley.Create();
begin
inherited Create();
t_cards := TStringList.Create();
end;
destructor TRelayKeithley.Destroy;
begin
t_cards.Free();
inherited Destroy();
end;
function TRelayKeithley.CloseRelays(const relays: string): boolean;
begin
result := false;
if assigned(t_curconn) then begin
result := t_curconn.SendStr(Format(C_MULTIMETER_CLOSE + AnsiChar(13), [relays]));
if result then result := VerifyClosedRelays(relays);
end;
end;
function TRelayKeithley.OpenRelays(const relays: string): boolean;
var set_relopen, set_relclose: TKeithleyChannelSet; s_relclose: string;
begin
result := false;
if assigned(t_curconn) then begin
result := t_curconn.SendStr(format(C_MULTIMETER_OPEN + AnsiChar(13), [relays]));
if result then begin
result := QueryRelays(s_relclose);
if result then begin
set_relclose := ChannelIndexSet(s_relclose);
set_relopen := ChannelIndexSet(relays);
result := ((set_relopen * set_relclose) = []);
end;
end;
end;
end;
function TRelayKeithley.OpenAllRelays(): boolean;
begin
result := false;
if assigned(t_curconn) then begin
result := t_curconn.SendStr(C_MULTIMETER_OPEN_ALL + Char(13));
if result then result := VerifyClosedRelays('');
end;
end;
function TRelayKeithley.QueryRelays(var relnrs: string): boolean;
var s_recv: string;
begin
result := false;
if assigned(t_curconn) then begin
result := t_curconn.SendStr(C_MULTIMETER_CLOSE_ASK + Char(13));
if result then begin
if t_curconn.ExpectStr(s_recv, ')', false) then
s_recv := trim(s_recv);
if (AnsiStartsText('(@', s_recv) and EndsText(')', s_recv)) then relnrs := AnsiMidStr(s_recv, 3, length(s_recv) - 3)
else relnrs := s_recv;
end;
end;
end;
function TRelayKeithley.VerifyClosedRelays(const refrelnrs: string): boolean;
var set_refrel, set_isrel: TKeithleyChannelSet; s_isrel: string;
begin
result := QueryRelays(s_isrel);
if result then begin
set_refrel := ChannelIndexSet(refrelnrs);
set_isrel := ChannelIndexSet(s_isrel);
result := (set_refrel = set_isrel);
end;
end;
end.
|
unit TetrixConst;
interface
uses
Types,Graphics;
type
TShapeType = (stDot,stFeat1,stFeat2,stBox,stLine,stZed1,stZed2,stShortLine,stTree);
const
BrickSize = 25;
BrickMaxCount= 5; // Total number of bricks per shape.
BoardXLines = 10;
BoardYLines = 20;
BoardShapeTipMax = 10;
ShapesCount = 9;
B_InitStart = 1000;
B_ReStart = 100;
B_EndGame = 0;
VK_KeyP = 80;
VK_KeyQ = 81;
ShapesStruct : array[0..ShapesCount-1,0..BrickMaxCount-1] of TPoint = (
((X:1;Y:1), (X:0;Y:0),(X:0;Y:0),(X:0;Y:0),(X:0;Y:0)), //Dot
((X:1;Y:1), (X:2;Y:1),(X:3;Y:1),(X:3;Y:2),(X:0;Y:0)), //Feat1
((X:3;Y:1), (X:2;Y:1),(X:1;Y:1),(X:1;Y:2),(X:0;Y:0)), //Feat2
((X:1;Y:1), (X:1;Y:2),(X:2;Y:1),(X:2;Y:2),(X:0;Y:0)), //Box
((X:1;Y:1), (X:2;Y:1),(X:3;Y:1),(X:4;Y:1),(X:0;Y:0)), //Line
((X:1;Y:1), (X:2;Y:1),(X:2;Y:2),(X:3;Y:2),(X:0;Y:0)), //Zed 1
((X:3;Y:1), (X:2;Y:1),(X:2;Y:2),(X:1;Y:2),(X:0;Y:0)), //Zed 2
((X:1;Y:1), (X:2;Y:1),(X:0;Y:0),(X:0;Y:0),(X:0;Y:0)), //Short Line
((X:1;Y:1), (X:2;Y:1),(X:3;Y:1),(X:2;Y:2),(X:0;Y:0)) //Tree
);
implementation
end.
|
unit ContractKindTest;
interface
uses dbTest, dbObjectTest, TestFramework, ObjectTest ;
type
TContractKindTest = class (TdbObjectTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TContractKind = class(TObjectTest)
private
function InsertDefault: integer; override;
public
function InsertUpdateContractKind(const Id: integer; Code: Integer;
Name: string): integer;
constructor Create; override;
end;
implementation
uses ZDbcIntfs, SysUtils, Storage, DBClient, XMLDoc, CommonData, Forms,
UtilConvert, UtilConst, ZLibEx, zLibUtil, JuridicalTest, Data.DB;
{TContractKindTest}
constructor TContractKind.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_Object_ContractKind';
spSelect := 'gpSelect_Object_ContractKind';
spGet := 'gpGet_Object_ContractKind';
end;
function TContractKind.InsertDefault: integer;
begin
result := InsertUpdateContractKind(0, -1, 'Вид договора');
inherited;
end;
function TContractKind.InsertUpdateContractKind;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inCode', ftInteger, ptInput, Code);
FParams.AddParam('inName', ftString, ptInput, Name);
result := InsertUpdate(FParams);
end;
procedure TContractKindTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'OBJECTS\ContractKind\';
inherited;
end;
procedure TContractKindTest.Test;
var Id: integer;
RecordCount: Integer;
ObjectTest: TContractKind;
begin
ObjectTest := TContractKind.Create;
// Получим список
RecordCount := ObjectTest.GetDataSet.RecordCount;
// Вставка Вида договора
Id := ObjectTest.InsertDefault;
try
// Получение данных о Вида договора
with ObjectTest.GetRecord(Id) do
Check((FieldByName('Name').AsString = 'Вид договора'), 'Не сходятся данные Id = ' + FieldByName('id').AsString);
finally
ObjectTest.Delete(Id);
end;
end;
initialization
TestFramework.RegisterTest('Объекты', TContractKindTest.Suite);
end.
|
PROGRAM PseudoGraphics(INPUT, OUTPUT);
CONST
FirstPos = 1;
SizeMatrix = 5;
LastPos = SizeMatrix * SizeMatrix;
TYPE
Range = SET OF FirstPos .. LastPos;
Symbols = SET OF CHAR;
VAR
Ch: CHAR;
WhichPlace: Range;
FUNCTION DefinesSymbol(Ch: CHAR): Range;
VAR
SelectedSymbols: Symbols;
BEGIN{WhichSymbol}
SelectedSymbols := ['A', 'B', 'C'];
IF NOT EOLN
THEN
BEGIN
READ(Ch);
IF Ch IN SelectedSymbols
THEN
CASE Ch OF
'A': DefinesSymbol := [3, 7, 9, 12 .. 14, 16, 20, 21, 25];
'B': DefinesSymbol := [1, 2, 6, 8, 11 .. 13, 16, 19, 21 .. 23];
'C': DefinesSymbol := [2, 3, 6, 11, 16, 22, 23]
END
ELSE
DefinesSymbol := []
END
ELSE
DefinesSymbol := []
END;{WhichSymbol}
PROCEDURE Printing(WhichPlace: Range);
VAR
Border, Index: INTEGER;
BEGIN{Printing}
Border := SizeMatrix;
IF WhichPlace <> []
THEN
FOR Index := FirstPos TO LastPos
DO
BEGIN
IF Index IN WhichPlace
THEN
WRITE('X')
ELSE
WRITE(' ');
IF Index = Border
THEN
BEGIN
WRITELN;
Border := Border + SizeMatrix
END
END
ELSE
WRITELN('Некорректные символы')
END;{Printing}
BEGIN{PseudoGraphics}
WhichPlace := DefinesSymbol(Ch);
Printing(WhichPlace)
END.{PseudoGraphics}
|
Unit ImageListView;
Interface
Uses
System.SysUtils, System.Classes, Winapi.Windows, Vcl.Controls, Vcl.ComCtrls, Winapi.CommCtrl, Vcl.ImgList,
Winapi.Messages, Winapi.GDIPAPI, Winapi.GDIPOBJ, Winapi.UxTheme;
Type
TILVItemSelected = Procedure(Sender: TObject; Index: Integer) Of Object;
TILVItemActivated = Procedure(Sender: TObject; Index: Integer) Of Object;
TILVDraw = Procedure(Sender: TObject; Item: PNMCustomDraw) Of Object;
TILVDrawItem = Procedure(Sender: TObject; Item: PNMCustomDraw) Of Object;
TILVShowMenu = Procedure(Sender: TObject; Index: Integer) Of Object;
TILVItemCountChanged = Procedure(Sender: TObject; Count: Integer) Of Object;
TImageListView = Class(TWinControl)
Private
{ Private declarations }
FImgList : HIMAGELIST;
FItemHeight : Integer;
FOnDraw : TILVDraw;
FOnDrawItem : TILVDrawItem;
FOnItemSelected : TILVItemSelected;
FOnItemActivated : TILVItemActivated;
FOnShowMenu : TILVShowMenu;
FOnItemCountChanged: TILVItemCountChanged;
FCount : Integer;
FLastSelected : Integer;
FCustomDrawItem : Boolean;
Procedure SetItemHeight(Height: Integer);
Protected
{ Protected declarations }
Procedure CNNotify(Var Message: TWMNotifyLV); Message CN_NOTIFY;
Procedure CreateParams(Var Params: TCreateParams); Override;
Procedure CreateWnd; Override;
Public
{ Public declarations }
Constructor Create(AOwner: TComponent); Override;
Destructor Destroy; Override;
Public
Function GetItemRect(Index: Integer): TRect;
Procedure SetItemCount(Count: Integer);
Procedure DeleteItem(Index: Integer);
Procedure SelectItem(Index: Integer);
Function GetSelected(): Integer;
Procedure RedrawItem(Index: Integer);
Procedure RedrawItemEx(iFirst, iLast: Integer);
Function GetItemState(Index: Integer): UINT;
Published
{ Published declarations }
Property Align;
Property CustomDrawItem : Boolean Read FCustomDrawItem Write FCustomDrawItem Default FALSE;
Property ItemHeight : Integer Read FItemHeight Write SetItemHeight Default 32;
Property OnDraw : TILVDraw Read FOnDraw Write FOnDraw;
Property OnDrawItem : TILVDrawItem Read FOnDrawItem Write FOnDrawItem;
Property OnItemSelected : TILVItemSelected Read FOnItemSelected Write FOnItemSelected;
Property OnItemActivated : TILVItemActivated Read FOnItemActivated Write FOnItemActivated;
Property OnShowMenu : TILVShowMenu Read FOnShowMenu Write FOnShowMenu;
Property OnItemCountChanged: TILVItemCountChanged Read FOnItemCountChanged Write FOnItemCountChanged;
Public
Property ItemIndex : Integer Read GetSelected Write SelectItem;
Property Count : Integer Read FCount Write SetItemCount;
Property ItemRect[Index: Integer]: TRect Read GetItemRect;
End;
Procedure Register;
Implementation
Procedure Register;
Begin
RegisterComponents('Samples', [TImageListView]);
End;
Constructor TImageListView.Create(AOwner: TComponent);
Begin
Inherited;
FLastSelected := -1;
ControlStyle := ControlStyle - [csCaptureMouse] + [csDisplayDragImage, csAcceptsControls, csReflector, csPannable];
If FItemHeight = 0 Then FItemHeight := 32;
FImgList := ImageList_Create(1, FItemHeight, ILC_COLOR32, 0, 1);
DoubleBuffered := TRUE;
TabStop := TRUE;
End;
Destructor TImageListView.Destroy();
Begin
ImageList_Destroy(FImgList);
Inherited;
End;
Function TImageListView.GetItemRect(Index: Integer): TRect;
Begin
ListView_GetItemRect(Handle, Index, Result, LVIR_BOUNDS);
End;
Function TImageListView.GetSelected: Integer;
Begin
Result := FLastSelected;
End;
Procedure TImageListView.CreateParams(Var Params: TCreateParams);
Begin
InitCommonControl(ICC_LISTVIEW_CLASSES);
Inherited CreateParams(Params);
CreateSubClass(Params, WC_LISTVIEW);
Params.Style := WS_CHILD Or WS_TABSTOP Or WS_CLIPCHILDREN Or WS_CLIPSIBLINGS Or WS_VSCROLL Or LVS_SHAREIMAGELISTS Or LVS_REPORT Or LVS_SINGLESEL Or LVS_SHOWSELALWAYS Or LVS_NOCOLUMNHEADER Or LVS_NOSORTHEADER Or LVS_OWNERDATA;
Params.ExStyle := Params.ExStyle Or WS_EX_CLIENTEDGE;
Params.WindowClass.Style := Params.WindowClass.Style And Not(CS_HREDRAW Or CS_VREDRAW);
End;
Procedure TImageListView.CreateWnd();
Var
Styles: DWORD;
Col : TLVColumn;
Begin
Inherited;
Styles := LVS_EX_DOUBLEBUFFER Or LVS_EX_FULLROWSELECT Or LVS_EX_AUTOSIZECOLUMNS Or LVS_EX_BORDERSELECT;
ListView_SetExtendedListViewStyle(Handle, Styles);
ListView_SetImageList(Handle, FImgList, LVSIL_SMALL);
SetWindowTheme(Handle, 'explorer', Nil);
FillChar(Col, sizeof(Col), 0);
Col.mask := LVCF_FMT Or LVCF_WIDTH;
Col.fmt := LVCFMT_FILL Or LVCFMT_NO_TITLE;
Col.cx := Width - 21;
ListView_InsertColumn(Handle, 0, Col);
ListView_SetItemCount(Handle, FCount);
If FLastSelected <> -1 Then
Begin
ListView_SetItemState(Handle, FLastSelected, LVIS_SELECTED, LVIS_SELECTED);
End;
End;
Procedure TImageListView.CNNotify(Var Message: TWMNotifyLV);
Var
lpnmitem: PNMITEMACTIVATE;
Begin
Case Message.NMHdr.code Of
NM_CUSTOMDRAW:
Begin
Message.Result := CDRF_DODEFAULT;
If (Message.NMCustomDraw.dwDrawStage = CDDS_PREPAINT) Then
Begin
If Assigned(FOnDraw) Then
Begin
FOnDraw(Self, Message.NMCustomDraw);
End;
Message.Result := CDRF_NOTIFYITEMDRAW;
End Else If (Message.NMCustomDraw.dwDrawStage = CDDS_ITEMPREPAINT) Then
Begin
If (FCustomDrawItem) And Assigned(FOnDrawItem) Then
Begin
FOnDrawItem(Self, Message.NMCustomDraw);
Message.Result := CDRF_SKIPDEFAULT;
End Else Begin
Message.Result := CDRF_NOTIFYPOSTPAINT;
End;
End Else If Message.NMCustomDraw.dwDrawStage = CDDS_ITEMPOSTPAINT Then
Begin
If (FCustomDrawItem = FALSE) And Assigned(FOnDrawItem) Then
Begin
FOnDrawItem(Self, Message.NMCustomDraw);
End;
End;
End;
LVN_ITEMCHANGED:
If (Message.NMListView.uChanged = LVIF_STATE) Then
Begin
If (Message.NMListView.uOldState And LVIS_SELECTED = 0) And
(Message.NMListView.uNewState And LVIS_SELECTED <> 0) And
(FLastSelected <> Message.NMListView.iItem)
Then
Begin
FLastSelected := Message.NMListView.iItem;
If Assigned(FOnItemSelected) Then FOnItemSelected(Self, Message.NMListView.iItem);
End;
End;
LVN_ITEMACTIVATE:
Begin
lpnmitem := PNMITEMACTIVATE(Message.NMListView);
If Assigned(FOnItemActivated) And (lpnmitem.iItem <> -1) Then
Begin
FOnItemActivated(Self, lpnmitem.iItem);
End;
Message.Result := 0;
End;
NM_CLICK:
Begin
lpnmitem := PNMITEMACTIVATE(Message.NMListView);
If (lpnmitem.iItem = -1) And (FLastSelected <> -1) Then
Begin
ListView_SetItemState(Handle, FLastSelected, LVIS_SELECTED, LVIS_SELECTED);
End;
Message.Result := 0;
End;
NM_RCLICK:
Begin
lpnmitem := PNMITEMACTIVATE(Message.NMListView);
If (lpnmitem.iItem = -1) And (FLastSelected <> -1) Then
Begin
ListView_SetItemState(Handle, FLastSelected, LVIS_SELECTED, LVIS_SELECTED);
End;
If Assigned(FOnShowMenu) Then
Begin
FOnShowMenu(Self, lpnmitem.iItem);
End;
Message.Result := 0;
End;
NM_DBLCLK, NM_RDBLCLK:
Begin
lpnmitem := PNMITEMACTIVATE(Message.NMListView);
If (lpnmitem.iItem = -1) And (FLastSelected <> -1) Then
Begin
ListView_SetItemState(Handle, FLastSelected, LVIS_SELECTED, LVIS_SELECTED);
End;
Message.Result := 0;
End;
End;
End;
Procedure TImageListView.SetItemCount(Count: Integer);
Var
Reselected: Integer;
Begin
FCount := Count;
Reselected := FLastSelected;
If FLastSelected >= FCount Then
Begin
FLastSelected := FCount - 1;
End;
ListView_SetItemCount(Handle, FCount);
If (FCount > 0) And (Reselected <> FLastSelected) Then
Begin
SelectItem(FLastSelected);
End;
If Assigned(FOnItemCountChanged) Then
Begin
FOnItemCountChanged(Self, FCount);
End;
End;
Procedure TImageListView.SetItemHeight(Height: Integer);
Begin
If Height <> FItemHeight Then
Begin
FItemHeight := Height;
ImageList_Destroy(FImgList);
FImgList := ImageList_Create(1, FItemHeight, ILC_COLOR32, 0, 1);
If HandleAllocated Then
Begin
ListView_SetImageList(Handle, FImgList, LVSIL_SMALL);
End;
End;
End;
Procedure TImageListView.DeleteItem(Index: Integer);
Begin
If Index < FCount Then
Begin
ListView_DeleteItem(Handle, Index);
FCount := FCount - 1;
If FCount > 0 Then
Begin
If FLastSelected >= FCount Then
Begin
SelectItem(FCount - 1);
End Else Begin
SelectItem(FLastSelected);
End;
End Else Begin
FLastSelected := -1;
If Assigned(FOnItemSelected) Then
Begin
FOnItemSelected(Self, -1);
End;
End;
If Assigned(FOnItemCountChanged) Then
Begin
FOnItemCountChanged(Self, FCount);
End;
End Else Begin
Raise Exception.Create('Error Message');
End;
End;
Procedure TImageListView.SelectItem(Index: Integer);
Begin
FLastSelected := Index;
ListView_SetItemState(Handle, Index, LVIS_SELECTED, LVIS_SELECTED);
ListView_EnsureVisible(Handle, Index, FALSE);
If Assigned(FOnItemSelected) Then
Begin
FOnItemSelected(Self, Index);
End;
End;
Procedure TImageListView.RedrawItem(Index: Integer);
Begin
ListView_RedrawItems(Handle, Index, Index);
End;
Procedure TImageListView.RedrawItemEx(iFirst, iLast: Integer);
Begin
ListView_RedrawItems(Handle, iFirst, iLast);
End;
Function TImageListView.GetItemState(Index: Integer): UINT;
Begin
Result := ListView_GetItemState(Handle, Index, LVIS_SELECTED Or LVIS_FOCUSED);
End;
End.
|
unit uConfINI;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IniFiles;
type
TForm1 = class(TForm)
edt1: TEdit;
chk1: TCheckBox;
btn1: TButton;
procedure btn1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btn1Click(Sender: TObject);
var
confFile : TIniFile;
begin
try
confFile := TIniFile.Create('C:\SQL\confINI.ini');
//Seção //Identificador //Valor
confFile.WriteString('confGeral', 'NomeOperador', edt1.Text);
confFile.WriteBool('confGeral', 'Teste1', chk1.Checked);
finally
FreeAndNil(confFile);
end;
end;
procedure TForm1.FormShow(Sender: TObject);
var
confFile : TIniFile;
begin
try
confFile := TIniFile.Create('C:\SQL\confINI.ini');
edt1.Text := confFile.ReadString('confGeral', 'NomeOperador','');
chk1.Checked := confFile.ReadBool('confGeral','Teste1',false);
finally
FreeAndNil(confFile);
end;
end;
end.
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program;
// if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Ported to Delphi by Michal Wojcik.
//
// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the GNU General Public License version 2 or later.
{$H+}
unit TestRunner;
interface
uses
FitServer,
TestRunnerFixtureListener,
CachingResultFormatter,
Classes,
Counts,
PageResult,
PrintStream;
type
TTestRunner = class
private
host : string;
port : Integer;
pageName : string;
fitServer : TFitServer;
Foutput : TPrintStream;
debug : boolean;
suiteFilter : string; //= null;
procedure usage();
procedure processClasspathDocument();
procedure finalCount();
public
fixtureListener : TTestRunnerFixtureListener;
handler : TCachingResultFormatter;
formatters : TList; //= new LinkedList<FormattingOption>();
verbose : boolean;
usingDownloadedPaths : boolean; //= true;
constructor Create(); overload;
constructor Create(output : TPrintStream); overload;
class procedure main(args : TStringList);
procedure run(args : TStringList);
function exitCode() : Integer;
procedure args(args : TStringList);
function makeHttpRequest() : string;
procedure doFormatting();
class procedure addItemsToClasspath(classpathItems : string);
function getCounts() : TCounts;
procedure acceptResults(results : TPageResult);
class procedure addUrlToClasspath(u : string {URL});
end;
implementation
uses
SysUtils,
FormattingOption,
CommandLine,
StandardResultHandler;
constructor TTestRunner.Create();
begin
Create(nil); //TODO // this(System.out);
end;
constructor TTestRunner.Create(output : TPrintStream);
begin
Foutput := output;
formatters := TList.Create;
handler := TCachingResultFormatter.Create();
usingDownloadedPaths := true;
end;
class procedure TTestRunner.main(args : TStringList);
var
runner : TTestRunner;
begin
runner := TTestRunner.Create();
runner.run(args);
Halt(runner.exitCode());
end;
procedure TTestRunner.args(args : TStringList);
var
commandLine : TCommandLine;
begin
commandLine :=
TCommandLine.Create('[-debug] [-v] [-results file] [-html file] [-xml file] [-nopath] [-suiteFilter filter] host port pageName');
if (not commandLine.parse(args)) then
usage();
host := commandLine.getArgument('host');
port := StrToInt(commandLine.getArgument('port'));
pageName := commandLine.getArgument('pageName');
if (commandLine.hasOption('debug')) then
debug := true;
if (commandLine.hasOption('v')) then
begin
verbose := true;
handler.addHandler(TStandardResultHandler.Create(Foutput));
end;
if (commandLine.hasOption('nopath')) then
usingDownloadedPaths := false;
if (commandLine.hasOption('results')) then
formatters.add(TFormattingOption.Create('raw', commandLine.getOptionArgument('results', 'file'), Foutput, host,
port,
pageName));
if (commandLine.hasOption('html')) then
formatters.add(TFormattingOption.Create('html', commandLine.getOptionArgument('html', 'file'), Foutput, host,
port,
pageName));
if (commandLine.hasOption('xml')) then
formatters.add(TFormattingOption.Create('xml', commandLine.getOptionArgument('xml', 'file'), Foutput, host, port,
pageName));
if (commandLine.hasOption('suiteFilter')) then
suiteFilter := commandLine.getOptionArgument('suiteFilter', 'filter');
end;
procedure TTestRunner.usage();
begin
WriteLn('usage: java fitnesse.runner.TestRunner [options] host port page-name');
WriteLn(#9'-v '#9'verbose: prints test progress to stdout');
WriteLn(#9'-results <filename|''stdout''>'#9'save raw test results to a file or dump to standard output');
WriteLn(#9'-html <filename|''stdout''>'#9'format results as HTML and save to a file or dump to standard output');
WriteLn(#9'-debug '#9'prints FitServer protocol actions to stdout');
WriteLn(#9'-nopath '#9'prevents downloaded path elements from being added to classpath');
System.ExitCode := -1;
Halt;
end;
procedure TTestRunner.run(args : TStringList);
begin
self.args(args);
fitServer := TFitServer.Create(host, port, debug);
fixtureListener := TTestRunnerFixtureListener.Create(self);
fitServer.fixtureListener := fixtureListener;
fitServer.establishConnection(makeHttpRequest());
fitServer.validateConnection();
if (usingDownloadedPaths) then
processClasspathDocument();
fitServer.process();
finalCount();
fitServer.closeConnection();
fitServer.exit();
doFormatting();
handler.cleanUp();
end;
procedure TTestRunner.processClasspathDocument();
var
classpathItems : string;
begin
classpathItems := fitServer.readDocument();
if (verbose) then
Foutput.println('Adding to classpath: ' + classpathItems);
addItemsToClasspath(classpathItems);
end;
procedure TTestRunner.finalCount();
begin
handler.acceptFinalCount(fitServer.getCounts());
end;
function TTestRunner.exitCode() : Integer;
begin
if (fitServer = nil) then
Result := -1
else
Result := fitServer.exitCode();
end;
function TTestRunner.makeHttpRequest() : string;
var
request : string;
begin
request := 'GET /' + pageName + '?responder=fitClient';
if (usingDownloadedPaths) then
request := request + '&includePaths=yes';
if (suiteFilter <> '') then
begin
request := request + '&suiteFilter=' + suiteFilter;
end;
Result := request + ' HTTP/1.1'#13#10#13#10;
end;
function TTestRunner.getCounts() : TCounts;
begin
Result := fitServer.getCounts();
end;
procedure TTestRunner.acceptResults(results : TPageResult);
var
counts : TCounts;
begin
counts := results.counts();
fitServer.writeCounts(counts);
handler.acceptResult(results);
end;
procedure TTestRunner.doFormatting();
var
i : Integer;
option : TFormattingOption;
begin
for i := 0 to formatters.Count - 1 do
begin
option := TFormattingOption(formatters[i]);
if (verbose) then
Writeln('Formatting as ' + option.format + ' to ' + option.filename);
option.process(handler.getResultStream(), handler.getByteCount());
end;
end;
class procedure TTestRunner.addItemsToClasspath(classpathItems : string);
var
items : TStringList;
i : Integer;
item : string;
begin
items := TFitServer.parseAssemblyList(classpathItems); //classpathItems.split(System.getProperty('path.separator'));
for i := 0 to items.Count - 1 do
begin
item := items[i];
if item[1] = '"' then
item := Copy(item, 2, Length(item) - 2);
if Pos('*', item) > 0 then
continue;
addUrlToClasspath(item); // TODO new File(item).toURL());
end;
end;
class procedure TTestRunner.addUrlToClasspath(u : string {URL});
begin
LoadPackage(u);
(* URLClassLoader sysloader := (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysclass := URLClassLoader.class;
Method method := sysclass.getDeclaredMethod('addURL', new Class[]{URL.class};);
method.setAccessible(true);
method.invoke(sysloader, new Object[]{};);
*)
end;
end.
|
unit AqDrop.Core.HTTP.Types;
interface
type
{TODO 3 -oTatu -cIncompleto: adicionar todos os tipos de headers}
TAqHTTPHeaderType = (hhtContentType, hhtAuthorization, hhtXContext);
{TODO 3 -oTatu -cIncompleto: adicionar todos os tipos de content type}
TAqHTTPHeaderContentType = (hctApplicationJSON);
TAqHTTPHeaderTypeHelper = record helper for TAqHTTPHeaderType
public
function ToString: string;
end;
TAqHTTPHeaderContentTypeHelper = record helper for TAqHTTPHeaderContentType
public
function ToString: string;
end;
implementation
uses
AqDrop.Core.Exceptions;
{ TAqHTTPHeaderTypeHelper }
function TAqHTTPHeaderTypeHelper.ToString: string;
begin
case Self of
hhtContentType:
Result := 'Content-Type';
hhtAuthorization:
Result := 'Authorization';
hhtXContext:
Result := 'X-Context';
else
raise EAqInternal.CreateFmt('Invalid HTTP Header type (%d).', [Int32(Self)]);
end;
end;
{ TAqHTTPHeaderContentTypeHelper }
function TAqHTTPHeaderContentTypeHelper.ToString: string;
begin
case Self of
hctApplicationJSON:
Result := 'application/json';
else
raise EAqInternal.CreateFmt('Invalid HTTP Header type (%d).', [Int32(Self)]);
end;
end;
end.
|
unit EquatableUnit;
interface
uses SysUtils, IGetSelfUnit;
type
IEquatable = interface (IGetSelf)
['{B34933B9-AB87-4DF9-9C9C-34F7E5A944FE}']
function Equals(Equatable: TObject): Boolean;
end;
implementation
end.
|
unit uDetailedBackupForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls, fgl,
Menus, VirtualTrees, uConfiguratorData, uBackupFormData, uLibrary;
type
{ TDetailedBackupForm }
TGroupItemList = specialize TFpgList<TGroupItemBackupData>;
TDetailedBackupForm = class(TDetailedForm)
ResetMenuItem: TMenuItem;
SaveBackupVarsToolButton: TToolButton;
VarPopupMenu: TPopupMenu;
VarTree: TVirtualStringTree;
VarImageList: TImageList;
ToolButtonImageList: TImageList;
ContentToolBar: TToolBar;
DelimiterToolButton: TToolButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ResetMenuItemClick(Sender: TObject);
procedure VarTreeChecked(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure VarTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure VarTreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; {%H-}Column: TColumnIndex;
var {%H-}Ghosted: Boolean; var ImageIndex: Integer);
procedure VarTreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
procedure VarTreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
{%H-}Column: TColumnIndex; {%H-}TextType: TVSTTextType; var CellText: String);
private
fModbusData: TModbusData;
fDeviceData: TDeviceData;
fBackupData: TBackupData;
fGroupItemList: TGroupItemList;
private
procedure PopulateVarTree;
public
procedure Load(const aContentData: array of TContentData); override;
procedure Unload; override;
end;
implementation
{$R *.lfm}
//type
//TTGroupItemListHelper = class helper for TGroupItemList
// public
// function BinarySearch()
//end;
{ TDetailedBackupForm }
procedure TDetailedBackupForm.VarTreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TBaseBackupData);
end;
procedure TDetailedBackupForm.VarTreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
P: Pointer;
begin
P := Sender.GetNodeData(Node);
TBaseBackupData(P^).Free;
end;
procedure TDetailedBackupForm.ResetMenuItemClick(Sender: TObject);
var
GroupItemBackupData: TGroupItemBackupData;
begin
for GroupItemBackupData in fGroupItemList do
GroupItemBackupData.Checked := False;
end;
procedure TDetailedBackupForm.FormCreate(Sender: TObject);
begin
fGroupItemList := TGroupItemList.Create;
end;
procedure TDetailedBackupForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(fGroupItemList);
end;
procedure TDetailedBackupForm.VarTreeChecked(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
P: Pointer;
begin
if Node^.CheckType = TCheckType.ctCheckBox then
begin
P := Sender.GetNodeData(Node);
if TBaseBackupData(P^) is TGroupItemBackupData then
TGroupItemBackupData(P^).Checked := not TGroupItemBackupData(P^).Checked;
end;
end;
procedure TDetailedBackupForm.VarTreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
var
P: Pointer;
begin
P := Sender.GetNodeData(Node);
case Kind of
ikNormal: ImageIndex := Ord(TBaseBackupData(P^).GetImage);
ikSelected: ImageIndex := Ord(TBaseBackupData(P^).GetSelected);
end;
end;
procedure TDetailedBackupForm.VarTreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: String);
var
P: Pointer;
begin
P := Sender.GetNodeData(Node);
CellText := TBaseBackupData(P^).Caption;
end;
procedure TDetailedBackupForm.PopulateVarTree;
procedure AddConfigs(const aNode: PVirtualNode; const aGroups: IGroups);
var
Groups: IGroups;
Node: PVirtualNode;
GroupItem: IGroupItem;
GroupItemBackupData: TGroupItemBackupData;
begin
for Groups in aGroups.GroupsList do
begin
Node := VarTree.AddChild(aNode, TGroupsBackupData.Create(Groups));
AddConfigs(Node, Groups);
end;
for GroupItem in aGroups.GetGroup do
begin
GroupItemBackupData := TGroupItemBackupData.Create(GroupItem);
Node := VarTree.AddChild(aNode, GroupItemBackupData);
Node^.CheckType := TCheckType.ctCheckBox;
GroupItemBackupData.OwnerNode := Node;
GroupItemBackupData.Tree := VarTree;
// Список элементов группы
fGroupItemList.Add(GroupItemBackupData);
end;
end;
begin
{$IFDEF DEBUG}
Assert(fDeviceData <> nil);
{$ENDIF}
VarTree.BeginUpdate;
try
AddConfigs(nil, fDeviceData.Module.ModuleDefine.Configuration);
fGroupItemList.Sort(@GroupItemCompare);
finally
VarTree.EndUpdate;
end;
end;
procedure TDetailedBackupForm.Load(const aContentData: array of TContentData);
var
I: Integer;
begin
{$IFDEF DEBUG}
Assert(Length(aContentData) = 3);
{$ENDIF}
// Инициализация
for I := Low(aContentData) to High(aContentData) do
begin
if aContentData[I] is TModbusData then
fModbusData := aContentData[I] as TModbusData;
if aContentData[I] is TDeviceData then
fDeviceData := aContentData[I] as TDeviceData;
if aContentData[I] is TBackupData then
fBackupData := aContentData[I] as TBackupData;
end;
PopulateVarTree;
end;
procedure TDetailedBackupForm.Unload;
begin
fGroupItemList.Clear;
end;
end.
|
unit zBHOManager;
interface
uses Windows, SysUtils, winsock, registry, Variants, Classes, zSharedFunctions,
RxVerInf, zutil;
type
// Информация о BHO
TBHOInfo = record
BinFileName : string; // Имя исполняемого файла
Descr : string; // Описание (если есть)
BinFileExists : boolean; // Признак существования файла на диске
BinFileInfo : string; // Информация о исполняемом файле
CheckResults : boolean; // Результаты проверки
RegRoot : HKEY; // Узел реестра
RegKEY : string; // Ключ реестра
RegValue : string; // Ключ или параметр реестра, идентифицирующий BHO
RegType : integer; // Тип ключа BHO
end;
// Менеджер BHO
TBHOManager = class
// Списки пространств имен
BHOListReg : array of TBHOInfo;
constructor Create;
// Обновление списков
function Refresh : boolean;
end;
implementation
{ TBHOManager }
constructor TBHOManager.Create;
begin
BHOListReg := nil;
end;
function TBHOManager.Refresh: boolean;
begin
BHOListReg := nil;
end;
end.
|
unit peninput;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, AdvToolBar, ImgList, Menus, AdvMenus, GifIMG,
MSINKAUTLib_TLB, DB, ToolWin, ComCtrls, StdCtrls, Buttons,
System.ImageList, Vcl.ExtCtrls;
type
Tpeninput_f = class(TForm)
ImageList4: TImageList;
popThickness: TAdvPopupMenu;
N7: TMenuItem;
N9: TMenuItem;
N11: TMenuItem;
pnlPenParent: TPanel;
PentoolBar: TToolBar;
pnlPen: TPanel;
btnSignpen: TButton;
btnEraser: TButton;
AdvToolBarButton3: TButton;
AdvToolBarButton2: TButton;
AdvToolBarButton1: TButton;
btnBlackSignPen: TButton;
btnRedSignPen: TButton;
btnGreenSignPen: TButton;
btnBlueSignPen: TButton;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure pnlPenMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure btnBlueSignPenClick(Sender: TObject);
procedure N7Click(Sender: TObject);
procedure btnEraserClick(Sender: TObject);
procedure AdvToolBarButton1Click(Sender: TObject);
private
viewmode: integer;
SysName: string;
procedure AllClear;
procedure LoadInkCollector;
procedure LoadPenChartImageForMod(varChartseq: Double);
procedure saveimageChart(varMode: integer; varChartSeq: Double);
function LoadPenChartImage(varChartseq: Double;
varRow: integer): string;
procedure ColorChange(varColor: tColor);
procedure ThickChange(varThick: integer);
procedure EraseStrokes(varptX, varPtY: integer;
varcurrentStroke: inkStrokes);
procedure PenKindChange(varPen: integer; sender: TObject);
{ Private declarations }
public
LoadType: integer; //0:참고사항 1:CC 2:문진 3:원장요구 4:환자요청 5:pi 6:imp 7:plan
varChartseq: integer;
varGridRow: integer;
varPeninputMode: integer; //0:insert 1:modify
varinputDate: string;
varTeam, varDam: string;
{ Public declarations }
end;
var
peninput_f: Tpeninput_f;
TxInkCollector: TinkCollector;
implementation
uses uConfig, uGogekData, uDm, uFunctions, umain, uSysInfo, saveChamgo;
{$R *.dfm}
procedure Tpeninput_f.FormShow(Sender: TObject);
var
varLeft, varTop, varRight, varBottom: integer;
SysInfo: SystemInfoRecord;
begin
Caption := '펜 입력 도구';
sysinfo := GetAllSystemInfo;
SysName := Sysinfo.ComputerName;
allClear;
//varGrdRow := grdProgress.Rowcount - 1;
// pnlPen.Color := clWhite;
pnlPen.align:=alClient;
// pnlPen.Left :=0;// penToolbar.Width;
// pnlPen.top := 0;
// pnlPen.width := pnlPenParent.Width - penToolbar.Width;
// pnlPen.Height := pnlPenParent.Height;
//
{ varLeft := main_f.pnlLeft.Width;
varTop := main_f.pnlLeft.Top;
varRight := varLeft + grdProgress.Width;
varBottom := varTop + 400;
}
// pnlPenParent.ManualFloat(Rect(varLeft, varTop, varRight, varBottom));
pnlPenParent.Visible := true;
if TxInkCollector.Enabled = false then
begin
//TxInkCollector.Enabled := true;
// allclear;
if varPeninputMode = 1 then
LoadPenChartImageForMod(varChartSeq);
TxInkCollector.hWnd_ := pnlPen.Handle;
TxInkCollector.Enabled := true;
pnlPen.Refresh;
end
else
begin
TxInkCollector.Enabled := false;
if varPeninputMode = 1 then
LoadPenChartImageForMod(varChartSeq);
TxInkCollector.hWnd_ := pnlPen.Handle;
TxInkCollector.Enabled := true;
pnlPen.Refresh;
end;
end;
procedure Tpeninput_f.FormCreate(Sender: TObject);
begin
if not DirectoryExists( ExtractFilePath(ParamStr(0)) + 'temp\TempImage\') then
ForceDirectories( ExtractFilePath(ParamStr(0)) + 'temp\TempImage\');
//ink start----------------------------------------------------------------
coInkCollector.Create;
TxInkCollector := TInkCollector.Create(self);
TxInkCollector.hwnd_ := pnlPen.Handle;
// TxInkCollector.hwnd := mnumemo.Handle;
// TxInkCollector.hwnd := advStringGrid1.Handle;
// TxInkCollector.hwnd := realGrid1.Handle;
// TxInkCollector.Transparency := 0;
//TxInkCollector.Ink.
TxInkCollector.DefaultDrawingAttributes.Color := clRed;
TxInkCollector.DefaultDrawingAttributes.Width := 90;
TxInkCollector.DefaultDrawingAttributes.Transparency := 100;
TxInkCollector.DefaultDrawingAttributes.IgnorePressure := true;
TxInkCollector.Enabled := true;
//ink end----------------------------------------------------------------
LoadInkCollector;
end;
procedure Tpeninput_f.LoadInkCollector;
begin
// coInkCollector.Create;
// TxInkCollector := TInkCollector.Create(self);
TxInkCollector.Enabled := false;
TxInkCollector.hWnd_ := pnlPen.Handle;
TxInkCollector.DefaultDrawingAttributes.Width := 20;
TxInkCollector.DefaultDrawingAttributes.Color := clRed;
TxInkCollector.DefaultDrawingAttributes.AntiAliased := true;
TxInkCollector.DefaultDrawingAttributes.FitToCurve := true;
TxInkCollector.DefaultDrawingAttributes.Height := 5;
TxInkCollector.DefaultDrawingAttributes.IgnorePressure := false;
TxInkCollector.DefaultDrawingAttributes.PenTip := IPT_Ball;
// IPT_Rectangle;
TxInkCollector.MousePointer := IMP_Default;
{
IRO_Black = $00000001;
IRO_NotMergePen = $00000002;
IRO_MaskNotPen = $00000003;
IRO_NotCopyPen = $00000004;
IRO_MaskPenNot = $00000005;
IRO_Not = $00000006;
IRO_XOrPen = $00000007;
IRO_NotMaskPen = $00000008;
IRO_MaskPen = $00000009;
IRO_NotXOrPen = $0000000A;
IRO_NoOperation = $0000000B;
IRO_MergeNotPen = $0000000C;
IRO_CopyPen = $0000000D;
IRO_MergePenNot = $0000000E;
IRO_MergePen = $0000000F;
IRO_White = $00000010;
}
{
IMP_Default = $00000000;
IMP_Arrow = $00000001;
IMP_Crosshair = $00000002;
IMP_Ibeam = $00000003;
IMP_SizeNESW = $00000004;
IMP_SizeNS = $00000005;
IMP_SizeNWSE = $00000006;
IMP_SizeWE = $00000007;
IMP_UpArrow = $00000008;
IMP_Hourglass = $00000009;
IMP_NoDrop = $0000000A;
IMP_ArrowHourglass = $0000000B;
IMP_ArrowQuestion = $0000000C;
IMP_SizeAll = $0000000D;
IMP_Hand = $0000000E;
IMP_Custom = $00000063;
}
TxInkCollector.DefaultDrawingAttributes.RasterOperation := IRO_CopyPen;
TxInkCollector.DefaultDrawingAttributes.Transparency := 0;
TxInkCollector.DefaultDrawingAttributes.width := 53;
TxInkCollector.Enabled := true;
end;
procedure Tpeninput_f.AllClear; //펜 이미지 삭제
var
strokesToDelete: inkStrokes;
begin
try
strokesToDelete := TxInkCollector.Ink.Strokes;
if not TxInkCollector.CollectingInk then
begin
TxInkCollector.Ink.DeleteStrokes(strokesToDelete);
pnlPen.Refresh;
end
else
Showmessage('Cannot clear ink while the ink collector is busy.');
// TxInkCollector.Ink.DeleteStrokes(strokesToDelete);
except
on E: Exception do
ExceptLogging('penAllClear:' + E.Message);
end;
end;
function Tpeninput_f.LoadPenChartImage(varChartseq: Double; varRow: integer):
string;
var
loadedInk: TinkDisp;
BinSize: integer;
nFileStream: Tfilestream;
BinData: array of byte;
S: string;
i: integer;
aString: TStringList;
MemSize: Integer;
BStream: TStream;
A: string;
Buffer: array of Byte;
VarBMP: TBitMap;
signature, ms: TMemoryStream;
// img: TGIFImage;
bt: array of byte;
varRowHeight: integer;
begin
// result := '';
// try
// with dm_f.sqlTemp do
// begin
// Close;
// SQL.Clear;
// Sql.Add('select * from ma_chart_i ');
// Sql.Add('where chartseq= :chartseq');
// ParamByName('chartseq').value := varChartSeq;
//
// Open;
//
// if not isEmpty then
// begin
// try
//
// BStream :=
// CreateBlobStream(FieldByName('ChartImage'),
// bmRead);
// MemSize := BStream.Size;
// SetLength(Buffer, MemSize);
// Inc(MemSize);
// BStream.Read(Pointer(Buffer)^, MemSize);
// for i := 0 to Memsize - 1 do
// begin
// A := A + Char(Buffer[i]);
// end;
//
// try
// aString := TStringList.Create;
// aString.Add(A);
// aString.SaveToFile(ExtractFilePath(ParamStr(0)) + 'temp\TempImage\' + floatTostr(varChartSeq) + '.txt');
// finally
// aString.Free;
// end;
//
// finally
// BStream.Free;
//
// end;
//
// S := ExtractFilePath(ParamStr(0)) + 'temp\TempImage\'
// + floatTostr(varChartSeq) + '.txt';
// nFileStream := TFileStream.Create(S, fmOpenRead);
// BinSize := nFileStream.Size;
// SetLength(BinData, BinSize);
//
// nFileStream.Position := 0;
// for i := 0 to BinSize - 3 do
// begin
// nFileStream.Read(BinData[i], 1);
// end;
// nFileStream.Free;
//
// TxInkCollector.Enabled := false;
//
// loadedInk := TinkDisp.Create(pnlPen);
// loadedInk.Load(BinData);
// TxInkCollector.Ink := loadedInk.Clone;
// TxInkCollector.Enabled := false;
//
// ms := TMemoryStream.Create;
// signature := TMemoryStream.Create;
// img := TGIFImage.Create;
//
//
// try
// bt := TxInkCollector.Ink.Save(IPF_GIF,
// IPCM_MaximumCompression);
// //IPCM_NoCompression); //IPCM_Default);
// ms.Size := length(bt);
// ms.Write(Pointer(bt)^, length(bt));
// ms.Position := 0;
// img.LoadFromStream(ms);
//
// img.Bitmap.SaveToStream(signature);
// varRowHeight := img.Height;
// signature.Position := 0;
// img.SaveToFile(extractFilePath(paramstr(0)) +
// 'temp\TempImage\' +
// floattostr(varChartSeq) +
// '.gif');
//
// // now to save the stream to a database you do the following
// //TBlobField(dataset.FieldByName('NameBlobField')).LoadFromStream(signature);
//
// result := extractFilePath(paramstr(0)) +
// 'temp\TempImage\' +
// floattostr(varChartSeq) +
// '.gif'
//
// finally // wrap up
// img.Destroy;
// signature.free;
// ms.Free;
// end; // try/finally
// //ShrinkWithAspectRatio
// { grdProgress.CreatePicture(3, varRow, false,
// noStretch, 0,
// AdvGrid.haLeft,
// AdvGrid.vaTop).LoadFromFile(ExtractFilePath(paramStr(0)) + 'temp\TempImage\' + floattostr(varChartSeq) + '.gif');
//
// grdProgress.RowHeights[varRow] :=
// varRowHeight;
// }
// end;
// end;
// except
// on E: Exception do
// ExceptLogging('LoadPenChartImage:' + E.Message);
// end;
end;
procedure Tpeninput_f.LoadPenChartImageForMod(varChartseq: Double);
var
loadedInk: TinkDisp;
BinSize: integer;
nFileStream: Tfilestream;
BinData: array of byte;
S: string;
i: integer;
aString: TStringList;
MemSize: Integer;
BStream: TStream;
A: string;
Buffer: array of Byte;
begin
allclear;
try
with dm_f.sqlTemp do
begin
Close;
SQL.Clear;
Sql.Add('select * from ma_chart_i ');
Sql.Add('where chartseq= :chartseq');
ParamByName('chartseq').value := varChartSeq;
Open;
if not isEmpty then
begin
try
BStream :=
CreateBlobStream(FieldByName('ChartImage'),
bmRead);
MemSize := BStream.Size;
SetLength(Buffer, MemSize);
Inc(MemSize);
BStream.Read(Pointer(Buffer)^, MemSize);
for i := 0 to Memsize - 1 do
begin
A := A + Char(Buffer[i]);
end;
try
aString := TStringList.Create;
aString.Add(A);
aString.SaveToFile(ExtractFilePath(ParamStr(0)) + 'temp\TempImage\' + floatTostr(varChartSeq) + '.txt');
finally
aString.Free;
end;
finally
BStream.Free;
end;
S := ExtractFilePath(ParamStr(0)) + 'temp\TempImage\'
+ floatTostr(varChartSeq) + '.txt';
nFileStream := TFileStream.Create(S, fmOpenRead);
BinSize := nFileStream.Size;
SetLength(BinData, BinSize);
nFileStream.Position := 0;
for i := 0 to BinSize - 3 do
begin
nFileStream.Read(BinData[i], 1);
end;
nFileStream.Free;
loadedInk := TinkDisp.Create(pnlPen);
loadedInk.Load(BinData);
TxInkCollector.Ink := loadedInk.Clone;
TxInkCollector.Enabled := false;
end;
end;
except
on E: Exception do
ExceptLogging('LoadPenChartImageForMod:' + E.Message);
end;
end;
procedure TpenInput_f.saveimageChart(varMode: integer; varChartSeq: Double);
var
myBytes: array of Byte;
aString: TStringList;
A: string;
i, bufferSize: integer;
strJinDay: string;
signature, ms: TMemoryStream;
img: TGIFImage;
bt: array of byte;
varRowHeight: integer;
begin
try
//여기서 null 차트. 0:참고사항 1:CC 2:문진medical Hx 3:원장요구 4:환자요청 5:pi 6:imp 7:Plan 에 저장 후 seq값 가져오기
if varChartSeq = 0 then
begin
case loadType of
0: //참고사항
begin
with dm_f.sqlwork do
begin
strJinDay := varInputDate;
Close;
Sql.Clear;
Sql.Add('insert into hxSRemark');
Sql.Add('(srchart, srDate, srMemo, Portion, isImage) values');
Sql.Add('(:srchart, :srDate, :srMemo, :Portion, :isImage)');
ParamByName('srchart').AsString := ma_chart;
ParamByName('srDate').AsDate := strToDate(strJinday);
paramByName('srMemo').asMemo := '';
paramByName('Portion').asString := '';
paramByName('isImage').asString := '1';
execsql;
Close;
sql.Clear;
sql.Add(' Select max(ID) as MaxChartSeq from hxSRemark');
Open;
varChartSeq := fieldByName('maxChartSeq').asinteger;
end;
end;
1: //CC
begin
with dm_f.sqlwork do
begin
strJinDay := varInputDate;
Close;
Sql.Clear;
Sql.Add('insert into hxCC');
Sql.Add('(CCchart, CCDate, CCMemo, portion, isImage) values');
Sql.Add('(:CCchart, :CCDate, :CCMemo, :portion, :isImage)');
ParamByName('CCChart').AsString := ma_chart;
ParamByName('CCDate').AsDate := strToDate(strJinday);
paramByName('CCMemo').asMemo := '';
paramByName('Portion').asString := '';
paramByName('isImage').asString := '1';
execsql;
Close;
sql.Clear;
sql.Add(' Select max(seq) as MaxChartSeq from hxcc ');
Open;
varChartSeq := fieldByName('maxChartSeq').asinteger;
end;
end;
2: //문진
begin
with dm_f.sqlwork do
begin
strJinDay := varInputDate;
Close;
Sql.Clear;
Sql.Add('insert into hxMed');
Sql.Add('(Medchart, MedDate, MedMemo, portion, isImage) values');
Sql.Add('(:Medchart, :MedDate, :MedMemo, :portion, :isImage)');
ParamByName('Medchart').AsString := ma_chart;
ParamByName('MedDate').AsDate := strToDate(strJinday);
paramByName('MedMemo').asMemo := '';
paramByName('Portion').asString := '';
paramByName('isImage').asString := '1';
execsql;
Close;
sql.Clear;
sql.Add(' Select max(seq) as MaxChartSeq from hxMed ');
Open;
varChartSeq := fieldByName('maxChartSeq').asinteger;
end;
end;
3: //원장 요구사항
begin
with dm_f.sqlwork do
begin
strJinDay := varInputDate;
Close;
Sql.Clear;
Sql.Add('insert into hxDent');
Sql.Add('(Dchart, DDate, DMemo, portion, isImage) values');
Sql.Add('(:Dchart, :DDate, :DMemo, :portion, :isImage)');
ParamByName('Dchart').AsString := ma_chart;
ParamByName('dDate').AsDate := strToDate(strJinday);
paramByName('dMemo').asMemo := '';
paramByName('Portion').asString := '';
paramByName('isImage').asString := '1';
execsql;
Close;
sql.Clear;
sql.Add(' Select max(seq) as MaxChartSeq from hxDent ');
Open;
varChartSeq := fieldByName('maxChartSeq').asinteger;
end;
end;
4: //환자요청사항
begin
with dm_f.sqlwork do
begin
strJinDay := varInputDate;
Close;
Sql.Clear;
Sql.Add('insert into hxDesire');
Sql.Add('(DSchart, DSDate, DSMemo, portion, isImage) values');
Sql.Add('(:DSchart, :DSDate, :DSMemo, :portion, :isImage)');
ParamByName('Dschart').AsString := ma_chart;
ParamByName('dsDate').AsDate := strToDate(strJinday);
paramByName('dsMemo').asMemo := '';
paramByName('Portion').asString := '';
paramByName('isImage').asString := '1';
execsql;
Close;
sql.Clear;
sql.Add(' Select max(seq) as MaxChartSeq from hxDesire ');
Open;
varChartSeq := fieldByName('maxChartSeq').asinteger;
end;
end;
5: //Present Ilness
begin
with dm_f.sqlwork do
begin
strJinDay := varInputDate;
Close;
Sql.Clear;
Sql.Add('insert into hxPi');
Sql.Add('(chart, jin_day, descript, portion, isImage) values');
Sql.Add('(:chart, :jin_day, :descript, :portion, :isImage)');
ParamByName('Chart').AsString := ma_chart;
ParamByName('jin_day').AsDate := strToDate(strJinday);
paramByName('descript').asMemo := '';
paramByName('Portion').asString := '';
paramByName('isImage').asString := '1';
execsql;
Close;
sql.Clear;
sql.Add(' Select max(seq) as MaxChartSeq from hxPi ');
Open;
varChartSeq := fieldByName('maxChartSeq').asinteger;
end;
end;
6: //IMP
begin
with dm_f.sqlwork do
begin
strJinDay := varInputDate;
Close;
Sql.Clear;
Sql.Add('insert into hximp');
Sql.Add('(chart, jin_day, descript, portion, isImage) values');
Sql.Add('(:chart, :jin_day, :descript, :portion, :isImage)');
ParamByName('Chart').AsString := ma_chart;
ParamByName('jin_day').AsDate := strToDate(strJinday);
paramByName('descript').asMemo := '';
paramByName('Portion').asString := '';
paramByName('isImage').asString := '1';
execsql;
Close;
sql.Clear;
sql.Add(' Select max(seq) as MaxChartSeq from hximp ');
Open;
varChartSeq := fieldByName('maxChartSeq').asinteger;
end;
end;
7: //Plan
begin
with dm_f.sqlwork do
begin
strJinDay := varInputDate;
Close;
Sql.Clear;
Sql.Add('insert into hxPlan');
Sql.Add('(chart, jin_day, descript, portion, isImage) values');
Sql.Add('(:chart, :jin_day, :descript, :portion, :isImage)');
ParamByName('Chart').AsString := ma_chart;
ParamByName('jin_day').AsDate := strToDate(strJinday);
paramByName('descript').asMemo := '';
paramByName('Portion').asString := '';
paramByName('isImage').asString := '1';
execsql;
Close;
sql.Clear;
sql.Add(' Select max(seq) as MaxChartSeq from hxPlan ');
Open;
varChartSeq := fieldByName('maxChartSeq').asinteger;
end;
end;
else
begin
with dm_f.sqlwork do
begin
Close;
Sql.Clear;
strJinDay := varInputDate;
SQL.Text := 'INSERT INTO ma_chart_s ( ' + #13#10 +
' chart ' + #13#10 +
' ,jin_day ' + #13#10 +
' ,code ' + #13#10 +
' ,descript ' + #13#10 +
' ,Price ' + #13#10 +
' ,portion ' + #13#10 +
' ,nOrd ' + #13#10 +
' ,Doctor ' + #13#10 +
' ,Hygine ' + #13#10 +
' ,userPcName' + #13#10 +
' ,isImage ' + #13#10 +
' ,userID ' + #13#10 +
' ) VALUES ( ' + #13#10 +
' ' +
QuotedStr(ma_chart) + #13#10 +
' ,' + QuotedStr(strJinDay) +
#13#10 +
' ,' + QuotedStr('Tx.') + #13#10
+
' ,' + QuotedStr('') + #13#10 +
' ,' + QuotedStr('') + #13#10 +
' ,' + QuotedStr('') +
#13#10 +
' ,' + QuotedStr('') + #13#10 +
' ,' + QuotedStr(varTeam) +
#13#10 +
' ,' + QuotedStr(varDam) +
#13#10 +
' ,' + QuotedStr(SysName) + #13#10
+
' ,' + QuotedStr('1') //isImage
+ #13#10 +
' ,' + QuotedStr(main_f.V_UserID)
+ #13#10 +
' )';
ExecSQL;
Close;
sql.Clear;
sql.Add(' Select max(chartseq) as MaxChartSeq from ma_Chart_s ');
Open;
varChartSeq := fieldByName('maxChartSeq').asinteger;
end;
end;
end;
end;
except
on E: Exception do
begin
ExceptLogging('saveChartClick:' + E.Message);
end;
end;
ms := TMemoryStream.Create;
signature := TMemoryStream.Create;
img := TGIFImage.Create;
try
bt := TxInkCollector.Ink.Save(IPF_GIF, IPCM_MaximumCompression);
//IPCM_NoCompression); //IPCM_Default);
ms.Size := length(bt);
ms.Write(Pointer(bt)^, length(bt));
ms.Position := 0;
img.LoadFromStream(ms);
//signed := true;
img.Bitmap.SaveToStream(signature);
varRowHeight := img.Height;
signature.Position := 0;
img.SaveToFile(ExtractFilePath(ParamStr(0)) + 'temp\tempImage\' +
floattostr(varChartSeq) + '.gif');
except
on E: Exception do
begin
ExceptLogging('saveChartClick:' + E.Message);
img.Destroy;
signature.free;
ms.Free;
end;
end;
try
myBytes := TxInkCollector.Ink.Save(IPF_InkSerializedFormat,
IPCM_Default); //(0,0);
bufferSize := length(myBytes);
aString := TStringList.Create;
for i := 0 to bufferSize - 1 do
begin
A := A + Char(myBytes[i]);
end;
aString.Add(A);
aString.SaveToFile(ExtractFilePath(ParamStr(0)) + 'temp\TempImage\'
+ floattostr(varChartSeq) + '.txt');
aString.Free;
with dm_f.sqlwork do
begin
Close;
sql.Clear;
sql.Add(' Select * from ma_Chart_i ');
sql.Add(' Where chartseq = :chartseq and kind=:kind');
ParamByName('chartSeq').value := varChartSeq;
ParamByName('kind').value := inttostr(loadType);
Open;
last;
if not IsEmpty then
begin
if Application.MessageBox(pchar('[' +
main_f.edtName.text +
']님의 입력된 문서를' + #13#13 +
'수정하시겠습니까?.'), '알림', MB_YESNO) =
IDYES then
begin
try
with dm_f.sqlTemp do
begin
Close;
sql.Clear;
sql.Add(' Update ma_Chart_i Set ');
sql.Add(' sDate = :sDate, chartImage = :ChartImage , modDay =:modDay');
sql.Add(' Where ChartSeq = :chartSeq and kind=:kind');
ParamByName('modDay').asDateTime := now;
ParamByName('chartSeq').asString := floattostr(varChartSeq);
ParamByName('kind').asString := inttostr(LoadType);
ParamByName('sDate').asString := formatdateTime('YYYY-MM-DD', now);
ParamByName('ChartImage').LoadFromFile(ExtractFilePath(ParamStr(0)) + 'temp\TempImage\' + floattostr(varChartSeq) + '.txt', ftblob);
ExecSQL;
Application.MessageBox(Pchar('입력하신 정보가 수정 되었습니다.'), '알림', mb_ok + mb_IconInformation);
end;
except
on E: Exception do
ExceptLogging('Tdm_f.saveimageChart:'
+ E.Message);
end;
end;
end
else
begin
try
with dm_f.sqlWork do
begin
Close;
sql.Clear;
sql.Add(' Insert Into ma_Chart_i ');
sql.Add(' (chart, chartImage, SDate, chartSeq, kind, modDay) ');
sql.Add(' VALUES( :chart, :chartImage, :SDate, :chartSeq, :kind, :modDay) ');
ParamByName('modDay').asDateTime := now;
ParamByName('chart').asString := ma_chart;
ParamByName('kind').asString := inttostr(LoadType);
ParamByName('chartSeq').asString := floattostr(varChartSeq);
ParamByName('sDate').asstring := formatdateTime('YYYY-MM-DD', now);
ParamByName('ChartImage').LoadFromFile(ExtractFilePath(ParamStr(0)) + 'temp\TempImage\' + floattostr(varChartSeq) + '.txt', ftblob);
ExecSQL;
Application.MessageBox(Pchar('입력하신 정보가 저장 되었습니다.'), '알림', mb_ok + mb_IconInformation);
end;
except
on E: Exception do
ExceptLogging('Tdm_f.saveimageChart:'
+
E.Message);
end;
end;
end;
except
on E: Exception do
begin
ExceptLogging('saveChartClick:' + E.Message);
img.Destroy;
signature.free;
ms.Free;
end;
end;
end;
procedure Tpeninput_f.EraseStrokes(varptX: integer; varPtY: integer;
varcurrentStroke: inkStrokes);
var
strokesHit: inkStrokes;
begin
// Use HitTest to find the collection of strokes that are intersected
// by the point. The HitTestRadius constant is used to specify the
// radius of the hit test circle in ink space coordinates (1 unit = .01mm).
strokesHit := TxInkCollector.Ink.HitTestCircle(varptX, varPtY, 30);
if (varcurrentStroke <> nil) then
//and (strokesHit.Contains(varcurrentStroke))then
//strokesHit
strokesHit.Remove(varcurrentStroke.Item(0));
// Delete all strokes that were hit by the point
TxInkCollector.Ink.DeleteStrokes(strokesHit);
if (strokesHit.Count > 0) then
begin
// Repaint the screen to reflect the change
pnlPen.Refresh;
end;
end;
procedure Tpeninput_f.PenKindChange(varPen: integer; sender: TObject);
begin
try
viewMode := 1;
case varPen of
0: //싸인펜
begin
TxInkCollector.DefaultDrawingAttributes.Transparency := 0;
TxInkCollector.DefaultDrawingAttributes.IgnorePressure := false;
TxInkCollector.Enabled := true;
end;
1: //볼펜
begin
TxInkCollector.DefaultDrawingAttributes.Transparency := 0;
TxInkCollector.DefaultDrawingAttributes.IgnorePressure := true;
end;
2: //형광펜
begin
TxInkCollector.DefaultDrawingAttributes.Transparency := 100;
TxInkCollector.DefaultDrawingAttributes.IgnorePressure := true;
end;
end;
// btnBluesignpen.Down := false;
// btnRedsignpen.Down := false;
// btnGreensignpen.Down := false;
// btnBlackSignpen.Down := false;
// (sender as TButton).Down := true;
TxInkCollector.Enabled := true;
except
on E: Exception do
ExceptLogging('Tdm_f.ColorChange:' + E.Message);
end;
end;
procedure Tpeninput_f.ColorChange(varColor: tColor);
begin
try
TxInkCollector.DefaultDrawingAttributes.Color := varColor;
TxInkCollector.Enabled := true;
except
on E: Exception do
ExceptLogging('ColorChange:' + E.Message);
end;
end;
procedure Tpeninput_f.ThickChange(varThick: integer);
begin
try
TxInkCollector.DefaultDrawingAttributes.Width := varthick;
viewMode := 1;
TxInkCollector.Enabled := true;
except
on E: Exception do
ExceptLogging('ThickChange:' + E.Message);
end;
end;
procedure Tpeninput_f.pnlPenMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
try
if (viewmode = 2) and (Shift = [ssLeft]) then
begin
TxInkCollector.Renderer.PixelToInkSpace(pnlPen.Handle, X,
Y);
EraseStrokes(X, Y, nil);
exit;
end;
except
on E: Exception do
ExceptLogging('ImgScreenMouseMove:' + E.Message);
end;
end;
procedure Tpeninput_f.btnBlueSignPenClick(Sender: TObject);
begin
PenKindChange(strtoInt(copy((sender as TButton).caption, 1,
1)), (sender as TButton));
ColorChange(stringToColor(substr((sender as TButton).caption,
2,
'_')));
ThickChange(strtoInt(substr((sender as TButton).caption, 3,
'_')));
end;
procedure Tpeninput_f.N7Click(Sender: TObject);
begin
ThickChange((sender as TMenuItem).Tag);
end;
procedure Tpeninput_f.btnEraserClick(Sender: TObject);
begin
// TxInkCollector.MousePointer := IMP_Crosshair;
// Screen.Cursor := CR_ER2;
try
viewMode := 2;
TxInkCollector.Enabled := false;
except
on E: Exception do
ExceptLogging('Tdm_f.btnEraserClick:' + E.Message);
end;
end;
procedure Tpeninput_f.AdvToolBarButton1Click(Sender: TObject);
begin
if varPeninputMode = 0 then
saveimageChart(varPeninputMode, 0)
else
saveimageChart(varPeninputMode, varChartSeq);
if assigned(saveChamgo_f) then
saveChamgo_f.LoadChamgo2(ma_chart);
close;
// selectChartSDataAdv(ma_chart, '', '');
end;
end.
|
unit IntegerX;
interface
uses
System.SysUtils, System.Math, System.Generics.Collections;
type
/// <summary>
/// Extended Precision Integer.
/// </summary>
/// <remarks>
/// <para>Inspired by the Microsoft.Scripting.Math.BigInteger code,
/// the java.math.BigInteger code, but mostly by Don Knuth's Art of Computer Programming, Volume 2.</para>
/// <para>The same as most other BigInteger representations, this implementation uses a sign/magnitude representation.</para>
/// <para>The magnitude is represented by an array of UInt32 in big-endian order.
/// <para>TIntegerX's are immutable.</para>
/// </remarks>
TIntegerX = record
strict private
/// <summary>
/// The sign of the integer. Must be -1, 0, +1.
/// </summary>
_sign: SmallInt;
/// <summary>
/// The magnitude of the integer (big-endian).
/// </summary>
/// <remarks>
/// <para>Big-endian = _data[0] is the most significant digit.</para>
/// <para> Some invariants:</para>
/// <list>
/// <item>If the integer is zero, then _data must be length zero array and _sign must be zero.</item>
/// <item>No leading zero UInt32.</item>
/// <item>Must be non-null. For zero, a zero-length array is used.</item>
/// </list>
/// These invariants imply a unique representation for every value.
/// They also force us to get rid of leading zeros after every operation that might create some.
/// </remarks>
_data: TArray<UInt32>;
/// <summary>
/// Getter function for <see cref="TIntegerX.Precision" />
/// </summary>
function GetPrecision: UInt32;
/// <summary>
/// Getter function for <see cref="TIntegerX.Zero" />
/// </summary>
class function GetZero: TIntegerX; static;
/// <summary>
/// Getter function for <see cref="TIntegerX.One" />
/// </summary>
class function GetOne: TIntegerX; static;
/// <summary>
/// Getter function for <see cref="TIntegerX.Two" />
/// </summary>
class function GetTwo: TIntegerX; static;
/// <summary>
/// Getter function for <see cref="TIntegerX.Five" />
/// </summary>
class function GetFive: TIntegerX; static;
/// <summary>
/// Getter function for <see cref="TIntegerX.Ten" />
/// </summary>
class function GetTen: TIntegerX; static;
/// <summary>
/// Getter function for <see cref="TIntegerX.NegativeOne" />
/// </summary>
class function GetNegativeOne: TIntegerX; static;
/// <summary>
/// Append a sequence of digits representing <paramref name="rem"/> to the <see cref="TStringBuilder"/>,
/// possibly adding leading null chars if specified.
/// </summary>
/// <param name="sb">The <see cref="TStringBuilder"/> to append characters to</param>
/// <param name="rem">The 'super digit' value to be converted to its string representation</param>
/// <param name="radix">The radix for the conversion</param>
/// <param name="charBuf">A character buffer used for temporary storage, big enough to hold the string
/// representation of <paramref name="rem"/></param>
/// <param name="leadingZeros">Whether or not to pad with the leading zeros if the value is not large enough to fill the buffer</param>
/// <remarks>Pretty much identical to DLR BigInteger.AppendRadix</remarks>
class procedure AppendDigit(var sb: TStringBuilder; rem: UInt32;
radix: UInt32; charBuf: TArray<Char>; leadingZeros: Boolean); static;
/// <summary>
/// Convert an (extended) digit to its value in the given radix.
/// </summary>
/// <param name="c">The character to convert</param>
/// <param name="radix">The radix to interpret the character in</param>
/// <param name="v">Set to the converted value</param>
/// <returns><value>true</value> if the conversion is successful; <value>false</value> otherwise</returns>
class function TryComputeDigitVal(c: Char; radix: Integer; out v: UInt32)
: Boolean; static;
/// <summary>
/// Return an indication of the relative values of two UInt32 arrays treated as unsigned big-endian values.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns><value>-1</value> if the first is less than second; <value>0</value> if equal; <value>+1</value> if greater</returns>
class function Compare(x: TArray<UInt32>; y: TArray<UInt32>): SmallInt;
overload; static;
/// <summary>
/// Compute the greatest common divisor of two <see cref="TIntegerX"/> values.
/// </summary>
/// <param name="a">The first value</param>
/// <param name="b">The second value</param>
/// <returns>The greatest common divisor</returns>
/// <remarks>Does the standard Euclidean algorithm until the two values are approximately
/// the same length, then switches to a binary gcd algorithm.</remarks>
class function HybridGcd(a: TIntegerX; b: TIntegerX): TIntegerX; static;
/// <summary>
/// Return the greatest common divisor of two uint values.
/// </summary>
/// <param name="a">The first value</param>
/// <param name="b">The second value</param>
/// <returns>The greatest common divisor</returns>
/// <remarks>Uses Knuth, 4.5.5, Algorithm B, highly optimized for getting rid of powers of 2.
/// </remarks>
class function BinaryGcd(a: UInt32; b: UInt32): UInt32; overload; static;
/// <summary>
/// Compute the greatest common divisor of two <see cref="TIntegerX"/> values.
/// </summary>
/// <param name="a">The first value</param>
/// <param name="b">The second value</param>
/// <returns>The greatest common divisor</returns>
/// <remarks>Intended for use when the two values have approximately the same magnitude.</remarks>
class function BinaryGcd(a: TIntegerX; b: TIntegerX): TIntegerX;
overload; static;
/// <summary>
/// Returns the number of trailing zero bits in a UInt32 value.
/// </summary>
/// <param name="val">The value</param>
/// <returns>The number of trailing zero bits </returns>
class function TrailingZerosCount(val: UInt32): Integer; static;
class function BitLengthForUInt32(x: UInt32): UInt32; static;
/// <summary>
/// Counts Leading zero bits.
/// This algo is in a lot of places.
/// </summary>
/// <param name="x">value to count leading zero bits on.</param>
/// <returns>leading zero bit count.</returns>
/// <seealso href="http://aggregate.org/MAGIC/#Leading%20Zero%20Count">[Leading Zero Count]</seealso>
class function LeadingZeroCount(x: UInt32): UInt32; static;
/// <summary>
/// This algo is in a lot of places.
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
/// <seealso href="http://aggregate.org/MAGIC/#Population%20Count%20(Ones%20Count)">[Ones Count]</seealso>
class function BitCount(x: UInt32): UInt32; overload; static;
/// <summary>
/// Returns the index of the lowest set bit in this instance's magnitude.
/// </summary>
/// <returns>The index of the lowest set bit</returns>
function GetLowestSetBit(): Integer;
/// <summary>
/// Returns the specified uint-digit pretending the number
/// is a little-endian two's complement representation.
/// </summary>
/// <param name="n">The index of the digit to retrieve</param>
/// <returns>The uint at the given index.</returns>
/// <remarks>If iterating through the data array, better to use
/// the incremental version that keeps track of whether or not
/// the first nonzero has been seen.</remarks>
function Get2CDigit(n: Integer): UInt32; overload;
/// <summary>
/// Returns the specified uint-digit pretending the number
/// is a little-endian two's complement representation.
/// </summary>
/// <param name="n">The index of the digit to retrieve</param>
/// <param name="seenNonZero">Set to true if a nonZero byte is seen</param>
/// <returns>The UInt32 at the given index.</returns>
function Get2CDigit(n: Integer; var seenNonZero: Boolean): UInt32; overload;
/// <summary>
/// Returns an UInt32 of all zeros or all ones depending on the sign (pos, neg).
/// </summary>
/// <returns>The UInt32 corresponding to the sign</returns>
function Get2CSignExtensionDigit(): UInt32;
/// <summary>
/// Returns the index of the first nonzero digit (there must be one), pretending the value is little-endian.
/// </summary>
/// <returns></returns>
function FirstNonzero2CDigitIndex(): Integer;
/// <summary>
/// Return the twos-complement of the integer represented by the UInt32 array.
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
class function MakeTwosComplement(a: TArray<UInt32>)
: TArray<UInt32>; static;
/// <summary>
/// Add two UInt32 arrays (big-endian).
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
class function Add(x: TArray<UInt32>; y: TArray<UInt32>): TArray<UInt32>;
overload; static;
/// <summary>
/// Add one digit.
/// </summary>
/// <param name="x"></param>
/// <param name="newDigit"></param>
/// <returns></returns>
class function AddSignificantDigit(x: TArray<UInt32>; newDigit: UInt32)
: TArray<UInt32>; overload; static;
/// <summary>
/// Subtract one instance from another (larger first).
/// </summary>
/// <param name="xs"></param>
/// <param name="ys"></param>
/// <returns></returns>
class function Subtract(xs: TArray<UInt32>; ys: TArray<UInt32>)
: TArray<UInt32>; overload; static;
/// <summary>
/// Multiply two big-endian UInt32 arrays.
/// </summary>
/// <param name="xs"></param>
/// <param name="ys"></param>
/// <returns></returns>
class function Multiply(xs: TArray<UInt32>; ys: TArray<UInt32>)
: TArray<UInt32>; overload; static;
/// <summary>
/// Return the quotient and remainder of dividing one <see cref="TIntegerX"/> by another.
/// </summary>
/// <param name="x">The dividend</param>
/// <param name="y">The divisor</param>
/// <param name="q">Set to the quotient</param>
/// <param name="r">Set to the remainder</param>
/// <remarks>Algorithm D in Knuth 4.3.1.</remarks>
class procedure DivMod(x: TArray<UInt32>; y: TArray<UInt32>;
out q: TArray<UInt32>; out r: TArray<UInt32>); overload; static;
/// <summary>
///
/// </summary>
/// <param name="xnorm"></param>
/// <param name="r"></param>
/// <param name="shift"></param>
class procedure Unnormalize(xnorm: TArray<UInt32>; out r: TArray<UInt32>;
shift: Integer); static;
/// <summary>
/// Do a multiplication and addition in place.
/// </summary>
/// <param name="data">The subject of the operation, receives the result</param>
/// <param name="mult">The value to multiply by</param>
/// <param name="addend">The value to add in</param>
class procedure InPlaceMulAdd(var data: TArray<UInt32>; mult: UInt32;
addend: UInt32); static;
/// <summary>
/// Return a (possibly new) UInt32 array with leading zero uints removed.
/// </summary>
/// <param name="data">The UInt32 array to prune</param>
/// <returns>A (possibly new) UInt32 array with leading zero UInt32's removed.</returns>
class function RemoveLeadingZeros(data: TArray<UInt32>)
: TArray<UInt32>; static;
class function StripLeadingZeroBytes(a: TArray<Byte>)
: TArray<UInt32>; static;
class function makePositive(a: TArray<Byte>): TArray<UInt32>; static;
/// <summary>
/// Do a division in place and return the remainder.
/// </summary>
/// <param name="data">The value to divide into, and where the result appears</param>
/// <param name="index">Starting index in <paramref name="data"/> for the operation</param>
/// <param name="divisor">The value to dif</param>
/// <returns>The remainder</returns>
/// <remarks>Pretty much identical to DLR BigInteger.div, except DLR's is little-endian
/// and this is big-endian.</remarks>
class function InPlaceDivRem(var data: TArray<UInt32>; var index: Integer;
divisor: UInt32): UInt32; static;
/// <summary>
/// Divide a big-endian UInt32 array by a UInt32 divisor, returning the quotient and remainder.
/// </summary>
/// <param name="data">A big-endian UInt32 array</param>
/// <param name="divisor">The value to divide by</param>
/// <param name="quotient">Set to the quotient (newly allocated)</param>
/// <returns>The remainder</returns>
class function CopyDivRem(data: TArray<UInt32>; divisor: UInt32;
out quotient: TArray<UInt32>): UInt32; static;
function signInt(): Integer;
function getInt(n: Integer): Integer;
function firstNonzeroIntNum(): Integer;
const
/// <summary>
/// The number of bits in one 'digit' of the magnitude.
/// </summary>
BitsPerDigit = 32; // UInt32 implementation
/// <summary>
/// Exponent bias in the 64-bit floating point representation.
/// </summary>
DoubleExponentBias = 1023;
/// <summary>
/// The size in bits of the significand in the 64-bit floating point representation.
/// </summary>
DoubleSignificandBitLength = 52;
/// <summary>
/// How much to shift to accommodate the exponent and the binary digits of the significand.
/// </summary>
DoubleShiftBias = DoubleExponentBias + DoubleSignificandBitLength;
/// <summary>
/// The minimum radix allowed in parsing.
/// </summary>
MinRadix = 2;
/// <summary>
/// The maximum radix allowed in parsing.
/// </summary>
MaxRadix = 36;
/// <summary>
/// Max UInt32 value.
/// </summary>
MaxUInt32Value = 4294967295;
/// <summary>
/// Min SmallInt value.
/// </summary>
MinSmallIntValue = -32768;
/// <summary>
/// Max SmallInt value.
/// </summary>
MaxSmallIntValue = 32767;
/// <summary>
/// Min ShortInt value.
/// </summary>
MinShortIntValue = -128;
/// <summary>
/// Max ShortInt value.
/// </summary>
MaxShortIntValue = 127;
/// <summary>
/// Max Word value.
/// </summary>
MaxWordValue = 65535;
class var
/// <summary>
/// FUIntLogTable.
/// </summary>
FUIntLogTable: TArray<UInt32>;
/// <summary>
/// The maximum number of digits in radix[i] that will fit into a UInt32.
/// </summary>
/// <remarks>
/// <para>FRadixDigitsPerDigit[i] = floor(log_i (2^32 - 1))</para>
/// </remarks>
FRadixDigitsPerDigit: TArray<Integer>;
/// <summary>
/// The super radix (power of given radix) that fits into a UInt32.
/// </summary>
/// <remarks>
/// <para>FSuperRadix[i] = 2 ^ FRadixDigitsPerDigit[i]</para>
/// </remarks>
FSuperRadix: TArray<UInt32>;
/// <summary>
/// The number of bits in one digit of radix[i] times 1024.
/// </summary>
/// <remarks>
/// <para>FBitsPerRadixDigit[i] = ceiling(1024*log_2(i))</para>
/// <para>The value is multiplied by 1024 to avoid fractions. Users will need to divide by 1024.</para>
/// </remarks>
FBitsPerRadixDigit: TArray<Integer>;
/// <summary>
/// The value at index i is the number of trailing zero bits in the value i.
/// </summary>
FTrailingZerosTable: TArray<Byte>;
class constructor Create();
public
/// <summary>
/// Support for TDecimalX, to compute precision.
/// </summary>
property Precision: UInt32 read GetPrecision;
/// <summary>
/// A Zero.
/// </summary>
class property Zero: TIntegerX read GetZero;
/// <summary>
/// A Positive One.
/// </summary>
class property One: TIntegerX read GetOne;
/// <summary>
/// A Two.
/// </summary>
class property Two: TIntegerX read GetTwo;
/// <summary>
/// A Five.
/// </summary>
class property Five: TIntegerX read GetFive;
/// <summary>
/// A Ten.
/// </summary>
class property Ten: TIntegerX read GetTen;
/// <summary>
/// A Negative One.
/// </summary>
class property NegativeOne: TIntegerX read GetNegativeOne;
/// <summary>
/// Create a <see cref="TIntegerX"/> from an unsigned Int64 value.
/// </summary>
/// <param name="v">The value</param>
/// <returns>A <see cref="TIntegerX"/>.</returns>
class function Create(v: UInt64): TIntegerX; overload; static;
/// <summary>
/// Create a <see cref="TIntegerX"/> from an unsigned integer value.
/// </summary>
/// <param name="v">The value</param>
/// <returns>A <see cref="TIntegerX"/>.</returns>
class function Create(v: UInt32): TIntegerX; overload; static;
/// <summary>
/// Create a <see cref="TIntegerX"/> from an (signed) Int64 value.
/// </summary>
/// <param name="v">The value</param>
/// <returns>A <see cref="TIntegerX"/>.</returns>
class function Create(v: Int64): TIntegerX; overload; static;
/// <summary>
/// Create a <see cref="TIntegerX"/> from an (signed) Integer value.
/// </summary>
/// <param name="v">The value</param>
/// <returns>A <see cref="TIntegerX"/>.</returns>
class function Create(v: Integer): TIntegerX; overload; static;
/// <summary>
/// Create a <see cref="TIntegerX"/> from a double value.
/// </summary>
/// <param name="v">The value</param>
/// <returns>A <see cref="TIntegerX"/>.</returns>
class function Create(v: Double): TIntegerX; overload; static;
/// <summary>
/// Create a <see cref="TIntegerX"/> from a string.
/// </summary>
/// <param name="v">The value</param>
/// <returns>A <see cref="TIntegerX"/>.</returns>
class function Create(v: String): TIntegerX; overload; static;
/// <summary>
/// Create a <see cref="TIntegerX"/> from a string representation (radix 10).
/// </summary>
/// <param name="x">The string to convert</param>
/// <returns>A <see cref="TIntegerX"/></returns>
/// <exception cref="EFormatException">Thrown if there is a bad minus sign (more than one or not leading)
/// or if one of the digits in the string is not valid for the given radix.</exception>
class function Parse(x: String): TIntegerX; overload; static;
/// <summary>
/// Create a <see cref="TIntegerX"/> from a string representation in the given radix.
/// </summary>
/// <param name="s">The string to convert</param>
/// <param name="radix">The radix of the numeric representation</param>
/// <returns>A <see cref="TIntegerX"/></returns>
/// <exception cref="EFormatException">Thrown if there is a bad minus sign (more than one or not leading)
/// or if one of the digits in the string is not valid for the given radix.</exception>
class function Parse(s: String; radix: Integer): TIntegerX;
overload; static;
/// <summary>
/// Try to create a <see cref="TIntegerX"/> from a string representation (radix 10)
/// </summary>
/// <param name="s">The string to convert</param>
/// <param name="v">Set to the <see cref="TIntegerX"/> corresponding to the string, if possible; set to null otherwise</param>
/// <returns><c>True</c> if the string is parsed successfully; <c>false</c> otherwise</returns>
class function TryParse(s: String; out v: TIntegerX): Boolean;
overload; static;
/// <summary>
/// Try to create a <see cref="TIntegerX"/> from a string representation in the given radix)
/// </summary>
/// <param name="s">The string to convert</param>
/// <param name="radix">The radix of the numeric representation</param>
/// <param name="v">Set to the <see cref="TIntegerX"/> corresponding to the string, if possible; set to null otherwise</param>
/// <returns><c>True</c> if the string is parsed successfully; <c>false</c> otherwise</returns>
/// <remarks>
/// <para>This is pretty much the same algorithm as in the Java implementation.
/// That's pretty much what is in Knuth ACPv2ed3, Sec. 4.4, Method 1b.
/// That's pretty much what you'd do by hand.</para>
/// <para>The only enhancement is that instead of doing one digit at a time, you translate a group of contiguous
/// digits into a UInt32, then do a multiply by the radix and add of the UInt32.
/// The size of each group of digits is the maximum number of digits in the radix
/// that will fit into a UInt32.</para>
/// <para>Once you've decided to make that enhancement to Knuth's algorithm, you pretty much
/// end up with the Java version's code.</para>
/// </remarks>
class function TryParse(s: String; radix: Integer; out v: TIntegerX)
: Boolean; overload; static;
/// <summary>
/// Convert a substring in a given radix to its equivalent numeric value as a UInt32.
/// </summary>
/// <param name="val">The string containing the substring to convert</param>
/// <param name="startIndex">The start index of the substring</param>
/// <param name="len">The length of the substring</param>
/// <param name="radix">The radix</param>
/// <param name="u">Set to the converted value, or 0 if the conversion is unsuccessful</param>
/// <returns><value>true</value> if successful, <value>false</value> otherwise</returns>
/// <remarks>The length of the substring must be small enough that the converted value is guaranteed to fit
/// into a UInt32.</remarks>
class function TryParseUInt(val: String; startIndex: Integer; len: Integer;
radix: Integer; out u: UInt32): Boolean; static;
/// <summary>
/// Extract the sign bit from a byte-array representaition of a double.
/// </summary>
/// <param name="v">A byte-array representation of a double</param>
/// <returns>The sign bit, either 0 (positive) or 1 (negative)</returns>
class function GetDoubleSign(v: TArray<Byte>): Integer; static;
/// <summary>
/// Extract the significand (AKA mantissa, coefficient) from a byte-array representation of a double.
/// </summary>
/// <param name="v">A byte-array representation of a double</param>
/// <returns>The significand</returns>
class function GetDoubleSignificand(v: TArray<Byte>): UInt64; static;
/// <summary>
/// Extract the exponent from a byte-array representation of a double.
/// </summary>
/// <param name="v">A byte-array representation of a double</param>
/// <returns>The exponent</returns>
class function GetDoubleBiasedExponent(v: TArray<Byte>): Word; static;
/// <summary>
/// Algorithm from Hacker's Delight, section 11-4. for internal use only
/// </summary>
/// <param name="v">value to use.</param>
/// <returns>The Precision</returns>
class function UIntPrecision(v: UInt32): UInt32; static;
/// <summary>
///
/// </summary>
/// <param name="xnorm"></param>
/// <param name="xnlen"></param>
/// <param name="x"></param>
/// <param name="xlen"></param>
/// <param name="shift"></param>
/// <remarks>
/// <para>Assume Length(xnorm) := xlen + 1 or xlen;</para>
/// <para>Assume shift in [0,31]</para>
/// <para>This should be private, but I wanted to test it.</para>
/// </remarks>
class procedure Normalize(var xnorm: TArray<UInt32>; xnlen: Integer;
x: TArray<UInt32>; xlen: Integer; shift: Integer); static;
/// <summary>
/// Implicitly convert from Byte to <see cref="TIntegerX"/>.
/// </summary>
/// <param name="v">The value to convert</param>
/// <returns>The equivalent <see cref="TIntegerX"/></returns>
class operator Implicit(v: Byte): TIntegerX;
/// <summary>
/// Implicitly convert from ShortInt to <see cref="TIntegerX"/>.
/// </summary>
/// <param name="v">The value to convert</param>
/// <returns>The equivalent <see cref="TIntegerX"/></returns>
class operator Implicit(v: ShortInt): TIntegerX;
/// <summary>
/// Implicitly convert from SmallInt to <see cref="TIntegerX"/>.
/// </summary>
/// <param name="v">The value to convert</param>
/// <returns>The equivalent <see cref="TIntegerX"/></returns>
class operator Implicit(v: SmallInt): TIntegerX;
/// <summary>
/// Implicitly convert from Word to <see cref="TIntegerX"/>.
/// </summary>
/// <param name="v">The value to convert</param>
/// <returns>The equivalent <see cref="TIntegerX"/></returns>
class operator Implicit(v: Word): TIntegerX;
/// <summary>
/// Implicitly convert from UInt32 to <see cref="TIntegerX"/>.
/// </summary>
/// <param name="v">The value to convert</param>
/// <returns>The equivalent <see cref="TIntegerX"/></returns>
class operator Implicit(v: UInt32): TIntegerX;
/// <summary>
/// Implicitly convert from Integer to <see cref="TIntegerX"/>.
/// </summary>
/// <param name="v">The value to convert</param>
/// <returns>The equivalent <see cref="TIntegerX"/></returns>
class operator Implicit(v: Integer): TIntegerX;
/// <summary>
/// Implicitly convert from UInt64 to <see cref="TIntegerX"/>.
/// </summary>
/// <param name="v">The value to convert</param>
/// <returns>The equivalent <see cref="TIntegerX"/></returns>
class operator Implicit(v: UInt64): TIntegerX;
/// <summary>
/// Implicitly convert from Int64 to <see cref="TIntegerX"/>.
/// </summary>
/// <param name="v">The value to convert</param>
/// <returns>The equivalent <see cref="TIntegerX"/></returns>
class operator Implicit(v: Int64): TIntegerX;
/// <summary>
/// Explicitly convert from double to <see cref="TIntegerX"/>.
/// </summary>
/// <param name="v">The value to convert</param>
/// <returns>The equivalent <see cref="TIntegerX"/></returns>
class operator Explicit(self: Double): TIntegerX;
/// <summary>
/// Explicitly convert from <see cref="TIntegerX"/> to Double.
/// </summary>
/// <param name="i">The <see cref="TIntegerX"/> to convert</param>
/// <returns>The equivalent double</returns>
class operator Explicit(i: TIntegerX): Double;
/// <summary>
/// Explicitly convert from <see cref="TIntegerX"/> to Byte.
/// </summary>
/// <param name="i">The <see cref="TIntegerX"/> to convert</param>
/// <returns>The equivalent byte</returns>
class operator Explicit(self: TIntegerX): Byte;
/// <summary>
/// Explicitly convert from <see cref="TIntegerX"/> to ShortInt.
/// </summary>
/// <param name="i">The <see cref="TIntegerX"/> to convert</param>
/// <returns>The equivalent ShortInt</returns>
class operator Explicit(self: TIntegerX): ShortInt;
/// <summary>
/// Explicitly convert from <see cref="TIntegerX"/> to Word.
/// </summary>
/// <param name="i">The <see cref="TIntegerX"/> to convert</param>
/// <returns>The equivalent Word</returns>
class operator Explicit(self: TIntegerX): Word;
/// <summary>
/// Explicitly convert from <see cref="TIntegerX"/> to SmallInt.
/// </summary>
/// <param name="i">The <see cref="TIntegerX"/> to convert</param>
/// <returns>The equivalent SmallInt</returns>
class operator Explicit(self: TIntegerX): SmallInt;
/// <summary>
/// Explicitly convert from <see cref="TIntegerX"/> to UInt32.
/// </summary>
/// <param name="i">The <see cref="TIntegerX"/> to convert</param>
/// <returns>The equivalent UInt32</returns>
class operator Explicit(self: TIntegerX): UInt32;
/// <summary>
/// Explicitly convert from <see cref="TIntegerX"/> to Integer.
/// </summary>
/// <param name="i">The <see cref="TIntegerX"/> to convert</param>
/// <returns>The equivalent Integer</returns>
class operator Explicit(self: TIntegerX): Integer;
/// <summary>
/// Explicitly convert from <see cref="TIntegerX"/> to Int64.
/// </summary>
/// <param name="i">The <see cref="TIntegerX"/> to convert</param>
/// <returns>The equivalent Int64</returns>
class operator Explicit(self: TIntegerX): Int64;
/// <summary>
/// Explicitly convert from <see cref="TIntegerX"/> to UInt64.
/// </summary>
/// <param name="i">The <see cref="TIntegerX"/> to convert</param>
/// <returns>The equivalent UInt64</returns>
class operator Explicit(self: TIntegerX): UInt64;
/// <summary>
/// Compare two <see cref="TIntegerX"/>'s for equivalent numeric values.
/// </summary>
/// <param name="x">First value to compare</param>
/// <param name="y">Second value to compare</param>
/// <returns><value>true</value> if equivalent; <value>false</value> otherwise</returns>
class operator Equal(x: TIntegerX; y: TIntegerX): Boolean;
/// <summary>
/// Compare two <see cref="TIntegerX"/>'s for non-equivalent numeric values.
/// </summary>
/// <param name="x">First value to compare</param>
/// <param name="y">Second value to compare</param>
/// <returns><value>true</value> if not equivalent; <value>false</value> otherwise</returns>
class operator NotEqual(x: TIntegerX; y: TIntegerX): Boolean;
/// <summary>
/// Compare two <see cref="TIntegerX"/>'s for <.
/// </summary>
/// <param name="x">First value to compare</param>
/// <param name="y">Second value to compare</param>
/// <returns><value>true</value> if <; <value>false</value> otherwise</returns>
class operator LessThan(x: TIntegerX; y: TIntegerX): Boolean;
/// <summary>
/// Compare two <see cref="TIntegerX"/>'s for <=.
/// </summary>
/// <param name="x">First value to compare</param>
/// <param name="y">Second value to compare</param>
/// <returns><value>true</value> if <=; <value>false</value> otherwise</returns>
class operator LessThanOrEqual(x: TIntegerX; y: TIntegerX): Boolean;
/// <summary>
/// Compare two <see cref="TIntegerX"/>'s for >.
/// </summary>
/// <param name="x">First value to compare</param>
/// <param name="y">Second value to compare</param>
/// <returns><value>true</value> if >; <value>false</value> otherwise</returns>
class operator GreaterThan(x: TIntegerX; y: TIntegerX): Boolean;
/// <summary>
/// Compare two <see cref="TIntegerX"/>'s for >=.
/// </summary>
/// <param name="x">First value to compare</param>
/// <param name="y">Second value to compare</param>
/// <returns><value>true</value> if >=; <value>false</value> otherwise</returns>
class operator GreaterThanOrEqual(x: TIntegerX; y: TIntegerX): Boolean;
/// <summary>
/// Compute <paramref name="x"/> + <paramref name="y"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The sum</returns>
class operator Add(x: TIntegerX; y: TIntegerX): TIntegerX;
/// <summary>
/// Compute <paramref name="x"/> - <paramref name="y"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The difference</returns>
class operator Subtract(x: TIntegerX; y: TIntegerX): TIntegerX;
/// <summary>
/// Compute the plus of <paramref name="x"/>.
/// </summary>
/// <param name="x"></param>
/// <returns>The positive</returns>
class operator Positive(x: TIntegerX): TIntegerX;
/// <summary>
/// Compute the negation of <paramref name="x"/>.
/// </summary>
/// <param name="x"></param>
/// <returns>The negation</returns>
class operator Negative(x: TIntegerX): TIntegerX;
/// <summary>
/// Compute <paramref name="x"/> * <paramref name="y"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The product</returns>
class operator Multiply(x: TIntegerX; y: TIntegerX): TIntegerX;
/// <summary>
/// Compute <paramref name="x"/> div <paramref name="y"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The quotient</returns>
class operator IntDivide(x: TIntegerX; y: TIntegerX): TIntegerX;
/// <summary>
/// Compute <paramref name="x"/> mod <paramref name="y"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The modulus</returns>
class operator modulus(x: TIntegerX; y: TIntegerX): TIntegerX;
/// <summary>
/// Compute <paramref name="x"/> + <paramref name="y"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The sum</returns>
class function Add(x: TIntegerX; y: TIntegerX): TIntegerX; overload; static;
/// <summary>
/// Compute <paramref name="x"/> - <paramref name="y"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The difference</returns>
class function Subtract(x: TIntegerX; y: TIntegerX): TIntegerX;
overload; static;
/// <summary>
/// Compute the negation of <paramref name="x"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The negation</returns>
class function Negate(x: TIntegerX): TIntegerX; overload; static;
/// <summary>
/// Compute <paramref name="x"/> * <paramref name="y"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The product</returns>
class function Multiply(x: TIntegerX; y: TIntegerX): TIntegerX;
overload; static;
/// <summary>
/// Compute <paramref name="x"/> div <paramref name="y"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The quotient</returns>
class function Divide(x: TIntegerX; y: TIntegerX): TIntegerX;
overload; static;
/// <summary>
/// Returns <paramref name="x"/> mod <paramref name="y"/>.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The modulus</returns>
class function Modulo(x: TIntegerX; y: TIntegerX): TIntegerX;
overload; static;
/// <summary>
/// Compute the quotient and remainder of dividing one <see cref="TIntegerX"/> by another.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="remainder">Set to the remainder after division</param>
/// <returns>The quotient</returns>
class function DivRem(x: TIntegerX; y: TIntegerX; out remainder: TIntegerX)
: TIntegerX; overload; static;
/// <summary>
/// Compute the absolute value.
/// </summary>
/// <param name="x"></param>
/// <returns>The absolute value</returns>
class function Abs(x: TIntegerX): TIntegerX; overload; static;
/// <summary>
/// Returns a <see cref="TIntegerX"/> raised to an int power.
/// </summary>
/// <param name="x">The value to exponentiate</param>
/// <param name="exp">The exponent</param>
/// <returns>The exponent</returns>
class function Power(x: TIntegerX; exp: Integer): TIntegerX;
overload; static;
/// <summary>
/// Returns a <see cref="TIntegerX"/> raised to an <see cref="TIntegerX"/> power modulo another <see cref="TIntegerX"/>
/// </summary>
/// <param name="x"></param>
/// <param name="power"></param>
/// <param name="modulo"></param>
/// <returns> x ^ e mod m</returns>
class function ModPow(x: TIntegerX; Power: TIntegerX; Modulo: TIntegerX)
: TIntegerX; overload; static;
/// <summary>
/// Returns the greatest common divisor.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>The greatest common divisor</returns>
class function Gcd(x: TIntegerX; y: TIntegerX): TIntegerX; overload; static;
/// <summary>
/// Returns the bitwise-AND.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
class operator BitwiseAnd(x: TIntegerX; y: TIntegerX): TIntegerX;
/// <summary>
/// Returns the bitwise-OR.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
class operator BitwiseOr(x: TIntegerX; y: TIntegerX): TIntegerX;
/// <summary>
/// Returns the bitwise-complement.
/// </summary>
/// <param name="x"></param>
/// <remarks>
/// ** In Delphi, You cannot overload the bitwise not operator, as
/// BitwiseNot is not supported by the compiler, You have to overload the logical 'not' operator instead.
/// </remarks>
/// <returns></returns>
class operator LogicalNot(x: TIntegerX): TIntegerX;
/// <summary>
/// Returns the bitwise-XOR.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
class operator BitwiseXor(x: TIntegerX; y: TIntegerX): TIntegerX;
/// <summary>
/// Returns the left-shift of a <see cref="TIntegerX"/> by an integer shift.
/// </summary>
/// <param name="x"></param>
/// <param name="shift"></param>
/// <returns></returns>
class operator LeftShift(x: TIntegerX; shift: Integer): TIntegerX;
/// <summary>
/// Returns the right-shift of a <see cref="TIntegerX"/> by an integer shift.
/// </summary>
/// <param name="x"></param>
/// <param name="shift"></param>
/// <returns></returns>
class operator RightShift(x: TIntegerX; shift: Integer): TIntegerX;
/// <summary>
/// Returns the bitwise-AND.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
class function BitwiseAnd(x: TIntegerX; y: TIntegerX): TIntegerX;
overload; static;
/// <summary>
/// Returns the bitwise-OR.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
class function BitwiseOr(x: TIntegerX; y: TIntegerX): TIntegerX;
overload; static;
/// <summary>
/// Returns the bitwise-XOR.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
class function BitwiseXor(x: TIntegerX; y: TIntegerX): TIntegerX;
overload; static;
/// <summary>
/// Returns the bitwise complement.
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
class function BitwiseNot(x: TIntegerX): TIntegerX; overload; static;
/// <summary>
/// Returns the bitwise x and (not y).
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
class function BitwiseAndNot(x: TIntegerX; y: TIntegerX): TIntegerX;
overload; static;
/// <summary>
/// Returns x shl shift.
/// </summary>
/// <param name="x"></param>
/// <param name="shift"></param>
/// <returns></returns>
class function LeftShift(x: TIntegerX; shift: Integer): TIntegerX;
overload; static;
/// <summary>
/// Returns x shr shift.
/// </summary>
/// <param name="x"></param>
/// <param name="shift"></param>
/// <returns></returns>
class function RightShift(x: TIntegerX; shift: Integer): TIntegerX;
overload; static;
/// <summary>
/// Test if a specified bit is set.
/// </summary>
/// <param name="x"></param>
/// <param name="n"></param>
/// <returns></returns>
class function TestBit(x: TIntegerX; n: Integer): Boolean; overload; static;
/// <summary>
/// Set the specified bit.
/// </summary>
/// <param name="x"></param>
/// <param name="n"></param>
/// <returns></returns>
class function SetBit(x: TIntegerX; n: Integer): TIntegerX;
overload; static;
/// <summary>
/// Set the specified bit to its negation.
/// </summary>
/// <param name="x"></param>
/// <param name="n"></param>
/// <returns></returns>
class function FlipBit(x: TIntegerX; n: Integer): TIntegerX;
overload; static;
/// <summary>
/// Clear the specified bit.
/// </summary>
/// <param name="x"></param>
/// <param name="n"></param>
/// <returns></returns>
class function ClearBit(x: TIntegerX; n: Integer): TIntegerX;
overload; static;
/// <summary>
/// Calculates Arithmetic shift right.
/// </summary>
/// <param name="value">Integer value to compute 'Asr' on.</param>
/// <param name="ShiftBits"> number of bits to shift value to.</param>
/// <returns>Shifted value.</returns>
/// <seealso href="http://stackoverflow.com/questions/21940986/">[Delphi ASR Implementation for Integer]</seealso>
class function Asr(value: Integer; ShiftBits: Integer): Integer; overload;
static; inline;
/// <summary>
/// Calculates Arithmetic shift right.
/// </summary>
/// <param name="value">Int64 value to compute 'Asr' on.</param>
/// <param name="ShiftBits"> number of bits to shift value to.</param>
/// <returns>Shifted value.</returns>
/// <seealso href="http://github.com/Spelt/ZXing.Delphi/blob/master/Lib/Classes/Common/MathUtils.pas">[Delphi ASR Implementation for Int64]</seealso>
class function Asr(value: Int64; ShiftBits: Integer): Int64; overload;
static; inline;
/// <summary>
/// Returns Self + y.
/// </summary>
/// <param name="y">The augend.</param>
/// <returns>The sum</returns>
function Add(y: TIntegerX): TIntegerX; overload;
/// <summary>
/// Returns Self - y
/// </summary>
/// <param name="y">The subtrahend</param>
/// <returns>The difference</returns>
function Subtract(y: TIntegerX): TIntegerX; overload;
/// <summary>
/// Returns the negation of this value.
/// </summary>
/// <returns>The negation</returns>
function Negate(): TIntegerX; overload;
/// <summary>
/// Returns Self * y
/// </summary>
/// <param name="y">The multiplicand</param>
/// <returns>The product</returns>
function Multiply(y: TIntegerX): TIntegerX; overload;
/// <summary>
/// Returns Self div y.
/// </summary>
/// <param name="y">The divisor</param>
/// <returns>The quotient</returns>
function Divide(y: TIntegerX): TIntegerX; overload;
/// <summary>
/// Returns Self mod y
/// </summary>
/// <param name="y">The divisor</param>
/// <returns>The modulus</returns>
function Modulo(y: TIntegerX): TIntegerX; overload;
/// <summary>
/// Returns the quotient and remainder of this divided by another.
/// </summary>
/// <param name="y">The divisor</param>
/// <param name="remainder">The remainder</param>
/// <returns>The quotient</returns>
function DivRem(y: TIntegerX; out remainder: TIntegerX): TIntegerX;
overload;
/// <summary>
/// Returns the absolute value of this instance.
/// </summary>
/// <returns>The absolute value</returns>
function Abs(): TIntegerX; overload;
/// <summary>
/// Returns the value of this instance raised to an integral power.
/// </summary>
/// <param name="exp">The exponent</param>
/// <returns>The exponetiated value</returns>
/// <exception cref="EArgumentOutOfRangeException">Thrown if the exponent is negative.</exception>
function Power(exp: Integer): TIntegerX; overload;
/// <summary>
/// Returns (Self ^ power) mod modulus
/// </summary>
/// <param name="power">The exponent</param>
/// <param name="modulus"></param>
/// <returns></returns>
function ModPow(Power: TIntegerX; modulus: TIntegerX): TIntegerX; overload;
/// <summary>
/// Returns the greatest common divisor of this and another value.
/// </summary>
/// <param name="y">The other value</param>
/// <returns>The greatest common divisor</returns>
function Gcd(y: TIntegerX): TIntegerX; overload;
/// <summary>
/// Return the bitwise-AND of this instance and another <see cref="TIntegerX"/>
/// </summary>
/// <param name="y">The value to AND to this instance.</param>
/// <returns>The bitwise-AND</returns>
function BitwiseAnd(y: TIntegerX): TIntegerX; overload;
/// <summary>
/// Return the bitwise-OR of this instance and another <see cref="TIntegerX"/>
/// </summary>
/// <param name="y">The value to OR to this instance.</param>
/// <returns>The bitwise-OR</returns>
function BitwiseOr(y: TIntegerX): TIntegerX; overload;
/// <summary>
/// Return the bitwise-XOR of this instance and another <see cref="TIntegerX"/>
/// </summary>
/// <param name="y">The value to XOR to this instance.</param>
/// <returns>The bitwise-XOR</returns>
function BitwiseXor(y: TIntegerX): TIntegerX; overload;
/// <summary>
/// Returns the bitwise complement of this instance.
/// </summary>
/// <returns>The bitwise complement</returns>
function OnesComplement(): TIntegerX; overload;
/// <summary>
/// Return the bitwise-AND-NOT of this instance and another <see cref="TIntegerX"/>
/// </summary>
/// <param name="y">The value to OR to this instance.</param>
/// <returns>The bitwise-AND-NOT</returns>
function BitwiseAndNot(y: TIntegerX): TIntegerX; overload;
/// <summary>
/// Returns the value of the given bit in this instance.
/// </summary>
/// <param name="n">Index of the bit to check</param>
/// <returns><value>true</value> if the bit is set; <value>false</value> otherwise</returns>
/// <exception cref="EArithmeticException">Thrown if the index is negative.</exception>
/// <remarks>The value is treated as if in twos-complement.</remarks>
function TestBit(n: Integer): Boolean; overload;
/// <summary>
/// Set the n-th bit.
/// </summary>
/// <param name="n">Index of the bit to set</param>
/// <returns>An instance with the bit set</returns>
/// <exception cref="EArithmeticException">Thrown if the index is negative.</exception>
/// <remarks>The value is treated as if in twos-complement.</remarks>
function SetBit(n: Integer): TIntegerX; overload;
/// <summary>
/// Clears the n-th bit.
/// </summary>
/// <param name="n">Index of the bit to clear</param>
/// <returns>An instance with the bit cleared</returns>
/// <exception cref="EArithmeticException">Thrown if the index is negative.</exception>
/// <remarks>The value is treated as if in twos-complement.</remarks>
function ClearBit(n: Integer): TIntegerX; overload;
/// <summary>
/// Toggles the n-th bit.
/// </summary>
/// <param name="n">Index of the bit to toggle</param>
/// <returns>An instance with the bit toggled</returns>
/// <exception cref="EArithmeticException">Thrown if the index is negative.</exception>
/// <remarks>The value is treated as if in twos-complement.</remarks>
function FlipBit(n: Integer): TIntegerX; overload;
/// <summary>
/// Returns the value of this instance left-shifted by the given number of bits.
/// </summary>
/// <param name="shift">The number of bits to shift.</param>
/// <returns>An instance with the magnitude shifted.</returns>
/// <remarks><para>The value is treated as if in twos-complement.</para>
/// <para>A negative shift count will be treated as a positive right shift.</para></remarks>
function LeftShift(shift: Integer): TIntegerX; overload;
/// <summary>
/// Returns the value of this instance right-shifted by the given number of bits.
/// </summary>
/// <param name="shift">The number of bits to shift.</param>
/// <returns>An instance with the magnitude shifted.</returns>
/// <remarks><para>The value is treated as if in twos-complement.</para>
/// <para>A negative shift count will be treated as a positive left shift.</para></remarks>
function RightShift(shift: Integer): TIntegerX; overload;
/// <summary>
/// Try to convert to an Integer.
/// </summary>
/// <param name="ret">Set to the converted value</param>
/// <returns><value>true</value> if successful; <value>false</value> if the value cannot be represented.</returns>
function AsInt32(out ret: Integer): Boolean;
/// <summary>
/// Try to convert to an Int64.
/// </summary>
/// <param name="ret">Set to the converted value</param>
/// <returns><value>true</value> if successful; <value>false</value> if the value cannot be represented.</returns>
function AsInt64(out ret: Int64): Boolean;
/// <summary>
/// Try to convert to an UInt32.
/// </summary>
/// <param name="ret">Set to the converted value</param>
/// <returns><value>true</value> if successful; <value>false</value> if the value cannot be represented.</returns>
function AsUInt32(out ret: UInt32): Boolean;
/// <summary>
/// Try to convert to an UInt64.
/// </summary>
/// <param name="ret">Set to the converted value</param>
/// <returns><value>true</value> if successful; <value>false</value> if the value cannot be represented.</returns>
function AsUInt64(out ret: UInt64): Boolean;
/// <summary>
/// Converts the value of this instance to an equivalent byte value
/// </summary>
/// <returns>The converted value</returns>
/// <exception cref="EOverflowException">Thrown if the value cannot be represented in a byte.</exception>
function ToByte(): Byte;
/// <summary>
/// Converts the value of this instance to an equivalent SmallInt value
/// </summary>
/// <returns>The converted value</returns>
/// <exception cref="EOverflowException">Thrown if the value cannot be represented in a SmallInt.</exception>
function ToSmallInt(): SmallInt;
/// <summary>
/// Converts the value of this instance to an equivalent ShortInt value
/// </summary>
/// <returns>The converted value</returns>
/// <exception cref="EOverflowException">Thrown if the value cannot be represented in a ShortInt.</exception>
function ToShortInt(): ShortInt;
/// <summary>
/// Converts the value of this instance to an equivalent Word value
/// </summary>
/// <returns>The converted value</returns>
/// <exception cref="EOverflowException">Thrown if the value cannot be represented in a Word.</exception>
function ToWord(): Word;
/// <summary>
/// Convert to an equivalent UInt32
/// </summary>
/// <returns>The equivalent value</returns>
/// <exception cref="EOverflowException">Thrown if the magnitude is too large for the conversion</exception>
function ToUInt32(): UInt32;
/// <summary>
/// Convert to an equivalent Integer
/// </summary>
/// <returns>The equivalent value</returns>
/// <exception cref="EOverflowException">Thrown if the magnitude is too large for the conversion</exception>
function ToInteger(): Integer;
/// <summary>
/// Convert to an equivalent UInt64
/// </summary>
/// <returns>The equivalent value</returns>
/// <exception cref="EOverflowException">Thrown if the magnitude is too large for the conversion</exception>
function ToUInt64(): UInt64;
/// <summary>
/// Convert to an equivalent Int64
/// </summary>
/// <returns>The equivalent value</returns>
/// <exception cref="EOverflowException">Thrown if the magnitude is too large for the conversion</exception>
function ToInt64(): Int64;
/// <summary>
/// Convert to an equivalent Double
/// </summary>
/// <returns>The equivalent value</returns>
/// <exception cref="EOverflowException">Thrown if the magnitude is too large for the conversion</exception>
function ToDouble: Double;
/// <summary>
/// Compares this instance to another specified instance and returns an indication of their relative values.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
function CompareTo(other: TIntegerX): Integer;
/// <summary>
/// Indicates whether this instance is equivalent to another object of the same type.
/// </summary>
/// <param name="other">The object to compare this instance against</param>
/// <returns><value>true</value> if equivalent; <value>false</value> otherwise</returns>
function Equals(other: TIntegerX): Boolean;
/// <summary>
/// Returns an indication of the relative values of the two <see cref="TIntegerX"/>'s
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns><value>-1</value> if the first is less than second; <value>0</value> if equal; <value>+1</value> if greater</returns>
class function Compare(x: TIntegerX; y: TIntegerX): Integer;
overload; static;
/// <summary>
/// Converts the numeric value of this <see cref="TIntegerX"/> to its string representation in radix 10.
/// </summary>
/// <returns>The string representation in radix 10</returns>
function ToString(): String; overload;
/// <summary>
/// Converts the numeric value of this <see cref="TIntegerX"/> to its string representation in the given radix.
/// </summary>
/// <param name="radix">The radix for the conversion</param>
/// <returns>The string representation in the given radix</returns>
/// <exception cref="EArgumentOutOfRangeException">Thrown if the radix is out of range [2,36].</exception>
/// <remarks>
/// <para>Compute a set of 'super digits' in a 'super radix' that is computed based on the <paramref name="radix"/>;
/// specifically, it is based on how many digits in the given radix can fit into a UInt32 when converted. Each 'super digit'
/// is then translated into a string of digits in the given radix and appended to the result string.
/// </para>
/// <para>The Java and the DLR code are very similar.</para>
/// </remarks>
function ToString(radix: UInt32): String; overload;
/// <summary>
/// Returns true if this instance is positive.
/// </summary>
function IsPositive: Boolean;
/// <summary>
/// Returns true if this instance is negative.
/// </summary>
function IsNegative: Boolean;
/// <summary>
/// Returns the sign (-1, 0, +1) of this instance.
/// </summary>
function Signum: Integer;
/// <summary>
/// Returns true if this instance has value 0.
/// </summary>
function IsZero: Boolean;
/// <summary>
/// Return true if this instance has an odd value.
/// </summary>
function IsOdd: Boolean;
/// <summary>
/// Return the magnitude as a big-endian array of UInt32's.
/// </summary>
/// <returns>The magnitude</returns>
/// <remarks>The returned array can be manipulated as you like = unshared.</remarks>
function GetMagnitude(): TArray<UInt32>;
function BitLength(): UInt32;
function BitCount(): UInt32; overload;
function ToByteArray(): TArray<Byte>;
/// <summary>
/// Creates a copy of a <see cref="TIntegerX"/>.
/// </summary>
/// <param name="copy">The <see cref="TIntegerX"/> to copy.</param>
constructor Create(copy: TIntegerX); overload;
constructor Create(val: TArray<Byte>); overload;
/// <summary>
/// Creates a <see cref="TIntegerX"/> from sign/magnitude data.
/// </summary>
/// <param name="sign">The sign (-1, 0, +1)</param>
/// <param name="data">The magnitude (big-endian)</param>
/// <exception cref="EArgumentException">Thrown when the sign is not one of -1, 0, +1,
/// or if a zero sign is given on a non-empty magnitude.</exception>
/// <remarks>
/// <para>Leading zero (UInt32) digits will be removed.</para>
/// <para>The sign will be set to zero if a zero-length array is passed.</para>
/// </remarks>
constructor Create(Sign: Integer; data: TArray<UInt32>); overload;
class var
/// <summary>
/// <see cref="TFormatSettings" /> used in <see cref="TIntegerX" />.
/// </summary>
_FS: TFormatSettings;
end;
EArithmeticException = EMathError;
EOverflowException = EOverflow;
EInvalidOperationException = EInvalidOpException;
EDivByZeroException = EDivByZero;
EFormatException = class(Exception);
var
/// <summary>
/// Temporary Variable to Hold <c>Zero </c><see cref="TIntegerX" />.
/// </summary>
ZeroX: TIntegerX;
/// <summary>
/// Temporary Variable to Hold <c>One </c><see cref="TIntegerX" />.
/// </summary>
OneX: TIntegerX;
/// <summary>
/// Temporary Variable to Hold <c>Two </c><see cref="TIntegerX" />.
/// </summary>
TwoX: TIntegerX;
/// <summary>
/// Temporary Variable to Hold <c>Five </c><see cref="TIntegerX" />.
/// </summary>
FiveX: TIntegerX;
/// <summary>
/// Temporary Variable to Hold <c>Ten </c><see cref="TIntegerX" />.
/// </summary>
TenX: TIntegerX;
/// <summary>
/// Temporary Variable to Hold <c>NegativeOne </c><see cref="TIntegerX" />.
/// </summary>
NegativeOneX: TIntegerX;
resourcestring
NaNOrInfinite = 'Infinity/NaN not supported in TIntegerX (yet)';
InvalidSign = 'Sign must be -1, 0, or +1';
InvalidSign2 = 'Zero sign on non-zero data';
InvalidFormat = 'Invalid input format';
OverFlowUInt32 = 'TIntegerX magnitude too large for UInt32';
OverFlowInteger = 'TIntegerX magnitude too large for Integer';
OverFlowUInt64 = 'TIntegerX magnitude too large for UInt64';
OverFlowInt64 = 'TIntegerX magnitude too large for Int64';
OverFlowByte = 'TIntegerX value won''t fit in byte';
OverFlowSmallInt = 'TIntegerX value won''t fit in a SmallInt';
OverFlowShortInt = 'TIntegerX value won''t fit in a ShortInt';
OverFlowWord = 'TIntegerX value won''t fit in a Word';
BogusCompareResult = 'Bogus result from Compare';
ExponentNegative = 'Exponent must be non-negative';
PowerNegative = 'power must be non-negative';
NegativeAddress = 'Negative bit address';
CarryOffLeft = 'Carry off left end.';
ValueOverFlow = 'Value can''t fit in specified type';
ZeroLengthValue = 'Zero length BigInteger';
implementation
class constructor TIntegerX.Create();
begin
// Create a Zero TIntegerX (a big integer with value as Zero)
ZeroX := TIntegerX.Create(0, TArray<UInt32>.Create());
// Create a One TIntegerX (a big integer with value as One)
OneX := TIntegerX.Create(1, TArray<UInt32>.Create(1));
// Create a Two TIntegerX (a big integer with value as Two)
TwoX := TIntegerX.Create(1, TArray<UInt32>.Create(2));
// Create a Five TIntegerX (a big integer with value as Five)
FiveX := TIntegerX.Create(1, TArray<UInt32>.Create(5));
// Create a Ten TIntegerX (a big integer with value as Ten)
TenX := TIntegerX.Create(1, TArray<UInt32>.Create(10));
// Create a NegativeOne TIntegerX (a big integer with value as NegativeOne)
NegativeOneX := TIntegerX.Create(-1, TArray<UInt32>.Create(1));
_FS := TFormatSettings.Create;
FUIntLogTable := TArray<UInt32>.Create(0, 9, 99, 999, 9999, 99999, 999999,
9999999, 99999999, 999999999, MaxUInt32Value);
FRadixDigitsPerDigit := TArray<Integer>.Create(0, 0, 31, 20, 15, 13, 12, 11,
10, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6);
FSuperRadix := TArray<UInt32>.Create(0, 0, $80000000, $CFD41B91, $40000000,
$48C27395, $81BF1000, $75DB9C97, $40000000, $CFD41B91, $3B9ACA00, $8C8B6D2B,
$19A10000, $309F1021, $57F6C100, $98C29B81, $10000000, $18754571, $247DBC80,
$3547667B, $4C4B4000, $6B5A6E1D, $94ACE180, $CAF18367, $B640000, $E8D4A51,
$1269AE40, $17179149, $1CB91000, $23744899, $2B73A840, $34E63B41, $40000000,
$4CFA3CC1, $5C13D840, $6D91B519, $81BF1000);
FBitsPerRadixDigit := TArray<Integer>.Create(0, 0, 1024, 1624, 2048, 2378,
2648, 2875, 3072, 3247, 3402, 3543, 3672, 3790, 3899, 4001, 4096, 4186,
4271, 4350, 4426, 4498, 4567, 4633, 4696, 4756, 4814, 4870, 4923, 4975,
5025, 5074, 5120, 5166, 5210, 5253, 5295);
FTrailingZerosTable := TArray<Byte>.Create(0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0,
2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2,
0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0,
1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1,
0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 7, 0, 1, 0, 2, 0, 1, 0, 3,
0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0,
1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1,
0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0,
2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2,
0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0);
end;
class function TIntegerX.Create(v: UInt64): TIntegerX;
var
most: UInt32;
begin
if (v = 0) then
begin
result := TIntegerX.Zero;
Exit;
end;
most := UInt32(v shr BitsPerDigit);
if (most = 0) then
begin
result := TIntegerX.Create(1, [UInt32(v)]);
Exit;
end
else
result := TIntegerX.Create(1, [most, UInt32(v)]);
end;
class function TIntegerX.Create(v: UInt32): TIntegerX;
begin
if (v = 0) then
begin
result := TIntegerX.Zero;
Exit;
end
else
begin
result := TIntegerX.Create(1, [v]);
Exit;
end;
end;
class function TIntegerX.Create(v: Int64): TIntegerX;
var
most: UInt32;
Sign: SmallInt;
begin
if (v = 0) then
begin
result := TIntegerX.Zero;
Exit;
end
else
begin
Sign := 1;
if (v < 0) then
begin
Sign := -1;
v := -v;
end;
// No need to use ASR (Arithmetic Shift Right) since sign is checked above and a negative "v" is
// multiplied by a negative sign making it positive
most := UInt32(v shr BitsPerDigit);
if (most = 0) then
begin
result := TIntegerX.Create(Sign, [UInt32(v)]);
Exit;
end
else
result := TIntegerX.Create(Sign, [most, UInt32(v)]);
end;
end;
class function TIntegerX.Create(v: Integer): TIntegerX;
begin
result := TIntegerX.Create(Int64(v));
end;
class function TIntegerX.Create(v: Double): TIntegerX;
var
dbytes: TArray<Byte>;
significand: UInt64;
exp: Integer;
tempRes, res: TIntegerX;
begin
if (IsNaN(v)) or (IsInfinite(v)) then
begin
raise EOverflowException.Create(NaNOrInfinite);
end;
SetLength(dbytes, SizeOf(v));
Move(v, dbytes[0], SizeOf(v));
significand := TIntegerX.GetDoubleSignificand(dbytes);
exp := TIntegerX.GetDoubleBiasedExponent(dbytes);
if (significand = 0) then
begin
if (exp = 0) then
begin
result := TIntegerX.Zero;
Exit;
end;
if v < 0.0 then
tempRes := TIntegerX.NegativeOne
else
tempRes := TIntegerX.One;
// TODO: Avoid extra allocation
tempRes := tempRes.LeftShift(exp - DoubleExponentBias);
result := tempRes;
Exit;
end
else
begin
significand := significand or UInt64($10000000000000);
res := TIntegerX.Create(significand);
// TODO: Avoid extra allocation
if exp > 1075 then
res := res shl (exp - DoubleShiftBias)
else
res := res shr (DoubleShiftBias - exp);
if v < 0.0 then
result := res * (-1)
else
result := res;
end;
end;
class function TIntegerX.Create(v: String): TIntegerX;
begin
result := Parse(v);
end;
class function TIntegerX.GetDoubleSign(v: TArray<Byte>): Integer;
begin
result := v[7] and $80;
end;
class function TIntegerX.GetDoubleSignificand(v: TArray<Byte>): UInt64;
var
i1, i2: UInt32;
begin
i1 := (UInt32(v[0]) or (UInt32(v[1]) shl 8) or (UInt32(v[2]) shl 16) or
(UInt32(v[3]) shl 24));
i2 := (UInt32(v[4]) or (UInt32(v[5]) shl 8) or (UInt32(v[6] and $F) shl 16));
result := UInt64(UInt64(i1) or (UInt64(i2) shl 32));
end;
class function TIntegerX.GetDoubleBiasedExponent(v: TArray<Byte>): Word;
begin
result := Word(((Word(v[7] and $7F)) shl Word(4)) or
((Word(v[6] and $F0)) shr 4));
end;
class function TIntegerX.Asr(value: Integer; ShiftBits: Integer): Integer;
begin
result := value shr ShiftBits;
if (value and $80000000) > 0 then
// if you don't want to cast ($FFFFFFFF) to an Integer, simply replace it with (-1) to avoid range check error.
result := result or (Integer($FFFFFFFF) shl (32 - ShiftBits));
end;
class function TIntegerX.Asr(value: Int64; ShiftBits: Integer): Int64;
begin
result := value shr ShiftBits;
if (value and $8000000000000000) > 0 then
result := result or ($FFFFFFFFFFFFFFFF shl (64 - ShiftBits));
end;
constructor TIntegerX.Create(copy: TIntegerX);
begin
_sign := copy._sign;
_data := copy._data;
end;
constructor TIntegerX.Create(val: TArray<Byte>);
begin
if (Length(val) = 0) then
raise EArgumentException.Create(ZeroLengthValue);
if (ShortInt(val[0]) < 0) then
begin
_data := makePositive(val);
_sign := -1;
end
else
begin
_data := StripLeadingZeroBytes(val);
if Length(_data) = 0 then
_sign := 0
else
_sign := 1;
end;
end;
constructor TIntegerX.Create(Sign: Integer; data: TArray<UInt32>);
begin
if ((Sign < -1) or (Sign > 1)) then
raise EArgumentException.Create(InvalidSign);
data := RemoveLeadingZeros(data);
if (Length(data) = 0) then
Sign := 0
else if (Sign = 0) then
raise EArgumentException.Create(InvalidSign2);
_sign := SmallInt(Sign);
_data := data;
end;
class function TIntegerX.Parse(x: String): TIntegerX;
begin
result := Parse(x, 10);
end;
class function TIntegerX.Parse(s: String; radix: Integer): TIntegerX;
var
v: TIntegerX;
begin
if (TryParse(s, radix, v)) then
begin
result := v;
Exit;
end;
raise EFormatException.Create(InvalidFormat);
end;
class function TIntegerX.TryParse(s: String; out v: TIntegerX): Boolean;
begin
result := TryParse(s, 10, v);
end;
class function TIntegerX.TryParse(s: String; radix: Integer;
out v: TIntegerX): Boolean;
var
Sign: SmallInt;
len, minusIndex, plusIndex, index, numDigits, numBits, numUints, groupSize,
firstGroupLen: Integer;
mult, u: UInt32;
data: TArray<UInt32>;
begin
if ((radix < MinRadix) or (radix > MaxRadix)) then
begin
v := Default (TIntegerX);
result := false;
Exit;
end;
Sign := 1;
len := Length(s);
// zero length bad,
// hyphen only bad, plus only bad,
// hyphen not leading bad, plus not leading bad
// (overkill) both hyphen and minus present (one would be caught by the tests above)
minusIndex := s.LastIndexOf('-');
plusIndex := s.LastIndexOf('+');
if ((len = 0) or ((minusIndex = 0) and (len = 1)) or
((plusIndex = 0) and (len = 1)) or (minusIndex > 0) or (plusIndex > 0)) then
begin
v := Default (TIntegerX);
result := false;
Exit;
end;
index := 0;
if (plusIndex <> -1) then
index := 1
else if (minusIndex <> -1) then
begin
Sign := -1;
index := 1;
end;
// skip leading zeros
while ((index < len) and (s.Chars[index] = '0')) do
Inc(index);
if (index = len) then
begin
v := TIntegerX.Create(TIntegerX.Zero);
result := true;
Exit;
end;
numDigits := len - index;
// We can compute size of magnitude. May be too large by one UInt32.
numBits := TIntegerX.Asr((numDigits * FBitsPerRadixDigit[radix]), 10) + 1;
numUints := (numBits + BitsPerDigit - 1) div BitsPerDigit;
SetLength(data, numUints);
groupSize := FRadixDigitsPerDigit[radix];
// the first group may be short
// the first group is the initial value for _data.
firstGroupLen := numDigits mod groupSize;
if (firstGroupLen = 0) then
firstGroupLen := groupSize;
if (not TryParseUInt(s, index, firstGroupLen, radix, data[Length(data) - 1]))
then
begin
v := Default (TIntegerX);
result := false;
Exit;
end;
index := index + firstGroupLen;
mult := FSuperRadix[radix];
while index < len do
begin
if (not TryParseUInt(s, index, groupSize, radix, u)) then
begin
v := Default (TIntegerX);
result := false;
Exit;
end;
InPlaceMulAdd(data, mult, u);
index := index + groupSize;
end;
v := TIntegerX.Create(Sign, RemoveLeadingZeros(data));
result := true;
end;
function TIntegerX.ToString(): String;
begin
result := ToString(10);
end;
function TIntegerX.ToString(radix: UInt32): String;
var
len, index, i: Integer;
LSuperRadix, rem: UInt32;
working: TArray<UInt32>;
rems: TList<UInt32>;
sb: TStringBuilder;
charBuf: TArray<Char>;
begin
if ((radix < UInt32(MinRadix)) or (radix > UInt32(MaxRadix))) then
raise EArgumentOutOfRangeException.Create
(Format('Radix %u is out of range. MinRadix = %d , MaxRadix = %d',
[radix, MinRadix, MaxRadix], _FS));
if (_sign = 0) then
begin
result := '0';
Exit;
end;
len := Length(_data);
working := copy(_data, 0, Length(_data));
LSuperRadix := FSuperRadix[radix];
// TODO: figure out max, pre-allocate space (in List)
rems := TList<UInt32>.Create;
try
index := 0;
while (index < len) do
begin
rem := InPlaceDivRem(working, index, LSuperRadix);
rems.Add(rem);
end;
sb := TStringBuilder.Create(rems.Count * FRadixDigitsPerDigit[radix] + 1);
try
if (_sign < 0) then
sb.Append('-');
SetLength(charBuf, (FRadixDigitsPerDigit[radix]));
AppendDigit(sb, rems[rems.Count - 1], radix, charBuf, false);
i := rems.Count - 2;
while i >= 0 do
begin
AppendDigit(sb, rems[i], radix, charBuf, true);
Dec(i);
end;
result := sb.ToString();
finally
sb.Free;
end;
finally
rems.Free;
end;
end;
class procedure TIntegerX.AppendDigit(var sb: TStringBuilder; rem: UInt32;
radix: UInt32; charBuf: TArray<Char>; leadingZeros: Boolean);
const
symbols = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var
bufLen, i: Integer;
digit: UInt32;
begin
bufLen := Length(charBuf);
i := bufLen - 1;
while ((i >= 0) and (rem <> 0)) do
begin
digit := rem mod radix;
rem := rem div radix;
charBuf[i] := symbols.Chars[Integer(digit)];
Dec(i);
end;
if (leadingZeros) then
begin
while i >= 0 do
begin
charBuf[i] := '0';
Dec(i);
end;
sb.Append(charBuf);
end
else
sb.Append(charBuf, i + 1, bufLen - i - 1);
end;
class function TIntegerX.TryParseUInt(val: String; startIndex: Integer;
len: Integer; radix: Integer; out u: UInt32): Boolean;
var
tempRes: UInt64;
i: Integer;
v: UInt32;
begin
u := 0;
tempRes := 0;
i := 0;
while i < len do
begin
if (not TryComputeDigitVal(val.Chars[startIndex + i], radix, v)) then
begin
result := false;
Exit;
end;
tempRes := tempRes * UInt32(radix) + v;
if (tempRes > MaxUInt32Value) then
begin
result := false;
Exit;
end;
Inc(i);
end;
u := UInt32(tempRes);
result := true;
end;
class function TIntegerX.TryComputeDigitVal(c: Char; radix: Integer;
out v: UInt32): Boolean;
begin
v := MaxUInt32Value;
if ((Ord('0') <= Ord(c)) and (Ord(c) <= Ord('9'))) then
v := UInt32(Ord(c) - Ord('0'))
else if ((Ord('a') <= Ord(c)) and (Ord(c) <= Ord('z'))) then
v := UInt32(10 + Ord(c) - Ord('a'))
else if ((Ord('A') <= Ord(c)) and (Ord(c) <= Ord('Z'))) then
v := UInt32(10 + Ord(c) - Ord('A'));
result := v < UInt32(radix);
end;
class operator TIntegerX.Implicit(v: Byte): TIntegerX;
begin
result := Create(UInt32(v));
end;
class operator TIntegerX.Implicit(v: ShortInt): TIntegerX;
begin
result := Create(Integer(v));
end;
class operator TIntegerX.Implicit(v: SmallInt): TIntegerX;
begin
result := Create(Integer(v));
end;
class operator TIntegerX.Implicit(v: Word): TIntegerX;
begin
result := Create(UInt32(v));
end;
class operator TIntegerX.Implicit(v: UInt32): TIntegerX;
begin
result := Create(v);
end;
class operator TIntegerX.Implicit(v: Integer): TIntegerX;
begin
result := Create(v);
end;
class operator TIntegerX.Implicit(v: UInt64): TIntegerX;
begin
result := Create(v);
end;
class operator TIntegerX.Implicit(v: Int64): TIntegerX;
begin
result := Create(v);
end;
class operator TIntegerX.Explicit(self: Double): TIntegerX;
begin
result := Create(self);
end;
class operator TIntegerX.Explicit(i: TIntegerX): Double;
begin
result := i.ToDouble();
end;
{$OVERFLOWCHECKS ON}
class operator TIntegerX.Explicit(self: TIntegerX): Byte;
var
tmp: Integer;
begin
if (self.AsInt32(tmp)) then
begin
result := Byte(tmp);
Exit;
end;
raise EOverflowException.Create(ValueOverFlow);
end;
{$OVERFLOWCHECKS OFF}
{$OVERFLOWCHECKS ON}
class operator TIntegerX.Explicit(self: TIntegerX): ShortInt;
var
tmp: Integer;
begin
if (self.AsInt32(tmp)) then
begin
result := ShortInt(tmp);
Exit;
end;
raise EOverflowException.Create(ValueOverFlow);
end;
{$OVERFLOWCHECKS OFF}
{$OVERFLOWCHECKS ON}
class operator TIntegerX.Explicit(self: TIntegerX): Word;
var
tmp: Integer;
begin
if (self.AsInt32(tmp)) then
begin
result := Word(tmp);
Exit;
end;
raise EOverflowException.Create(ValueOverFlow);
end;
{$OVERFLOWCHECKS OFF}
{$OVERFLOWCHECKS ON}
class operator TIntegerX.Explicit(self: TIntegerX): SmallInt;
var
tmp: Integer;
begin
if (self.AsInt32(tmp)) then
begin
result := SmallInt(tmp);
Exit;
end;
raise EOverflowException.Create(ValueOverFlow);
end;
{$OVERFLOWCHECKS OFF}
class operator TIntegerX.Explicit(self: TIntegerX): UInt32;
var
tmp: UInt32;
begin
if (self.AsUInt32(tmp)) then
begin
result := tmp;
Exit;
end;
raise EOverflowException.Create(ValueOverFlow);
end;
class operator TIntegerX.Explicit(self: TIntegerX): Integer;
var
tmp: Integer;
begin
if (self.AsInt32(tmp)) then
begin
result := tmp;
Exit;
end;
raise EOverflowException.Create(ValueOverFlow);
end;
class operator TIntegerX.Explicit(self: TIntegerX): Int64;
var
tmp: Int64;
begin
if (self.AsInt64(tmp)) then
begin
result := tmp;
Exit;
end;
raise EOverflowException.Create(ValueOverFlow);
end;
class operator TIntegerX.Explicit(self: TIntegerX): UInt64;
var
tmp: UInt64;
begin
if (self.AsUInt64(tmp)) then
begin
result := tmp;
Exit;
end;
raise EOverflowException.Create(ValueOverFlow);
end;
class operator TIntegerX.Equal(x: TIntegerX; y: TIntegerX): Boolean;
begin
result := Compare(x, y) = 0;
end;
class operator TIntegerX.NotEqual(x: TIntegerX; y: TIntegerX): Boolean;
begin
result := Compare(x, y) <> 0;
end;
class operator TIntegerX.LessThan(x: TIntegerX; y: TIntegerX): Boolean;
begin
result := Compare(x, y) < 0;
end;
class operator TIntegerX.LessThanOrEqual(x: TIntegerX; y: TIntegerX): Boolean;
begin
result := Compare(x, y) <= 0;
end;
class operator TIntegerX.GreaterThan(x: TIntegerX; y: TIntegerX): Boolean;
begin
result := Compare(x, y) > 0;
end;
class operator TIntegerX.GreaterThanOrEqual(x: TIntegerX; y: TIntegerX)
: Boolean;
begin
result := Compare(x, y) >= 0;
end;
class operator TIntegerX.Add(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Add(y);
end;
class operator TIntegerX.Subtract(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Subtract(y);
end;
class operator TIntegerX.Positive(x: TIntegerX): TIntegerX;
begin
result := x;
end;
class operator TIntegerX.Negative(x: TIntegerX): TIntegerX;
begin
result := x.Negate();
end;
class operator TIntegerX.Multiply(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Multiply(y);
end;
class operator TIntegerX.IntDivide(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Divide(y);
end;
class operator TIntegerX.modulus(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Modulo(y);
end;
class function TIntegerX.Add(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Add(y);
end;
class function TIntegerX.Subtract(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Subtract(y);
end;
class function TIntegerX.Negate(x: TIntegerX): TIntegerX;
begin
result := x.Negate();
end;
class function TIntegerX.Multiply(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Multiply(y);
end;
class function TIntegerX.Divide(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Divide(y);
end;
class function TIntegerX.Modulo(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Modulo(y);
end;
class function TIntegerX.DivRem(x: TIntegerX; y: TIntegerX;
out remainder: TIntegerX): TIntegerX;
begin
result := x.DivRem(y, remainder);
end;
class function TIntegerX.Abs(x: TIntegerX): TIntegerX;
begin
result := x.Abs();
end;
class function TIntegerX.Power(x: TIntegerX; exp: Integer): TIntegerX;
begin
result := x.Power(exp);
end;
class function TIntegerX.ModPow(x: TIntegerX; Power: TIntegerX;
Modulo: TIntegerX): TIntegerX;
begin
result := x.ModPow(Power, Modulo);
end;
class function TIntegerX.Gcd(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.Gcd(y);
end;
class operator TIntegerX.BitwiseAnd(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.BitwiseAnd(y);
end;
class operator TIntegerX.BitwiseOr(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.BitwiseOr(y);
end;
class operator TIntegerX.LogicalNot(x: TIntegerX): TIntegerX;
begin
result := x.OnesComplement();
end;
class operator TIntegerX.BitwiseXor(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.BitwiseXor(y);
end;
class operator TIntegerX.LeftShift(x: TIntegerX; shift: Integer): TIntegerX;
begin
result := x.LeftShift(shift);
end;
class operator TIntegerX.RightShift(x: TIntegerX; shift: Integer): TIntegerX;
begin
result := x.RightShift(shift);
end;
class function TIntegerX.BitwiseAnd(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.BitwiseAnd(y);
end;
class function TIntegerX.BitwiseOr(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.BitwiseOr(y);
end;
class function TIntegerX.BitwiseXor(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.BitwiseXor(y);
end;
class function TIntegerX.BitwiseNot(x: TIntegerX): TIntegerX;
begin
result := x.OnesComplement();
end;
class function TIntegerX.BitwiseAndNot(x: TIntegerX; y: TIntegerX): TIntegerX;
begin
result := x.BitwiseAndNot(y);
end;
class function TIntegerX.LeftShift(x: TIntegerX; shift: Integer): TIntegerX;
begin
result := x.LeftShift(shift);
end;
class function TIntegerX.RightShift(x: TIntegerX; shift: Integer): TIntegerX;
begin
result := x.RightShift(shift);
end;
class function TIntegerX.TestBit(x: TIntegerX; n: Integer): Boolean;
begin
result := x.TestBit(n);
end;
class function TIntegerX.SetBit(x: TIntegerX; n: Integer): TIntegerX;
begin
result := x.SetBit(n);
end;
class function TIntegerX.FlipBit(x: TIntegerX; n: Integer): TIntegerX;
begin
result := x.FlipBit(n);
end;
class function TIntegerX.ClearBit(x: TIntegerX; n: Integer): TIntegerX;
begin
result := x.ClearBit(n);
end;
function TIntegerX.AsInt32(out ret: Integer): Boolean;
begin
ret := 0;
case (Length(_data)) of
0:
begin
result := true;
Exit;
end;
1:
begin
if (_data[0] > UInt32($80000000)) then
begin
result := false;
Exit;
end;
if ((_data[0] = UInt32($80000000)) and (_sign = 1)) then
begin
result := false;
Exit;
end;
ret := (Integer(_data[0])) * _sign;
result := true;
Exit;
end
else
begin
result := false;
Exit;
end;
end;
end;
function TIntegerX.AsInt64(out ret: Int64): Boolean;
var
tmp: UInt64;
begin
ret := 0;
case (Length(_data)) of
0:
begin
result := true;
Exit;
end;
1:
begin
ret := _sign * Int64(_data[0]);
result := true;
Exit;
end;
2:
begin
tmp := (UInt64(_data[0]) shl 32) or (UInt64(_data[1]));
if (tmp > ($8000000000000000)) then
begin
result := false;
Exit;
end;
if ((tmp = ($8000000000000000)) and (_sign = 1)) then
begin
result := false;
Exit;
end;
ret := (Int64(tmp)) * _sign;
result := true;
Exit;
end;
else
begin
result := false;
Exit;
end;
end;
end;
function TIntegerX.AsUInt32(out ret: UInt32): Boolean;
begin
ret := 0;
if (_sign = 0) then
begin
result := true;
Exit;
end;
if (_sign < 0) then
begin
result := false;
Exit;
end;
if (Length(_data) > 1) then
begin
result := false;
Exit;
end;
ret := _data[0];
result := true;
end;
function TIntegerX.AsUInt64(out ret: UInt64): Boolean;
begin
ret := 0;
if (_sign < 0) then
begin
result := false;
Exit;
end;
case (Length(_data)) of
0:
begin
result := true;
Exit;
end;
1:
begin
ret := UInt64(_data[0]);
result := true;
Exit;
end;
2:
begin
ret := UInt64(_data[1]) or (UInt64(_data[0]) shl 32);
result := true;
Exit;
end;
else
begin
result := false;
Exit;
end;
end;
end;
function TIntegerX.ToByte(): Byte;
var
ret: UInt32;
begin
if (AsUInt32(ret) and (ret <= $FF)) then
begin
result := Byte(ret);
Exit;
end;
raise EOverflowException.Create(OverFlowByte);
end;
function TIntegerX.ToSmallInt(): SmallInt;
var
ret: Integer;
begin
if (AsInt32(ret) and (MinSmallIntValue <= ret) and (ret <= MaxSmallIntValue))
then
begin
result := SmallInt(ret);
Exit;
end;
raise EOverflowException.Create(OverFlowSmallInt);
end;
function TIntegerX.ToShortInt(): ShortInt;
var
ret: Integer;
begin
if (AsInt32(ret) and (MinShortIntValue <= ret) and (ret <= MaxShortIntValue))
then
begin
result := ShortInt(ret);
Exit;
end;
raise EOverflowException.Create(OverFlowSmallInt);
end;
function TIntegerX.ToWord(): Word;
var
ret: UInt32;
begin
if (AsUInt32(ret) and (ret <= MaxWordValue)) then
begin
result := Word(ret);
Exit;
end;
raise EOverflowException.Create(OverFlowWord);
end;
function TIntegerX.ToUInt32(): UInt32;
var
ret: UInt32;
begin
if (AsUInt32(ret)) then
begin
result := ret;
Exit;
end;
raise EOverflowException.Create(OverFlowUInt32);
end;
function TIntegerX.ToInteger(): Integer;
var
ret: Integer;
begin
if (AsInt32(ret)) then
begin
result := ret;
Exit;
end;
raise EOverflowException.Create(OverFlowInteger);
end;
function TIntegerX.ToUInt64(): UInt64;
var
ret: UInt64;
begin
if (AsUInt64(ret)) then
begin
result := ret;
Exit;
end;
raise EOverflowException.Create(OverFlowUInt64);
end;
function TIntegerX.ToInt64(): Int64;
var
ret: Int64;
begin
if (AsInt64(ret)) then
begin
result := ret;
Exit;
end;
raise EOverflowException.Create(OverFlowInt64);
end;
function TIntegerX.ToDouble: Double;
begin
result := StrtoFloat(self.ToString(10), _FS);
end;
function TIntegerX.CompareTo(other: TIntegerX): Integer;
begin
result := Compare(self, other);
end;
function TIntegerX.Equals(other: TIntegerX): Boolean;
begin
result := self = other;
end;
class function TIntegerX.Compare(x: TIntegerX; y: TIntegerX): Integer;
begin
if x._sign = y._sign then
begin
result := x._sign * Compare(x._data, y._data);
Exit;
end
else
begin
if x._sign < y._sign then
begin
result := -1;
Exit;
end
else
begin
result := 1;
Exit;
end;
end;
end;
class function TIntegerX.Compare(x: TArray<UInt32>; y: TArray<UInt32>)
: SmallInt;
var
xlen, ylen, i: Integer;
begin
xlen := Length(x);
ylen := Length(y);
if (xlen < ylen) then
begin
result := -1;
Exit;
end;
if (xlen > ylen) then
begin
result := 1;
Exit;
end;
i := 0;
while i < xlen do
begin
if (x[i] < y[i]) then
begin
result := -1;
Exit;
end;
if (x[i] > y[i]) then
begin
result := 1;
Exit;
end;
Inc(i);
end;
result := 0;
end;
function TIntegerX.Add(y: TIntegerX): TIntegerX;
var
c: Integer;
begin
if (self._sign = 0) then
begin
result := y;
Exit;
end;
if (y._sign = 0) then
begin
result := self;
Exit;
end;
if (self._sign = y._sign) then
begin
result := TIntegerX.Create(_sign, Add(self._data, y._data));
Exit;
end
else
begin
c := Compare(self._data, y._data);
case (c) of
- 1:
begin
result := TIntegerX.Create(-self._sign,
Subtract(y._data, self._data));
Exit;
end;
0:
begin
result := TIntegerX.Create(TIntegerX.Zero);
Exit;
end;
1:
begin
result := TIntegerX.Create(self._sign, Subtract(self._data, y._data));
Exit;
end;
else
raise EInvalidOperationException.Create(BogusCompareResult);
end;
end;
end;
function TIntegerX.Subtract(y: TIntegerX): TIntegerX;
var
cmp: Integer;
mag: TArray<UInt32>;
begin
if (y._sign = 0) then
begin
result := self;
Exit;
end;
if (self._sign = 0) then
begin
result := y.Negate();
Exit;
end;
if (self._sign <> y._sign) then
begin
result := TIntegerX.Create(self._sign, Add(self._data, y._data));
Exit;
end;
cmp := Compare(self._data, y._data);
if (cmp = 0) then
begin
result := TIntegerX.Zero;
Exit;
end;
if cmp > 0 then
mag := Subtract(self._data, y._data)
else
mag := Subtract(y._data, self._data);
result := TIntegerX.Create(cmp * self._sign, mag);
end;
function TIntegerX.Negate(): TIntegerX;
begin
result := TIntegerX.Create(-self._sign, self._data);
end;
function TIntegerX.Multiply(y: TIntegerX): TIntegerX;
var
mag: TArray<UInt32>;
begin
if (self._sign = 0) then
begin
result := TIntegerX.Zero;
Exit;
end;
if (y._sign = 0) then
begin
result := TIntegerX.Zero;
Exit;
end;
mag := Multiply(self._data, y._data);
result := TIntegerX.Create(self._sign * y._sign, mag);
end;
function TIntegerX.Divide(y: TIntegerX): TIntegerX;
var
rem: TIntegerX;
begin
result := DivRem(y, rem);
end;
function TIntegerX.Modulo(y: TIntegerX): TIntegerX;
var
rem: TIntegerX;
begin
DivRem(y, rem);
result := rem;
end;
function TIntegerX.DivRem(y: TIntegerX; out remainder: TIntegerX): TIntegerX;
var
q, r: TArray<UInt32>;
begin
DivMod(_data, y._data, q, r);
remainder := TIntegerX.Create(_sign, r);
result := TIntegerX.Create(_sign * y._sign, q);
end;
function TIntegerX.Abs(): TIntegerX;
begin
if _sign > -0 then
result := self
else
result := self.Negate();
end;
function TIntegerX.Power(exp: Integer): TIntegerX;
var
mult, tempRes: TIntegerX;
begin
if (exp < 0) then
raise EArgumentOutOfRangeException.Create(ExponentNegative);
if (exp = 0) then
begin
result := TIntegerX.One;
Exit;
end;
if (_sign = 0) then
begin
result := self;
Exit;
end;
// Exponentiation by repeated squaring
mult := self;
tempRes := TIntegerX.One;
while (exp <> 0) do
begin
if ((exp and 1) <> 0) then
tempRes := tempRes * mult;
if (exp = 1) then
break;
mult := mult * mult;
exp := exp shr 1;
end;
result := tempRes;
end;
function TIntegerX.ModPow(Power: TIntegerX; modulus: TIntegerX): TIntegerX;
var
mult, tempRes: TIntegerX;
begin
// TODO: Look at Java implementation for a more efficient version
if (Power < 0) then
raise EArgumentOutOfRangeException.Create(PowerNegative);
if (Power._sign = 0) then
begin
result := TIntegerX.One;
Exit;
end;
if (_sign = 0) then
begin
result := self;
Exit;
end;
// Exponentiation by repeated squaring
mult := self;
tempRes := TIntegerX.One;
while (Power <> TIntegerX.Zero) do
begin
if (Power.IsOdd) then
begin
tempRes := tempRes * mult;
tempRes := tempRes mod modulus;
end;
if (Power = TIntegerX.One) then
break;
mult := mult * mult;
mult := mult mod modulus;
Power := Power shr 1;
end;
result := tempRes;
end;
function TIntegerX.Gcd(y: TIntegerX): TIntegerX;
begin
// We follow Java and do a hybrid/binary gcd
if (y._sign = 0) then
self.Abs()
else if (self._sign = 0) then
begin
result := y.Abs();
Exit;
end;
// TODO: get rid of unnecessary object creation?
result := HybridGcd(self.Abs(), y.Abs());
end;
class function TIntegerX.HybridGcd(a: TIntegerX; b: TIntegerX): TIntegerX;
var
r: TIntegerX;
begin
while (Length(b._data) <> 0) do
begin
if (System.Abs(Length(a._data) - Length(b._data)) < 2) then
begin
result := BinaryGcd(a, b);
Exit;
end;
a.DivRem(b, r);
a := b;
b := r;
end;
result := a;
end;
class function TIntegerX.BinaryGcd(a: TIntegerX; b: TIntegerX): TIntegerX;
var
s1, s2, tsign, k, lb: Integer;
t: TIntegerX;
x, y: UInt32;
begin
// From Knuth, 4.5.5, Algorithm B
// TODO: make this create fewer values, do more in-place manipulations
// Step B1: Find power of 2
s1 := a.GetLowestSetBit();
s2 := b.GetLowestSetBit();
k := Min(s1, s2);
if (k <> 0) then
begin
a := a.RightShift(k);
b := b.RightShift(k);
end;
// Step B2: Initialize
if (k = s1) then
begin
t := b;
tsign := -1;
end
else
begin
t := a;
tsign := 1;
end;
lb := t.GetLowestSetBit();
while ((lb) >= 0) do
begin
// Steps B3 and B4 Halve t until not even.
t := t.RightShift(lb);
// Step B5: reset max(u,v)
if (tsign > 0) then
a := t
else
b := t;
// One word?
if ((a.AsUInt32(x)) and (b.AsUInt32(y))) then
begin
x := BinaryGcd(x, y);
t := TIntegerX.Create(x);
if (k > 0) then
t := t.LeftShift(k);
result := t;
Exit;
end;
// Step B6: Subtract
// TODO: Clean up extra object creation here.
t := a - b;
if (t.IsZero) then
break;
if (t.IsPositive) then
tsign := 1
else
begin
tsign := -1;
t := t.Abs();
end;
lb := t.GetLowestSetBit();
end;
if (k > 0) then
a := a.LeftShift(k);
result := a;
end;
class function TIntegerX.BinaryGcd(a: UInt32; b: UInt32): UInt32;
var
y, aZeros, bZeros, t: Integer;
x: UInt32;
begin
// From Knuth, 4.5.5, Algorithm B
if (b = 0) then
begin
result := a;
Exit;
end;
if (a = 0) then
begin
result := b;
Exit;
end;
aZeros := 0;
x := a and $FF;
while ((x) = 0) do
begin
a := a shr 8;
aZeros := aZeros + 8;
x := a and $FF;
end;
y := FTrailingZerosTable[x];
aZeros := aZeros + y;
a := a shr y;
bZeros := 0;
x := b and $FF;
while ((x) = 0) do
begin
b := b shr 8;
bZeros := bZeros + 8;
x := b and $FF;
end;
y := FTrailingZerosTable[x];
bZeros := bZeros + y;
b := b shr y;
if aZeros < bZeros then
t := aZeros
else
t := bZeros;
while (a <> b) do
begin
if (a > b) then
begin
a := a - b;
x := a and $FF;
while ((x) = 0) do
begin
a := a shr 8;
x := a and $FF;
end;
a := a shr FTrailingZerosTable[x];
end
else
begin
b := b - a;
x := b and $FF;
while ((x) = 0) do
begin
b := b shr 8;
x := b and $FF;
end;
b := b shr FTrailingZerosTable[x];
end;
end;
result := a shl t;
end;
class function TIntegerX.TrailingZerosCount(val: UInt32): Integer;
var
byteVal: UInt32;
begin
byteVal := val and $FF;
if (byteVal <> 0) then
begin
result := FTrailingZerosTable[byteVal];
Exit;
end;
byteVal := (val shr 8) and $FF;
if (byteVal <> 0) then
begin
result := FTrailingZerosTable[byteVal] + 8;
Exit;
end;
byteVal := (val shr 16) and $FF;
if (byteVal <> 0) then
begin
result := FTrailingZerosTable[byteVal] + 16;
Exit;
end;
byteVal := (val shr 24) and $FF;
result := FTrailingZerosTable[byteVal] + 24;
end;
class function TIntegerX.BitLengthForUInt32(x: UInt32): UInt32;
begin
result := 32 - LeadingZeroCount(x);
end;
class function TIntegerX.LeadingZeroCount(x: UInt32): UInt32;
begin
x := x or (x shr 1);
x := x or (x shr 2);
x := x or (x shr 4);
x := x or (x shr 8);
x := x or (x shr 16);
result := UInt32(32) - BitCount(x);
end;
class function TIntegerX.BitCount(x: UInt32): UInt32;
begin
x := x - ((x shr 1) and $55555555);
x := (((x shr 2) and $33333333) + (x and $33333333));
x := (((x shr 4) + x) and $0F0F0F0F);
x := x + (x shr 8);
x := x + (x shr 16);
result := (x and $0000003F);
end;
function TIntegerX.GetLowestSetBit(): Integer;
var
j: Integer;
begin
if (_sign = 0) then
begin
result := -1;
Exit;
end;
j := Length(_data) - 1;
while ((j > 0) and (_data[j] = 0)) do
begin
Dec(j);
end;
result := ((Length(_data) - j - 1) shl 5) + TrailingZerosCount(_data[j]);
end;
function TIntegerX.BitwiseAnd(y: TIntegerX): TIntegerX;
var
rlen, i: Integer;
tempRes: TArray<UInt32>;
xdigit, ydigit: UInt32;
seenNonZeroX, seenNonZeroY: Boolean;
begin
rlen := Max(Length(_data), Length(y._data));
SetLength(tempRes, rlen);
seenNonZeroX := false;
seenNonZeroY := false;
i := 0;
while i < rlen do
begin
xdigit := Get2CDigit(i, seenNonZeroX);
ydigit := y.Get2CDigit(i, seenNonZeroY);
tempRes[rlen - i - 1] := xdigit and ydigit;
Inc(i);
end;
// result is negative only if both this and y are negative
if ((self.IsNegative) and (y.IsNegative)) then
result := TIntegerX.Create(-1,
RemoveLeadingZeros(MakeTwosComplement(tempRes)))
else
result := TIntegerX.Create(1, RemoveLeadingZeros(tempRes));
end;
function TIntegerX.BitwiseOr(y: TIntegerX): TIntegerX;
var
rlen, i: Integer;
tempRes: TArray<UInt32>;
seenNonZeroX, seenNonZeroY: Boolean;
xdigit, ydigit: UInt32;
begin
rlen := Max(Length(_data), Length(y._data));
SetLength(tempRes, rlen);
seenNonZeroX := false;
seenNonZeroY := false;
i := 0;
while i < rlen do
begin
xdigit := Get2CDigit(i, seenNonZeroX);
ydigit := y.Get2CDigit(i, seenNonZeroY);
tempRes[rlen - i - 1] := xdigit or ydigit;
Inc(i);
end;
// result is negative only if either this or y is negative
if ((self.IsNegative) or (y.IsNegative)) then
result := TIntegerX.Create(-1,
RemoveLeadingZeros(MakeTwosComplement(tempRes)))
else
result := TIntegerX.Create(1, RemoveLeadingZeros(tempRes));
end;
function TIntegerX.BitwiseXor(y: TIntegerX): TIntegerX;
var
rlen, i: Integer;
tempRes: TArray<UInt32>;
seenNonZeroX, seenNonZeroY: Boolean;
xdigit, ydigit: UInt32;
begin
rlen := Max(Length(_data), Length(y._data));
SetLength(tempRes, rlen);
seenNonZeroX := false;
seenNonZeroY := false;
i := 0;
while i < rlen do
begin
xdigit := Get2CDigit(i, seenNonZeroX);
ydigit := y.Get2CDigit(i, seenNonZeroY);
tempRes[rlen - i - 1] := xdigit xor ydigit;
Inc(i);
end;
// result is negative only if either x and y have the same sign.
if (self.Signum = y.Signum) then
result := TIntegerX.Create(-1,
RemoveLeadingZeros(MakeTwosComplement(tempRes)))
else
result := TIntegerX.Create(1, RemoveLeadingZeros(tempRes));
end;
function TIntegerX.OnesComplement(): TIntegerX;
var
len, i: Integer;
tempRes: TArray<UInt32>;
xdigit: UInt32;
seenNonZero: Boolean;
begin
len := Length(_data);
SetLength(tempRes, len);
seenNonZero := false;
i := 0;
while i < len do
begin
xdigit := Get2CDigit(i, seenNonZero);
tempRes[len - i - 1] := not xdigit;
Inc(i);
end;
if (self.IsNegative) then
result := TIntegerX.Create(1, RemoveLeadingZeros(tempRes))
else
result := TIntegerX.Create(-1,
RemoveLeadingZeros(MakeTwosComplement(tempRes)));
end;
function TIntegerX.BitwiseAndNot(y: TIntegerX): TIntegerX;
var
rlen, i: Integer;
tempRes: TArray<UInt32>;
seenNonZeroX, seenNonZeroY: Boolean;
xdigit, ydigit: UInt32;
begin
rlen := Max(Length(_data), Length(y._data));
SetLength(tempRes, rlen);
seenNonZeroX := false;
seenNonZeroY := false;
i := 0;
while i < rlen do
begin
xdigit := Get2CDigit(i, seenNonZeroX);
ydigit := y.Get2CDigit(i, seenNonZeroY);
tempRes[rlen - i - 1] := xdigit and (not ydigit);
Inc(i);
end;
// result is negative only if either this is negative and y is positive
if ((self.IsNegative) and (y.IsPositive)) then
result := TIntegerX.Create(-1,
RemoveLeadingZeros(MakeTwosComplement(tempRes)))
else
result := TIntegerX.Create(1, RemoveLeadingZeros(tempRes));
end;
function TIntegerX.TestBit(n: Integer): Boolean;
begin
if (n < 0) then
raise EArithmeticException.Create(NegativeAddress);
result := (Get2CDigit(n div 32) and (1 shl (n mod 32))) <> 0;
end;
function TIntegerX.SetBit(n: Integer): TIntegerX;
var
index, len, i: Integer;
tempRes: TArray<UInt32>;
seenNonZero: Boolean;
begin
// This will work if the bit is already set.
if (TestBit(n)) then
begin
result := self;
Exit;
end;
index := n div 32;
SetLength(tempRes, Max(Length(_data), index + 1));
len := Length(tempRes);
seenNonZero := false;
i := 0;
while i < len do
begin
tempRes[len - i - 1] := Get2CDigit(i, seenNonZero);
Inc(i);
end;
tempRes[len - index - 1] := tempRes[len - index - 1] or
(UInt32(1) shl (n mod 32));
if (self.IsNegative) then
result := TIntegerX.Create(-1,
RemoveLeadingZeros(MakeTwosComplement(tempRes)))
else
result := TIntegerX.Create(1, RemoveLeadingZeros(tempRes));
end;
function TIntegerX.ClearBit(n: Integer): TIntegerX;
var
index, len, i: Integer;
tempRes: TArray<UInt32>;
seenNonZero: Boolean;
begin
// This will work if the bit is already clear.
if (not TestBit(n)) then
begin
result := self;
Exit;
end;
index := n div 32;
SetLength(tempRes, Max(Length(_data), index + 1));
len := Length(tempRes);
seenNonZero := false;
i := 0;
while i < len do
begin
tempRes[len - i - 1] := Get2CDigit(i, seenNonZero);
Inc(i);
end;
tempRes[len - index - 1] := tempRes[len - index - 1] and
(not(UInt32(1) shl (n mod 32)));
if (self.IsNegative) then
result := TIntegerX.Create(-1,
RemoveLeadingZeros(MakeTwosComplement(tempRes)))
else
result := TIntegerX.Create(1, RemoveLeadingZeros(tempRes));
end;
function TIntegerX.FlipBit(n: Integer): TIntegerX;
var
index, len, i: Integer;
tempRes: TArray<UInt32>;
seenNonZero: Boolean;
begin
if (n < 0) then
raise EArithmeticException.Create(NegativeAddress);
index := n div 32;
SetLength(tempRes, Max(Length(_data), index + 1));
len := Length(tempRes);
seenNonZero := false;
i := 0;
while i < len do
begin
tempRes[len - i - 1] := Get2CDigit(i, seenNonZero);
Inc(i);
end;
tempRes[len - index - 1] := tempRes[len - index - 1]
xor (UInt32(1) shl (n mod 32));
if (self.IsNegative) then
result := TIntegerX.Create(-1,
RemoveLeadingZeros(MakeTwosComplement(tempRes)))
else
result := TIntegerX.Create(1, RemoveLeadingZeros(tempRes));
end;
function TIntegerX.LeftShift(shift: Integer): TIntegerX;
var
digitShift, bitShift, xlen, rShift, i, j: Integer;
tempRes: TArray<UInt32>;
highBits: UInt32;
begin
if (shift = 0) then
begin
result := self;
Exit;
end;
if (_sign = 0) then
begin
result := self;
Exit;
end;
if (shift < 0) then
begin
result := RightShift(-shift);
Exit;
end;
digitShift := shift div BitsPerDigit;
bitShift := shift mod BitsPerDigit;
xlen := Length(_data);
if (bitShift = 0) then
begin
SetLength(tempRes, xlen + digitShift);
Move(_data[0], tempRes[0], Length(_data) * SizeOf(UInt32));
end
else
begin
rShift := BitsPerDigit - bitShift;
highBits := _data[0] shr rShift;
if (highBits = 0) then
begin
SetLength(tempRes, xlen + digitShift);
i := 0;
end
else
begin
SetLength(tempRes, xlen + digitShift + 1);
tempRes[0] := highBits;
i := 1;
end;
j := 0;
while j < xlen - 1 do
begin
tempRes[i] := (_data[j] shl bitShift) or (_data[j + 1] shr rShift);
Inc(j);
Inc(i);
end;
tempRes[i] := _data[xlen - 1] shl bitShift;
end;
result := TIntegerX.Create(_sign, tempRes);
end;
function TIntegerX.RightShift(shift: Integer): TIntegerX;
var
digitShift, bitShift, xlen, lShift, rlen, i, j: Integer;
tempRes: TArray<UInt32>;
highBits: UInt32;
begin
if (shift = 0) then
begin
result := self;
Exit;
end;
if (_sign = 0) then
begin
result := self;
Exit;
end;
if (shift < 0) then
begin
result := LeftShift(-shift);
Exit;
end;
digitShift := shift div BitsPerDigit;
bitShift := shift mod BitsPerDigit;
xlen := Length(_data);
if (digitShift >= xlen) then
begin
if _sign >= 0 then
begin
result := TIntegerX.Zero;
Exit;
end
else
begin
result := TIntegerX.NegativeOne;
Exit;
end;
end;
if (bitShift = 0) then
begin
rlen := xlen - digitShift;
SetLength(tempRes, rlen);
i := 0;
while i < rlen do
begin
tempRes[i] := _data[i];
Inc(i);
end;
end
else
begin
highBits := _data[0] shr bitShift;
if (highBits = 0) then
begin
rlen := xlen - digitShift - 1;
SetLength(tempRes, rlen);
i := 0;
end
else
begin
rlen := xlen - digitShift;
SetLength(tempRes, rlen);
tempRes[0] := highBits;
i := 1;
end;
lShift := BitsPerDigit - bitShift;
j := 0;
while j < xlen - digitShift - 1 do
begin
tempRes[i] := (_data[j] shl lShift) or (_data[j + 1] shr bitShift);
Inc(j);
Inc(i);
end;
end;
result := TIntegerX.Create(_sign, tempRes);
end;
function TIntegerX.Get2CDigit(n: Integer): UInt32;
var
digit: UInt32;
begin
if (n < 0) then
begin
result := 0;
Exit;
end;
if (n >= Length(_data)) then
begin
result := Get2CSignExtensionDigit();
Exit;
end;
digit := _data[Length(_data) - n - 1];
if (_sign >= 0) then
begin
result := digit;
Exit;
end;
if (n <= FirstNonzero2CDigitIndex()) then
begin
result := (not digit) + 1;
Exit;
end
else
result := not digit;
end;
function TIntegerX.Get2CDigit(n: Integer; var seenNonZero: Boolean): UInt32;
var
digit: UInt32;
begin
if (n < 0) then
begin
result := 0;
Exit;
end;
if (n >= Length(_data)) then
begin
result := Get2CSignExtensionDigit();
Exit;
end;
digit := _data[Length(_data) - n - 1];
if (_sign >= 0) then
begin
result := digit;
Exit;
end;
if (seenNonZero) then
begin
result := not digit;
Exit;
end
else
begin
if (digit = 0) then
begin
result := 0;
Exit;
end
else
begin
seenNonZero := true;
result := not digit + 1;
end;
end;
end;
function TIntegerX.Get2CSignExtensionDigit(): UInt32;
begin
if _sign < 0 then
result := MaxUInt32Value
else
result := 0;
end;
function TIntegerX.FirstNonzero2CDigitIndex(): Integer;
var
i: Integer;
begin
// The Java version caches this value on first computation
i := Length(_data) - 1;
while (i >= 0) and (_data[i] = 0) do
begin
Dec(i);
end;
result := Length(_data) - i - 1;
end;
class function TIntegerX.MakeTwosComplement(a: TArray<UInt32>): TArray<UInt32>;
var
i: Integer;
digit: UInt32;
begin
i := Length(a) - 1;
digit := 0; // to prevent exit on first test
while ((i >= 0) and (digit = 0)) do
begin
digit := not a[i] + 1;
a[i] := digit;
Dec(i);
end;
while i >= 0 do
begin
a[i] := not a[i];
Dec(i);
end;
result := a;
end;
function TIntegerX.Signum: Integer;
begin
result := _sign;
end;
function TIntegerX.IsPositive: Boolean;
begin
result := _sign > 0;
end;
function TIntegerX.IsNegative: Boolean;
begin
result := _sign < 0;
end;
function TIntegerX.IsZero: Boolean;
begin
result := _sign = 0;
end;
function TIntegerX.IsOdd: Boolean;
begin
begin
result := ((_data <> Nil) and (Length(_data) > 0) and
((_data[Length(_data) - 1] and 1) <> 0));
end;
end;
function TIntegerX.GetMagnitude(): TArray<UInt32>;
begin
result := copy(self._data, 0, Length(self._data));
end;
function TIntegerX.BitLength(): UInt32;
var
m: TArray<UInt32>;
len, n, magBitLength, i: UInt32;
pow2: Boolean;
begin
m := self._data;
len := Length(m);
if len = 0 then
begin
n := 0;
end
else
begin
magBitLength := ((len - 1) shl 5) + BitLengthForUInt32(m[0]);
if Signum < 0 then
begin
pow2 := BitCount(m[0]) = 1;
i := 1;
while ((i < len) and (pow2)) do
begin
pow2 := m[i] = 0;
Inc(i);
end;
if pow2 then
n := magBitLength - 1
else
n := magBitLength;
end
else
begin
n := magBitLength;
end;
end;
result := n;
end;
function TIntegerX.BitCount(): UInt32;
var
bc, i, len, magTrailingZeroCount, j: UInt32;
m: TArray<Cardinal>;
begin
m := self._data;
bc := 0;
i := 0;
len := Length(self._data);
while i < len do
begin
bc := bc + BitCount(m[i]);
Inc(i);
end;
if (Signum < 0) then
begin
// Count the trailing zeros in the magnitude
magTrailingZeroCount := 0;
j := len - 1;
while m[j] = 0 do
begin
magTrailingZeroCount := magTrailingZeroCount + 32;
Dec(j);
end;
magTrailingZeroCount := magTrailingZeroCount +
UInt32(TrailingZerosCount(m[j]));
bc := bc + magTrailingZeroCount - 1;
end;
result := bc;
end;
function TIntegerX.ToByteArray(): TArray<Byte>;
var
byteLen, i, bytesCopied, nextInt, intIndex: Integer;
begin
byteLen := Integer(self.BitLength() div 8) + 1;
SetLength(result, byteLen);
i := byteLen - 1;
bytesCopied := 4;
nextInt := 0;
intIndex := 0;
while i >= 0 do
begin
if (bytesCopied = 4) then
begin
nextInt := getInt(intIndex);
Inc(intIndex);
bytesCopied := 1;
end
else
begin
nextInt := Asr(nextInt, 8);
Inc(bytesCopied);
end;
result[i] := Byte(nextInt);
Dec(i);
end;
end;
function TIntegerX.GetPrecision: UInt32;
var
digits: UInt32;
work: TArray<UInt32>;
index: Integer;
begin
if (self.IsZero) then
begin
result := 1; // 0 is one digit
Exit;
end;
digits := 0;
work := self.GetMagnitude(); // need a working copy.
index := 0;
while (index < Pred(Length(work))) do
begin
InPlaceDivRem(work, index, UInt32(1000000000));
digits := digits + 9;
end;
if (index = Pred(Length(work))) then
digits := digits + UIntPrecision(work[index]);
result := digits;
end;
{$IFNDEF _FIXINSIGHT_} // tells FixInsight to Ignore this Function
class function TIntegerX.UIntPrecision(v: UInt32): UInt32;
var
i: UInt32;
begin
i := 1;
while true do
begin
if (v <= FUIntLogTable[i]) then
begin
result := i;
Exit;
end;
Inc(i);
end;
end;
{$ENDIF}
class function TIntegerX.Add(x: TArray<UInt32>; y: TArray<UInt32>)
: TArray<UInt32>;
var
temp, tempRes: TArray<UInt32>;
xi, yi: Integer;
sum: UInt64;
begin
// make sure x is longer, y shorter, swapping if necessary
if (Length(x) < Length(y)) then
begin
temp := x;
x := y;
y := temp;
end;
xi := Length(x);
yi := Length(y);
SetLength(tempRes, xi);
sum := 0;
// add common parts, with carry
while (yi > 0) do
begin
Dec(xi);
Dec(yi);
sum := (sum shr BitsPerDigit) + x[xi] + y[yi];
tempRes[xi] := UInt32(sum);
end;
// copy longer part of x, while carry required
sum := sum shr BitsPerDigit;
while ((xi > 0) and (sum <> 0)) do
begin
Dec(xi);
sum := (UInt64(x[xi])) + 1;
tempRes[xi] := UInt32(sum);
sum := sum shr BitsPerDigit;
end;
// copy remaining part, no carry required
while (xi > 0) do
begin
Dec(xi);
tempRes[xi] := x[xi];
end;
// if carry still required, we must grow
if (sum <> 0) then
tempRes := AddSignificantDigit(tempRes, UInt32(sum));
result := tempRes;
end;
class function TIntegerX.AddSignificantDigit(x: TArray<UInt32>;
newDigit: UInt32): TArray<UInt32>;
var
tempRes: TArray<UInt32>;
i: Integer;
begin
SetLength(tempRes, Length(x) + 1);
tempRes[0] := newDigit;
i := 0;
while i < Length(x) do
begin
tempRes[i + 1] := x[i];
Inc(i);
end;
result := tempRes;
end;
class function TIntegerX.Subtract(xs: TArray<UInt32>; ys: TArray<UInt32>)
: TArray<UInt32>;
var
xlen, ylen, ix, iy: Integer;
tempRes: TArray<UInt32>;
borrow: Boolean;
x, y: UInt32;
begin
// Assume xs > ys
xlen := Length(xs);
ylen := Length(ys);
SetLength(tempRes, xlen);
borrow := false;
ix := xlen - 1;
iy := ylen - 1;
while iy >= 0 do
begin
x := xs[ix];
y := ys[iy];
if (borrow) then
begin
if (x = 0) then
begin
x := $FFFFFFFF;
borrow := true;
end
else
begin
x := x - 1;
borrow := false;
end;
end;
borrow := borrow or (y > x);
tempRes[ix] := x - y;
Dec(iy);
Dec(ix);
end;
while ((borrow) and (ix >= 0)) do
begin
tempRes[ix] := xs[ix] - 1;
borrow := tempRes[ix] = $FFFFFFFF;
Dec(ix);
end;
while ix >= 0 do
begin
tempRes[ix] := xs[ix];
Dec(ix);
end;
result := RemoveLeadingZeros(tempRes);
end;
class function TIntegerX.Multiply(xs: TArray<UInt32>; ys: TArray<UInt32>)
: TArray<UInt32>;
var
xlen, ylen, xi, zi, yi: Integer;
zs: TArray<UInt32>;
x, product: UInt64;
begin
xlen := Length(xs);
ylen := Length(ys);
SetLength(zs, xlen + ylen);
xi := xlen - 1;
while xi >= 0 do
begin
x := xs[xi];
zi := xi + ylen;
product := 0;
yi := ylen - 1;
while yi >= 0 do
begin
product := product + x * ys[yi] + zs[zi];
zs[zi] := UInt32(product);
product := product shr BitsPerDigit;
Dec(yi);
Dec(zi);
end;
while (product <> 0) do
begin
product := product + zs[zi];
zs[zi] := UInt32(product);
Inc(zi);
product := product shr BitsPerDigit;
end;
Dec(xi);
end;
result := RemoveLeadingZeros(zs);
end;
class procedure TIntegerX.DivMod(x: TArray<UInt32>; y: TArray<UInt32>;
out q: TArray<UInt32>; out r: TArray<UInt32>);
const
SuperB: UInt64 = $100000000;
var
ylen, xlen, cmp, shift, j, k, i: Integer;
rem: UInt32;
toptwo, qhat, rhat, val, carry: UInt64;
borrow, temp: Int64;
xnorm, ynorm: TArray<UInt32>;
begin
// Handle some special cases first.
ylen := Length(y);
// Special case: divisor = 0
if (ylen = 0) then
raise EDivByZeroException.Create('');
xlen := Length(x);
// Special case: dividend = 0
if (xlen = 0) then
begin
SetLength(q, 0);
SetLength(r, 0);
Exit;
end;
cmp := Compare(x, y);
// Special case: dividend = divisor
if (cmp = 0) then
begin
q := TArray<UInt32>.Create(1);
r := TArray<UInt32>.Create(0);
Exit;
end;
// Special case: dividend < divisor
if (cmp < 0) then
begin
SetLength(q, 0);
r := copy(x, 0, Length(x));
Exit;
end;
// Special case: divide by single digit (UInt32)
if (ylen = 1) then
begin
rem := CopyDivRem(x, y[0], q);
r := TArray<UInt32>.Create(rem);
Exit;
end;
// Okay.
// Special cases out of the way, let do Knuth's algorithm.
// THis is almost exactly the same as in DLR's BigInteger.
// TODO: Look at the optimizations in the Colin Plumb C library
// (used in the Java BigInteger code).
// D1. Normalize
// Using suggestion to take d = a power of 2 that makes v(n-1) >= b/2.
shift := Integer(LeadingZeroCount(y[0]));
SetLength(xnorm, xlen + 1);
SetLength(ynorm, ylen);
Normalize(xnorm, xlen + 1, x, xlen, shift);
Normalize(ynorm, ylen, y, ylen, shift);
SetLength(q, xlen - ylen + 1);
r := Nil;
// Main loop:
// D2: Initialize j
// D7: Loop on j
// Our loop goes the opposite way because of big-endian
j := 0;
while j <= (xlen - ylen) do
begin
// D3: Calculate qhat.
toptwo := xnorm[j] * SuperB + xnorm[j + 1];
qhat := toptwo div ynorm[0];
rhat := toptwo mod ynorm[0];
// adjust if estimate is too big
while (true) do
begin
if ((qhat < SuperB) and ((qhat * ynorm[1]) <= (SuperB * rhat +
xnorm[j + 2]))) then
break;
Dec(qhat);
// qhat := qhat - 1;
rhat := rhat + UInt64(ynorm[0]);
if (rhat >= SuperB) then
break;
end;
// D4: Multiply and subtract
// Read Knuth very carefully when it comes to
// possibly being too large, borrowing, readjusting.
// It sucks.
borrow := 0;
k := ylen - 1;
while k >= 0 do
begin
i := j + k + 1;
val := ynorm[k] * qhat;
temp := Int64(xnorm[i]) - Int64(UInt32(val)) - borrow;
xnorm[i] := UInt32(temp);
val := val shr BitsPerDigit;
temp := TIntegerX.Asr(temp, BitsPerDigit);
borrow := Int64(val) - temp;
Dec(k);
end;
temp := Int64(xnorm[j]) - borrow;
xnorm[j] := UInt32(temp);
// D5: Test remainder
// We now know the quotient digit at this index
q[j] := UInt32(qhat);
// D6: Add back
// If we went negative, add ynorm back into the xnorm.
if (temp < 0) then
begin
Dec(q[j]);
carry := 0;
k := ylen - 1;
while k >= 0 do
begin
i := j + k + 1;
carry := UInt64(ynorm[k]) + xnorm[i] + carry;
xnorm[i] := UInt32(carry);
carry := carry shr BitsPerDigit;
Dec(k);
end;
carry := carry + UInt64(xnorm[j]);
xnorm[j] := UInt32(carry);
end;
Inc(j);
end;
Unnormalize(xnorm, r, shift);
end;
class procedure TIntegerX.Normalize(var xnorm: TArray<UInt32>; xnlen: Integer;
x: TArray<UInt32>; xlen: Integer; shift: Integer);
var
sameLen: Boolean;
offset, rShift, i: Integer;
carry, xi: UInt32;
begin
sameLen := xnlen = xlen;
if sameLen then
offset := 0
else
offset := 1;
if (shift = 0) then
begin
// just copy, with the added zero at the most significant end.
if (not sameLen) then
xnorm[0] := 0;
i := 0;
while i < xlen do
begin
xnorm[i + offset] := x[i];
Inc(i);
end;
Exit;
end;
rShift := BitsPerDigit - shift;
carry := 0;
i := xlen - 1;
while i >= 0 do
begin
xi := x[i];
xnorm[i + offset] := (xi shl shift) or carry;
carry := xi shr rShift;
Dec(i);
end;
if (sameLen) then
begin
if (carry <> 0) then
raise EInvalidOperationException.Create(CarryOffLeft);
end
else
xnorm[0] := carry;
end;
class procedure TIntegerX.Unnormalize(xnorm: TArray<UInt32>;
out r: TArray<UInt32>; shift: Integer);
var
len, lShift, i: Integer;
carry, lval: UInt32;
begin
len := Length(xnorm);
SetLength(r, len);
if (shift = 0) then
begin
i := 0;
while i < len do
begin
r[i] := xnorm[i];
Inc(i);
end;
end
else
begin
lShift := BitsPerDigit - shift;
carry := 0;
i := 0;
while i < len do
begin
lval := xnorm[i];
r[i] := (lval shr shift) or carry;
carry := lval shl lShift;
Inc(i);
end;
end;
r := RemoveLeadingZeros(r);
end;
class procedure TIntegerX.InPlaceMulAdd(var data: TArray<UInt32>; mult: UInt32;
addend: UInt32);
var
len, i: Integer;
sum, product, carry: UInt64;
begin
len := Length(data);
// Multiply
carry := 0;
i := len - 1;
while i >= 0 do
begin
product := (UInt64(data[i])) * mult + carry;
data[i] := UInt32(product);
carry := product shr BitsPerDigit;
Dec(i);
end;
// Add
sum := (UInt64(data[len - 1])) + addend;
data[len - 1] := UInt32(sum);
carry := sum shr BitsPerDigit;
i := len - 2;
while ((i >= 0) and (carry > 0)) do
begin
sum := (UInt64(data[i])) + carry;
data[i] := UInt32(sum);
carry := sum shr BitsPerDigit;
Dec(i);
end;
end;
class function TIntegerX.RemoveLeadingZeros(data: TArray<UInt32>)
: TArray<UInt32>;
var
len, index, i: Integer;
tempRes: TArray<UInt32>;
begin
len := Length(data);
index := 0;
while ((index < len) and (data[index] = 0)) do
Inc(index);
if (index = 0) then
begin
result := data;
Exit;
end;
// we have leading zeros. Allocate new array.
SetLength(tempRes, len - index);
i := 0;
while (i < (len - index)) do
begin
tempRes[i] := data[index + i];
Inc(i);
end;
result := tempRes;
end;
class function TIntegerX.StripLeadingZeroBytes(a: TArray<Byte>): TArray<UInt32>;
var
byteLength, keep, intLength, b, i, bytesRemaining, bytesToTransfer,
j: Integer;
begin
byteLength := Length(a);
keep := 0;
// Find first nonzero byte
while ((keep < byteLength) and (a[keep] = 0)) do
begin
Inc(keep);
end;
// Allocate new array and copy relevant part of input array
intLength := Asr(((byteLength - keep) + 3), 2);
SetLength(result, intLength);
b := byteLength - 1;
i := intLength - 1;
while i >= 0 do
begin
result[i] := (a[b] and $FF);
Dec(b);
bytesRemaining := b - keep + 1;
bytesToTransfer := Min(3, bytesRemaining);
j := 8;
while j <= (bytesToTransfer shl 3) do
begin
result[i] := result[i] or ((a[b] and $FF) shl j);
Dec(b);
Inc(j, 8);
end;
Dec(i);
end;
end;
class function TIntegerX.makePositive(a: TArray<Byte>): TArray<UInt32>;
var
keep, k, byteLength, extraByte, intLength, b, i, numBytesToTransfer, j,
mask: Integer;
begin
byteLength := Length(a);
// Find first non-sign ($ff) byte of input
keep := 0;
while ((keep < byteLength) and (ShortInt(a[keep]) = -1)) do
begin
Inc(keep);
end;
{ /* Allocate output array. If all non-sign bytes are $00, we must
* allocate space for one extra output byte. */ }
k := keep;
while ((k < byteLength) and (ShortInt(a[k]) = 0)) do
begin
Inc(k);
end;
if k = byteLength then
extraByte := 1
else
extraByte := 0;
intLength := ((byteLength - keep + extraByte) + 3) div 4;
SetLength(result, intLength);
{ /* Copy one's complement of input into output, leaving extra
* byte (if it exists) = $00 */ }
b := byteLength - 1;
i := intLength - 1;
while i >= 0 do
begin
result[i] := (a[b]) and $FF;
Dec(b);
numBytesToTransfer := Min(3, b - keep + 1);
if (numBytesToTransfer < 0) then
numBytesToTransfer := 0;
j := 8;
while j <= 8 * numBytesToTransfer do
begin
result[i] := result[i] or ((a[b] and $FF) shl j);
Dec(b);
Inc(j, 8);
end;
// Mask indicates which bits must be complemented
mask := Asr(UInt32(-1), (8 * (3 - numBytesToTransfer)));
result[i] := (not result[i]) and mask;
Dec(i);
end;
// Add one to one's complement to generate two's complement
i := Length(result) - 1;
while i >= 0 do
begin
result[i] := Integer((result[i] and $FFFFFFFF) + 1);
if (result[i] <> 0) then
break;
Dec(i);
end;
end;
class function TIntegerX.InPlaceDivRem(var data: TArray<UInt32>;
var index: Integer; divisor: UInt32): UInt32;
var
rem: UInt64;
seenNonZero: Boolean;
len, i: Integer;
q: UInt32;
begin
rem := 0;
seenNonZero := false;
len := Length(data);
i := index;
while i < len do
begin
rem := rem shl BitsPerDigit;
rem := rem or data[i];
q := UInt32(rem div divisor);
data[i] := q;
if (q = 0) then
begin
if (not seenNonZero) then
Inc(index);
end
else
seenNonZero := true;
rem := rem mod divisor;
Inc(i);
end;
result := UInt32(rem);
end;
class function TIntegerX.CopyDivRem(data: TArray<UInt32>; divisor: UInt32;
out quotient: TArray<UInt32>): UInt32;
var
rem: UInt64;
len, i: Integer;
q: UInt32;
begin
SetLength(quotient, Length(data));
rem := 0;
len := Length(data);
i := 0;
while i < len do
begin
rem := rem shl BitsPerDigit;
rem := rem or data[i];
q := UInt32(rem div divisor);
quotient[i] := q;
rem := rem mod divisor;
Inc(i);
end;
quotient := RemoveLeadingZeros(quotient);
result := UInt32(rem);
end;
function TIntegerX.signInt(): Integer;
begin
if self.Signum < 0 then
result := -1
else
result := 0;
end;
function TIntegerX.getInt(n: Integer): Integer;
var
magInt: Integer;
begin
if (n < 0) then
begin
result := 0;
Exit;
end;
if (n >= Length(self._data)) then
begin
result := signInt();
Exit;
end;
magInt := self._data[Length(self._data) - n - 1];
if Signum >= 0 then
result := magInt
else
begin
if n <= firstNonzeroIntNum() then
result := -magInt
else
result := not magInt;
end;
end;
function TIntegerX.firstNonzeroIntNum(): Integer;
var
fn, i, mlen: Integer;
begin
// Search for the first nonzero int
mlen := Length(self._data);
i := mlen - 1;
while ((i >= 0) and (self._data[i] = 0)) do
begin
Dec(i);
end;
fn := mlen - i - 1;
result := fn;
end;
class function TIntegerX.GetZero: TIntegerX;
begin
result := ZeroX;
end;
class function TIntegerX.GetOne: TIntegerX;
begin
result := OneX;
end;
class function TIntegerX.GetTwo: TIntegerX;
begin
result := TwoX;
end;
class function TIntegerX.GetFive: TIntegerX;
begin
result := FiveX;
end;
class function TIntegerX.GetTen: TIntegerX;
begin
result := TenX;
end;
class function TIntegerX.GetNegativeOne: TIntegerX;
begin
result := NegativeOneX;
end;
end.
|
{*********************************************************************************}
{ }
{ XML Data Binding }
{ }
{ Generated on: 21.11.2019 13:34:44 }
{ Generated from: D:\Work\Project\XML\contrl_20190815010843_276888325.xml }
{ Settings stored in: D:\Work\Project\XML\contrl_20190815010843_276888325.xdb }
{ }
{*********************************************************************************}
unit ContrlXML;
interface
uses xmldom, XMLDoc, XMLIntf;
type
{ Forward Decls }
IXMLCONTRLType = interface;
{ IXMLCONTRLType }
IXMLCONTRLType = interface(IXMLNode)
['{EB1A919D-056A-4060-834E-8A9F333C9128}']
{ Property Accessors }
function Get_NUMBER: Integer;
function Get_DATE: UnicodeString;
function Get_RECADVDATE: UnicodeString;
function Get_ORDERNUMBER: UnicodeString;
function Get_ORDERDATE: UnicodeString;
function Get_RECIPIENT: Integer;
function Get_SUPPLIER: Integer;
function Get_BUYER: Integer;
function Get_ACTION: Integer;
procedure Set_NUMBER(Value: Integer);
procedure Set_DATE(Value: UnicodeString);
procedure Set_RECADVDATE(Value: UnicodeString);
procedure Set_ORDERNUMBER(Value: UnicodeString);
procedure Set_ORDERDATE(Value: UnicodeString);
procedure Set_RECIPIENT(Value: Integer);
procedure Set_SUPPLIER(Value: Integer);
procedure Set_BUYER(Value: Integer);
procedure Set_ACTION(Value: Integer);
{ Methods & Properties }
property NUMBER: Integer read Get_NUMBER write Set_NUMBER;
property DATE: UnicodeString read Get_DATE write Set_DATE;
property RECADVDATE: UnicodeString read Get_RECADVDATE write Set_RECADVDATE;
property ORDERNUMBER: UnicodeString read Get_ORDERNUMBER write Set_ORDERNUMBER;
property ORDERDATE: UnicodeString read Get_ORDERDATE write Set_ORDERDATE;
property RECIPIENT: Integer read Get_RECIPIENT write Set_RECIPIENT;
property SUPPLIER: Integer read Get_SUPPLIER write Set_SUPPLIER;
property BUYER: Integer read Get_BUYER write Set_BUYER;
property ACTION: Integer read Get_ACTION write Set_ACTION;
end;
{ Forward Decls }
TXMLCONTRLType = class;
{ TXMLCONTRLType }
TXMLCONTRLType = class(TXMLNode, IXMLCONTRLType)
protected
{ IXMLCONTRLType }
function Get_NUMBER: Integer;
function Get_DATE: UnicodeString;
function Get_RECADVDATE: UnicodeString;
function Get_ORDERNUMBER: UnicodeString;
function Get_ORDERDATE: UnicodeString;
function Get_RECIPIENT: Integer;
function Get_SUPPLIER: Integer;
function Get_BUYER: Integer;
function Get_ACTION: Integer;
procedure Set_NUMBER(Value: Integer);
procedure Set_DATE(Value: UnicodeString);
procedure Set_RECADVDATE(Value: UnicodeString);
procedure Set_ORDERNUMBER(Value: UnicodeString);
procedure Set_ORDERDATE(Value: UnicodeString);
procedure Set_RECIPIENT(Value: Integer);
procedure Set_SUPPLIER(Value: Integer);
procedure Set_BUYER(Value: Integer);
procedure Set_ACTION(Value: Integer);
end;
{ Global Functions }
function GetContrl(Doc: IXMLDocument): IXMLCONTRLType;
function LoadContrl(const FileName: string): IXMLCONTRLType;
function NewContrl: IXMLCONTRLType;
const
TargetNamespace = '';
implementation
{ Global Functions }
function GetContrl(Doc: IXMLDocument): IXMLCONTRLType;
begin
Result := Doc.GetDocBinding('Contrl', TXMLCONTRLType, TargetNamespace) as IXMLCONTRLType;
end;
function LoadContrl(const FileName: string): IXMLCONTRLType;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('Contrl', TXMLCONTRLType, TargetNamespace) as IXMLCONTRLType;
end;
function NewContrl: IXMLCONTRLType;
begin
Result := NewXMLDocument.GetDocBinding('Contrl', TXMLCONTRLType, TargetNamespace) as IXMLCONTRLType;
end;
{ TXMLCONTRLType }
function TXMLCONTRLType.Get_NUMBER: Integer;
begin
Result := ChildNodes['NUMBER'].NodeValue;
end;
procedure TXMLCONTRLType.Set_NUMBER(Value: Integer);
begin
ChildNodes['NUMBER'].NodeValue := Value;
end;
function TXMLCONTRLType.Get_DATE: UnicodeString;
begin
Result := ChildNodes['DATE'].Text;
end;
procedure TXMLCONTRLType.Set_DATE(Value: UnicodeString);
begin
ChildNodes['DATE'].NodeValue := Value;
end;
function TXMLCONTRLType.Get_RECADVDATE: UnicodeString;
begin
Result := ChildNodes['RECADVDATE'].Text;
end;
procedure TXMLCONTRLType.Set_RECADVDATE(Value: UnicodeString);
begin
ChildNodes['RECADVDATE'].NodeValue := Value;
end;
function TXMLCONTRLType.Get_ORDERNUMBER: UnicodeString;
begin
Result := ChildNodes['ORDERNUMBER'].Text;
end;
procedure TXMLCONTRLType.Set_ORDERNUMBER(Value: UnicodeString);
begin
ChildNodes['ORDERNUMBER'].NodeValue := Value;
end;
function TXMLCONTRLType.Get_ORDERDATE: UnicodeString;
begin
Result := ChildNodes['ORDERDATE'].Text;
end;
procedure TXMLCONTRLType.Set_ORDERDATE(Value: UnicodeString);
begin
ChildNodes['ORDERDATE'].NodeValue := Value;
end;
function TXMLCONTRLType.Get_RECIPIENT: Integer;
begin
Result := ChildNodes['RECIPIENT'].NodeValue;
end;
procedure TXMLCONTRLType.Set_RECIPIENT(Value: Integer);
begin
ChildNodes['RECIPIENT'].NodeValue := Value;
end;
function TXMLCONTRLType.Get_SUPPLIER: Integer;
begin
Result := ChildNodes['SUPPLIER'].NodeValue;
end;
procedure TXMLCONTRLType.Set_SUPPLIER(Value: Integer);
begin
ChildNodes['SUPPLIER'].NodeValue := Value;
end;
function TXMLCONTRLType.Get_BUYER: Integer;
begin
Result := ChildNodes['BUYER'].NodeValue;
end;
procedure TXMLCONTRLType.Set_BUYER(Value: Integer);
begin
ChildNodes['BUYER'].NodeValue := Value;
end;
function TXMLCONTRLType.Get_ACTION: Integer;
begin
Result := ChildNodes['ACTION'].NodeValue;
end;
procedure TXMLCONTRLType.Set_ACTION(Value: Integer);
begin
ChildNodes['ACTION'].NodeValue := Value;
end;
end. |
unit Settings;
{
Copyright (c) 2014 Josh Blake
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License, as described at
http://www.apache.org/licenses/ and http://www.pp4s.co.uk/licenses/
}
interface
const
ENEMY_CREATION_SPEED = 0.07; //start creation speed
ENEMY_CREATION_MULTIPLIER = 1000; //speed of increase
BACKGROUND_COLOR = 'black';
PLAYER_COLOR = 'blue';
ENEMY_COLOR = 'red';
BULLET_COLOR = 'white';
ENEMY_SPEED = 3;
PLAYER_SPEED = 2;
BULLET_SPEED = 5;
BULLET_INTERVAL = 0.00001;
DEBUG = true;
procedure Log(aMessage: String);
implementation
procedure Log(aMessage: String);
begin
if DEBUG then begin
asm
console.log((@aMessage));
end;
end;
end;
end. |
unit ProductionUnionTechEdit;
interface
uses
AncestorEditDialog, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters,
Vcl.Menus, cxControls, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils,
dsdGuides, cxDropDownEdit, cxCalendar, cxMaskEdit, cxButtonEdit, cxTextEdit,
cxCurrencyEdit, Vcl.Controls, cxLabel, dsdDB, dsdAction, System.Classes,
Vcl.ActnList, cxPropertiesStore, dsdAddOn, Vcl.StdCtrls, cxButtons,
dxSkinsCore, dxSkinsDefaultPainters, dxSkinBlack, dxSkinBlue, dxSkinBlueprint,
dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven,
dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver,
dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld,
dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue;
type
TProductionUnionTechEditForm = class(TAncestorEditDialogForm)
cxLabel1: TcxLabel;
ceOperDate: TcxDateEdit;
ceRealWeight: TcxCurrencyEdit;
cxLabel7: TcxLabel;
ceRecipe: TcxButtonEdit;
ReceiptGuides: TdsdGuides;
cxLabel6: TcxLabel;
GuidesFiller: TGuidesFiller;
cxLabel10: TcxLabel;
ceComment: TcxTextEdit;
ceGooods: TcxButtonEdit;
cxLabel12: TcxLabel;
ReceiptGoodsGuides: TdsdGuides;
cxLabel3: TcxLabel;
ceCount: TcxCurrencyEdit;
cxLabel4: TcxLabel;
ceŅuterCount: TcxCurrencyEdit;
cxLabel11: TcxLabel;
ceŅuterCountOrder: TcxCurrencyEdit;
cxLabel13: TcxLabel;
ceAmountOrder: TcxCurrencyEdit;
cxLabel2: TcxLabel;
cxLabel5: TcxLabel;
GooodsKindGuides: TdsdGuides;
ceGooodsKindGuides: TcxButtonEdit;
ceReceiptCode: TcxTextEdit;
cxLabel8: TcxLabel;
ceGooodsKindCompleteGuides: TcxButtonEdit;
GooodsKindCompleteGuides: TdsdGuides;
cxLabel9: TcxLabel;
ceCuterWeight: TcxCurrencyEdit;
cxLabel14: TcxLabel;
edDocumentKind: TcxButtonEdit;
GuidesDocumentKind: TdsdGuides;
cxLabel15: TcxLabel;
ceAmount: TcxCurrencyEdit;
cxLabel16: TcxLabel;
ceRealWeightMsg: TcxCurrencyEdit;
ceRealWeightShp: TcxCurrencyEdit;
cxLabel17: TcxLabel;
cxLabel18: TcxLabel;
ceCountReal: TcxCurrencyEdit;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TProductionUnionTechEditForm);
end.
|
unit dsdDataSetDataLink;
interface
uses DB;
type
// Вызываем события при изменении каких параметров датасета
IDataSetAction = interface
procedure DataSetChanged;
procedure UpdateData;
end;
TDataSetDataLink = class(TDataLink)
private
FAction: IDataSetAction;
// вешаем флаг, потому что UpdateData срабатывает ДВАЖДЫ!!!
FModified: Boolean;
protected
procedure EditingChanged; override;
procedure DataSetChanged; override;
procedure UpdateData; override;
public
constructor Create(Action: IDataSetAction);
end;
implementation
{ TActionDataLink }
constructor TDataSetDataLink.Create(Action: IDataSetAction);
begin
inherited Create;
FAction := Action;
end;
procedure TDataSetDataLink.DataSetChanged;
begin
inherited;
if Assigned(FAction) then
FAction.DataSetChanged;
end;
procedure TDataSetDataLink.EditingChanged;
begin
inherited;
if Assigned(DataSource) and (DataSource.State in [dsEdit, dsInsert]) then
FModified := true;
end;
procedure TDataSetDataLink.UpdateData;
begin
inherited;
if Assigned(FAction) and FModified then
FAction.UpdateData;
FModified := false;
end;
end.
|
unit MT19937;
{$R-} {range checking off}
{$Q-} {overflow checking off}
{----------------------------------------------------------------------
Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
Pseudo-Random Number Generator.
What is Mersenne Twister?
Mersenne Twister(MT) is a pseudorandom number generator developped by
Makoto Matsumoto and Takuji Nishimura (alphabetical order) during
1996-1997. MT has the following merits:
It is designed with consideration on the flaws of various existing
generators.
Far longer period and far higher order of equidistribution than any
other implemented generators. (It is proved that the period is 2^19937-1,
and 623-dimensional equidistribution property is assured.)
Fast generation. (Although it depends on the system, it is reported that
MT is sometimes faster than the standard ANSI-C library in a system
with pipeline and cache memory.)
Efficient use of the memory. (The implemented C-code mt19937.c
consumes only 624 words of working area.)
home page
http://www.math.keio.ac.jp/~matumoto/emt.html
original c source
http://www.math.keio.ac.jp/~nisimura/random/int/mt19937int.c
Coded by Takuji Nishimura, considering the suggestions by
Topher Cooper and Marc Rieffel in July-Aug. 1997.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later
version.
This library 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 Library General Public License for more details.
You should have received a copy of the GNU Library General
Public License along with this library; if not, write to the
Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura.
When you use this, send an email to: matumoto@math.keio.ac.jp
with an appropriate reference to your work.
REFERENCE
M. Matsumoto and T. Nishimura,
"Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
Pseudo-Random Number Generator",
ACM Transactions on Modeling and Computer Simulation,
Vol. 8, No. 1, January 1998, pp 3--30.
Translated to OP and Delphi interface added by Roman Krejci (6.12.1999)
http://www.rksolution.cz/delphi/tips.htm
Revised 21.6.2000: Bug in the function RandInt_MT19937 fixed
----------------------------------------------------------------------}
interface
{ Period parameter }
Const
MT19937N=624;
Type
tMT19937StateArray = array [0..MT19937N-1] of longint; // the array for the state vector
procedure sgenrand_MT19937(seed: longint); // Initialization by seed
procedure lsgenrand_MT19937(const seed_array: tMT19937StateArray); // Initialization by array of seeds
procedure randomize_MT19937; // randomization
function randInt_MT19937(Range: longint):longint; // integer RANDOM with positive range
function genrand_MT19937: longint; // random longint (full range);
function randFloat_MT19937: Double; // float RANDOM on 0..1 interval
implementation
{ Period parameters }
const
MT19937M=397;
MT19937MATRIX_A =$9908b0df; // constant vector a
MT19937UPPER_MASK=$80000000; // most significant w-r bits
MT19937LOWER_MASK=$7fffffff; // least significant r bits
{ Tempering parameters }
TEMPERING_MASK_B=$9d2c5680;
TEMPERING_MASK_C=$efc60000;
VAR
mt : tMT19937StateArray;
mti: integer=MT19937N+1; // mti=MT19937N+1 means mt[] is not initialized
{ Initializing the array with a seed }
procedure sgenrand_MT19937(seed: longint);
var
i: integer;
begin
for i := 0 to MT19937N-1 do begin
mt[i] := seed and $ffff0000;
seed := 69069 * seed + 1;
mt[i] := mt[i] or ((seed and $ffff0000) shr 16);
seed := 69069 * seed + 1;
end;
mti := MT19937N;
end;
{
Initialization by "sgenrand_MT19937()" is an example. Theoretically,
there are 2^19937-1 possible states as an intial state.
This function (lsgenrand_MT19937) allows to choose any of 2^19937-1 ones.
Essential bits in "seed_array[]" is following 19937 bits:
(seed_array[0]&MT19937UPPER_MASK), seed_array[1], ..., seed_array[MT19937-1].
(seed_array[0]&MT19937LOWER_MASK) is discarded.
Theoretically,
(seed_array[0]&MT19937UPPER_MASK), seed_array[1], ..., seed_array[MT19937N-1]
can take any values except all zeros.
}
procedure lsgenrand_MT19937(const seed_array: tMT19937StateArray);
VAR
i: integer;
begin
for i := 0 to MT19937N-1 do mt[i] := seed_array[i];
mti := MT19937N;
end;
function genrand_MT19937: longint;
const
mag01 : array [0..1] of longint =(0, MT19937MATRIX_A);
var
y: longint;
kk: integer;
begin
if mti >= MT19937N { generate MT19937N longints at one time }
then begin
if mti = (MT19937N+1) then // if sgenrand_MT19937() has not been called,
sgenrand_MT19937(4357); // default initial seed is used
for kk:=0 to MT19937N-MT19937M-1 do begin
y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
mt[kk] := mt[kk+MT19937M] xor (y shr 1) xor mag01[y and $00000001];
end;
for kk:= MT19937N-MT19937M to MT19937N-2 do begin
y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
mt[kk] := mt[kk+(MT19937M-MT19937N)] xor (y shr 1) xor mag01[y and $00000001];
end;
y := (mt[MT19937N-1] and MT19937UPPER_MASK) or (mt[0] and MT19937LOWER_MASK);
mt[MT19937N-1] := mt[MT19937M-1] xor (y shr 1) xor mag01[y and $00000001];
mti := 0;
end;
y := mt[mti]; inc(mti);
y := y xor (y shr 11);
y := y xor (y shl 7) and TEMPERING_MASK_B;
y := y xor (y shl 15) and TEMPERING_MASK_C;
y := y xor (y shr 18);
Result := y;
end;
{ Delphi interface }
procedure Randomize_MT19937;
Var OldRandSeed: longint;
begin
OldRandSeed := System.randseed; // save system RandSeed value
System.randomize; // randseed value based on system time is generated
sgenrand_MT19937(System.randSeed); // initialize generator state array
System.randseed := OldRandSeed; // restore system RandSeed
end;
// bug fixed 21.6.2000.
Function RandInt_MT19937(Range: longint):longint;
// EAX <- Range
// Result -> EAX
asm
PUSH EAX
CALL genrand_MT19937
POP EDX
MUL EDX
MOV EAX,EDX
end;
function RandFloat_MT19937: Double;
const Minus32: double = -32.0;
asm
CALL genrand_MT19937
PUSH 0
PUSH EAX
FLD Minus32
FILD qword ptr [ESP]
ADD ESP,8
FSCALE
FSTP ST(1)
end;
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2019 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit Server.MainData;
interface
uses
System.SysUtils, System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, Data.DB, FireDAC.Comp.Client, FireDAC.Phys.FB,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.VCLUI.Wait, FireDAC.Comp.UI,
FireDAC.Phys.SQLite, FireDAC.Stan.ExprFuncs,
WiRL.Data.FireDAC.DataModule,
WiRL.Core.Attributes,
WiRL.http.URL,
WiRL.Core.Auth.Context, FireDAC.Phys.SQLiteDef;
type
[Path('/maindata')]
TMainDataResource = class(TWiRLFDDataModuleResource)
FDConnection1: TFDConnection;
employee: TFDQuery;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
private
public
// [GET, Path('/standard')]
// function StandardDataSet: TArray<TDataset>;
// [GET, Path('/employee')]
// function EmployeeDataSet: TDataSet;
end;
implementation
{$R *.dfm}
uses
WiRL.Core.Registry;
{ TMainDataResource }
//function TMainDataResource.EmployeeDataSet: TDataSet;
//begin
// Result := Employee;
//end;
//
//function TMainDataResource.StandardDataSet: TArray<TDataset>;
//begin
// Result := [employee];
//end;
initialization
TWiRLResourceRegistry.Instance.RegisterResource<TMainDataResource>(
function: TObject
begin
Result := TMainDataResource.Create(nil);
end
);
end.
|
unit uProduto;
interface
Type
TProduto = class
private
FEstoqueAtual: Double;
FdescricaoFiscal: string;
FPrecoCusto: Double;
FPrecoVenda: Double;
FidProduto: integer;
FNCM: String;
FAliquota: Double;
FcodigoBarra: string;
FST: Integer;
FUnidade: String;
FReferencia: String;
FOrigem: Integer;
procedure SetAliquota(const Value: Double);
procedure SetcodigoBarra(const Value: string);
procedure SetdescricaoFiscal(const Value: string);
procedure SetEstoqueAtual(const Value: Double);
procedure SetidProduto(const Value: integer);
procedure SetNCM(const Value: String);
procedure SetOrigem(const Value: Integer);
procedure SetPrecoCusto(const Value: Double);
procedure SetPrecoVenda(const Value: Double);
procedure SetReferencia(const Value: String);
procedure SetST(const Value: Integer);
procedure SetUnidade(const Value: String);
published
property idProduto : integer read FidProduto write SetidProduto;
property Referencia : String read FReferencia write SetReferencia;
property codigoBarra : string read FcodigoBarra write SetcodigoBarra;
property descricaoFiscal : string read FdescricaoFiscal write SetdescricaoFiscal;
property NCM : String read FNCM write SetNCM;
property PrecoCusto : Double read FPrecoCusto write SetPrecoCusto;
property PrecoVenda : Double read FPrecoVenda write SetPrecoVenda;
property EstoqueAtual : Double read FEstoqueAtual write SetEstoqueAtual;
property Unidade : String read FUnidade write SetUnidade;
property Origem : Integer read FOrigem write SetOrigem;
property ST : Integer read FST write SetST;
property Aliquota : Double read FAliquota write SetAliquota;
end;
implementation
{ TProduto }
procedure TProduto.SetAliquota(const Value: Double);
begin
FAliquota := Value;
end;
procedure TProduto.SetcodigoBarra(const Value: string);
begin
FcodigoBarra := Value;
end;
procedure TProduto.SetdescricaoFiscal(const Value: string);
begin
FdescricaoFiscal := Value;
end;
procedure TProduto.SetEstoqueAtual(const Value: Double);
begin
FEstoqueAtual := Value;
end;
procedure TProduto.SetidProduto(const Value: integer);
begin
FidProduto := Value;
end;
procedure TProduto.SetNCM(const Value: String);
begin
FNCM := Value;
end;
procedure TProduto.SetOrigem(const Value: Integer);
begin
FOrigem := Value;
end;
procedure TProduto.SetPrecoCusto(const Value: Double);
begin
FPrecoCusto := Value;
end;
procedure TProduto.SetPrecoVenda(const Value: Double);
begin
FPrecoVenda := Value;
end;
procedure TProduto.SetReferencia(const Value: String);
begin
FReferencia := Value;
end;
procedure TProduto.SetST(const Value: Integer);
begin
FST := Value;
end;
procedure TProduto.SetUnidade(const Value: String);
begin
FUnidade := Value;
end;
end.
|
PROGRAM Phase1 (Infile,Outfile,input,output);
{Reads a text file of the users choice and writes it to a print file
with all lines within the user set line length - no split words, no
hyphens)
TYPE Line = Packed Array[1..80] of char;
Filename = Packed Array[1..12] of char;
VAR OutBuffer,Word: Line;
WordLength,LineLength,OutLength: integer;
Ch,Spacing: char;
File1,File2: Filename;
InFile,OutFile: text;
%INCLUDE 'GetPut.Pas'
(*************************************************************************(
PROCEDURE Init(var InFile,OutFile: text;
File1,File2: Filename);
{Opens the Files requested by user as InFile and OutFile and puts
them in the proper mode}
BEGIN {Init}
OPEN(InFile,File1,History:=Old);
RESET(InFile);
OPEN(OutFile,File2,History:=Old);
REWRITE(OutFile);
END; {Init}
(*************************************************************************)
PROCEDURE GetInfo(var File1,File2: Filename;
var LineLength,Spacing: integer);
{Asks user to enter the input and output files, line lenght (60
or 70) and spacing (1 for single, 2 for double)}
BEGIN {GetInfo}
Writeln('Input file ? ');
Readln(File1);
Writeln('Output File ?);
Readln(File2);
Writeln('Maximum Line Length - 60 or 70 ?');
Readln(LineLength);
Writeln('Spacing - 1 for Single, 2 for Double');
Readln(Spacing);
END; {GetInfo}
(*************************************************************************)
PROCEDURE GetLine(var InFile: Text;
var OutBuffer: Line;
var Ch; char;
LineLength: integer);
{Reads from the file and builds the line until is reaches line
Length)
VAR WordLength,Counter: integer;
Word: Line;
BEGIN {GetLine}
Clear(OutBuffer);
Clear(Word);
Word[1] := Ch;
OutBuffer[1] := Ch;
LineSize := 0;
WHILE (LineSize <= LineLength) AND (Ch <> ENDFILE) DO
BEGIN {While}
WordLength := 0;
Clear(Word);
REPEAT
WordLength := WordLength + 1;
Getcf(InFile,Ch);
Word[WordLength] := Ch;
UNTIL (Ch = Blank) OR (Ch = ENDFILE);
IF (WordLength + LineSize) < LineLength
THEN FOR Counter := (LineSize + 2) TO (LineSize + WordLength) DO
BEGIN {FOR}
OutBuffer[Counter] := Word[Counter];
LineSize := Counter;
END; {FOR}
END; {WHILE
Writeln(OutBuffer);
END; {GetLine}
(*************************************************************************)
BEGIN {Phase1}
Initio;
GetInfo(File1,File2,LineLength,Spacing);
Init(InFile,OutFile,File1,File2);
GetLine(InFile,OutBuffer,Ch,LineLength);
END. {Phase1}
|
unit i_VectorItemLonLat;
interface
uses
t_GeoTypes,
i_EnumDoublePoint,
i_LonLatRect,
i_Datum;
type
ILonLatPathLine = interface
['{26634DF5-7845-42C1-8B74-C6F4FFA7E27E}']
function GetEnum: IEnumLonLatPoint;
function IsSame(const ALine: ILonLatPathLine): Boolean;
function GetBounds: ILonLatRect;
property Bounds: ILonLatRect read GetBounds;
function CalcLength(const ADatum: IDatum): Double;
function GetCount: Integer;
property Count: Integer read GetCount;
function GetPoints: PDoublePointArray;
property Points: PDoublePointArray read GetPoints;
end;
ILonLatPolygonLine = interface
['{A1F32B46-8C0B-46F1-97E9-D2347CF9FF5B}']
function GetEnum: IEnumLonLatPoint;
function IsSame(const ALine: ILonLatPolygonLine): Boolean;
function GetBounds: ILonLatRect;
property Bounds: ILonLatRect read GetBounds;
function CalcPerimeter(const ADatum: IDatum): Double;
function CalcArea(const ADatum: IDatum): Double;
function GetCount: Integer;
property Count: Integer read GetCount;
function GetPoints: PDoublePointArray;
property Points: PDoublePointArray read GetPoints;
end;
ILonLatPath = interface
['{0E85CB46-D324-4052-BDE3-63F1C4A2665A}']
function GetEnum: IEnumLonLatPoint;
function IsSame(const APath: ILonLatPath): Boolean;
function GetBounds: ILonLatRect;
property Bounds: ILonLatRect read GetBounds;
function CalcLength(const ADatum: IDatum): Double;
function GetCount: Integer;
property Count: Integer read GetCount;
function GetItem(AIndex: Integer): ILonLatPathLine;
property Item[AIndex: Integer]: ILonLatPathLine read GetItem;
end;
ILonLatPolygon = interface
['{04CEBFBE-8FC1-4AB0-8B39-3C283287BF46}']
function GetEnum: IEnumLonLatPoint;
function IsSame(const APolygon: ILonLatPolygon): Boolean;
function GetBounds: ILonLatRect;
property Bounds: ILonLatRect read GetBounds;
function CalcPerimeter(const ADatum: IDatum): Double;
function CalcArea(const ADatum: IDatum): Double;
function GetCount: Integer;
property Count: Integer read GetCount;
function GetItem(AIndex: Integer): ILonLatPolygonLine;
property Item[AIndex: Integer]: ILonLatPolygonLine read GetItem;
end;
implementation
end.
|
unit rVclUtils;
interface
uses
Classes, Controls, SysUtils;
type
RId2 = record
iId1: Integer;
iId2: Integer;
end;
RKindId = record
Id: Integer;
Kind: Integer;
end;
TTextStyle = ^RTextStyle;
RTextStyle = record
FontStyle: Integer;
FontColor: Integer;
BackColor: Integer;
end;
TIntegerObject = class (TObject)
private
fValue: Integer;
public
constructor Create(const aValue: Integer);
property Value: Integer read fValue write fValue;
end;
TId = ^Integer;
TId2 = ^RId2;
TKindId = ^RKindId;
TByteSet = set of Byte;
EDllException = class(Exception);
EDLLLoadError = class(Exception);
EDLLCantFindProc = class(Exception);
const
intDisable = -1;
intFieldToColumnWidth = 6;
// Форматирование полей записей
SNullText = '<NULL>';
SBlobText = '{DATA}';
SNoneText = '???';
SFieldText = '%s="%s"';
// Расширения файлов
SAnyFile = '*.*';
SIniExt = '.ini';
// Разделитель списков "по умолчанию"
chListDivChar = ',';
chDefDivChar = ';';
chDivChars = [',',';'];
// Стандартные коды операций
tagDbUpdate = 9995;
tagError = 9998;
// Коды изображений
imBm_Properties = 9;
imBm_Folder = 26;
imBm_OpenFolder = 27;
imOk = 0;
imCancel = 1;
imSave = -1;
imNew = 8;
imEdit = 9;
imDeleted = 10;
imLink = 28;
imFree = 29;
cEOF = #13#10;
cCR = #10;
cLF = #13;
cTAB = #9;
{ == Проверка, включено ли значение в динамический список ====================== }
function ValueInList(const Value: Integer; const ValuesList: array of Integer): Boolean;
{ == Смена курсора на время занятости приложения =============================== }
procedure StartWait;
procedure StopWait;
procedure ExitWait;
procedure PauseWait;
procedure ContiniueWait;
function IsNotWait: Boolean;
{ == Блокировка элементов управления =========================================== }
procedure ToggleControls(Control: TWinControl; const Enabled: Boolean);
{ == Вывод информации в главную строку статуса приложения ====================== }
procedure ShowInStatusBar(const Msg: string);
procedure ShowInStatusBarPanel(const Panel: Integer; Msg: string);
{ == Задержка выполнения программы ============================================= }
procedure Delay(MSecs: Longint);
{ == Генерация записи RKindId ================================================== }
function KindId(const AId, AKind: Integer): RKindId;
{ == Правильное преобразование Boolean в строку и обратно ====================== }
function RBoolToStr(const aValue: Boolean): string;
function RStrToBool(const aValue: string): Boolean;
{ == Преобразование строки в число (кривые символы игнорируются) =============== }
function RIntToStr(const aValue: Integer): string;
function RFloatToStr(const aValue: Extended): string;
function RStrToInt(const StrValue: string): Integer;
function RStrToIntDef(const StrValue: string; const DefValue: Integer): Integer;
function RStrToFloat(const StrValue: string): Extended;
function RStrToFloatDef(const StrValue: string; const DefValue: Extended): Extended;
{ == Преобразование вариантов в число ========================================== }
function RVarToInteger(const VarValue: Variant): Integer;
implementation
uses
Forms, Windows, StdCtrls, ComCtrls, Variants;
const
StatusBarName = 'StatusBar';
var
iWaitCount, tWaitCount: Integer;
{ TIntegerObject }
constructor TIntegerObject.Create(const aValue: Integer);
begin
inherited Create;
fValue := aValue;
end;
{ == Проверка, включено ли значение в динамический список ====================== }
function ValueInList(const Value: Integer; const ValuesList: array of Integer): Boolean;
var
i: Integer;
begin
Result := False;
for i := Low(ValuesList) to High(ValuesList) do
begin
Result := Value = ValuesList[i];
if Result then Break;
end;
end;
{ == Смена курсора на время занятости приложения =============================== }
procedure StartWait;
begin
Inc(iWaitCount);
Screen.Cursor := crHourGlass;
end;
procedure StopWait;
begin
if iWaitCount > 0 then Dec(iWaitCount);
if iWaitCount = 0 then Screen.Cursor := crDefault;
end;
procedure ExitWait;
begin
iWaitCount := 0;
Screen.Cursor := crDefault;
end;
function IsNotWait: Boolean;
begin
Result := iWaitCount = 0;
end;
procedure PauseWait;
begin
tWaitCount := iWaitCount;
ExitWait;
end;
procedure ContiniueWait;
begin
iWaitCount := tWaitCount;
if iWaitCount = 0 then Screen.Cursor := crDefault else Screen.Cursor := crHourGlass;
end;
{ == Блокировка элементов управления =========================================== }
procedure ToggleControls(Control: TWinControl; const Enabled: Boolean);
var
i: Integer;
begin
for i := 0 to Control.ControlCount - 1 do
begin
if Control.Controls[i] is TWinControl
then ToggleControls(TWinControl(Control.Controls[i]), Enabled);
if not (Control.Controls[i] is TLabel) then
Control.Controls[i].Enabled := Enabled;
end;
end;
{ == Вывод информации в главную строку статуса приложения ====================== }
procedure ShowInStatusBar(const Msg: string);
var
Sb: TStatusBar;
begin
if Assigned(Application.MainForm) then
begin
Sb := TStatusBar(Application.MainForm.FindComponent(StatusBarName));
if Assigned(Sb) then
begin
if Sb.SimplePanel
then Sb.SimpleText := Msg
else Sb.Panels[Sb.Tag].Text := Msg;
end;
end;
Application.ProcessMessages;
end;
procedure ShowInStatusBarPanel(const Panel: Integer; Msg: string);
var
Sb: TStatusBar;
begin
Sb := TStatusBar(Application.MainForm.FindComponent(StatusBarName));
if Assigned(Sb) then Sb.Panels[Panel].Text := Msg;
Application.ProcessMessages;
end;
{ == Задержка выполнения программы ============================================= }
procedure Delay(MSecs: Longint);
var
FirstTickCount, Now: Longint;
begin
FirstTickCount := GetTickCount;
repeat
Application.ProcessMessages;
Now := GetTickCount;
until (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount);
end;
{ == Генерация записи RKindId ================================================== }
function KindId(const AId, AKind: Integer): RKindId;
begin
Result.Id := AId;
Result.Kind := AKind;
end;
{ == Правильное преобразование Boolean в строку и обратно ====================== }
function RBoolToStr(const aValue: Boolean): string;
begin
if aValue then Result := '1' else Result := '0';
end;
function RStrToBool(const aValue: string): Boolean;
begin
Result := aValue = '1';
end;
{ == Преобразование строки в число (кривые символы игнорируются) =============== }
function RIntToStr(const aValue: Integer): string;
var
i: Integer;
begin
Result := IntToStr(aValue);
i := Length(Result) - 2;
while i > 1 do
begin
Insert(#32, Result, i);
i := i - 3;
end;
end;
function RFloatToStr(const aValue: Extended): string;
begin
Result := StringReplace(FloatToStr(aValue), FormatSettings.DecimalSeparator, '.', [rfReplaceAll]);
end;
function RStrToInt(const StrValue: string): Integer;
var
i: Integer;
IntValue: string;
begin
IntValue := EmptyStr;
for i := 1 to Length(StrValue) do
if CharInSet(StrValue[i], ['-','0'..'9']) then
IntValue := IntValue + StrValue[i];
Result := StrToInt(IntValue);
end;
function RStrToIntDef(const StrValue: string; const DefValue: Integer): Integer;
var
i: Integer;
IntValue: string;
begin
IntValue := EmptyStr;
for i := 1 to Length(StrValue) do
if CharInSet(StrValue[i], ['-','0'..'9']) then
IntValue := IntValue + StrValue[i];
Result := StrToIntDef(IntValue, DefValue);
end;
function RStrToFloat(const StrValue: string): Extended;
var
i: Integer;
IntValue: string;
begin
IntValue := EmptyStr;
for i := 1 to Length(StrValue) do
if CharInSet(StrValue[i], ['-','0'..'9']) then
IntValue := IntValue + StrValue[i]
else begin
if CharInSet(StrValue[i], ['.',',',FormatSettings.DecimalSeparator]) then
IntValue := IntValue + FormatSettings.DecimalSeparator;
end;
Result := StrToFloat(IntValue);
end;
function RStrToFloatDef(const StrValue: string; const DefValue: Extended): Extended;
var
i: Integer;
IntValue: string;
begin
IntValue := EmptyStr;
for i := 1 to Length(StrValue) do
if CharInSet(StrValue[i], ['-','0'..'9']) then
IntValue := IntValue + StrValue[i]
else begin
if CharInSet(StrValue[i], ['.',',', FormatSettings.DecimalSeparator]) then
IntValue := IntValue + FormatSettings.DecimalSeparator;
end;
Result := StrToFloatDef(IntValue, DefValue);
end;
{ == Преобразование вариантов в число ========================================== }
function RVarToInteger(const VarValue: Variant): Integer;
begin
if not VarIsNull(VarValue) and VarIsOrdinal(VarValue) then
Result := VarValue
else
Result := -1
end;
initialization
iWaitCount := 0;
tWaitCount := 0;
end.
|
{ $HDR$}
{**********************************************************************}
{ Unit archived using Team Coherence }
{ Team Coherence is Copyright 2002 by Quality Software Components }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.TeamCoherence.com }
{**********************************************************************}
{
$Log: 21826: EZEliza.pas
Rev 1.0 2003.07.13 12:12:00 AM czhower
Initial checkin
Rev 1.0 2003.05.19 2:54:14 PM czhower
}
unit ezEliza;
interface
{$ifdef fpc}
{$mode objfpc}{$H+}
{$endif}
uses
EZPersonality;
type
TPersonalityEliza = class(TEZPersonality)
protected
procedure InitReplies; override;
public
class function Attributes: TEZPersonalityAttributes; override;
end;
implementation
{ TPersonalityEliza }
class function TPersonalityEliza.Attributes: TEZPersonalityAttributes;
begin
with Result do begin
Name := 'Eliza';
Description := 'Original Eliza implementation.';
end;
end;
procedure TPersonalityEliza.InitReplies;
begin
// These are parsed in order - first one wins
// If no space before, it can be the end of a word
// If no space on either side, can be the middle of word
AddReply([' CAN YOU '], [
'Don''t you believe that I can *?'
, 'Perhaps you would like to be like me.'
, 'You want me to be able to *?'
]);
AddReply([' CAN I '], [
'Perhaps you don''t want to *?'
, 'Do you want to be able to *?'
]);
AddReply([' YOU ARE ', ' YOU''RE '], [
'What makes you think I am *?'
, 'Does it please you to believe I am *?'
, 'Perhaps you would like to be", *?'
, 'Do you sometimes wish you were *?'
]);
AddReply(['I DON''T '], [
'don''t you really *?'
, 'Why don''t you *?'
, 'Do you wish to be able to *?'
, 'Does that trouble you?'
]);
AddReply(['I FEEL '], [
'Do you often feel *?'
, 'Do you enjoy feeling *?'
]);
AddReply(['WHY DON''T YOU '], [
'Do you really believe I don''t *?'
, 'Perhaps in good time I will", *?'
, 'Do you want me to *?'
]);
AddReply(['WHY CAN''T I '], [
'Do you think you should be able to *?'
, 'Why can''t you *?'
]);
AddReply(['ARE YOU '], [
'Why are you interested in whether or not I am *?'
, 'Would you prefer if I were not *?'
, 'Perhaps in your fantasies I am", *?'
]);
AddReply(['I CAN''T ', 'I CANNOT', 'I CAN NOT'], [
'How do you know you can''t *?'
, 'Have you tried?'
, 'Perhaps you can now *.'
]);
AddReply(['I AM ', 'I''M'], [
'Did you come to me because you are *?'
, 'How long have you been *?'
, 'Do you believe it is normal to be *?'
, 'Do you enjoy being *?'
]);
AddReply(['YOU '], [
'We were discussing you--not me.'
, 'Oh, I ?'
, 'You''re not really talking about me, are you?'
]);
AddReply(['I WANT '], [
'What would it mean to you if you got *?'
, 'Why do you want *?'
, 'Suppose you soon got *?'
, 'What if you never got *?'
, 'I sometimes also want *?'
]);
AddReply(['WHAT ', 'HOW ', 'WHO ', 'WHERE ', 'WHEN ', 'WHY '], [
'Why do you ask?'
, 'Does that question interest you?'
, 'What answer would please you the most?'
, 'What do you think?'
, 'Are such questions on your mind often?'
, 'What is it that you really want to know?'
, 'Have you asked anyone else?'
, 'Have you asked such questions before?'
, 'What else comes to mind when you ask that?'
]);
AddReply(['NAME '], [
'Names don''t interest me.'
, 'I don''t care about names --please go on.'
]);
AddReply(['CAUSE '], [
'Is that the real reason?'
, 'don''t any other reasons come to mind?'
, 'Does that reason explain anything else?'
, 'What other reasons might there be?'
]);
AddReply(['SORRY '], [
'Please don''t apologize!'
, 'Apologies are not necessary.'
, 'What feelings do you have when you apologize?'
, 'don''t be so defensive!'
]);
AddReply(['DREAM '], [
'What does that dream suggest to you?'
, 'Do you dream often?'
, 'What persons appear in your dreams?'
, 'Are you disturbed by your dreams?'
]);
AddReply(['HELLO ', 'HI '], [
'How do you do ...please state your problem.'
]);
AddReply(['MAYBE '], [
'You don''t seem quite certain.'
, 'Why the uncertain tone?'
, 'can''t you be more positive?'
, 'You aren''t sure?'
, 'don''t you know?'
]);
AddReply(['NO '], [
'Are you saying no just to be negative?'
, 'You are being a bit negative.'
, 'Why not?'
, 'Are you sure?'
, 'Why no?'
]);
AddReply(['YOUR '], [
'Why are you concerned about my *?'
, 'What about your own *?'
]);
AddReply(['ALWAYS '], [
'Can you think of a specific example?'
, 'When?'
, 'What are you thinking of?'
, 'Really, always?'
]);
AddReply(['THINK '], [
'Do you really think so?'
, 'But you are not sure you, *?'
, 'Do you doubt you *?'
]);
AddReply(['ALIKE '], [
'In what way?'
, 'What resemblance do you see?'
, 'What does the similarity suggest to you?'
, 'What other connections do you see?'
, 'Could there really be some connection?'
, 'How?'
, 'You seem quite positive.'
]);
AddReply(['YES '], [
'Are you sure?'
, 'I see.'
, 'I understand.'
]);
AddReply(['FRIEND '], [
'Why do you bring up the topic of friends?'
, 'Do your friends worry you?'
, 'Do your friends pick on you?'
, 'Are you sure you have any friends?'
, 'Do you impose on your friends?'
, 'Perhaps your love for friends worries you.'
]);
AddReply(['COMPUTER'], [
'Do computers worry you?'
, 'Are you talking about me in particular?'
, 'Are you frightened by machines?'
, 'Why do you mention computers?'
, 'What do you think machines have to do with your problem?'
, 'don''t you think computers can help people?'
, 'What is it about machines that worries you?'
]);
AddReply(['--NOKEYFOUND--'], [
'Say, do you have any psychological problems?'
, 'What does that suggest to you?'
, 'I see.'
, 'I''m not sure I understand you fully.'
, 'Come come elucidate your thoughts.'
, 'Can you elaborate on that?'
, 'That is quite interesting.'
]);
end;
initialization
TPersonalityEliza.RegisterPersonality;
end.
|
unit MapStructure;
interface
Uses dglOpenGL, PhysicsArifm, Windows;
Type
TMapVertex = record
X, Y, Z: Single;
end;
TTextureCoord = record
X, Y: Single;
end;
TTriangleVertex = record
Vertex: TMapVertex;
TextureCoord: TTextureCoord;
end;
TSector = record // Сектор
NumTriangles: integer;
Vertexs: array of TMapVertex;
Colors: array of TRGBTriple;
Normals: array of TMapVertex;
TextureCoords: array of TTextureCoord;
Texturez: array of GLUInt;
end;
Function SetColor (const Red, Green, Blue: byte): TRGBTriple;
implementation
Function SetColor (const Red, Green, Blue: byte): TRGBTriple;
begin
Result.rgbtRed := Red;
Result.rgbtGreen := Green;
Result.rgbtBlue := Blue;
end;
end.
|
unit ufrmExportSettings2;
interface
uses
uDataComputer,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, System.Types, System.IOUtils, System.Diagnostics,
Vcl.Controls, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.FileCtrl,
Vcl.CheckLst, Vcl.ComCtrls, Vcl.Menus, Vcl.Forms;
type
TfrmExportSettings2 = class(TForm)
ScrollBox1: TScrollBox;
Label5: TLabel;
edtColumnGroupCount: TEdit;
edtColumnGroupCount2: TEdit;
btnConfirm: TButton;
Label1: TLabel;
chkExportFile: TCheckBox;
chkExportFile2: TCheckBox;
chkExportFile3: TCheckBox;
edtExportCodeNameCount: TEdit;
edtExportCodeNameCount2: TEdit;
edtExportCodeNameCount3: TEdit;
Label3: TLabel;
Label15: TLabel;
procedure FormCreate(Sender: TObject);
procedure btnConfirmClick(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure FormShow(Sender: TObject);
private
fSettings: TSettings;
function CheckColumnGroupCount(var ValueCount, ValueCount2: Integer): Boolean;
public
property Settings: TSettings read fSettings;
end;
var
frmExportSettings2: TfrmExportSettings2;
implementation
uses
uControlHelper;
{$R *.dfm}
function TfrmExportSettings2.CheckColumnGroupCount(var ValueCount, ValueCount2: Integer): Boolean;
begin
Result := edtColumnGroupCount.TryToValue(ValueCount);
if not Result then Exit;
Result := edtColumnGroupCount2.TryToValue(ValueCount2);
if not Result then Exit;
if not ((ValueCount = 0) and (ValueCount2 = 0)) then
Result := (ValueCount > 0) and (ValueCount2 >= ValueCount);
end;
procedure TfrmExportSettings2.FormCreate(Sender: TObject);
var
v: Variant;
begin
ScrollBox1.VertScrollBar.Position := 0;
fSettings.Flag := 9;
fSettings.ExportFile := True;
fSettings.ExportFile2 := True;
fSettings.ExportFile3 := True;
fKeyValue.GetKeyValue('Settings9', v);
if not VarIsEmpty(v) then fSettings := fSerializer.Deserialize<TSettings>(v);
end;
procedure TfrmExportSettings2.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
ScrollBox1.VertScrollBar.Position := ScrollBox1.VertScrollBar.Position - WheelDelta div 2;
end;
procedure TfrmExportSettings2.FormShow(Sender: TObject);
var
gc: TGroupCount;
begin
edtColumnGroupCount.Text := '';
edtColumnGroupCount2.Text := '';
for gc in fSettings.GroupCounts do
begin
if gc.Value3 > 0 then
edtColumnGroupCount.Text := gc.Value3.ToString;
if gc.Value4 > 0 then
edtColumnGroupCount2.Text := gc.Value4.ToString;
end;
chkExportFile.Checked := fSettings.ExportFile;
chkExportFile2.Checked := fSettings.ExportFile2;
chkExportFile3.Checked := fSettings.ExportFile3;
if fSettings.ExportCodeNameCount > 0 then
edtExportCodeNameCount.Text := fSettings.ExportCodeNameCount.ToString;
if fSettings.ExportCodeNameCount2 > 0 then
edtExportCodeNameCount2.Text := fSettings.ExportCodeNameCount2.ToString;
if fSettings.ExportCodeNameCount3 > 0 then
edtExportCodeNameCount3.Text := fSettings.ExportCodeNameCount3.ToString;
end;
procedure TfrmExportSettings2.btnConfirmClick(Sender: TObject);
var
GroupCount, GroupCount2,
iExportCodeNameCount, iExportCodeNameCount2, iExportCodeNameCount3: Integer;
gc: TGroupCount;
gcs: TArray<TGroupCount>;
begin
if not CheckColumnGroupCount(GroupCount, GroupCount2) then
raise Exception.Create('请输入有效组合个数范围');
if GroupCount > 0 then
begin
gc.Number := 1;
gc.Value := 1;
gc.Value2 := 1;
gc.Value3 := GroupCount;
gc.Value4 := GroupCount2;
SetLength(gcs, 1);
gcs[0] := gc;
end;
if not edtExportCodeNameCount.TryToValue(iExportCodeNameCount) then
raise Exception.Create('请输入有效导出代号数');
if not edtExportCodeNameCount2.TryToValue(iExportCodeNameCount2) then
raise Exception.Create('请输入有效导出代号数');
if not edtExportCodeNameCount3.TryToValue(iExportCodeNameCount3) then
raise Exception.Create('请输入有效导出代号数');
fSettings.Flag := 9;
fSettings.GroupCounts := gcs;
fSettings.ExportFile := chkExportFile.Checked;
fSettings.ExportFile2 := chkExportFile2.Checked;
fSettings.ExportFile3 := chkExportFile3.Checked;
fSettings.ExportCodeNameCount := iExportCodeNameCount;
fSettings.ExportCodeNameCount2 := iExportCodeNameCount2;
fSettings.ExportCodeNameCount3 := iExportCodeNameCount3;
fKeyValue.SetKeyValue('Settings9', fSerializer.Serialize(fSettings));
ModalResult := mrOk;
end;
end.
|
unit Game;
interface uses
System.types, UiTypes, Messages, SysUtils, Classes, IdContext, Contnrs, Math, IdIOHandler, FMX.Types, FMX.Forms;
type
TScreenObj = class
Loc, Size, Speed: TPointF;
Color: DWord;
procedure Paint(Canvas: TCanvas); virtual;
procedure Move(delta: Single); virtual;
end;
TBall = class(TScreenObj)
RotationSpeed, CurrentAngle: Single;
procedure Paint(Canvas: TCanvas); override;
procedure Move(delta: Single); override;
procedure Reset;
procedure Restart(Team: Integer = 1);
end;
TClientData = packed record
AccX, AccY, AccZ, timeDelta: Single
end;
TPlayer = class(TScreenObj)
private
cnt: Integer;
lastDT: TDateTime;
Sensor: TClientData;
Ping: single;
FLastCmd: Integer;
FLastData:TBytes;
FLastTx: TDateTime;
function Intersects(AShape: TScreenObj; out Where: Single): Boolean;
procedure TryToHitTheBall(Ball: TBall);
public
NetContext: TIdContext;
Team: Integer;
Name: string;
constructor Create(Pattern: TPointF);
destructor Destroy; override;
procedure Move(delta: Single); override;
procedure Paint(Canvas: TCanvas); override;
procedure ListenToClient(); // threaded !
end;
TGame = class(TObjectList)
const
MinPlayers = 2;
private
class var FieldSize: TPointF;
FScore: array[0..1] of Integer;
FGoalShowing: Boolean;
GoalTime: TDateTime;
LastScorer: Integer;
procedure Rearrange;
function GetItem(Index: Integer): TPlayer;
procedure ShowGoal(Team: Integer);
protected
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
PlayerPattern: TPointF;
Ball: TBall;
constructor Create;
destructor Destroy; override;
procedure Resize(w,h: Integer);
procedure CreatePlayer(NetContext: TIdContext);
function FindByContext(NetContext: TIdContext): TPlayer;
procedure Move(delta: Single);
procedure Paint(Canvas: TCanvas);
function GetScore: string;
property Players[Index: Integer]: TPlayer read GetItem; default;
end;
implementation
{ TScreenObj }
procedure TScreenObj.Move(delta: Single);
begin
Loc.x := Loc.x + Speed.x{-AvgValue}*delta;
Loc.y := Loc.y + Speed.y{-AvgValue}*delta;
end;
procedure TScreenObj.Paint(Canvas: TCanvas);
begin
Canvas.Fill.Color := Color;
Canvas.FillEllipse(tRectf.Create(Loc.x-Size.x, Loc.y-Size.y,
Loc.x+Size.x, Loc.y+Size.y), 1);
Canvas.DrawEllipse(tRectf.Create(Loc.x-Size.x, Loc.y-Size.y,
Loc.x+Size.x, Loc.y+Size.y), 1);
end;
{ TBall }
procedure TBall.Move(delta: Single);
var
spd: Single;
spdAngle: Single;
HitRotationBonus: Boolean;
begin
inherited Move(delta);
HitRotationBonus := false;
if Loc.y <= Size.y then begin
Loc.y := Size.y;
Speed.y := -Speed.y;
HitRotationBonus := true;
end;
if Loc.y >= TGame.FieldSize.y-Size.y then begin
Loc.y := TGame.FieldSize.y-Size.y;
Speed.y := -Speed.y;
HitRotationBonus := true;
end;
if TGame.MinPlayers < 2 then begin
if Loc.x >= TGame.FieldSize.x-Size.x then begin
Loc.x := TGame.FieldSize.x-Size.x-1;
Speed.x := -Speed.x;
HitRotationBonus := true;
end;
end;
CurrentAngle := CurrentAngle + RotationSpeed*delta;
spdAngle := ArcTan2(Speed.Y, Speed.X);
if HitRotationBonus then begin
spdAngle := delta*RotationSpeed/10 + spdAngle;
RotationSpeed := RotationSpeed/10;
end else begin
spdAngle := delta*RotationSpeed/100 + spdAngle;
RotationSpeed := RotationSpeed*Exp(-delta/10);
end;
spd := Sqrt(Sqr(Speed.X) + Sqr(Speed.Y));
Speed.X := cos(spdAngle)*spd;
Speed.Y := sin(spdAngle)*spd;
end;
procedure TBall.Paint(Canvas: TCanvas);
var
x, y: Single;
begin
inherited;
x := Loc.x+sin(CurrentAngle)*Size.X*0.7;
y := Loc.y+cos(CurrentAngle)*Size.Y*0.7;
Canvas.Fill.Color := TAlphaColorRec.Black;
Canvas.FillEllipse(tRectf.Create(x-2, y-2, x+2, y+2), 1);
end;
procedure TBall.Reset;
begin
Speed.x := 0;
Speed.y := 0;
Loc.x := TGame.FieldSize.x /2;
Loc.y := TGame.FieldSize.y /2;
RotationSpeed := 0;
end;
procedure TBall.Restart(Team: Integer);
begin
Speed.x := (1-Team*2)*TGame.FieldSize.x / 04;
Speed.y := 0;
end;
{ TPlayerInfo }
constructor TPlayer.Create(Pattern: TPointF);
begin
Color := TAlphaColorRec.Pink;
Size.x := Pattern.X/2;
Size.y := Pattern.Y/2;
Loc.y := TGame.FieldSize.y/2;
end;
destructor TPlayer.Destroy;
begin
inherited;
end;
function TPlayer.Intersects(AShape: TScreenObj; out Where: Single): Boolean;
begin
Result := (AShape.Loc.y + AShape.Size.y >= Loc.y - Size.y)
and (AShape.Loc.y - AShape.Size.y <= Loc.y + Size.y);
Result := Result and
(AShape.Loc.x + AShape.Size.x >= Loc.x - Size.x)
and (AShape.Loc.x - AShape.Size.x <= Loc.x + Size.x);
if Result then
Where := (AShape.Loc.y - Loc.y)/Size.y;
end;
procedure TPlayer.ListenToClient;
var
io: TIdIOHandler;
cmd: Integer;
const
OsColors: array[0..4] of DWord = (TAlphaColorRec.Black, TAlphaColorRec.Yellow, TAlphaColorRec.Blue,
TAlphaColorRec.Silver, TAlphaColorRec.Maroon);
procedure onExit;
begin
FLastCmd := cmd;
if lastDT = 0 then
lastDT := now
else
inc(cnt);
if (Now-lastDT>1/86400) then begin
Ping := (Now-lastDT)*86400000/cnt;
lastDT := Now;
cnt := 0;
end;
end;
begin
io := NetContext.Connection.IOHandler;
io.CheckForDataOnSource(1);
while not io.InputBufferIsEmpty do begin
cmd := io.ReadLongInt();
FLastData := nil;
case cmd of
0: begin
io.ReadBytes(FLastData, 16);
system.Move(FLastData[0], Sensor, 16);
Move(Sensor.timeDelta);
end;
1: try
Color := OsColors[io.ReadLongInt];
except end;
2: begin
SetLength(Name, io.ReadLongInt);
Name := io.ReadString(length(Name)*2, TEncoding.Unicode);
end;
else
io.ReadBytes(FLastData, io.InputBuffer.Size);
end;
onExit;
end;
end;
procedure TPlayer.Move(delta: Single);
begin
Speed.y := -Sensor.AccY;
inherited Move(delta);
Loc.y := Max(Size.y*0.5, Loc.y);
Loc.y := Min(TGame.FieldSize.y-Size.y*0.5, Loc.y);
FLastTx := Now;
end;
procedure TPlayer.Paint(Canvas: TCanvas);
begin
inherited Paint(Canvas);
Canvas.Font.Size := 9;
Canvas.Fill.Color := TAlphaColorRec.White;
Canvas.FillText(TRectf.Create(Loc.x-Size.x, Loc.y-Size.y-8, Loc.x+Size.x, Loc.y-Size.y),
Name, false, 1, [], TTextAlign.taCenter);
if Color = TAlphaColorRec.Black then
Canvas.Fill.Color := TAlphaColorRec.Yellow
else
Canvas.Fill.Color := TAlphaColorRec.Black;
if Ping <> 0 then
Canvas.FillText(TRectf.Create(Loc.x-Size.x, Loc.y-8, Loc.x+Size.x, Loc.y),
Format('%2.0f ms', [Ping]), false, 1, [], TTextAlign.taCenter);
{ Canvas.FillText(TRectf.Create(Loc.x-Size.x, Loc.y+8, Loc.x+Size.x, Loc.y+16),
FormatDateTime('zzz', FLastTx), false, 1, [], TTextAlign.taCenter);}
end;
procedure TPlayer.TryToHitTheBall(Ball: TBall);
var
sp, wh: Single;
begin
if not Intersects(Ball, wh) then
Exit;
if (Team = 0) xor (Ball.Speed.x>0) then begin
sp := (1.1-abs(wh)/10) * sqrt(sqr(Ball.Speed.x)+Sqr(Ball.Speed.y));
Ball.Speed.x := - sign(Ball.Speed.x) * sp * cos(wh);
Ball.Speed.y := sin(wh) * sp;
end;
Ball.RotationSpeed := -Sensor.AccX*sqrt(sqr(Ball.Speed.X)+sqr(Ball.Speed.Y))/10;
end;
{ TPlayers }
constructor TGame.Create;
begin
Ball := TBall.Create;
Ball.Color := TAlphaColorRec.White;
end;
procedure TGame.CreatePlayer(NetContext: TIdContext);
var
pi: TPlayer;
begin
pi := TPlayer.Create(PlayerPattern);
pi.NetContext := NetContext;
Add(pi);
if Count >= MinPlayers then
Ball.Restart;
end;
destructor TGame.Destroy;
begin
inherited;
FreeAndNil(Ball);
end;
function TGame.FindByContext(NetContext: TIdContext): TPlayer;
var
i: Integer;
begin
Result := nil;
for i := 0 to Count-1 do
if Players[i].NetContext = NetContext then
Result := Players[i];
end;
function TGame.GetItem(Index: Integer): TPlayer;
begin
Result := TPlayer(inherited GetItem(index))
end;
function TGame.GetScore: string;
begin
Result := Format('%d:%d', [fscore[0], fscore[1]]);
end;
procedure TGame.ShowGoal(Team: Integer);
begin
Inc(FScore[1-team]);
GoalTime := Now;
FGoalShowing := true;
LastScorer := Team;
end;
procedure TGame.Move(delta: Single);
var
i: Integer;
begin
if FGoalShowing then begin
if round(Now*86400000) mod 1000 < 500 then
Ball.Color := TAlphaColorRec.Red
else
Ball.Color := TAlphaColorRec.White;
if Now - GoalTime > 3/86400 then begin
FGoalShowing := false;
Ball.Color := TAlphaColorRec.White;
Ball.Reset;
if Count >= MinPlayers then
Ball.Restart(LastScorer);
end else
Exit;
end;
Ball.Move(delta);
if Ball.Loc.x <= Ball.Size.x then
ShowGoal(0);
if Ball.Loc.x >= FieldSize.x-Ball.Size.x then
ShowGoal(1);
for i := 0 to Count-1 do
Players[i].TryToHitTheBall(Ball);
end;
procedure TGame.Notify(Ptr: Pointer; Action: TListNotification);
begin
inherited;
Rearrange;
if Count < 2 then
Ball.Reset;
end;
procedure TGame.Paint(Canvas: TCanvas);
var
i: Integer;
begin
Canvas.Clear(TAlphaColorRec.Green);
Canvas.Fill.Color := TAlphaColorRec.White;
Canvas.FillRect(TRectf.Create(4, 4, FieldSize.x-4, 8), 0, 0, [], 1);
Canvas.FillRect(TRectf.Create(4, 4, 8, round(FieldSize.y-4)), 0, 0, [], 1);
Canvas.FillRect(TRectf.Create(round(FieldSize.x-8), 4, round(FieldSize.x-4), round(FieldSize.y-4)), 0, 0, [], 1);
Canvas.FillRect(TRectf.Create(4, round(FieldSize.y-8), round(FieldSize.x-4), round(FieldSize.y-4)), 0, 0, [], 1);
for i := 0 to Count-1 do
Players[i].Paint(Canvas);
Ball.Paint(Canvas);
Canvas.Fill.Color := TAlphaColorRec.Green;
end;
procedure TGame.Rearrange;
var
i: Integer;
begin
for i := 0 to Count-1 do begin
Players[i].Team := i mod 2;
if Players[i].Team = 0 then
Players[i].Loc.x := PlayerPattern.X*(i+1)
else
Players[i].Loc.x := FieldSize.x - PlayerPattern.X*(i+1);
end;
if Ball <> nil then
Ball.Reset;
FScore[0] := 0;
FScore[1] := 0;
end;
procedure TGame.Resize(w, h: Integer);
begin
FieldSize.x := w;
FieldSize.y := h;
Ball.Size.x := FieldSize.x/80;
Ball.Size.y := Ball.Size.x;
end;
end.
|
namespace Sunko;
type
ErrorResources = static class
private static files := Arr('ru.lng', 'en.lng');
private static fLang := 0;
private static langs: array of Dictionary<string, string>;
public static property Lang: integer read fLang write fLang;
private static function GetKeyValue(s: string): KeyValuePair<string, string>;
begin
var ss := s.ToWords('=');
Result := new KeyValuePair<string, string>(Parser.GetString(ss[0], '"'), Parser.GetString(ss[1], '"'));
end;
public static procedure Init;
begin
langs := new Dictionary<string, string>[2];
langs[0] := new Dictionary<string, string>;
langs[1] := new Dictionary<string, string>;
var sr := new System.IO.StreamReader(GetResourceStream('ru.lng'));
var a := sr.ReadToEnd;
foreach var x in a.ToWords(newline.ToArray) do
begin
var xx := GetKeyValue(x);
langs[0].Add(xx.Key, xx.Value);
end;
sr := new System.IO.StreamReader(GetResourceStream('en.lng'));
var b := sr.ReadToEnd;
foreach var x in b.ToWords(newline.ToArray) do
begin
var xx := GetKeyValue(x);
langs[1].Add(xx.Key, xx.Value);
end;
end;
public static function GetErrorResourceString(param: boolean; s: string; params a: array of string): string;
begin
{$ifdef DEBUG}try{$endif}
if not param then Result := string.Format(langs[fLang][s], a.ConvertAll(x -> object(x))) else Result := langs[fLang][s];
{$ifdef DEBUG}except
on e: System.Exception do
begin
writeln(s, a, langs[fLang]);
raise;
end;
end;{$endif}
end;
end;
SunkoError = class(System.Exception)
private fSource: integer;
public property Source: integer read fSource;
private msg: string;
private fParams: array of string;
public function GetErrorMessage: string;
begin
Result := ErrorResources.GetErrorResourceString(fParams = nil, msg, fParams)
end;
public constructor(msg: string) := inherited Create(msg);
public constructor(msg: string; source: integer; params p: array of string);
begin
Create(msg);
self.msg := msg;
fSource := source;
fParams := p;
end;
end;
SemanticError = class(SunkoError)
end;
SyntaxError = class(SunkoError)
end;
end. |
unit ETL.Component.Factory;
interface
uses
ETL.Component,
Vcl.Controls;
const
KIND_COMPONENT_QUERY = 0;
KIND_COMPONENT_FILE = 1;
KIND_COMPONENT_FILTER = 2;
KIND_COMPONENT_CONVERSION = 3;
KIND_COMPONENT_DERIVATION = 4;
KIND_COMPONENT_JOIN = 5;
KIND_COMPONENT_CONDENSATION = 6;
KIND_COMPONENT_EXECUTE = 7;
KIND_COMPONENT_SCRIPT = 8;
type
TComponentETLFactory = class
public
class function New(const AParent: TWinControl; const AKind: Byte; const AGUID: string)
: TComponentETL;
end;
implementation
uses
ETL.Component.Extract.Query,
ETL.Component.Extract.Files,
ETL.Component.Transform,
ETL.Component.Transform.Condensation,
ETL.Component.Load,
ETL.Component.Load.Script;
{ TComponentETLFactory }
class function TComponentETLFactory.New(const AParent: TWinControl; const AKind: Byte;
const AGUID: string): TComponentETL;
begin
case AKind of
KIND_COMPONENT_QUERY:
Result := TCompQuery.Create(AParent, AGUID);
KIND_COMPONENT_FILE:
Result := TCompFiles.Create(AParent, AGUID);
KIND_COMPONENT_FILTER:
Result := TCompFilter.Create(AParent, AGUID);
KIND_COMPONENT_CONVERSION:
Result := TCompConversion.Create(AParent, AGUID);
KIND_COMPONENT_DERIVATION:
Result := TCompDerivation.Create(AParent, AGUID);
KIND_COMPONENT_JOIN:
Result := TCompJoin.Create(AParent, AGUID);
KIND_COMPONENT_CONDENSATION:
Result := TCompCondensation.Create(AParent, AGUID);
KIND_COMPONENT_EXECUTE:
Result := TCompExecute.Create(AParent, AGUID);
else
// KIND_COMPONENT_SCRIPT:
Result := TCompScript.Create(AParent, AGUID);
end;
Result.Tag := AKind;
end;
end.
|
unit BoardPainter;
interface
uses Graphics, Types,
Board;
// ****************************************************
// BOARD PAINTER DRAWS TRACKS ON A BITMAP
// ****************************************************
type TbrBoardPainter = class
protected
// drawing settings
FPixelsPerCell : integer;
FBoardColor : TColor;
FStripColor : TColor;
FStripWidth1000 : integer;
FStripsVisible : boolean;
FHolesVisible : boolean;
FHoleColor : TColor;
FHoleOutlineColor : TColor;
FHoleDiameter1000 : integer;
public
// appearance
property PixelsPerCell : integer read FPixelsPerCell write FPixelsPerCell;
property BoardColor : TColor read FBoardColor write FBoardColor;
property StripColor : TColor read FStripColor write FStripColor;
property StripWidth1000 : integer read FStripWidth1000 write FStripWidth1000;
property StripsVisible : boolean read FStripsVisible write FStripsVisible;
property HolesVisible : boolean read FHolesVisible write FHolesVisible;
property HoleColor : TColor read FHoleColor write FHoleColor;
property HoleOutlineColor : TColor read FHoleOutlineColor write FHoleOutlineColor;
property HoleDiameter1000 : integer read FHoleDiameter1000 write FHoleDiameter1000;
// draw entire board on Bitmap - using current appearance properties
// if necessary, resizing bitmap to suit
procedure Paint( Canvas : TCanvas; Board : TbrBoard );
constructor Create;
end;
implementation
constructor TbrBoardPainter.Create;
begin
FPixelsPerCell := 24;
FBoardColor := clWhite;
FStripColor := $E0E0E0; // light grey
FStripWidth1000 := 500; // half width
FStripsVisible := True;
FHolesVisible := True;
FHoleDiameter1000 := 167; // 1/6th of a cell
FHoleColor := clWhite;
FHoleOutlineColor := clWhite;
end;
procedure TbrBoardPainter.Paint( Canvas : TCanvas; Board : TbrBoard );
var
PixelsWidth : integer;
PixelsHeight : integer;
StripWidth : integer;
// InterStripWidth : integer;
TopStripY : integer;
LeftStripX : integer;
i : integer;
Strip : TbrStrip;
Segment : TbrSegment;
x,y : integer;
StripX, StripY : integer;
HoleDiam, HoleRadius : integer;
begin
// * defined patterns get drawn using Board.StripSets *
// calculate TPaintbox or TCustomControl dimensions : 2 extra pixels for border
PixelsWidth := (Board.Width * FPixelsPerCell) +2;
PixelsHeight := (Board.Height * FPixelsPerCell) +2;
// calculate common parameters
StripWidth := (FPixelsPerCell * FStripWidth1000) div 1000;
TopStripY := FPixelsPerCell div 2;
LeftStripX := TopStripY;
// draw board
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := FBoardColor;
Canvas.FillRect( Rect(0, 0, PixelsWidth, PixelsHeight ) );
// draw strips and segments
if FStripsVisible then begin
// draw strips as lines on top of board background
Canvas.Pen.Style := psSolid;
Canvas.Pen.Width := StripWidth;
Canvas.Pen.Mode := pmCopy;
// XOR reveals how tracks drawn : make this a menu item, just for
// editor use - Editor.XORMode := True - property sets a XORMode in
// Editor.Board. Or just do Editor.Board.XORMode := True etc. Use
// menu item that has checkmark
// Canvas.Pen.Mode := pmXOR;
Canvas.Pen.Color := FStripColor;
for i := 0 to Board.StripCount - 1 do begin
Strip := Board.Strips[i];
Canvas.MoveTo(
(Strip.Start.X * FPixelsPerCell) + LeftStripX,
(Strip.Start.Y * FPixelsPerCell) + TopStripY );
Canvas.LineTo(
(Strip.Finish.X * FPixelsPerCell) + LeftStripX,
(Strip.Finish.Y * FPixelsPerCell) + TopStripY );
end;
// Draw segments (non-strip) copper segments, for display only
// 500 offset is half a cell - moves segments onto the centre of cell
// coords used by strips
for i := 0 to Board.SegmentCount - 1 do begin
Segment := Board.Segments[i];
Canvas.Pen.Width := (PixelsPerCell * Segment.Width_1000) div 1000;
Canvas.MoveTo(
((Segment.X1_1000 + 500) * FPixelsPerCell) div 1000,
((Segment.Y1_1000 + 500) * FPixelsPerCell) div 1000
);
Canvas.LineTo(
((Segment.X2_1000 + 500) * FPixelsPerCell) div 1000,
((Segment.Y2_1000 + 500) * FPixelsPerCell) div 1000
);
end;
end;
// draw holes
if FHolesVisible then begin
// ellipse is outlined using Pen, and filled fsBrush.
Canvas.Pen.Style := psDot;
Canvas.Pen.Width := 1;
Canvas.Pen.Mode := pmCopy;
Canvas.Pen.Color := FHoleOutlineColor;
Canvas.Brush.Color := FHoleColor;
HoleDiam := ( FPixelsPerCell * FHoleDiameter1000 ) div 1000;
HoleRadius := ( FPixelsPerCell * FHoleDiameter1000 ) div 2000;
{ // draw holes using HoleArray - defined rectangles of holes
for i := 0 to Board.HoleArrayCount - 1 do begin
HoleArray := Board.HoleArrays[i];
StripY := (HoleArray.Top * FPixelsPerCell) + TopStripY - HoleRadius;
for y := HoleArray.Top to HoleArray.Bottom do begin
StripX := (HoleArray.Left * FPixelsPerCell) + LeftStripX - HoleRadius;
for x := HoleArray.Left to HoleArray.Right do begin
Canvas.Ellipse(
StripX, StripY,
StripX + HoleDiam +1, StripY + HoleDiam +1);
Inc( StripX, FPixelsPerCell );
end;
Inc( StripY, FPixelsPerCell );
end;
end;
}
// draw holes in all strips
for i := 0 to Board.StripCount - 1 do begin
Strip := Board.Strips[i];
// coords of top or left hole
StripX := (Strip.Start.X * FPixelsPerCell) + LeftStripX - HoleRadius;
StripY := (Strip.Start.Y * FPixelsPerCell) + TopStripY - HoleRadius;
// horizontal
if Strip.Direction = diHorizontal then begin
for x := Strip.Start.X to Strip.Finish.X do begin
Canvas.Ellipse(
StripX, StripY,
StripX + HoleDiam +1, StripY + HoleDiam +1);
Inc( StripX, FPixelsPerCell );
end;
end
// vertical
else begin
for y := Strip.Start.Y to Strip.Finish.Y do begin
Canvas.Ellipse(
StripX, StripY,
StripX + HoleDiam +1, StripY + HoleDiam +1);
Inc( StripY, FPixelsPerCell );
end;
end;
end;
end;
end;
end.
|
unit MyScreens;
interface
uses MyScreen;
type
Screens= class
screens: array of screen;
constructor Create();
begin
SetLength(screens,0)
end;
procedure AddScreen(name: string; InitializeProc:procedure; UpdateProc:procedure; KeyDown: procedure (key: integer));
procedure Activate(name:string);
procedure RenderActive();
procedure InitializeActive();
function GetActiveScreenIndex():integer;
function GetActiveScreenKeyDown():procedure (Key:integer);
end;
implementation
procedure Screens.AddScreen(name: string; InitializeProc:procedure; UpdateProc:procedure; KeyDown: procedure (key: integer));
begin
var screen := new MyScreen.Screen(name, InitializeProc, UpdateProc, KeyDown);
SetLength(screens, screens.Length + 1);
screens[screens.Length - 1] := screen;
end;
procedure Screens.Activate(name:string);
begin
var activeScreenIndex := GetActiveScreenIndex();
screens[activeScreenIndex].active := false;
for var i := 0 to screens.Length - 1 do begin
if screens[i].name = name then begin
screens[i].active := true;
end;
end;
end;
procedure Screens.RenderActive();
begin
var activeScreenIndex := GetActiveScreenIndex();
screens[activeScreenIndex].UpdateProc();
end;
procedure Screens.InitializeActive();
begin
var activeSCreenIndex := GetActiveScreenIndex();
screens[activeScreenIndex].InitializeProc();
end;
// Functions
function Screens.GetActiveScreenIndex():integer;
begin
for var i := 0 to screens.Length - 1 do begin
if screens[i].active then begin
Result := i;
end;
end;
end;
function Screens.GetActiveScreenKeyDown():procedure (Key:integer);
begin
var activeScreenIndex := GetActiveScreenIndex();
Result := screens[activeScreenIndex].KeyDown;
end;
initialization
finalization
end.
|
unit FlyCapture2Defs_C;
interface
uses
Windows;
const
FULL_32BIT_VALUE : Integer = $7FFFFFFF;
MAX_STRING_LENGTH = 512;
type
TCallBackData = Pointer;
PCallBackData = ^TCallBackData;
TFC2String = array[1..MAX_STRING_LENGTH] of Char;
TFC2Version = record
Major : DWord;
Minor : DWord;
VType : DWord;
Build : DWord;
end;
// A context to the FlyCapture2 C library. It must be created before
// performing any calls to the library.
TFC2Context = Pointer;
PFC2Context = ^TFC2Context;
// A context to the FlyCapture2 C GUI library. It must be created before
// performing any calls to the library.
TFC2GuiContext = Pointer;
TFC2Error = Integer;
const
FC2_ERROR_UNDEFINED = -1; // ???
FC2_ERROR_OK = 0; // /**< Function returned with no errors. */
FC2_ERROR_FAILED = 1; // /**< General failure. */
FC2_ERROR_NOT_IMPLEMENTED = 2; // /**< Function has not been implemented. */
FC2_ERROR_FAILED_BUS_MASTER_CONNECTION = 3; // /**< Could not connect to Bus Master. */
FC2_ERROR_NOT_CONNECTED = 4; // /**< Camera has not been connected. */
FC2_ERROR_INIT_FAILED = 5; // /**< Initialization failed. */
FC2_ERROR_NOT_INTITIALIZED = 6; // /**< Camera has not been initialized. */
FC2_ERROR_INVALID_PARAMETER = 7; // /**< Invalid parameter passed to function. */
FC2_ERROR_INVALID_SETTINGS = 8; // /**< Setting set to camera is invalid. */
FC2_ERROR_INVALID_BUS_MANAGER = 9; // /**< Invalid Bus Manager object. */
FC2_ERROR_MEMORY_ALLOCATION_FAILED = 10; // /**< Could not allocate memory. */
FC2_ERROR_LOW_LEVEL_FAILURE = 11; // /**< Low level error. */
FC2_ERROR_NOT_FOUND = 12; // /**< Device not found. */
FC2_ERROR_FAILED_GUID = 13; // /**< GUID failure. */
FC2_ERROR_INVALID_PACKET_SIZE = 14; // /**< Packet size set to camera is invalid. */
FC2_ERROR_INVALID_MODE = 15; // /**< Invalid mode has been passed to function. */
FC2_ERROR_NOT_IN_FORMAT7 = 16; // /**< Error due to not being in Format7. */
FC2_ERROR_NOT_SUPPORTED = 17; // /**< This feature is unsupported. */
FC2_ERROR_TIMEOUT = 18; // /**< Timeout error. */
FC2_ERROR_BUS_MASTER_FAILED = 19; // /**< Bus Master Failure. */
FC2_ERROR_INVALID_GENERATION = 20; // /**< Generation Count Mismatch. */
FC2_ERROR_LUT_FAILED = 21; // /**< Look Up Table failure. */
FC2_ERROR_IIDC_FAILED = 22; // /**< IIDC failure. */
FC2_ERROR_STROBE_FAILED = 23; // /**< Strobe failure. */
FC2_ERROR_TRIGGER_FAILED = 24; // /**< Trigger failure. */
FC2_ERROR_PROPERTY_FAILED = 25; // /**< Property failure. */
FC2_ERROR_PROPERTY_NOT_PRESENT = 26; // /**< Property is not present. */
FC2_ERROR_REGISTER_FAILED = 27; // /**< Register access failed. */
FC2_ERROR_READ_REGISTER_FAILED = 28; // /**< Register read failed. */
FC2_ERROR_WRITE_REGISTER_FAILED = 29; // /**< Register write failed. */
FC2_ERROR_ISOCH_FAILED = 30; // /**< Isochronous failure. */
FC2_ERROR_ISOCH_ALREADY_STARTED = 31; // /**< Isochronous transfer has already been started. */
FC2_ERROR_ISOCH_NOT_STARTED = 32; // /**< Isochronous transfer has not been started. */
FC2_ERROR_ISOCH_START_FAILED = 33; // /**< Isochronous start failed. */
FC2_ERROR_ISOCH_RETRIEVE_BUFFER_FAILED = 34; // /**< Isochronous retrieve buffer failed. */
FC2_ERROR_ISOCH_STOP_FAILED = 35; // /**< Isochronous stop failed. */
FC2_ERROR_ISOCH_SYNC_FAILED = 36; // /**< Isochronous image synchronization failed. */
FC2_ERROR_ISOCH_BANDWIDTH_EXCEEDED = 37; // /**< Isochronous bandwidth exceeded. */
FC2_ERROR_IMAGE_CONVERSION_FAILED = 38; // /**< Image conversion failed. */
FC2_ERROR_IMAGE_LIBRARY_FAILURE = 39; // /**< Image library failure. */
FC2_ERROR_BUFFER_TOO_SMALL = 40; // /**< Buffer is too small. */
FC2_ERROR_IMAGE_CONSISTENCY_ERROR = 41; // /**< There is an image consistency error. */
FC2_ERROR_INCOMPATIBLE_DRIVER = 42; // /**< The installed driver is not compatible with the library. */
type
TFC2Interface = Integer;
const
FC2_INTERFACE_IEEE1394 = 0;//Integer = 0;
FC2_INTERFACE_USB_2 = 1;
FC2_INTERFACE_USB_3 = 2;
FC2_INTERFACE_GIGE = 3;
FC2_INTERFACE_UNKNOWN = 4;
type
TFC2PGRGuid = record
Value : array[1..4] of DWord;
end;
TFC2CallbackHandle = Pointer;
// An internal pointer used in the fc2Image structure.
TFC2ImageImpl = Pointer;
TFC2BusCallbackType = Integer;
const
FC2_BUS_RESET = 0;
FC2_ARRIVAL = 1;
FC2_REMOVAL = 2;
type
TFC2PropertyType = Integer;
const
FC2_BRIGHTNESS = 0;
FC2_AUTO_EXPOSURE = 1;
FC2_SHARPNESS = 2;
FC2_WHITE_BALANCE = 3;
FC2_HUE = 4;
FC2_SATURATION = 5;
FC2_GAMMA = 6;
FC2_IRIS = 7;
FC2_FOCUS = 8;
FC2_ZOOM = 9;
FC2_PAN = 10;
FC2_TILT = 11;
FC2_SHUTTER = 12;
FC2_GAIN = 13;
FC2_TRIGGER_MODE = 14;
FC2_TRIGGER_DELAY = 15;
FC2_FRAME_RATE = 16;
FC2_TEMPERATURE = 17;
FC2_UNSPECIFIED_PROPERTY_TYPE = 18;
type
TFC2Property = record
PropertyType : TFC2PropertyType;
Present : Bool;
AbsControl : Bool;
OnePush : Bool;
OnOff : Bool;
AutoManualMode : Bool;
ValueA : DWord; // All but white balance blue
ValueB : DWord; // only for white balance blue
AbsValue : Single;
Reserved : array[1..8] of DWord;
end;
// For convenience, trigger delay is the same structure
// used in a separate function along with trigger mode.
TFC2TriggerDelay = TFC2Property;
type
TFC2PropertyInfo = record
PropertyType : TFC2PropertyType;
Present : Bool;
AutoSupported : Bool;
ManualSupported : Bool;
OnOffSupported : Bool;
OnePushSupported : Bool;
AbsValSupported : Bool;
ReadOutSupported : Bool;
Min : DWord;
Max : DWord;
AbsMin : Single;
AbsMax : Single;
Units : TFC2String; //array[1..MAX_STRING_LENGTH] of Char;
Reserved : array[1..8] of DWord;
end;
TFC2PixelFormat = Integer;
const
FC2_PIXEL_FORMAT_MONO8 = $80000000; // 8 bits of mono information.
FC2_PIXEL_FORMAT_411YUV8 = $40000000; // YUV 4:1:1.
FC2_PIXEL_FORMAT_422YUV8 = $20000000; // YUV 4:2:2.
FC2_PIXEL_FORMAT_444YUV8 = $10000000; // YUV 4:4:4.
FC2_PIXEL_FORMAT_RGB8 = $08000000; // R = G = B = 8 bits.
FC2_PIXEL_FORMAT_MONO16 = $04000000; // 16 bits of mono information.
FC2_PIXEL_FORMAT_RGB16 = $02000000; // R = G = B = 16 bits.
FC2_PIXEL_FORMAT_S_MONO16 = $01000000; // 16 bits of signed mono information.
FC2_PIXEL_FORMAT_S_RGB16 = $00800000; // R = G = B = 16 bits signed.
FC2_PIXEL_FORMAT_RAW8 = $00400000; // 8 bit raw data output of sensor.
FC2_PIXEL_FORMAT_RAW16 = $00200000; // 16 bit raw data output of sensor.
FC2_PIXEL_FORMAT_MONO12 = $00100000; // 12 bits of mono information.
FC2_PIXEL_FORMAT_RAW12 = $00080000; // 12 bit raw data output of sensor.
FC2_PIXEL_FORMAT_BGR = $80000008; // 24 bit BGR.
FC2_PIXEL_FORMAT_BGRU = $40000008; // 32 bit BGRU.
FC2_PIXEL_FORMAT_RGB = FC2_PIXEL_FORMAT_RGB8; // 24 bit RGB
FC2_PIXEL_FORMAT_RGBU = $40000002; // 32 bit RGBU
FC2_PIXEL_FORMAT_BGR16 = $02000001; // R = G = B = 16 bits.
FC2_PIXEL_FORMAT_BGRU16 = $02000002; // 64 bit BGRU.
FC2_PIXEL_FORMAT_422YUV8_JPEG = $40000001; // JPEG compressed stream.
FC2_NUM_PIXEL_FORMATS = 20; // Number of pixel formats
FC2_UNSPECIFIED_PIXEL_FORMAT = 0; // Unspecified pixel format.
type
TFC2BayerTileFormat = Integer;
const
FC2_BT_NONE = 0; // No bayer tile format.
FC2_BT_RGGB = 1; // Red-Green-Green-Blue.
FC2_BT_GRBG = 2; // Green-Red-Blue-Green.
FC2_BT_GBRG = 3; // Green-Blue-Red-Green.
FC2_BT_BGGR = 4; // Blue-Green-Green-Red.
type
TFC2DriverType = Integer;
const
FC2_DRIVER_1394_CAM = 0; // PGRCam.sys
FC2_DRIVER_1394_PRO = 1; // PGR1394.sys
FC2_DRIVER_1394_JUJU = 2; // firewire_core
FC2_DRIVER_1394_VIDEO1394 = 3; // video1394
FC2_DRIVER_1394_RAW1394 = 4; // raw1394
FC2_DRIVER_USB_NONE = 5; // No usb driver used just BSD stack. (Linux only)
FC2_DRIVER_USB_CAM = 6; // PGRUsbCam.sys
FC2_DRIVER_USB3_PRO = 7; // PGRXHCI.sys
FC2_DRIVER_GIGE_NONE = 8; // no gige drivers used,MS/BSD stack.
FC2_DRIVER_GIGE_FILTER = 9; // PGRGigE.sys
FC2_DRIVER_GIGE_PRO = 10; // PGRGigEPro.sys
FC2_DRIVER_GIGE_LWF = 11; // PgrLwf.sys
FC2_DRIVER_UNKNOWN = -1; // Unknown driver type
type
TFC2Image = record
Rows : DWord;
Cols : DWord;
Stride : DWord;
Data : PByte;
DataSize : DWord;
RxDataSize : DWord;
Format : TFC2PixelFormat;
BayerFormat : TFC2BayerTileFormat;
ImageImpl : TFC2ImageImpl;
end;
TFC2BusSpeed = Integer;
const
FC2_BUSSPEED_S100 = 0; // 100Mbits/sec. */
FC2_BUSSPEED_S200 = 1; // 200Mbits/sec. */
FC2_BUSSPEED_S400 = 2; // 400Mbits/sec. */
FC2_BUSSPEED_S480 = 3; // 480Mbits/sec. Only for USB2 cameras. */
FC2_BUSSPEED_S800 = 4; // 800Mbits/sec. */
FC2_BUSSPEED_S1600 = 5; // 1600Mbits/sec. */
FC2_BUSSPEED_S3200 = 6; // 3200Mbits/sec. */
FC2_BUSSPEED_S5000 = 7; // 5000Mbits/sec. Only for USB3 cameras. */
FC2_BUSSPEED_10BASE_T = 8; // 10Base-T. Only for GigE cameras. */
FC2_BUSSPEED_100BASE_T = 9; // 100Base-T. Only for GigE cameras.*/
FC2_BUSSPEED_1000BASE_T = 10; // 1000Base-T (Gigabit Ethernet). Only for GigE cameras. */
FC2_BUSSPEED_10000BASE_T = 11; // 10000Base-T. Only for GigE cameras. */
FC2_BUSSPEED_S_FASTEST = 12; // The fastest speed available. */
FC2_BUSSPEED_ANY = 13; // Any speed that is available. */
FC2_BUSSPEED_SPEED_UNKNOWN = -1; // Unknown bus speed. */
type
TFC2PCIeBusSpeed = Integer;
const
FC2_PCIE_BUSSPEED_2_5 = 0; // 2.5 Gb/s
FC2_PCIE_BUSSPEED_5_0 = 1; // 5.0 Gb/s */
FC2_PCIE_BUSSPEED_UNKNOWN = -1; // ???
type
TFC2ConfigROM = record
NodeVendorId : DWord;
ChipIdHi : DWord;
ChipIdLo : DWord;
UnitSpecId : DWord;
UnitSWVer : DWord;
UnitSubSWVer : DWord;
VendorUniqueInfo_0 : DWord;
VendorUniqueInfo_1 : DWord;
VendorUniqueInfo_2 : DWord;
VendorUniqueInfo_3 : DWord;
PszKeyword : TFC2String;
Reserved : array[1..16] of DWord;
end;
TFC2IpAddress = record
Octets : array[1..4] of Byte;
end;
TFC2MACAddress = record
Octets : array[1..6] of Byte;
end;
TFC2CameraInfo = record
SerialNumber : DWord;
InterfaceType : TFC2Interface;
DriverType : TFC2DriverType;
IsColorCamera : Bool;
ModelName : TFC2String;
VendorName : TFC2String;
SensorInfo : TFC2String;
SensorResolution : TFC2String;
DriverName : TFC2String;
FirmwareVersion : TFC2String;
FirmwareBuildTime : TFC2String;
MaximumBusSpeed : TFC2BusSpeed;
PcieBusSpeed : TFC2PCIeBusSpeed;
BayerTileFormat : TFC2BayerTileFormat;
BusNumber : Word;
NodeNumber : Word;
IIDCVer : DWord;
ConfigRom : TFC2ConfigROM;
GigEMajorVersion : DWord;
GigEMinorVersion : DWord;
UserDefinedName : TFC2String;
XmlURL1 : TFC2String;
XmlURL2 : TFC2String;
MacAddress : TFC2MacAddress;
IPAddress : TFC2IpAddress;
SubnetMask : TFC2IPAddress;
DefaultGateway : TFC2IPAddress;
CcpStatus : DWord;
ApplicationIPAddress : DWord;
ApplicationPort : DWord;
Reserved : array[1..16] of DWord;
end;
TFC2BusEventCallBack = procedure(UserData:Pointer; SerialNumber:DWord); cdecl;
TFC2ImageEventCallBack = procedure(var Image:TFC2Image; Data:Pointer); cdecl;
PFC2ImageEventCallBack = ^TFC2ImageEventCallBack;
TFC2AsyncCommandCallBack = procedure(Error:TFC2Error; Data:Pointer); cdecl;
TFC2GigEStreamChannel = record
NetworkInterfaceIndex : DWord;
HostPort : DWord;
DoNotFragment : Bool;
PacketSize : DWord;
InterPacketDelay : DWord;
DestinationIP : TFC2IPAddress;
SourcePort : DWord;
Reserved : array[1..8] of DWord;
end;
TFC2GigEImageSettingsInfo = record
MaxWidth : DWord;
MaxHeight : DWord;
OffsetHStepSize : DWord;
OffsetVStepSize : DWord;
ImageHStepSize : DWord;
ImageVStepSize : DWord;
PixelFormatBitField : DWord;
VendorPixelFormatBitField : DWord;
Reserved : array[1..16] of DWord;
end;
TFC2GigEImageSettings = record
OffsetX : DWord;
OffsetY : DWord;
Width : DWord;
Height : DWord;
PixelFormat : TFC2PixelFormat;
Reserved : array[1..8] of DWord;
end;
TFC2AVIContext = Pointer;
TFC2ImageStatisticsContext = Pointer;
TFC2FrameRate = Integer;
const
FC2_FRAMERATE_1_875 = 0; // 1.875 fps. */
FC2_FRAMERATE_3_75 = 1; // 3.75 fps. */
FC2_FRAMERATE_7_5 = 2; // 7.5 fps. */
FC2_FRAMERATE_15 = 3; // 15 fps. */
FC2_FRAMERATE_30 = 4; // 30 fps. */
FC2_FRAMERATE_60 = 5; // 60 fps. */
FC2_FRAMERATE_120 = 6; // 120 fps. */
FC2_FRAMERATE_240 = 7; // 240 fps. */
FC2_FRAMERATE_FORMAT7 = 8; // Custom frame rate for Format7 functionality. */
FC2_NUM_FRAMERATES = 9; // Number of possible camera frame rates. */
type
TFC2TriggerModeInfo = record
Present : Bool;
ReadOutSupported : Bool;
OnOffSupported : Bool;
PolaritySupported : Bool;
ValueReadable : Bool;
SourceMask : DWord;
SoftwareTriggerSupported : Bool;
ModeMask : DWord;
Reserved : array[1..8] of DWord;
end;
TFC2TriggerMode = record
OnOff : Bool;
Polarity : DWord;
Source : DWord;
Mode : DWord;
Parameter : DWord;
Reserved : array[1..8] of DWord;
end;
TFC2GrabMode = Integer;
const
FC2_DROP_FRAMES = 0;
FC2_BUFFER_FRAMES = 1;
FC2_UNSPECIFIED_GRAB_MODE = 2;
type
TFC2GrabTimeout = Integer;
const
FC2_TIMEOUT_NONE = 0;
FC2_TIMEOUT_INFINITE = -1;
FC2_TIMEOUT_UNSPECIFIED = -2;
type
TFC2BandwidthAllocation = Integer;
const
FC2_BANDWIDTH_ALLOCATION_OFF = 0;
FC2_BANDWIDTH_ALLOCATION_ON = 1;
FC2_BANDWIDTH_ALLOCATION_UNSUPPORTED = 2;
FC2_BANDWIDTH_ALLOCATION_UNSPECIFIED = 3;
type
TFC2Config = record
NumBuffers : DWord;
NumImageNotifications : DWord;
MinNumImageNotifications : DWord;
GrabTimeout : Integer;
GrabMode : TFC2GrabMode;
HighPerfRetrieveBuffer : Bool;
IsochBusSpeed : TFC2BusSpeed;
AsyncBusSpeed : TFC2BusSpeed;
BandwidthAllocation : TFC2BandwidthAllocation;
RegisterTimeoutRetries : DWord;
RegisterTimeout : DWord;
Reserved : array[1..16] of DWord;
end;
TFC2TimeStamp = record
Seconds : Int64;
MicroSeconds : DWord;
CycleSeconds : DWord;
CycleCount : DWord;
CycleOffset : DWord;
Reserved : array[1..8] of DWord;
end;
TFC2StrobeInfo = record
Source : DWord;
Present : Bool;
ReadOutSupported : Bool;
OnOffSupported : Bool;
PolaritySupported : Bool;
MinValue : Single;
MaxValue : Single;
Reserved : array[1..8] of DWord;
end;
TFC2StrobeControl = record
Source : DWord;
OnOff : Bool;
Polarity : DWord;
Delay : Single;
Duration : Single;
Reserved : array[1..8] of DWord;
end;
TFC2EmbeddedImageInfoProperty = record
Available : Bool;
OnOff : Bool;
end;
TFC2EmbeddedImageInfo = record
Timestamp : TFC2EmbeddedImageInfoProperty;
Gain : TFC2EmbeddedImageInfoProperty;
Shutter : TFC2EmbeddedImageInfoProperty;
Brightness : TFC2EmbeddedImageInfoProperty;
Exposure : TFC2EmbeddedImageInfoProperty;
WhiteBalance : TFC2EmbeddedImageInfoProperty;
FrameCounter : TFC2EmbeddedImageInfoProperty;
StrobePattern : TFC2EmbeddedImageInfoProperty;
GPIOPinState : TFC2EmbeddedImageInfoProperty;
ROIPosition : TFC2EmbeddedImageInfoProperty;
end;
TFC2ImageMetaData = record
EmbeddedTimeStamp : DWord;
EmbeddedGain : DWord;
EmbeddedShutter : DWord;
EmbeddedBrightness : DWord;
EmbeddedExposure : DWord;
EmbeddedWhiteBalance : DWord;
EmbeddedFrameCounter : DWord;
EmbeddedStrobePattern : DWord;
EmbeddedGPIOPinState : DWord;
EmbeddedROIPosition : DWord;
Reserved : array[1..31] of DWord;
end;
implementation
end.
typedef enum _fc2GrabMode
{
FC2_DROP_FRAMES,
FC2_BUFFER_FRAMES,
FC2_UNSPECIFIED_GRAB_MODE,
FC2_GRAB_MODE_FORCE_32BITS = FULL_32BIT_VALUE
} fc2GrabMode;
typedef enum _fc2GrabTimeout
{
FC2_TIMEOUT_NONE = 0,
FC2_TIMEOUT_INFINITE = -1,
FC2_TIMEOUT_UNSPECIFIED = -2,
FC2_GRAB_TIMEOUT_FORCE_32BITS = FULL_32BIT_VALUE
} fc2GrabTimeout;
typedef enum _fc2BandwidthAllocation
{
FC2_BANDWIDTH_ALLOCATION_OFF = 0,
FC2_BANDWIDTH_ALLOCATION_ON = 1,
FC2_BANDWIDTH_ALLOCATION_UNSUPPORTED = 2,
FC2_BANDWIDTH_ALLOCATION_UNSPECIFIED = 3,
FC2_BANDWIDTH_ALLOCATION_FORCE_32BITS = FULL_32BIT_VALUE
}fc2BandwidthAllocation;
typedef enum _fc2VideoMode
{
FC2_VIDEOMODE_160x120YUV444 = ; // 160x120 YUV444. */
FC2_VIDEOMODE_320x240YUV422 = ; // 320x240 YUV422. */
FC2_VIDEOMODE_640x480YUV411 = ; // 640x480 YUV411. */
FC2_VIDEOMODE_640x480YUV422 = ; // 640x480 YUV422. */
FC2_VIDEOMODE_640x480RGB = ; // 640x480 24-bit RGB. */
FC2_VIDEOMODE_640x480Y8 = ; // 640x480 8-bit. */
FC2_VIDEOMODE_640x480Y16 = ; // 640x480 16-bit. */
FC2_VIDEOMODE_800x600YUV422 = ; // 800x600 YUV422. */
FC2_VIDEOMODE_800x600RGB = ; // 800x600 RGB. */
FC2_VIDEOMODE_800x600Y8 = ; // 800x600 8-bit. */
FC2_VIDEOMODE_800x600Y16 = ; // 800x600 16-bit. */
FC2_VIDEOMODE_1024x768YUV422 = ; // 1024x768 YUV422. */
FC2_VIDEOMODE_1024x768RGB = ; // 1024x768 RGB. */
FC2_VIDEOMODE_1024x768Y8 = ; // 1024x768 8-bit. */
FC2_VIDEOMODE_1024x768Y16 = ; // 1024x768 16-bit. */
FC2_VIDEOMODE_1280x960YUV422 = ; // 1280x960 YUV422. */
FC2_VIDEOMODE_1280x960RGB = ; // 1280x960 RGB. */
FC2_VIDEOMODE_1280x960Y8 = ; // 1280x960 8-bit. */
FC2_VIDEOMODE_1280x960Y16 = ; // 1280x960 16-bit. */
FC2_VIDEOMODE_1600x1200YUV422 = ; // 1600x1200 YUV422. */
FC2_VIDEOMODE_1600x1200RGB = ; // 1600x1200 RGB. */
FC2_VIDEOMODE_1600x1200Y8 = ; // 1600x1200 8-bit. */
FC2_VIDEOMODE_1600x1200Y16 = ; // 1600x1200 16-bit. */
FC2_VIDEOMODE_FORMAT7 = ; // Custom video mode for Format7 functionality. */
FC2_NUM_VIDEOMODES = ; // Number of possible video modes. */
FC2_VIDEOMODE_FORCE_32BITS = FULL_32BIT_VALUE
} fc2VideoMode;
typedef enum _fc2Mode
{
FC2_MODE_0 = 0,
FC2_MODE_1,
FC2_MODE_2,
FC2_MODE_3,
FC2_MODE_4,
FC2_MODE_5,
FC2_MODE_6,
FC2_MODE_7,
FC2_MODE_8,
FC2_MODE_9,
FC2_MODE_10,
FC2_MODE_11,
FC2_MODE_12,
FC2_MODE_13,
FC2_MODE_14,
FC2_MODE_15,
FC2_MODE_16,
FC2_MODE_17,
FC2_MODE_18,
FC2_MODE_19,
FC2_MODE_20,
FC2_MODE_21,
FC2_MODE_22,
FC2_MODE_23,
FC2_MODE_24,
FC2_MODE_25,
FC2_MODE_26,
FC2_MODE_27,
FC2_MODE_28,
FC2_MODE_29,
FC2_MODE_30,
FC2_MODE_31,
FC2_NUM_MODES = ; // Number of modes */
FC2_MODE_FORCE_32BITS = FULL_32BIT_VALUE
} fc2Mode;
typedef enum _fc2ColorProcessingAlgorithm
{
FC2_DEFAULT,
FC2_NO_COLOR_PROCESSING,
FC2_NEAREST_NEIGHBOR_FAST,
FC2_EDGE_SENSING,
FC2_HQ_LINEAR,
FC2_RIGOROUS,
FC2_IPP,
FC2_DIRECTIONAL,
FC2_COLOR_PROCESSING_ALGORITHM_FORCE_32BITS = FULL_32BIT_VALUE
} fc2ColorProcessingAlgorithm;
typedef enum _fc2ImageFileFormat
{
FC2_FROM_FILE_EXT = -1 = ; // Determine file format from file extension. */
FC2_PGM = ; // Portable gray map. */
FC2_PPM = ; // Portable pixmap. */
FC2_BMP = ; // Bitmap. */
FC2_JPEG = ; // JPEG. */
FC2_JPEG2000 = ; // JPEG 2000. */
FC2_TIFF = ; // Tagged image file format. */
FC2_PNG = ; // Portable network graphics. */
FC2_RAW = ; // Raw data. */
FC2_IMAGE_FILE_FORMAT_FORCE_32BITS = FULL_32BIT_VALUE
} fc2ImageFileFormat;
typedef enum _fc2GigEPropertyType
{
FC2_HEARTBEAT,
FC2_HEARTBEAT_TIMEOUT
} fc2GigEPropertyType;
typedef enum _fc2StatisticsChannel
{
FC2_STATISTICS_GREY,
FC2_STATISTICS_RED,
FC2_STATISTICS_GREEN,
FC2_STATISTICS_BLUE,
FC2_STATISTICS_HUE,
FC2_STATISTICS_SATURATION,
FC2_STATISTICS_LIGHTNESS,
FC2_STATISTICS_FORCE_32BITS = FULL_32BIT_VALUE
} fc2StatisticsChannel;
typedef enum _fc2OSType
{
FC2_WINDOWS_X86,
FC2_WINDOWS_X64,
FC2_LINUX_X86,
FC2_LINUX_X64,
FC2_MAC,
FC2_UNKNOWN_OS,
FC2_OSTYPE_FORCE_32BITS = FULL_32BIT_VALUE
} fc2OSType;
typedef enum _fc2ByteOrder
{
FC2_BYTE_ORDER_LITTLE_ENDIAN,
FC2_BYTE_ORDER_BIG_ENDIAN,
FC2_BYTE_ORDER_FORCE_32BITS = FULL_32BIT_VALUE
} fc2ByteOrder;
//=============================================================================
// Structures
//=============================================================================
//
// Description:
// An image. It is comparable to the Image class in the C++ library.
// The fields in this structure should be considered read only.
//
typedef struct _fc2SystemInfo
{
fc2OSType osType;
char osDescription[ MAX_STRING_LENGTH];
fc2ByteOrder byteOrder;
size_t sysMemSize;
char cpuDescription[ MAX_STRING_LENGTH];
size_t numCpuCores;
char driverList[ MAX_STRING_LENGTH];
char libraryList[ MAX_STRING_LENGTH];
char gpuDescription[ MAX_STRING_LENGTH];
size_t screenWidth;
size_t screenHeight;
unsigned int reserved[16];
} fc2SystemInfo;
typedef struct _fc2Config
{
unsigned int numBuffers;
unsigned int numImageNotifications;
unsigned int minNumImageNotifications;
int grabTimeout;
fc2GrabMode grabMode;
fc2BusSpeed isochBusSpeed;
fc2BusSpeed asyncBusSpeed;
fc2BandwidthAllocation bandwidthAllocation;
unsigned int registerTimeoutRetries;
unsigned int registerTimeout;
unsigned int reserved[16];
} fc2Config;
typedef struct _fc2StrobeInfo
{
unsigned int source;
BOOL present;
BOOL readOutSupported;
BOOL onOffSupported;
BOOL polaritySupported;
float minValue;
float maxValue;
unsigned int reserved[8];
} fc2StrobeInfo;
typedef struct _fc2StrobeControl
{
unsigned int source;
BOOL onOff;
unsigned int polarity;
float delay;
float duration;
unsigned int reserved[8];
} fc2StrobeControl;
typedef struct _fc2Format7ImageSettings
{
fc2Mode mode;
unsigned int offsetX;
unsigned int offsetY;
unsigned int width;
unsigned int height;
fc2PixelFormat pixelFormat;
unsigned int reserved[8];
} fc2Format7ImageSettings;
typedef struct _fc2Format7Info
{
fc2Mode mode;
unsigned int maxWidth;
unsigned int maxHeight;
unsigned int offsetHStepSize;
unsigned int offsetVStepSize;
unsigned int imageHStepSize;
unsigned int imageVStepSize;
unsigned int pixelFormatBitField;
unsigned int vendorPixelFormatBitField;
unsigned int packetSize;
unsigned int minPacketSize;
unsigned int maxPacketSize;
float percentage;
unsigned int reserved[16];
} fc2Format7Info;
typedef struct _fc2Format7PacketInfo
{
unsigned int recommendedBytesPerPacket;
unsigned int maxBytesPerPacket;
unsigned int unitBytesPerPacket;
unsigned int reserved[8];
} fc2Format7PacketInfo;
typedef struct _fc2GigEProperty
{
fc2GigEPropertyType propType;
BOOL isReadable;
BOOL isWritable;
unsigned int min;
unsigned int max;
unsigned int value;
unsigned int reserved[8];
} fc2GigEProperty;
typedef struct _fc2GigEStreamChannel
{
unsigned int networkInterfaceIndex;
unsigned int hostPost;
BOOL doNotFragment;
unsigned int packetSize;
unsigned int interPacketDelay;
fc2IPAddress destinationIpAddress;
unsigned int sourcePort;
unsigned int reserved[8];
} fc2GigEStreamChannel;
typedef struct _fc2GigEConfig
{
/** Turn on/off packet resend functionality */
BOOL enablePacketResend;
/** The number of miliseconds to wait for each requested packet */
unsigned int timeoutForPacketResend;
/** The max number of packets that can be requested to be resend */
unsigned int maxPacketsToResend;
unsigned int reserved[8];
} fc2GigEConfig;
typedef struct _fc2TimeStamp
{
long long seconds;
unsigned int microSeconds;
unsigned int cycleSeconds;
unsigned int cycleCount;
unsigned int cycleOffset;
unsigned int reserved[8];
} fc2TimeStamp;
typedef struct _fc2LUTData
{
BOOL supported;
BOOL enabled;
unsigned int numBanks;
unsigned int numChannels;
unsigned int inputBitDepth;
unsigned int outputBitDepth;
unsigned int numEntries;
unsigned int reserved[8];
} fc2LUTData;
typedef struct _fc2PNGOption
{
BOOL interlaced;
unsigned int compressionLevel;
unsigned int reserved[16];
} fc2PNGOption;
typedef struct _fc2PPMOption
{
BOOL binaryFile;
unsigned int reserved[16];
} fc2PPMOption ;
typedef struct _fc2PGMOption
{
BOOL binaryFile;
unsigned int reserved[16];
} fc2PGMOption;
typedef enum _fc2TIFFCompressionMethod
{
FC2_TIFF_NONE = 1,
FC2_TIFF_PACKBITS,
FC2_TIFF_DEFLATE,
FC2_TIFF_ADOBE_DEFLATE,
FC2_TIFF_CCITTFAX3,
FC2_TIFF_CCITTFAX4,
FC2_TIFF_LZW,
FC2_TIFF_JPEG,
} fc2TIFFCompressionMethod;
typedef struct _fc2TIFFOption
{
fc2TIFFCompressionMethod compression;
unsigned int reserved[16];
} fc2TIFFOption;
typedef struct _fc2JPEGOption
{
BOOL progressive;
unsigned int quality;
unsigned int reserved[16];
} fc2JPEGOption;
typedef struct _fc2JPG2Option
{
unsigned int quality;
unsigned int reserved[16];
} fc2JPG2Option;
typedef struct _fc2AVIOption
{
float frameRate;
unsigned int reserved[256];
} fc2AVIOption;
typedef struct _fc2MJPGOption
{
float frameRate;
unsigned int quality;
unsigned int reserved[256];
} fc2MJPGOption;
typedef struct _fc2H264Option
{
float frameRate;
unsigned int width;
unsigned int height;
unsigned int bitrate;
unsigned int reserved[256];
} fc2H264Option;
|
object Splash: TSplash
Left = 189
Top = 211
Hint = 'the Carpathian sphinx, the Bucegi mountains'
BorderStyle = bsNone
Caption = 'Splash'
ClientHeight = 425
ClientWidth = 895
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Tahoma'
Font.Style = []
FormStyle = fsStayOnTop
OldCreateOrder = False
Position = poDesktopCenter
ShowHint = True
OnClick = FormClick
OnClose = FormClose
PixelsPerInch = 115
TextHeight = 16
object LabelFile: TLabel
Left = 0
Top = 409
Width = 895
Height = 16
Align = alBottom
Caption = '...'
Color = clBtnHighlight
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Tahoma'
Font.Style = []
ParentColor = False
ParentFont = False
Transparent = False
end
object Kind: TLabel
Left = 16
Top = 138
Width = 607
Height = 31
Caption = 'is time to stop joking, and start doing things...'
Font.Charset = DEFAULT_CHARSET
Font.Color = clLime
Font.Height = -26
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
Transparent = True
end
object Logo: TLabel
Left = 20
Top = 96
Width = 478
Height = 39
Caption = 'the power of men...his mind...'
Font.Charset = DEFAULT_CHARSET
Font.Color = clLime
Font.Height = -32
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
Transparent = True
end
object Prog: TLabel
Left = 12
Top = 0
Width = 597
Height = 70
Caption = 'Kogaion (RqWork 7)'
Font.Charset = DEFAULT_CHARSET
Font.Color = clLime
Font.Height = -58
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
Transparent = True
end
object version: TLabel
Left = 24
Top = 72
Width = 6
Height = 23
Font.Charset = DEFAULT_CHARSET
Font.Color = clLime
Font.Height = -19
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
Transparent = True
end
object Copyright: TLabel
Left = 608
Top = 384
Width = 274
Height = 17
Caption = 'Copyright (c02020 vasile eodor nastasa'
Color = clYellow
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -14
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentColor = False
ParentFont = False
Transparent = False
end
object LabelLegal: TLabel
Left = 8
Top = 384
Width = 240
Height = 19
Caption = 'Legal TradeMark: FREEWARE'
Color = clYellow
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -16
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentColor = False
ParentFont = False
Transparent = False
end
object LabelVersion: TLabel
Left = 16
Top = 76
Width = 157
Height = 23
Caption = 'version 7 BETA'
Font.Charset = DEFAULT_CHARSET
Font.Color = clLime
Font.Height = -19
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
Transparent = True
end
end
|
// Fit4Delphi Copyright (C) 2008. Sabre Inc.
// This program is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program;
// if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// Derived from Fixture.java by Martin Chernenkoff, CHI Software Design
// Ported to Delphi by Michal Wojcik.
//
unit MusicLibrary;
interface
uses
Classes, SysUtils, Music;
type
TMusicLibrary = class (TObject)
protected
FLibrary: string;
FSelectIndex: Integer;
MusicLibrary : TList;
function GetCount: Integer;
function GetSelectedSong: TMusic;
public
constructor Create;
destructor Destroy; override;
procedure LoadLibrary(FileName : string);
procedure Select(index : integer);
procedure SetSongAsSelected (index : Integer);
function GetSong(Index : integer) : TMusic;
procedure findAlbum(a : string);
procedure findArtist(a : string);
procedure findAll;
function CountSelectedSongs : Integer;
procedure DisplayContents(results : TList);
property Count: Integer read GetCount;
property Selected: Integer read FSelectIndex;
property SelectedSong: TMusic read GetSelectedSong;
end;
var
looking : TMusic;
procedure searchComplete;
procedure Select(index : integer);
procedure findAlbum(a: string);
procedure findArtist(a : string);
procedure findAll;
procedure search(seconds : double);
function displayCount : integer;
function SelectedSong : TMusic;
procedure LoadLibrary(FileName : string);
function Count: Integer;
procedure DisplayContents(results: TList);
implementation
uses
MusicPlayer, Simulator;
var
FMusicLibrary : TMusicLibrary;
procedure DisplayContents(results: TList);
begin
// FMusicLibrary.LoadLibrary('c:\fitnesse\source\DelphiFit\eg\music\Music.txt');
// FMusicLibrary.select(3);
FMusicLibrary.DisplayContents(results);
end;
function Count : Integer;
begin
result := FMusicLibrary.Count;
end;
procedure Select(index : integer);
begin
FMusicLibrary.Select(index);
end;
procedure LoadLibrary(FileName : string);
begin
FMusicLibrary.LoadLibrary(FileName);
end;
function SelectedSong : TMusic;
begin
result := FMusicLibrary.GetSelectedSong;
end;
function displayCount : integer;
begin
(*
static int displayCount() {
int count = 0;
for (int i=0; i<library.length; i++) {
count += (library[i].selected ? 1 : 0);
}
return count;
}
*)
result := FMusicLibrary.CountSelectedSongs;
end;
procedure Search(seconds : double);
begin
(*
static void search(double seconds){
Music.status = "searching";
Simulator.nextSearchComplete = Simulator.schedule(seconds);
}
*)
Music.status := 'searching';
Simulator.nextSearchComplete := Simulator.schedule(seconds);
end;
procedure findAlbum(a: string);
begin
(*
static void findAlbum(String a) {
search(1.1);
for (int i=0; i<library.length; i++) {
library[i].selected = library[i].album.equals(a);
}
}
*)
search(1.1);
FMusicLibrary.findAlbum(a);
end;
procedure findArtist(a : string);
begin
search(2.3);
FMusicLibrary.findArtist(a);
end;
procedure findAll;
begin
search(3.2);
FMusicLibrary.findAll;
end;
procedure searchComplete;
begin
(*
static void searchComplete() {
Music.status = MusicPlayer.playing == null ? "ready" : "playing";
}
*)
if MusicPlayer.playing = nil then
Music.status := 'ready'
else
Music.status := 'playing';
end;
{ TTestMusicLibrary }
{
{ TMusicLibrary }
{
******************************** TMusicLibrary *********************************
}
function TMusicLibrary.CountSelectedSongs: Integer;
var
i, iSelCount : integer;
begin
iSelCount := 0;
for i := 0 to Count - 1 do begin
if TMusic(MusicLibrary.Items[i]).Selected then
Inc(iSelCount);
end;
result := iSelCount;
end;
constructor TMusicLibrary.Create;
begin
MusicLibrary := TList.Create;
end;
destructor TMusicLibrary.Destroy;
begin
MusicLibrary.Free;
end;
function TMusicLibrary.GetCount: Integer;
begin
result := MusicLibrary.Count;
end;
function TMusicLibrary.GetSelectedSong: TMusic;
begin
result := MusicLibrary.Items[FSelectIndex - 1];
end;
function TMusicLibrary.GetSong(Index: integer): TMusic;
begin
result := TMusic.Create;
end;
procedure TMusicLibrary.LoadLibrary(FileName : string);
var
i : integer;
aMusic : TMusic;
aStringList : TStringList;
begin
FLibrary := FileName;
aStringList := TStringList.Create;
aStringList.LoadFromFile(FLibrary);
MusicLibrary.Clear;
for i := 1 to aStringList.Count - 1 do begin
aMusic := TMusic.Create;
aMusic.parse(aStringList[i]);
MusicLibrary.Add(aMusic);
end;
aStringList.Free;
end;
procedure TMusicLibrary.Select(index : integer);
begin
FSelectIndex := index;
looking := GetSelectedSong;
end;
procedure TMusicLibrary.SetSongAsSelected(index: Integer);
begin
TMusic(MusicLibrary.Items[Index - 1]).Selected := True;
end;
procedure TMusicLibrary.findAll;
var
i : integer;
begin
(*
static void findAll() {
search(3.2);
for (int i=0; i<library.length; i++) {
library[i].selected = true;
}
}
*)
for i := 0 to Count - 1 do
TMusic(MusicLibrary.Items[i]).Selected := True;
end;
procedure TMusicLibrary.findAlbum(a: string);
var
i : integer;
aMusic : TMusic;
begin
(*
static void findAlbum(String a) {
search(1.1);
for (int i=0; i<library.length; i++) {
library[i].selected = library[i].album.equals(a);
}
}
*)
for i := 1 to Count do begin
aMusic := TMusic(MusicLibrary.Items[i-1]);
aMusic.Selected := aMusic.album = a;
end;
end;
procedure TMusicLibrary.findArtist(a: string);
var
i : integer;
aMusic : TMusic;
begin
for i := 1 to Count do begin
aMusic := TMusic(MusicLibrary.Items[i-1]);
aMusic.Selected := aMusic.artist = a;
end;
end;
procedure TMusicLibrary.DisplayContents(results: TList);
var
i : integer;
aMusic : TMusic;
begin
for i := 1 to Count do begin
aMusic := TMusic(MusicLibrary.Items[i-1]);
if aMusic.Selected then
results.Add(aMusic);
end;
end;
initialization
looking := nil;
FMusicLibrary := TMusicLibrary.Create;
finalization
FMusicLibrary.Free;
end.
|
unit TPathfinding_Algos;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, TFeld, math;
type
TSchritt = record
x: Integer;
y: Integer;
end;
TKnoten = record
kosten_hierher: Integer;
kosten_ziel: Integer;
Gesamtkosten: Integer;
Pos_x, Pos_y: Integer;
end;
TPathfinding = class
private
Karte: ^TKarte;
Start_x, Start_y: Integer;
Ziel_x, Ziel_y: Integer;
Schritt: Array of Tschritt;
Schritte_Anzahl: Integer;
function errechneter_weg(x, y: integer): Integer;
public
constructor create(var Karte_par: TKarte);
function Anzahl_schritte(): Integer;
function Ziel_anpassen(x, y: Integer): Boolean;
function Start_Anpassen(x, y: Integer): Boolean;
function AStern_schnell(): Integer;
function AStern_kurz(): Integer;
Function read_Ziel_x(): Integer;
Function read_Ziel_y(): Integer;
Function read_Start_x(): Integer;
Function read_Start_y(): Integer;
function schritt_x(nummer: Integer): Integer;
function schritt_y(nummer: Integer): Integer;
end;
implementation
{ TPathfinding.schritt_x(nummer: Integer)
*Liefert die Position in x richtung des gegebenen schrittes zurück
*Sie liefert -1 zurück falls dieser Schritt noch nicht vorhanden ist
*damit sie überhaupt was zurückliefert muss AStern_schnell oder AStern_kurz eine 0 zurückgeben
}
function TPathfinding.schritt_x(nummer: Integer): Integer;
begin
if(nummer > 0) and (nummer <= Schritte_anzahl) then
result := Schritt[nummer].x
else
result := -1;
end;
{ TPathfinding.schritt_y(nummer: Integer)
*Liefert die Position in y richtung des gegebenen schrittes zurück
*Sie liefert -1 zurück falls dieser Schritt noch nicht vorhanden ist
*damit sie überhaupt was zurückliefert muss AStern_schnell oder AStern_kurz eine 0 zurückgeben
}
function TPathfinding.schritt_y(nummer: Integer): Integer;
begin
if(nummer > 0) and (nummer <= Schritte_anzahl) then
result := Schritt[nummer].y
else
result := -1;
end;
{ TPathfinding.read_Ziel_x
*Diese Funktion gibt den X wert des Zieles zurück
}
function TPathfinding.read_Ziel_x(): Integer;
begin
result := Ziel_x;
end;
{ TPathfinding.read_Ziel_y
*Diese Funktion gibt den y wert des Zieles zurück
}
function TPathfinding.read_Ziel_y(): Integer;
begin
result := Ziel_y;
end;
{ TPathfinding.read_Start_x
*Diese Funktion gibt den X wert des Startes zurück
}
function TPathfinding.read_Start_x(): Integer;
begin
result := Start_x;
end;
{ TPathfinding.read_Start_y
*Diese Funktion gibt den y wert des Startes zurück
}
function TPathfinding.read_Start_y(): Integer;
begin
result := Start_y;
end;
{ TPathfinding.AStern_kurz
*Diese Funktion beschreibt den kürzesten Weg vom Start zum Ziel
*sie hat folgende Rückgabe werte:
0: alles hat funktioniert
1: kein Weg gefunden
2: ziel nicht definiert
3: ziel liegt außerhalb des Intervalls
4: Start nicht definiert
5: Start liegt außerhalb des Intervalls
6: Start = Zeile
7: Start ist Hindernis
8: Ziel ist Hindernis
}
function TPathfinding.AStern_kurz(): Integer;
var
i, j, u, k, bestes_Kosten, bestes_nummer: Integer;
offene_liste, abgearbeitete_Liste, buffer_Liste: Array of TKnoten;
aktueller_Knoten, abgearbeitete_Knoten, neuer_Knoten: TKnoten;
ziel_gefunden, schon_vorhanden: Boolean;
Anzahl_offen, Anzahl_abgearbeitet: Integer;
Buffer_schritte: Array of TSchritt;
begin
Schritte_Anzahl := 0;
Setlength(Schritt, 0);
//überprüfen ob Start Definiert ist;
if((Start_x = -1) Or (Start_y = -1)) then
begin
result := 4;
exit;
end;
//überprüfen ob Start im Intervall liegt
if((Start_x >= Karte.read_grosse_x()) Or (Start_y >= Karte.read_grosse_y())) then
begin
result := 5;
exit;
end;
//überprüfen ob Ziel Definiert ist;
if((Ziel_x = -1) Or (Ziel_y = -1)) then
begin
result := 2;
exit;
end;
//überprüfen ob Ziel im Intervall liegt
if((Ziel_x >= Karte.read_grosse_x()) Or (Ziel_y >= Karte.read_grosse_y())) then
begin
result := 3;
exit;
end;
// Die Start Information anlegen
neuer_Knoten.Pos_x := Start_x;
neuer_Knoten.Pos_y := Start_y;
neuer_Knoten.kosten_ziel := errechneter_weg(neuer_Knoten.Pos_x, neuer_Knoten.Pos_y);
neuer_Knoten.kosten_hierher := 0;
Setlength(offene_Liste, 2);
Anzahl_offen := 1;
offene_liste[1] := neuer_Knoten;
anzahl_abgearbeitet := 0;
// Hier gehts jetzt Richtig los^^
ziel_gefunden := FALSE;
Repeat
// Rausfinden welches die geringsten gesamtkosten hat
//dazu wird das erste Element aus der liste genommen
aktueller_Knoten := Offene_Liste[1];
bestes_kosten := aktueller_Knoten.Gesamtkosten;
bestes_nummer := 1;
// und dann werden die gesamtkosten mit allen andern ELementen aus der offenen Liste verglichen
for i:=1 to anzahl_offen do
begin
aktueller_Knoten := offene_liste[i];
// Form1.Memo1.Lines.Add('Nummer: ' + inttostr(i) + ' Kosten: ' + inttostr(offene_liste[i].Gesamtkosten));
if(aktueller_Knoten.Gesamtkosten < bestes_kosten) then
begin
bestes_kosten := aktueller_Knoten.Gesamtkosten;
bestes_nummer := i;
end;
end;
aktueller_Knoten := offene_liste[bestes_nummer];
//Das Beste ist gefunden
//Nun wird das ELement überprüft ob es schon das Ziel ist
// Form1.Memo1.Lines.Add('x:' + inttostr(aktueller_Knoten.Pos_x) + 'y:' + inttostr(aktueller_Knoten.Pos_y));
if(aktueller_Knoten.kosten_ziel = 0) then
begin
Ziel_gefunden := TRUE;
break;
end;
// Das Ziel wurde noch nicht gefunden
// die 8 rundherum in die offene Liste aufnehmen
for i:= -1 to +1 do
begin
for j:= -1 to +1 do
begin
// überprüfen ob die Elemente schon in der abgearbeiten Liste sind
// Position überprüfen
if(aktueller_Knoten.Pos_x + i < 1) OR (aktueller_Knoten.Pos_x + i > Karte.read_grosse_x) then
continue;
if(aktueller_Knoten.Pos_y + j < 1) OR (aktueller_Knoten.Pos_y + j > Karte.read_grosse_y) then
continue;
// Testen ob das Feld Passierbar ist
if(Karte.read_kosten_feld(aktueller_Knoten.Pos_x + i, aktueller_Knoten.Pos_y + j) = 0) then
continue;
schon_vorhanden := FALSE;
for u:= 1 to anzahl_abgearbeitet do
begin
abgearbeitete_Knoten := abgearbeitete_Liste[u];
if(abgearbeitete_Knoten.Pos_x = aktueller_Knoten.Pos_x + i) and (abgearbeitete_Knoten.Pos_y = aktueller_Knoten.Pos_y + j) then
begin
//Falls das Element schon vorhanden ist, seine Kosten dahin aber kleiner sind
if( abs(i + j) = 1) then
k := 2
else
k := 3;
if(abgearbeitete_Knoten.kosten_hierher > aktueller_Knoten.kosten_hierher +k) then
begin
abgearbeitete_Liste[u].kosten_hierher := aktueller_Knoten.kosten_hierher +k;
end;
schon_vorhanden := TRUE;
break;
end;
end;
for u:=1 to anzahl_offen do
begin
abgearbeitete_Knoten := offene_liste[u];
if(abgearbeitete_Knoten.Pos_x = aktueller_Knoten.Pos_x + i) and (abgearbeitete_Knoten.Pos_y = aktueller_Knoten.Pos_y + j) then
begin
//Falls das Element schon vorhanden ist, seine Kosten dahin aber kleiner sind
if( abs(i + j) = 1) then
k := 2
else
k := 3;
if(abgearbeitete_Knoten.kosten_hierher > aktueller_Knoten.kosten_hierher +k) then
begin
offene_liste[u].kosten_hierher := aktueller_Knoten.kosten_hierher +k;
end;
schon_vorhanden := TRUE;
break;
end;
end;
// Das Element ist schon vorhanden
if(schon_vorhanden = TRUE) then
continue;
//Die Position hinzufügen
neuer_Knoten.Pos_x := aktueller_Knoten.Pos_x + i;
neuer_Knoten.Pos_y := aktueller_Knoten.Pos_y + j;
// Die kosten dahin bestimmen
if( abs(i + j) = 1) then
neuer_Knoten.kosten_hierher := aktueller_Knoten.kosten_hierher + 2
else
neuer_Knoten.kosten_hierher := aktueller_Knoten.kosten_hierher + 3;
neuer_Knoten.kosten_ziel := errechneter_weg(neuer_Knoten.Pos_x, neuer_Knoten.Pos_y);
neuer_Knoten.Gesamtkosten := neuer_Knoten.kosten_hierher + neuer_Knoten.kosten_ziel;
//Zur Offenen Liste hinzufügen
// erstmal alles in einen Buffer schreiben da bei Setlength der Inhalt gelöscht wird
Setlength(Buffer_liste, anzahl_offen+1);
for u:=1 to anzahl_offen do
Buffer_liste[u] := offene_Liste[u];
anzahl_offen := anzahl_offen + 1;
Setlength(offene_Liste, anzahl_offen+1);
for u:=1 to anzahl_offen-1 do
offene_Liste[u] :=Buffer_liste[u];
offene_Liste[anzahl_offen] := neuer_Knoten;
end;
end;
// das benutzte Element in die Abgearbeite Liste schieben
Setlength(Buffer_liste, anzahl_abgearbeitet+1);
for u:=1 to anzahl_abgearbeitet do
Buffer_liste[u] := Abgearbeitete_Liste[u];
anzahl_abgearbeitet := anzahl_abgearbeitet + 1;
Setlength(Abgearbeitete_Liste, anzahl_abgearbeitet+1);
for u:=1 to anzahl_abgearbeitet-1 do
Abgearbeitete_Liste[u] :=Buffer_liste[u];
Abgearbeitete_Liste[anzahl_abgearbeitet] := offene_Liste[bestes_nummer];
//Es aus der offenen Liste löschen
for u:= bestes_nummer to anzahl_offen-1 do
begin
Offene_liste[u] := Offene_liste[u+1];
end;
Setlength(Buffer_liste, anzahl_offen);
for u:=1 to anzahl_offen-1 do
Buffer_liste[u] := offene_Liste[u];
anzahl_offen := anzahl_offen - 1;
Setlength(offene_Liste, anzahl_offen+1);
for u:=1 to anzahl_offen do
offene_Liste[u] :=Buffer_liste[u];
Until (anzahl_offen = 0) or (Ziel_gefunden = True);
// Hier beginnt die Zerückfolgung des Weges
if(Ziel_gefunden = True) then
begin
repeat
Schritte_Anzahl := Schritte_Anzahl + 1;
for i:= -1 to +1 do
begin
for j:= -1 to +1 do
begin
//Erstmal schauen welches Element angrenzt
if(i = 0) and (j = 0) then
continue;
begin
for u:= 1 to Anzahl_abgearbeitet do
begin
if(abgearbeitete_Liste[u].Pos_x = aktueller_Knoten.Pos_x + i) and (abgearbeitete_Liste[u].Pos_y = aktueller_Knoten.Pos_y + j) then
begin
if(Karte.read_kosten_feld(abgearbeitete_Liste[u].Pos_x, abgearbeitete_Liste[u].Pos_y) > 0) then
begin
// schauen welches Element die geringsten kosten haben
if(abgearbeitete_Liste[u].kosten_hierher < neuer_Knoten.kosten_hierher ) then
begin
neuer_Knoten := abgearbeitete_Liste[u];
end;
end;
end;
end;
end;
end;
end;
// schritte dazuzählen
Setlength(Buffer_Schritte, Schritte_anzahl);
For i:= 1 to Schritte_anzahl-1 do
Buffer_Schritte[i] := Schritt[i];
Setlength(Schritt, Schritte_Anzahl+1);
For i:= 1 to Schritte_anzahl-1 do
Schritt[i] := Buffer_Schritte[i];
Schritt[Schritte_anzahl].x := aktueller_Knoten.Pos_x;
Schritt[Schritte_anzahl].y := aktueller_Knoten.Pos_y;
aktueller_Knoten := neuer_Knoten;
Until aktueller_Knoten.kosten_hierher = 0;
result := 0;
end
else
result := 1;
end;
{ TPathfinding.AStern_schnell
*Diese Funktion beschreibt den schnellsten Weg vom Start zum Ziel
*sie hat folgende Rückgabe werte:
0: alles hat funktioniert
1: kein Weg gefunden
2: ziel nicht definiert
3: ziel liegt ausserhalb des intevalls
4: start nicht definiert
5: start liegt ausserhalb des intervalls
6: Start = Zeile
7: Start ist Hinderniss
8: Ziel ist Hinderniss
}
function TPathfinding.AStern_schnell(): Integer;
var
i, j, u, bestes_Kosten, bestes_nummer: Integer;
offene_liste, abgearbeitete_Liste, hinderniss_Liste, buffer_Liste: Array of TKnoten;
aktueller_Knoten, abgearbeitete_Knoten, neuer_Knoten: TKnoten;
ziel_gefunden, schon_vorhanden: Boolean;
Anzahl_offen, Anzahl_abgearbeitet: Integer;
Buffer_schritte: Array of TSchritt;
begin
Schritte_Anzahl := 0;
Setlength(Schritt, 0);
//überprüfen ob Start Definiert ist;
if((Start_x = -1) Or (Start_y = -1)) then
begin
result := 4;
exit;
end;
//überprüfen ob Start im Intervall liegt
if((Start_x >= Karte.read_grosse_x()) Or (Start_y >= Karte.read_grosse_y())) then
begin
result := 5;
exit;
end;
//überprüfen ob Ziel Definiert ist;
if((Ziel_x = -1) Or (Ziel_y = -1)) then
begin
result := 2;
exit;
end;
//überprüfen ob Ziel im Intervall liegt
if((Ziel_x >= Karte.read_grosse_x()) Or (Ziel_y >= Karte.read_grosse_y())) then
begin
result := 3;
exit;
end;
// Die Start Information anlegen
neuer_Knoten.Pos_x := Start_x;
neuer_Knoten.Pos_y := Start_y;
neuer_Knoten.kosten_ziel := errechneter_weg(neuer_Knoten.Pos_x, neuer_Knoten.Pos_y);
neuer_Knoten.kosten_hierher := 0;
Setlength(offene_Liste, 2);
Anzahl_offen := 1;
offene_liste[1] := neuer_Knoten;
anzahl_abgearbeitet := 0;
// Hier gehts jetzt Richtig los^^
ziel_gefunden := FALSE;
Repeat
// Rausfinden welches die geringsten gesamtkosten hat
//dazu wird das erste Element aus der liste genommen
aktueller_Knoten := Offene_Liste[1];
bestes_kosten := aktueller_Knoten.Gesamtkosten;
bestes_nummer := 1;
// und dann werden die gesamtkosten mit allen andern ELementen aus der offenen Liste verglichen
for i:=1 to anzahl_offen do
begin
aktueller_Knoten := offene_liste[i];
// Form1.Memo1.Lines.Add('Nummer: ' + inttostr(i) + ' Kosten: ' + inttostr(offene_liste[i].Gesamtkosten));
if(aktueller_Knoten.Gesamtkosten < bestes_kosten) then
begin
bestes_kosten := aktueller_Knoten.Gesamtkosten;
bestes_nummer := i;
end;
end;
aktueller_Knoten := offene_liste[bestes_nummer];
//Das Beste ist gefunden
//Nun wird das ELement überprüft ob es schon das Ziel ist
// Form1.Memo1.Lines.Add('x:' + inttostr(aktueller_Knoten.Pos_x) + 'y:' + inttostr(aktueller_Knoten.Pos_y));
if(aktueller_Knoten.kosten_ziel = 0) then
begin
Ziel_gefunden := TRUE;
break;
end;
// Das Ziel wurde noch nicht gefunden
// die 8 rundherum in die offene Liste aufnehmen
for i:= -1 to +1 do
begin
for j:= -1 to +1 do
begin
// überprüfen ob die Elemente schon in der abgearbeiten Liste sind
// Position überprüfen
if(aktueller_Knoten.Pos_x + i < 1) OR (aktueller_Knoten.Pos_x + i > Karte.read_grosse_x) then
continue;
if(aktueller_Knoten.Pos_y + j < 1) OR (aktueller_Knoten.Pos_y + j > Karte.read_grosse_y) then
continue;
// Testen ob das Feld Passierbar ist
if(Karte.read_kosten_feld(aktueller_Knoten.Pos_x + i, aktueller_Knoten.Pos_y + j) = 0) then
continue;
schon_vorhanden := FALSE;
for u:= 1 to anzahl_abgearbeitet do
begin
abgearbeitete_Knoten := abgearbeitete_Liste[u];
if(abgearbeitete_Knoten.Pos_x = aktueller_Knoten.Pos_x + i) and (abgearbeitete_Knoten.Pos_y = aktueller_Knoten.Pos_y + j) then
begin
schon_vorhanden := TRUE;
break;
end;
end;
for u:=1 to anzahl_offen do
begin
abgearbeitete_Knoten := offene_liste[u];
if(abgearbeitete_Knoten.Pos_x = aktueller_Knoten.Pos_x + i) and (abgearbeitete_Knoten.Pos_y = aktueller_Knoten.Pos_y + j) then
begin
schon_vorhanden := TRUE;
break;
end;
end;
// Das Element ist schon vorhanden
if(schon_vorhanden = TRUE) then
continue;
//Die Position hinzufügen
neuer_Knoten.Pos_x := aktueller_Knoten.Pos_x + i;
neuer_Knoten.Pos_y := aktueller_Knoten.Pos_y + j;
// Die kosten dahin bestimmen
if( abs(i + j) = 1) then
neuer_Knoten.kosten_hierher := aktueller_Knoten.kosten_hierher + 2*Karte.read_kosten_feld(neuer_Knoten.Pos_x, neuer_Knoten.Pos_y)
else
neuer_Knoten.kosten_hierher := aktueller_Knoten.kosten_hierher + 3*Karte.read_kosten_feld(neuer_Knoten.Pos_x, neuer_Knoten.Pos_y);
neuer_Knoten.kosten_ziel := errechneter_weg(neuer_Knoten.Pos_x, neuer_Knoten.Pos_y);
neuer_Knoten.Gesamtkosten := neuer_Knoten.kosten_hierher + neuer_Knoten.kosten_ziel;
//Zur Offenen Liste hinzufügen
// erstmal alles in einen Buffer schreiben da bei Setlength der Inhalt gelöscht wird
Setlength(Buffer_liste, anzahl_offen+1);
for u:=1 to anzahl_offen do
Buffer_liste[u] := offene_Liste[u];
anzahl_offen := anzahl_offen + 1;
Setlength(offene_Liste, anzahl_offen+1);
for u:=1 to anzahl_offen-1 do
offene_Liste[u] :=Buffer_liste[u];
offene_Liste[anzahl_offen] := neuer_Knoten;
end;
end;
// das benutzte Element in die Abgearbeite Liste schieben
Setlength(Buffer_liste, anzahl_abgearbeitet+1);
for u:=1 to anzahl_abgearbeitet do
Buffer_liste[u] := Abgearbeitete_Liste[u];
anzahl_abgearbeitet := anzahl_abgearbeitet + 1;
Setlength(Abgearbeitete_Liste, anzahl_abgearbeitet+1);
for u:=1 to anzahl_abgearbeitet-1 do
Abgearbeitete_Liste[u] :=Buffer_liste[u];
Abgearbeitete_Liste[anzahl_abgearbeitet] := offene_Liste[bestes_nummer];
//Es aus der offenen Liste löschen
for u:= bestes_nummer to anzahl_offen-1 do
begin
Offene_liste[u] := Offene_liste[u+1];
end;
Setlength(Buffer_liste, anzahl_offen);
for u:=1 to anzahl_offen-1 do
Buffer_liste[u] := offene_Liste[u];
anzahl_offen := anzahl_offen - 1;
Setlength(offene_Liste, anzahl_offen+1);
for u:=1 to anzahl_offen do
offene_Liste[u] :=Buffer_liste[u];
//form1.Memo1.Lines.Add(inttostr(Anzahl_offen));
Until (anzahl_offen = 0) or (Ziel_gefunden = True);
if(Ziel_gefunden = True) then
begin
repeat
Schritte_Anzahl := Schritte_Anzahl + 1;
for i:= -1 to +1 do
begin
for j:= -1 to +1 do
begin
//Erstmal schauen welches Element angrenzt
if(i = 0) and (j = 0) then
continue;
begin
for u:= 1 to Anzahl_abgearbeitet do
begin
if(abgearbeitete_Liste[u].Pos_x = aktueller_Knoten.Pos_x + i) and (abgearbeitete_Liste[u].Pos_y = aktueller_Knoten.Pos_y + j) then
begin
//showmessage('x: ' + inttostr(abgearbeitete_Liste[u].Pos_x ) + ' y:' + inttostr(abgearbeitete_Liste[u].Pos_y) + ' kosten: ' + inttostr(Karte.read_kosten_feld(abgearbeitete_Liste[u].Pos_x, abgearbeitete_Liste[u].Pos_y)));
if(Karte.read_kosten_feld(abgearbeitete_Liste[u].Pos_x, abgearbeitete_Liste[u].Pos_y) > 0) then
begin
// schauen welches Element die geringsten kosten haben
if(abgearbeitete_Liste[u].kosten_hierher < neuer_Knoten.kosten_hierher ) then
begin
//Form1.Memo1.Lines.Add('Kosten Karte: '+inttostr(Karte.read_kosten_feld(abgearbeitete_Liste[u].Pos_x, abgearbeitete_Liste[u].Pos_y)));
neuer_Knoten := abgearbeitete_Liste[u];
end;
end;
end;
end;
end;
end;
end;
// schritte dazuzählen
Setlength(Buffer_Schritte, Schritte_anzahl);
For i:= 1 to Schritte_anzahl-1 do
Buffer_Schritte[i] := Schritt[i];
Setlength(Schritt, Schritte_Anzahl+1);
For i:= 1 to Schritte_anzahl-1 do
Schritt[i] := Buffer_Schritte[i];
Schritt[Schritte_anzahl].x := aktueller_Knoten.Pos_x;
Schritt[Schritte_anzahl].y := aktueller_Knoten.Pos_y;
aktueller_Knoten := neuer_Knoten;
// Form1.Memo1.Lines.Add(inttostr(anzahl_abgearbeitet));
Until aktueller_Knoten.kosten_hierher = 0;
result := 0;
end
else
result := 1;
end;
{Konstruktor
*erwartet einen Zeiger einer TKarte als Parameter
*Setzt alle Variablen auf ihre Startwerte
}
constructor TPathfinding.create(var Karte_par: TKarte);
begin
Karte := @Karte_par;
Ziel_x := -1;
Ziel_y := -1;
Start_x := -1;
Start_y := -1;
end;
{ TPathfinding.errechneter_weg
*errechnet Die geschätzten Kosten bis zum Ziel
* Erwartet eine Positionsangabe als Parameter
}
function TPathfinding.errechneter_weg(x, y: Integer): Integer;
begin
result := abs(Ziel_x - x) * 2 + Abs(Ziel_y - y) * 2;
end;
{ TPathfinding.Anzahl_schritte
* Liefert die anzahl der schritte, die man vom Start zum Ziel benötigt
}
function TPathfinding.Anzahl_schritte(): Integer;
begin
result := Schritte_anzahl;
end;
{ TPathfinding.Ziel_anpassen
* Erwartete eine Positionsangabe als Parameter
* ändert die Zielposition in die Parameter Position
* Liefert True Zurück falls es geklappt hat
}
function TPathfinding.Ziel_anpassen(x, y: Integer): Boolean;
begin
if((x >= 0) and (x < Karte.read_grosse_x)) then
if((y >= 0) and (y < Karte.read_grosse_y)) then
begin
Ziel_x := x;
Ziel_y := y;
result := TRUE;
exit;
end;
result := False;
end;
{ TPathfinding.Start_anpassen
* Erwartete eine Positionsangabe als Parameter
* ändert die Startposition in die Parameter Position
* Liefert True Zurück falls es geklappt hat
}
function TPathfinding.Start_anpassen(x, y: Integer): boolean;
begin
if((x >= 0) and (x < Karte.read_grosse_x)) then
if((y >= 0) and (y < Karte.read_grosse_y)) then
begin
Start_x := x;
Start_y := y;
result := TRUE;
exit;
end;
result := False;
end;
end.
|
program gtmenu;
{$IFNDEF HASAMIGA}
{$FATAL This source is compatible with Amiga, AROS and MorphOS only !}
{$ENDIF}
{$MODE OBJFPC}{$H+}{$HINTS ON}
{$UNITPATH ../../../Base/CHelpers}
{$UNITPATH ../../../Base/Trinity}
{$UNITPATH ../../../Base/Sugar}
{$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF}
{$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF}
{$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF}
{
===========================================================================
Project : gtmenu
Topic : Example of menus made with gadtools
Author : Thomas Rapp
Source : http://thomas-rapp.homepage.t-online.de/examples/gtmenu.c
===========================================================================
This example was originally written in c by Thomas Rapp.
The original examples are available online and published at Thomas Rapp's
website (http://thomas-rapp.homepage.t-online.de/examples)
The c-sources were converted to Free Pascal, and (variable) names and
comments were translated from German into English as much as possible.
Free Pascal sources were adjusted in order to support the following targets
out of the box:
- Amiga-m68k, AROS-i386 and MorphOS-ppc
In order to accomplish that goal, some use of support units is used that
aids compilation in a more or less uniform way.
Conversion to Free Pascal and translation was done by Magorium in 2015,
with kind permission from Thomas Rapp to be able to publish.
===========================================================================
Unless otherwise noted, you must consider these examples to be
copyrighted by their respective owner(s)
===========================================================================
}
Uses
Exec, AmigaDOS, Intuition, Gadtools, Utility,
{$IFDEF AMIGA}
systemvartags,
{$ENDIF}
CHelpers,
Trinity;
//*-------------------------------------------------------------------------*/
//* */
//*-------------------------------------------------------------------------*/
const
newmenu : Array[0..16-1] of TNewMenu =
(
( nm_Type: NM_TITLE; nm_Label: 'Project'; nm_CommKey: nil; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Open...'; nm_CommKey: 'O'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Save'; nm_CommKey: 'S'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Save As...'; nm_CommKey: 'A'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: PChar(NM_BARLABEL); nm_CommKey: nil; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Quit'; nm_CommKey: 'Q'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_TITLE; nm_Label: 'Edit'; nm_CommKey: nil; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Mark'; nm_CommKey: 'B'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Cut'; nm_CommKey: 'X'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Copy'; nm_CommKey: 'C'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Paste'; nm_CommKey: 'V'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_TITLE; nm_Label: 'Settings'; nm_CommKey: nil; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Reset to defaults'; nm_CommKey: 'D'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Reset to last saved'; nm_CommKey: 'L'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_ITEM; nm_Label: 'Previous settings'; nm_CommKey: 'P'; nm_Flags: 0; nm_MutualExclude: 0; nm_UserData: nil ),
( nm_Type: NM_END )
);
//*-------------------------------------------------------------------------*/
//* Main program */
//*-------------------------------------------------------------------------*/
function main: integer;
var
win : PWindow;
scr : PScreen;
imsg : PIntuiMessage;
cont : Boolean;
vi : APTR = nil;
menu : PMenu = nil;
item : PMenuItem;
begin
if SetAndTest(win, OpenWindowTags (nil,
[
TAG_(WA_Left) , 20,
TAG_(WA_Top) , 30,
TAG_(WA_Width) , 100,
TAG_(WA_Height) , 50,
TAG_(WA_Flags) , TAG_(WFLG_CLOSEGADGET or WFLG_DRAGBAR or WFLG_DEPTHGADGET or WFLG_ACTIVATE or WFLG_NEWLOOKMENUS or WFLG_NOCAREREFRESH),
TAG_(WA_IDCMP) , TAG_(IDCMP_CLOSEWINDOW or IDCMP_VANILLAKEY or IDCMP_MENUPICK),
TAG_END
])) then
begin
scr := win^.WScreen;
if SetAndTest(vi, GetVisualInfoA(scr, nil))
then if SetAndTest(menu, CreateMenusA(newmenu, nil))
then if (LayoutMenus(menu, vi, [TAG_(GTMN_NewLookMenus), TAG_(TRUE), TAG_END]))
then SetMenuStrip(win, menu);
cont := TRUE;
while cont do
begin
if (Wait ((1 shl win^.UserPort^.mp_SigBit) or SIGBREAKF_CTRL_C) and SIGBREAKF_CTRL_C) <> 0
then cont := FALSE;
while SetAndTest(imsg, PIntuiMessage(GetMsg(win^.UserPort))) do
begin
case (imsg^.IClass) of
IDCMP_VANILLAKEY:
begin
if (imsg^.Code = $1b) //* Esc */
then cont := FALSE;
end;
IDCMP_CLOSEWINDOW:
begin
cont := FALSE;
end;
IDCMP_MENUPICK:
begin
item := ItemAddress(menu, imsg^.Code);
while assigned(Item) do
begin
WriteLn('menu selected: ', PIntuiText(item^.ItemFill)^.IText);
item := ItemAddress(menu, item^.NextSelect);
end;
end;
end;
ReplyMsg(PMessage(imsg));
end;
end; // while
ClearMenuStrip(win);
if assigned(menu) then FreeMenus(menu);
if assigned(vi) then FreeVisualInfo(vi);
CloseWindow(win);
end;
result := (0);
end;
//*-------------------------------------------------------------------------*/
//* End of original source text */
//*-------------------------------------------------------------------------*/
Function OpenLibs: boolean;
begin
Result := False;
{$IF DEFINED(MORPHOS) or DEFINED(AMIGA)}
GadToolsBase := OpenLibrary(GADTOOLSNAME, 0);
if not assigned(GadToolsBase) then Exit;
{$ENDIF}
{$IF DEFINED(MORPHOS)}
IntuitionBase := OpenLibrary(INTUITIONNAME, 0);
if not assigned(IntuitionBase) then Exit;
{$ENDIF}
Result := True;
end;
Procedure CloseLibs;
begin
{$IF DEFINED(MORPHOS)}
if assigned(IntuitionBase) then CloseLibrary(pLibrary(IntuitionBase));
{$ENDIF}
{$IF DEFINED(MORPHOS) or DEFINED(AMIGA)}
if assigned(GadToolsBase) then CloseLibrary(pLibrary(GadToolsBase));
{$ENDIF}
end;
begin
if OpenLibs
then ExitCode := Main
else ExitCode := 10;
CloseLibs;
end.
|
unit ProceduralTypesForm;
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.Controls.Presentation, FMX.ScrollBox, FMX.Memo;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
CheckBox1: TCheckBox;
procedure Button1Click(Sender: TObject);
procedure CheckBox1Change(Sender: TObject);
private
{ Private declarations }
public
procedure Show(const Msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
type
// proceduraly type, specifying parameters and return type (if function)
// this type is compatible with any routine with same parameters etc
TIntProc = procedure(var Num: Integer);
// this procedure is of the same type as TIntProc
procedure DoubleTheValue(var Value: Integer);
begin
Value := Value * 2;
end;
procedure TripleTheValue(var Value: Integer);
begin
Value := Value * 3;
end;
var
IntProc: TIntProc = DoubleTheValue;
Value: Integer = 1;
procedure TForm1.Button1Click(Sender: TObject);
begin
// Value is passed to IntProc (of type TIntProc, initialised as DoubleTheValue)
// rather than DoubleTheValue directly
IntProc(Value);
Show(Value.ToString);
end;
procedure TForm1.CheckBox1Change(Sender: TObject);
begin
if CheckBox1.IsChecked then
IntProc := TripleTheValue
else
IntProc := DoubleTheValue;
end;
procedure TForm1.Show(const Msg: string);
begin
Memo1.Lines.Add(Msg);
end;
end.
|
unit uFrmCadastroVenda;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmCadastroPai, DB, StdCtrls, ExtCtrls, DBCtrls, uClienteController,
Generics.Collections, uClienteModel, Grids, uVendaItemModel, uVendaModel,
uVendaItemController, uProdutosController, uProdutosModel, uVendasController,
ZAbstractRODataset, ZAbstractDataset, ZDataset, frxClass, frxDBSet;
type
TfrmCadastroVendas = class(TfrmCadastroPai)
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label5: TLabel;
txtCodigo: TEdit;
txtDataVenda: TEdit;
txtDataFaturado: TEdit;
chkFaturado: TCheckBox;
cmbClientes: TComboBox;
Panel2: TPanel;
CmbItens: TComboBox;
txtQtd: TEdit;
txtValorUnitario: TEdit;
txtDesconto: TEdit;
txtSubTotal: TEdit;
StrGridVendasItens: TStringGrid;
Label4: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
txtTotal: TEdit;
Label11: TLabel;
btnAddItem: TButton;
frVenda: TfrxReport;
frxDadosVenda: TfrxDBDataset;
qryItens: TZQuery;
frxItensVenda: TfrxDBDataset;
qryVendas: TZQuery;
btnImprimir: TButton;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnAddItemClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
private
{ Private declarations }
procedure CarregaComboCliente;
procedure PreencheComboCliente(ListaClientes:TObjectList<TClienteModel>);
procedure ConfirguraGrid;
procedure ZeraIndiceGrid;
procedure IncrementaIndiceLinhaGrid;
procedure AdicionaItemGrid;
procedure CarregaComboProdutos;
procedure CriarVenda;
procedure PreencheObjetoVenda(VendaModel:TVendasModel);
procedure PreencheObjetoProduto(ListaDeProdutos:TObjectList<TProdutosModel>);
procedure CarregaRelatorio(const pReport:TfrxReport);
public
{ Public declarations }
end;
var
frmCadastroVendas: TfrmCadastroVendas;
indiceLinhaItemGrid: Integer;
implementation
{$R *.dfm}
procedure TfrmCadastroVendas.AdicionaItemGrid;
begin
StrGridVendasItens.Cells[0,indiceLinhaItemGrid] := IntToStr(Integer(CmbItens.Items.Objects[CmbItens.ItemIndex]));
StrGridVendasItens.Cells[1,indiceLinhaItemGrid] := CmbItens.Text;
StrGridVendasItens.Cells[2,indiceLinhaItemGrid] := txtQtd.Text;
StrGridVendasItens.Cells[3,indiceLinhaItemGrid] := txtValorUnitario.Text;
StrGridVendasItens.Cells[4,indiceLinhaItemGrid] := txtDesconto.Text;
StrGridVendasItens.Cells[5,indiceLinhaItemGrid] := txtSubTotal.Text;
StrGridVendasItens.Cells[6,indiceLinhaItemGrid] := txtTotal.Text;
IncrementaIndiceLinhaGrid;
end;
procedure TfrmCadastroVendas.btnAddItemClick(Sender: TObject);
begin
inherited;
AdicionaItemGrid;
end;
procedure TfrmCadastroVendas.btnGravarClick(Sender: TObject);
begin
inherited;
CriarVenda;
{todo -c: verificar baixa de estoque}
end;
procedure TfrmCadastroVendas.btnImprimirClick(Sender: TObject);
begin
inherited;
CarregaRelatorio(frVenda);
end;
procedure TfrmCadastroVendas.CarregaComboCliente;
var
ListaClientes:TObjectList<TClienteModel>;
ClienteController : TClienteController;
begin
ClienteController := TClienteController.Create;
ListaClientes := ClienteController.RetornaClientes;
PreencheComboCliente(ListaClientes);
ListaClientes.Free;
ClienteController.Free;
end;
procedure TfrmCadastroVendas.CarregaComboProdutos;
var
ListaProdutos : TObjectList<TProdutosModel>;
ProdutoModel : TProdutosModel;
ProdutosController : TProdutosController;
begin
ProdutosController := TProdutosController.Create;
ListaProdutos := ProdutosController.RetornaListaProdutos;
for ProdutoModel in ListaProdutos do
begin
CmbItens.Items.AddObject(ProdutoModel.Descricao, TObject(ProdutoModel.Id));
end;
ListaProdutos.Free;
ProdutosController.Free;
end;
procedure TfrmCadastroVendas.CarregaRelatorio(const pReport: TfrxReport);
begin
pReport.PrepareReport;
pReport.ShowPreparedReport;
end;
procedure TfrmCadastroVendas.ConfirguraGrid;
begin
StrGridVendasItens.Cells[0,0] := 'Código';
StrGridVendasItens.Cells[1,0] := 'Item';
StrGridVendasItens.Cells[2,0] := 'Qtd';
StrGridVendasItens.Cells[3,0] := 'Valor. Unit.';
StrGridVendasItens.Cells[4,0] := 'Desconto';
StrGridVendasItens.Cells[5,0] := 'Sub total';
StrGridVendasItens.Cells[6,0] := 'Total';
end;
procedure TfrmCadastroVendas.CriarVenda;
var
VendasModel:TVendasModel;
ProdutoModel:TProdutosModel;
VendasController: TVendasController;
begin
VendasModel := TVendasModel.Create;
ProdutoModel := TProdutosModel.Create;
VendasController := TVendasController.Create;
try
PreencheObjetoVenda(VendasModel);
PreencheObjetoProduto(VendasModel.ListaDeProdutos);
if VendasController.Gravar(VendasModel) then
ShowMessage('Venda cadastrada com sucesso')
else
ShowMessage('Erro ao criar venda !');
finally
VendasController.Free;
ProdutoModel.Free;
VendasModel.Free;
end;
end;
procedure TfrmCadastroVendas.FormCreate(Sender: TObject);
begin
inherited;
ZeraIndiceGrid;
end;
procedure TfrmCadastroVendas.FormShow(Sender: TObject);
begin
inherited;
CarregaComboCliente;
CarregaComboProdutos;
ConfirguraGrid;
end;
procedure TfrmCadastroVendas.IncrementaIndiceLinhaGrid;
begin
Inc(indiceLinhaItemGrid);
end;
procedure TfrmCadastroVendas.PreencheComboCliente(
ListaClientes: TObjectList<TClienteModel>);
var
ClienteModel:TClienteModel;
begin
for ClienteModel in ListaClientes do
begin
cmbClientes.Items.AddObject(ClienteModel.Nome, TObject(ClienteModel.Id));
end;
end;
procedure TfrmCadastroVendas.PreencheObjetoProduto(
ListaDeProdutos:TObjectList<TProdutosModel>);
var
ProdutoModel: TProdutosModel;
begin
ZeraIndiceGrid;
while(True)do
begin
if (StrToIntDef(StrGridVendasItens.Cells[0,indiceLinhaItemGrid],0)> 0) then
begin
ProdutoModel := TProdutosModel.Create;
ProdutoModel.Id := StrToInt(StrGridVendasItens.Cells[0,indiceLinhaItemGrid]);
ProdutoModel.Descricao := StrGridVendasItens.Cells[1,indiceLinhaItemGrid];
ProdutoModel.Qtd := StrToFloat(StrGridVendasItens.Cells[2,indiceLinhaItemGrid]);
ProdutoModel.Custo := StrToFloat(StrGridVendasItens.Cells[3,indiceLinhaItemGrid]);
ProdutoModel.Desconto := StrToFloat(StrGridVendasItens.Cells[4,indiceLinhaItemGrid]);
ListaDeProdutos.Add(ProdutoModel);
IncrementaIndiceLinhaGrid;
end
else
Break;
end;
end;
procedure TfrmCadastroVendas.PreencheObjetoVenda(VendaModel: TVendasModel);
begin
VendaModel.Id := 0;
VendaModel.Cliente.Id := Integer(cmbClientes.Items.Objects[cmbClientes.ItemIndex]);
VendaModel.DataVenda := StrToDate(txtDataVenda.Text);
VendaModel.DataFaturado := StrToDate(txtDataFaturado.Text);
VendaModel.Faturado := chkFaturado.Checked;
end;
procedure TfrmCadastroVendas.ZeraIndiceGrid;
begin
indiceLinhaItemGrid := 1;
end;
end.
|
{
Sobre o autor:
Guinther Pauli
Delphi Certified Professional - 3,5,6,7,2005,2006,Delphi Web,Kylix,XE
Microsoft Certified Professional - MCP,MCAD,MCSD.NET,MCTS,MCPD (C#, ASP.NET, Arquitetura)
Colaborador Editorial Revistas .net Magazine e ClubeDelphi
MVP (Most Valuable Professional) - Embarcadero Technologies - US
http://gpauli.com
http://www.facebook.com/guintherpauli
http://www.twitter.com/guintherpauli
http://br.linkedin.com/in/guintherpauli
}
unit uFramework;
interface
uses
System.SysUtils;
type
// Handler
Autenticacao = class abstract
protected _sucessor: Autenticacao;
public procedure setSucessor(Sucessor: Autenticacao);
public function Autenticar(UserName, Password: string): boolean; virtual; abstract;
end;
// ConcreteHandler
Formulario = class(Autenticacao)
public function Autenticar(Usuario, Senha: string): boolean; override;
end;
// ConcreteHandler
Server = class(Autenticacao)
public function Autenticar(Usuario, Senha: string): boolean; override;
end;
// ConcreteHandler
BancoDados = class(Autenticacao)
public function Autenticar(Usuario, Senha: string): boolean; override;
end;
implementation
{ Autenticacao }
procedure Autenticacao.setSucessor(Sucessor: Autenticacao);
begin
self._sucessor := Sucessor;
end;
{ Formulario }
function Formulario.Autenticar(Usuario, Senha: string): boolean;
begin
result := (Usuario = 'guinther') and (Senha = '123');
WriteLn('Validação feita no Formulário:' + BoolToStr(result,true));
// encadeia chamada
if (_sucessor <> nil) then
result := _sucessor.Autenticar(Usuario, Senha);
end;
{ Server }
function Server.Autenticar(Usuario, Senha: string): boolean;
begin
result := (Usuario = 'guinther') and (Senha = '123');
WriteLn('Validação feita no AppServer:' + BoolToStr(result,true));
// encadeia chamada
if (_sucessor <> nil) then
result := _sucessor.Autenticar(Usuario, Senha);
end;
{ BancoDados }
function BancoDados.Autenticar(Usuario, Senha: string): boolean;
begin
result := (Usuario = 'guinther') and (Senha = '123');
WriteLn('Validação feita no Banco de Dados:' + BoolToStr(result,true));
// encadeia chamada
if (_sucessor <> nil) then
result := _sucessor.Autenticar(Usuario, Senha);
end;
end.
|
unit unCadDespesaConfiguracao;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.Buttons, Vcl.Mask, DateUtils, Data.DB, ZAbstractRODataset,
ZAbstractDataset, ZDataset, AdvAppStyler, AdvGlowButton, AdvFontCombo,
AdvSpin, AdvEdit, AdvMoneyEdit, AdvCombo, AdvEdBtn, AdvPanel, Vcl.ExtCtrls,
unFornecedor, unFormaPagamento;
type
TfmCadDespesaConfiguracao = class(TForm)
FormStyler: TAdvFormStyler;
PanelBotoes: TAdvPanel;
BitBtnFechar: TAdvGlowButton;
BitBtnAplicar: TAdvGlowButton;
PanelInfo: TAdvPanel;
LabelCamposRequeridos: TLabel;
PanelTitulos: TAdvPanel;
LabelPeriodo: TLabel;
LabelValorDespesa: TLabel;
LabelDiaVencimento: TLabel;
LabelFormaPagamento: TLabel;
LabelFornecedor: TLabel;
PanelCampos: TAdvPanel;
ButtonLimparFormaPagamento: TAdvGlowButton;
ButtonLimparFornecedor: TAdvGlowButton;
ButtonNovoFormaPagamento: TAdvGlowButton;
ButtonNovoFornecedor: TAdvGlowButton;
ComboBoxCadastroMesEncerramento: TAdvOfficeComboBox;
ComboBoxCadastroMesInicio: TAdvOfficeComboBox;
ComboEditCadastroNMFORMAPAGAMENTO: TAdvEditBtn;
ComboEditCadastroNMFORNECEDOR: TAdvEditBtn;
EditCadastroCDFORMAPAGAMENTO: TAdvEdit;
EditCadastroCDFORNECEDOR: TAdvEdit;
LabelPeriodoSeparador: TLabel;
LabelPeriodoSeparador2: TLabel;
LabelPeriodoSeparador3: TLabel;
SpinEditCadastroAnoEncerramento: TAdvSpinEdit;
SpinEditCadastroAnoInicio: TAdvSpinEdit;
SpinEditCadastroDiaVencimento: TAdvSpinEdit;
EditCadastroValorDespesa: TAdvMoneyEdit;
procedure BitBtnFecharClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormResize(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BitBtnAplicarClick(Sender: TObject);
procedure ButtonLimparFormaPagamentoClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ButtonNovoFormaPagamentoClick(Sender: TObject);
procedure EditCadastroCDFORMAPAGAMENTOExit(Sender: TObject);
procedure ComboEditCadastroNMFORMAPAGAMENTOExit(Sender: TObject);
procedure ButtonLimparFornecedorClick(Sender: TObject);
procedure ButtonNovoFornecedorClick(Sender: TObject);
procedure EditCadastroCDFORNECEDORExit(Sender: TObject);
procedure ComboEditCadastroNMFORNECEDORExit(Sender: TObject);
procedure ComboEditCadastroNMFORMAPAGAMENTOClickBtn(Sender: TObject);
procedure ComboEditCadastroNMFORNECEDORClickBtn(Sender: TObject);
private
{ Private declarations }
pId: TGUID;
plFormaPagamento, plFornecedor: TStringList;
pFornecedor: TFornecedor;
pFormaPagamento: TFormaPagamento;
FMesInicio, FMesEncerramento, FAnoInicio, FAnoEncerramento,
FDiaVencimento, FFormaPagamento, FFornecedor: integer;
FValorDespesa: currency;
procedure configuraCampos;
procedure carregaImagensBotoes;
public
{ Public declarations }
property MesInicio: integer read FMesInicio write FMesInicio;
property MesEncerramento: integer read FMesEncerramento write FMesEncerramento;
property AnoInicio: integer read FAnoInicio write FAnoInicio;
property AnoEncerramento: integer read FAnoEncerramento write FAnoEncerramento;
property DiaVencimento: integer read FDiaVencimento write FDiaVencimento;
property ValorDespesa: currency read FValorDespesa write FValorDespesa;
property FormaPagamento: integer read FFormaPagamento write FFormaPagamento;
property Fornecedor: integer read FFornecedor write FFornecedor;
end;
var
fmCadDespesaConfiguracao: TfmCadDespesaConfiguracao;
implementation
{$R *.dfm}
uses unPrincipal, unCadFormaPagamento, undmPrincipal, undmEstilo,
unConFiltroPadrao, unCadFornecedor;
procedure TfmCadDespesaConfiguracao.BitBtnAplicarClick(Sender: TObject);
var
vMensagem: string;
begin
// Realiza validações.
vMensagem := EmptyStr;
if SpinEditCadastroAnoInicio.Value > SpinEditCadastroAnoEncerramento.Value then
vMensagem := '- O ano inicial deve ser inferior ao ano de encerramento.'#13#10'Favor informar um ano inicial inferior ao ano de encerramento.'#13+#10;
if SpinEditCadastroAnoInicio.Value = SpinEditCadastroAnoEncerramento.Value then
if ComboBoxCadastroMesInicio.ItemIndex > ComboBoxCadastroMesEncerramento.ItemIndex then
vMensagem := vMensagem + '- O mês inicial deve ser inferior ao mês de encerramento.'#13#10'Favor informar um mês inicial inferior ao mês de encerramento.'#13+#10;
if EditCadastroValorDespesa.Value = 0 then
vMensagem := vMensagem + '- O valor da despesa deve ser maior que zero.'#13#10'Favor informar um valor maior que zero para o valor da despesa.';
if vMensagem <> EmptyStr then
begin
MessageBox(fmPrincipal.Handle, PWideChar(vMensagem), cTituloMensagemErro, MB_OK or MB_ICONERROR);
ActiveControl := ComboBoxCadastroMesInicio;
Exit;
end;
// Fim Realiza validações.
// Seta os valores;
MesInicio := ComboBoxCadastroMesInicio.ItemIndex;
MesEncerramento := ComboBoxCadastroMesEncerramento.ItemIndex;
AnoInicio := Trunc(SpinEditCadastroAnoInicio.Value);
AnoEncerramento := Trunc(SpinEditCadastroAnoEncerramento.Value);
DiaVencimento := Trunc(SpinEditCadastroDiaVencimento.Value);
ValorDespesa := EditCadastroValorDespesa.Value;
// Se selecionou, seta a forma de pagamento.
if plFormaPagamento.Count > 0 then
FormaPagamento := StrToInt(plFormaPagamento.Strings[0])
else
FormaPagamento := -1;
// Se selecionou, seta a fornecedor.
if plFornecedor.Count > 0 then
Fornecedor := StrToInt(plFornecedor.Strings[0])
else
Fornecedor := -1;
Close;
end;
procedure TfmCadDespesaConfiguracao.BitBtnFecharClick(Sender: TObject);
begin
ValorDespesa := -1;
Close;
end;
procedure TfmCadDespesaConfiguracao.ButtonLimparFormaPagamentoClick(
Sender: TObject);
begin
plFormaPagamento.Clear;
EditCadastroCDFORMAPAGAMENTO.Clear;
ComboEditCadastroNMFORMAPAGAMENTO.Clear;
EditCadastroCDFORMAPAGAMENTO.Enabled := true;
ComboEditCadastroNMFORMAPAGAMENTO.Enabled := true;
ButtonLimparFormaPagamento.Enabled := false;
ButtonNovoFormaPagamento.Enabled := true;
end;
procedure TfmCadDespesaConfiguracao.ButtonLimparFornecedorClick(
Sender: TObject);
begin
plFornecedor.Clear;
EditCadastroCDFORNECEDOR.Clear;
ComboEditCadastroNMFORNECEDOR.Clear;
EditCadastroCDFORNECEDOR.Enabled := true;
ComboEditCadastroNMFORNECEDOR.Enabled := true;
ButtonLimparFornecedor.Enabled := false;
ButtonNovoFornecedor.Enabled := true;
end;
procedure TfmCadDespesaConfiguracao.ButtonNovoFormaPagamentoClick(
Sender: TObject);
var
vcdFormaPagamento: integer;
begin
vcdFormaPagamento := 0;
try
fmCadFormaPagamento := TfmCadFormaPagamento.Create(Self);
with fmCadFormaPagamento do
begin
try
Tag := 1;
ShowModal;
vcdFormaPagamento := fmCadFormaPagamento.Codigo;
except
on E: exception do
raise exception.Create('Não foi possível abrir a tela de Cadastro de Forma de Pagamento.'+#13#10+E.Message);
end;
end;
finally
// Verifica se foi cadastrada uma forma de pagamento.
if vcdFormaPagamento > 0 then
begin
ActiveControl := BitBtnAplicar;
EditCadastroCDFORMAPAGAMENTO.Text := IntToStr(vcdFormaPagamento);
EditCadastroCDFORMAPAGAMENTOExit(EditCadastroCDFORMAPAGAMENTO);
ButtonLimparFormaPagamento.Enabled := true;
ButtonNovoFormaPagamento.Enabled := false;
end;
end;
end;
procedure TfmCadDespesaConfiguracao.ButtonNovoFornecedorClick(Sender: TObject);
var
vcdFornecedor: integer;
begin
vcdFornecedor := 0;
try
fmCadFornecedor := TfmCadFornecedor.Create(Self);
with fmCadFornecedor do
begin
try
Tag := 1;
ShowModal;
vcdFornecedor := fmCadFornecedor.Codigo;
except
on E: exception do
raise exception.Create('Não foi possível abrir a tela de Cadastro de Fornecedor.'+#13#10+E.Message);
end;
end;
finally
// Verifica se foi cadastrado um fornecedor.
if vcdFornecedor > 0 then
begin
ActiveControl := BitBtnAplicar;
EditCadastroCDFORNECEDOR.Text := IntToStr(vcdFornecedor);
EditCadastroCDFORNECEDORExit(EditCadastroCDFORNECEDOR);
ButtonLimparFornecedor.Enabled := true;
ButtonNovoFornecedor.Enabled := false;
end;
end;
end;
procedure TfmCadDespesaConfiguracao.carregaImagensBotoes;
begin
EditCadastroValorDespesa.Button.Glyph.Assign(fmPrincipal.fnGeral.obtemImagemCalculadora);
ComboEditCadastroNMFORMAPAGAMENTO.Button.Glyph.Assign(fmPrincipal.fnGeral.obtemImagemPesquisa);
ComboEditCadastroNMFORNECEDOR.Button.Glyph.Assign(fmPrincipal.fnGeral.obtemImagemPesquisa);
ButtonLimparFormaPagamento.Picture.LoadFromFile(fmPrincipal.LocalIcones + 'erase-e-16.png');
ButtonLimparFormaPagamento.HotPicture.LoadFromFile(fmPrincipal.LocalIcones + 'erase-h-16.png');
ButtonLimparFormaPagamento.DisabledPicture.LoadFromFile(fmPrincipal.LocalIcones + 'erase-d-16.png');
ButtonLimparFornecedor.Picture.LoadFromFile(fmPrincipal.LocalIcones + 'erase-e-16.png');
ButtonLimparFornecedor.HotPicture.LoadFromFile(fmPrincipal.LocalIcones + 'erase-h-16.png');
ButtonLimparFornecedor.DisabledPicture.LoadFromFile(fmPrincipal.LocalIcones + 'erase-d-16.png');
ButtonNovoFormaPagamento.Picture.LoadFromFile(fmPrincipal.LocalIcones + 'new-e-16.png');
ButtonNovoFormaPagamento.HotPicture.LoadFromFile(fmPrincipal.LocalIcones + 'new-h-16.png');
ButtonNovoFormaPagamento.DisabledPicture.LoadFromFile(fmPrincipal.LocalIcones + 'new-d-16.png');
ButtonNovoFornecedor.Picture.LoadFromFile(fmPrincipal.LocalIcones + 'new-e-16.png');
ButtonNovoFornecedor.HotPicture.LoadFromFile(fmPrincipal.LocalIcones + 'new-h-16.png');
ButtonNovoFornecedor.DisabledPicture.LoadFromFile(fmPrincipal.LocalIcones + 'new-d-16.png');
end;
procedure TfmCadDespesaConfiguracao.ComboEditCadastroNMFORMAPAGAMENTOClickBtn(
Sender: TObject);
var
i: integer;
begin
// Para que o evento não seja executado.
EditCadastroCDFORMAPAGAMENTO.OnExit := nil;
ComboEditCadastroNMFORMAPAGAMENTO.OnExit := nil;
ComboEditCadastroNMFORMAPAGAMENTO.OnClickBtn := nil;
fmConFiltroPadrao := TfmConFiltroPadrao.Create(Self);
try
with fmConFiltroPadrao do
begin
try
setaTitulo('Consulta de Formas de Pagamento');
setaConsulta(pFormaPagamento.filtro);
setaOpcao('R');
executaFiltro(0,EmptyStr);
ShowModal;
finally
plFormaPagamento.Clear;
with pResSearch do
for i := 0 to Count -1 do
if objResSearch[i].Id = buscaId then
begin
plFormaPagamento.Add(objResSearch[i].Codigo);
EditCadastroCDFORMAPAGAMENTO.Text := objResSearch[i].Codigo;
ComboEditCadastroNMFORMAPAGAMENTO.Text := objResSearch[i].Nome1;
end;
end;
end;
finally
EditCadastroCDFORMAPAGAMENTO.Enabled := (plFormaPagamento.Count = 0);
ComboEditCadastroNMFORMAPAGAMENTO.Enabled := (plFormaPagamento.Count = 0);
ButtonLimparFormaPagamento.Enabled := (plFormaPagamento.Count > 0);
ButtonNovoFormaPagamento.Enabled := (plFormaPagamento.Count = 0);
// Valida para qual campo vai se posicionar.
if plFormaPagamento.Count > 0 then
ActiveControl := EditCadastroCDFORNECEDOR
else
ActiveControl := ComboEditCadastroNMFORMAPAGAMENTO;
end;
// Para que o evento volte a ser executado.
EditCadastroCDFORMAPAGAMENTO.OnExit := EditCadastroCDFORMAPAGAMENTOExit;
ComboEditCadastroNMFORMAPAGAMENTO.OnExit := ComboEditCadastroNMFORMAPAGAMENTOExit;
ComboEditCadastroNMFORMAPAGAMENTO.OnClickBtn := ComboEditCadastroNMFORMAPAGAMENTOClickBtn;
end;
procedure TfmCadDespesaConfiguracao.ComboEditCadastroNMFORMAPAGAMENTOExit(
Sender: TObject);
var
i: integer;
vQuery: TZQuery;
begin
if Length(Trim(ComboEditCadastroNMFORMAPAGAMENTO.Text)) = 0 then
Exit;
// Para que o evento não seja executado.
EditCadastroCDFORMAPAGAMENTO.OnExit := nil;
ComboEditCadastroNMFORMAPAGAMENTO.OnExit := nil;
ComboEditCadastroNMFORMAPAGAMENTO.OnClickBtn := nil;
try
vQuery := pFormaPagamento.filtro;
with vQuery do
begin
SQL.Add('WHERE UPPER("NM-Forma Pagamento") LIKE :NMFORMAPAGAMENTO');
Params.ParamByName('NMFORMAPAGAMENTO').AsString := '%'+AnsiUpperCase(ComboEditCadastroNMFORMAPAGAMENTO.Text)+'%';
dmPrincipal.executaConsulta(vQuery);
if RecordCount > 1 then
begin
fmConFiltroPadrao := TfmConFiltroPadrao.Create(Self);
with fmConFiltroPadrao do
begin
try
setaTitulo('Consulta de Formas de Pagamento');
setaConsulta(pFormaPagamento.filtro);
setaOpcao('R');
executaFiltro(2,ComboEditCadastroNMFORMAPAGAMENTO.Text);
ShowModal;
finally
plFormaPagamento.Clear;
with pResSearch do
for i := 0 to Count -1 do
if objResSearch[i].Id = buscaId then
begin
plFormaPagamento.Add(objResSearch[i].Codigo);
EditCadastroCDFORMAPAGAMENTO.Text := objResSearch[i].Codigo;
ComboEditCadastroNMFORMAPAGAMENTO.Text := objResSearch[i].Nome1;
end;
end;
end;
end
else
if not Eof then
begin
plFormaPagamento.Clear;
plFormaPagamento.Add(Fields.Fields[0].AsString);
EditCadastroCDFORMAPAGAMENTO.Text := Fields.Fields[0].AsString;
ComboEditCadastroNMFORMAPAGAMENTO.Text := Fields.Fields[1].AsString;
end
else
fmPrincipal.apresentaResultadoCadastro('Nenhum registro encontrado.');
Active := false;
end;
finally
FreeAndNil(vQuery);
EditCadastroCDFORMAPAGAMENTO.Enabled := (plFormaPagamento.Count = 0);
ComboEditCadastroNMFORMAPAGAMENTO.Enabled := (plFormaPagamento.Count = 0);
ButtonLimparFormaPagamento.Enabled := (plFormaPagamento.Count > 0);
ButtonNovoFormaPagamento.Enabled := (plFormaPagamento.Count = 0);
// Valida para qual campo vai se posicionar.
if plFormaPagamento.Count > 0 then
ActiveControl := EditCadastroCDFORNECEDOR
else
ActiveControl := ComboEditCadastroNMFORMAPAGAMENTO;
end;
// Para que o evento volte a ser executado.
EditCadastroCDFORMAPAGAMENTO.OnExit := EditCadastroCDFORMAPAGAMENTOExit;
ComboEditCadastroNMFORMAPAGAMENTO.OnExit := ComboEditCadastroNMFORMAPAGAMENTOExit;
ComboEditCadastroNMFORMAPAGAMENTO.OnClickBtn := ComboEditCadastroNMFORMAPAGAMENTOClickBtn;
end;
procedure TfmCadDespesaConfiguracao.ComboEditCadastroNMFORNECEDORClickBtn(
Sender: TObject);
var
i: integer;
begin
// Para que o evento não seja executado.
EditCadastroCDFORNECEDOR.OnExit := nil;
ComboEditCadastroNMFORNECEDOR.OnExit := nil;
ComboEditCadastroNMFORNECEDOR.OnClickBtn := nil;
fmConFiltroPadrao := TfmConFiltroPadrao.Create(Self);
try
with fmConFiltroPadrao do
begin
try
setaTitulo('Consulta de Fornecedores');
setaConsulta(pFornecedor.filtro);
setaOpcao('R');
executaFiltro(0,EmptyStr);
ShowModal;
finally
plFornecedor.Clear;
with pResSearch do
for i := 0 to Count -1 do
if objResSearch[i].Id = buscaId then
begin
plFornecedor.Add(objResSearch[i].Codigo);
EditCadastroCDFORNECEDOR.Text := objResSearch[i].Codigo;
ComboEditCadastroNMFORNECEDOR.Text := objResSearch[i].Nome2;
end;
end;
end;
finally
EditCadastroCDFORNECEDOR.Enabled := (plFornecedor.Count = 0);
ComboEditCadastroNMFORNECEDOR.Enabled := (plFornecedor.Count = 0);
ButtonLimparFornecedor.Enabled := (plFornecedor.Count > 0);
ButtonNovoFornecedor.Enabled := (plFornecedor.Count = 0);
// Valida para qual campo vai se posicionar.
if plFornecedor.Count > 0 then
ActiveControl := BitBtnAplicar
else
ActiveControl := ComboEditCadastroNMFORNECEDOR;
end;
// Para que o evento volte a ser executado.
EditCadastroCDFORNECEDOR.OnExit := EditCadastroCDFORNECEDORExit;
ComboEditCadastroNMFORNECEDOR.OnExit := ComboEditCadastroNMFORNECEDORExit;
ComboEditCadastroNMFORNECEDOR.OnClickBtn := ComboEditCadastroNMFORNECEDORClickBtn;
end;
procedure TfmCadDespesaConfiguracao.ComboEditCadastroNMFORNECEDORExit(
Sender: TObject);
var
i: integer;
vQuery: TZQuery;
begin
if Length(Trim(ComboEditCadastroNMFORNECEDOR.Text)) = 0 then
Exit;
// Para que o evento não seja executado.
EditCadastroCDFORNECEDOR.OnExit := nil;
ComboEditCadastroNMFORNECEDOR.OnExit := nil;
ComboEditCadastroNMFORNECEDOR.OnClickBtn := nil;
try
vQuery := pFornecedor.filtro;
with vQuery do
begin
SQL.Add('WHERE UPPER("NM-Fornecedor") LIKE :NMFORNECEDOR');
Params.ParamByName('NMFORNECEDOR').AsString := '%'+AnsiUpperCase(ComboEditCadastroNMFORNECEDOR.Text)+'%';
dmPrincipal.executaConsulta(vQuery);
if RecordCount > 1 then
begin
fmConFiltroPadrao := TfmConFiltroPadrao.Create(Self);
with fmConFiltroPadrao do
begin
try
setaTitulo('Consulta de Fornecedores');
setaConsulta(pFornecedor.filtro);
setaOpcao('R');
executaFiltro(2,ComboEditCadastroNMFORNECEDOR.Text);
ShowModal;
finally
plFornecedor.Clear;
with pResSearch do
for i := 0 to Count -1 do
if objResSearch[i].Id = buscaId then
begin
plFornecedor.Add(objResSearch[i].Codigo);
EditCadastroCDFORNECEDOR.Text := objResSearch[i].Codigo;
ComboEditCadastroNMFORNECEDOR.Text := objResSearch[i].Nome2;
end;
end;
end;
end
else
if not Eof then
begin
plFornecedor.Clear;
plFornecedor.Add(Fields.Fields[0].AsString);
EditCadastroCDFORNECEDOR.Text := Fields.Fields[0].AsString;
ComboEditCadastroNMFORNECEDOR.Text := Fields.Fields[2].AsString;
end
else
fmPrincipal.apresentaResultadoCadastro('Nenhum registro encontrado.');
Active := false;
end;
finally
FreeAndNil(vQuery);
EditCadastroCDFORNECEDOR.Enabled := (plFornecedor.Count = 0);
ComboEditCadastroNMFORNECEDOR.Enabled := (plFornecedor.Count = 0);
ButtonLimparFornecedor.Enabled := (plFornecedor.Count > 0);
ButtonNovoFornecedor.Enabled := (plFornecedor.Count = 0);
// Valida para qual campo vai se posicionar.
if plFornecedor.Count > 0 then
ActiveControl := BitBtnAplicar
else
ActiveControl := ComboEditCadastroNMFORNECEDOR;
end;
// Para que o evento volte a ser executado.
EditCadastroCDFORNECEDOR.OnExit := EditCadastroCDFORNECEDORExit;
ComboEditCadastroNMFORNECEDOR.OnExit := ComboEditCadastroNMFORNECEDORExit;
ComboEditCadastroNMFORNECEDOR.OnClickBtn := ComboEditCadastroNMFORNECEDORClickBtn;
end;
procedure TfmCadDespesaConfiguracao.configuraCampos;
var
vnuDia, vnuMes, vnuAno: integer;
begin
// Formata os valores dos campos.
vnuDia := DayOf(Now);
vnuMes := MonthOfTheYear(Now);
vnuAno := YearOf(Now);
ComboBoxCadastroMesInicio.ItemIndex := vnuMes -1;
with SpinEditCadastroAnoInicio do
Value := vnuAno;
if ComboBoxCadastroMesEncerramento.Items.Count <> vnuMes then
ComboBoxCadastroMesEncerramento.ItemIndex := vnuMes
else
ComboBoxCadastroMesEncerramento.ItemIndex := 0;
with SpinEditCadastroAnoEncerramento do
begin
Value := vnuAno;
if ComboBoxCadastroMesEncerramento.ItemIndex = 0 then
Value := Value + 1;
end;
SpinEditCadastroDiaVencimento.Value := vnuDia;
EditCadastroValorDespesa.Value := 0;
ActiveControl := ComboBoxCadastroMesInicio;
end;
procedure TfmCadDespesaConfiguracao.EditCadastroCDFORMAPAGAMENTOExit(
Sender: TObject);
var
vQuery: TZQuery;
begin
// Se não digitou nada, sai sem abrir a search.
if Length(Trim(EditCadastroCDFORMAPAGAMENTO.Text)) = 0 then
Exit;
// Para que o evento não seja executado.
EditCadastroCDFORMAPAGAMENTO.OnExit := nil;
ComboEditCadastroNMFORMAPAGAMENTO.OnExit := nil;
ComboEditCadastroNMFORMAPAGAMENTO.OnClickBtn := nil;
try
vQuery := pFormaPagamento.filtro;
with vQuery do
begin
SQL.Add('WHERE "NU-Código" = :CDFORMAPAGAMENTO');
Params.ParamByName('CDFORMAPAGAMENTO').AsString := EditCadastroCDFORMAPAGAMENTO.Text;
dmPrincipal.executaConsulta(vQuery);
if not Eof then
begin
plFormaPagamento.Clear;
plFormaPagamento.Add(Fields.Fields[0].AsString);
EditCadastroCDFORMAPAGAMENTO.Text := Fields.Fields[0].AsString;
ComboEditCadastroNMFORMAPAGAMENTO.Text := Fields.Fields[1].AsString;
end
else
begin
plFormaPagamento.Clear;
EditCadastroCDFORMAPAGAMENTO.Clear;
ComboEditCadastroNMFORMAPAGAMENTO.Clear;
fmPrincipal.apresentaResultadoCadastro('Nenhum registro encontrado.');
end;
Active := false;
end;
finally
FreeAndNil(vQuery);
EditCadastroCDFORMAPAGAMENTO.Enabled := (plFormaPagamento.Count = 0);
ComboEditCadastroNMFORMAPAGAMENTO.Enabled := (plFormaPagamento.Count = 0);
ButtonLimparFormaPagamento.Enabled := (plFormaPagamento.Count > 0);
ButtonNovoFormaPagamento.Enabled := (plFormaPagamento.Count = 0);
// Se este painel estiver visível é porque a aquisição foi encerrada ou cancelada.
// Valida para qual campo vai se posicionar.
if plFormaPagamento.Count > 0 then
ActiveControl := EditCadastroCDFORNECEDOR
else
ActiveControl := EditCadastroCDFORMAPAGAMENTO;
end;
// Para que o evento volte a ser executado.
EditCadastroCDFORMAPAGAMENTO.OnExit := EditCadastroCDFORMAPAGAMENTOExit;
ComboEditCadastroNMFORMAPAGAMENTO.OnExit := ComboEditCadastroNMFORMAPAGAMENTOExit;
ComboEditCadastroNMFORMAPAGAMENTO.OnClickBtn := ComboEditCadastroNMFORMAPAGAMENTOClickBtn;
end;
procedure TfmCadDespesaConfiguracao.EditCadastroCDFORNECEDORExit(
Sender: TObject);
var
vQuery: TZQuery;
begin
// Se não digitou nada, sai sem abrir a search.
if Length(Trim(EditCadastroCDFORNECEDOR.Text)) = 0 then
Exit;
// Para que o evento não seja executado.
EditCadastroCDFORNECEDOR.OnExit := nil;
ComboEditCadastroNMFORNECEDOR.OnExit := nil;
ComboEditCadastroNMFORNECEDOR.OnClickBtn := nil;
try
vQuery := pFornecedor.filtro;
with vQuery do
begin
SQL.Add('WHERE "NU-Código" = :CDFORNECEDOR');
Params.ParamByName('CDFORNECEDOR').AsString := EditCadastroCDFORNECEDOR.Text;
dmPrincipal.executaConsulta(vQuery);
if not Eof then
begin
plFornecedor.Clear;
plFornecedor.Add(Fields.Fields[0].AsString);
EditCadastroCDFORNECEDOR.Text := Fields.Fields[0].AsString;
ComboEditCadastroNMFORNECEDOR.Text := Fields.Fields[2].AsString;
end
else
begin
plFornecedor.Clear;
EditCadastroCDFORNECEDOR.Clear;
ComboEditCadastroNMFORNECEDOR.Clear;
fmPrincipal.apresentaResultadoCadastro('Nenhum registro encontrado.');
end;
Active := false;
end;
finally
FreeAndNil(vQuery);
EditCadastroCDFORNECEDOR.Enabled := (plFornecedor.Count = 0);
ComboEditCadastroNMFORNECEDOR.Enabled := (plFornecedor.Count = 0);
ButtonLimparFornecedor.Enabled := (plFornecedor.Count > 0);
ButtonNovoFornecedor.Enabled := (plFornecedor.Count = 0);
// Se este painel estiver visível é porque a aquisição foi encerrada ou cancelada.
// Valida para qual campo vai se posicionar.
if plFornecedor.Count > 0 then
ActiveControl := BitBtnAplicar
else
ActiveControl := EditCadastroCDFORNECEDOR;
end;
// Para que o evento volte a ser executado.
EditCadastroCDFORNECEDOR.OnExit := EditCadastroCDFORNECEDORExit;
ComboEditCadastroNMFORNECEDOR.OnExit := ComboEditCadastroNMFORNECEDORExit;
ComboEditCadastroNMFORNECEDOR.OnClickBtn := ComboEditCadastroNMFORNECEDORClickBtn;
end;
procedure TfmCadDespesaConfiguracao.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfmCadDespesaConfiguracao.FormCreate(Sender: TObject);
begin
try
CreateGUID(pId);
Color := Self.Color;
FormStyler.AutoThemeAdapt := false;
plFormaPagamento := TStringList.Create;
plFornecedor := TStringList.Create;
pFornecedor := TFornecedor.Create;
pFormaPagamento := TFormaPagamento.Create;
// Inicializa os valores;
MesInicio := -1;
MesEncerramento := -1;
AnoInicio := -1;
AnoEncerramento := -1;
DiaVencimento := -1;
ValorDespesa := -1;
FormaPagamento := -1;
ComboBoxCadastroMesEncerramento.AutoThemeAdapt := false;
ComboBoxCadastroMesInicio.AutoThemeAdapt := false;
EditCadastroValorDespesa.Button.Flat := true;
carregaImagensBotoes;
FormResize(Sender);
except
on E: Exception do
begin
fmPrincipal.manipulaExcecoes(Sender,E);
Close;
end;
end;
end;
procedure TfmCadDespesaConfiguracao.FormDestroy(Sender: TObject);
begin
FreeAndNil(plFormaPagamento);
FreeAndNil(plFornecedor);
FreeAndNil(pFornecedor);
FreeAndNil(pFormaPagamento);
end;
procedure TfmCadDespesaConfiguracao.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Exit;
end;
procedure TfmCadDespesaConfiguracao.FormResize(Sender: TObject);
begin
BitBtnFechar.Left := PanelBotoes.Width - BitBtnFechar.Width - fmPrincipal.EspacamentoFinalBotao;
BitBtnAplicar.Left := BitBtnFechar.Left - BitBtnAplicar.Width - fmPrincipal.EspacamentoEntreBotoes;
end;
procedure TfmCadDespesaConfiguracao.FormShow(Sender: TObject);
begin
configuraCampos;
end;
end.
|
unit uAppLib;
interface
uses
FMX.Forms;
type
TAppLib = class
class function NumberFormat(value: string): double;
class procedure ChangeReadOnly(form: TForm; bValue: boolean);
end;
implementation
uses
System.SysUtils, FMX.Dialogs, FMX.Edit;
{ TAppLib }
class procedure TAppLib.ChangeReadOnly(form: TForm; bValue: boolean);
var
i: Integer;
begin
for i := 0 to form.ComponentCount-1 do
if form.Components[i].Tag = 99 then
TEdit(form.Components[i]).ReadOnly := bValue;
end;
class function TAppLib.NumberFormat(value: string): double;
var s: string;
begin
s := StringReplace(value, '.', '', [rfReplaceAll]);
if not TryStrToFloat(s, result) then
ShowMessage('Valor inválido!');
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Forms.Border;
interface
uses
System.TypInfo, System.Math, System.Classes, System.SysUtils, System.Types,
System.UITypes, FMX.Types, FMX.Types3D, System.Generics.Collections,
FMX.ActnList, FMX.Messages, FMX.Styles, FMX.Controls, FMX.Forms,
FMX.StdCtrls, FMX.TextLayout, FMX.Graphics;
{$SCOPEDENUMS ON}
type
{ TStyledWindowBorder }
TStyledWindowBorder = class(TWindowBorder, IRoot, IStyleBookOwner, IScene, IContainerObject, IAlignRoot)
private
FNeedStyleLookup: Boolean;
FLastWidth, FLastHeight: Single;
FMousePos, FDownPos: TPointF;
FHovered, FCaptured, FFocused: IControl;
FStyleChangedId: Integer;
FWinService: IFMXWindowService;
function GetStyleObject: TControl;
{ IRoot }
function GetObject: TFmxObject;
function GetActiveControl: IControl;
procedure SetActiveControl(const AControl: IControl);
procedure SetCaptured(const Value: IControl);
function NewFocusedControl(const Value: IControl): IControl;
procedure SetFocused(const Value: IControl);
procedure SetHovered(const Value: IControl);
function GetCaptured: IControl;
function GetFocused: IControl;
function GetBiDiMode: TBiDiMode;
function GetHovered: IControl;
procedure BeginInternalDrag(const Source: TObject; const ABitmap: TObject);
{ IScene }
procedure AddUpdateRect(R: TRectF);
function GetUpdateRectsCount: Integer;
function GetUpdateRect(const Index: Integer): TRectF;
function LocalToScreen(P: TPointF): TPointF;
function ScreenToLocal(P: TPointF): TPointF;
function GetSceneScale: Single;
procedure ChangeScrollingState(const AControl: TControl; const Active: Boolean);
{ IStyleBookOwner }
function GetStyleBook: TStyleBook;
procedure SetStyleBook(const Value: TStyleBook);
{ IContainerObject }
function GetContainerWidth: Single;
function GetContainerHeight: Single;
{ }
function GetActive: Boolean;
procedure StyleChangedHandler(const Sender: TObject; const Msg: FMX.Messages.TMessage);
protected
FClientObject: TControl;
FCloseObject: TControl;
FIconObject: TControl;
FTitleObject: TControl;
FMinObject: TControl;
FMaxObject: TControl;
FResObject: TControl;
FMaskObject: TControl;
FDisableAlign: Boolean;
FResourceLink: TControl;
procedure ApplyStyleLookup;
procedure DoApplyStyle; virtual;
procedure DoCloseClick(Sender: TObject);
procedure DoMaxClick(Sender: TObject);
procedure DoResClick(Sender: TObject);
procedure DoMinClick(Sender: TObject);
function GetStyleLookup: string; virtual;
protected
procedure FreeNotification(AObject: TObject); override;
procedure DoAddObject(const AObject: TFmxObject); override;
procedure DoAddUpdateRect(R: TRectF); virtual;
function GetClientMargins: TRect; virtual;
procedure StyleChanged; override;
procedure ScaleChanged; override;
procedure Invalidate; virtual;
{ TWindowBorder }
procedure Resize; override;
procedure Activate; override;
procedure Deactivate; override;
function GetSupported: Boolean; override;
{ IScene }
function GetCanvas: TCanvas; virtual;
{ IAlignRoot }
procedure Realign;
procedure ChildrenAlignChanged;
public
constructor Create(const AForm: TCommonCustomForm); override;
destructor Destroy; override;
function ObjectAtPoint(P: TPointF): IControl;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure MouseMove(Shift: TShiftState; X, Y: Single);
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure MouseLeave;
property ClientMargins: TRect read GetClientMargins;
property IsActive: Boolean read GetActive;
end;
implementation
uses
FMX.Platform, FMX.Menus, FMX.Filter, FMX.Text;
type
TOpenFmxObject = class(TFmxObject);
TOpenControl = class(TControl);
{ TStyledWindowBorder }
constructor TStyledWindowBorder.Create(const AForm: TCommonCustomForm);
begin
inherited;
if not TPlatformServices.Current.SupportsPlatformService(IFMXWindowService, IInterface(FWinService)) then
raise EUnsupportedPlatformService.Create('IFMXWindowService');
FNeedStyleLookup := True;
FStyleChangedId := TMessageManager.DefaultManager.SubscribeToMessage(TStyleChangedMessage, StyleChangedHandler);
end;
destructor TStyledWindowBorder.Destroy;
begin
TMessageManager.DefaultManager.Unsubscribe(TStyleChangedMessage, FStyleChangedId);
DeleteChildren;
inherited;
end;
procedure TStyledWindowBorder.DoAddObject(const AObject: TFmxObject);
begin
inherited;
AObject.SetRoot(Self);
if AObject is TControl then
TControl(AObject).SetNewScene(Self);
Realign;
if (AObject is TControl) then
begin
TOpenControl(AObject).RecalcOpacity;
TOpenControl(AObject).RecalcAbsolute;
TOpenControl(AObject).RecalcUpdateRect;
TOpenControl(AObject).RecalcHasClipParent;
end;
end;
procedure TStyledWindowBorder.FreeNotification(AObject: TObject);
begin
inherited;
if Assigned(FHovered) and (FHovered.GetObject = AObject) then
FHovered := nil;
if Assigned(FCaptured) and (FCaptured.GetObject = AObject) then
FCaptured := nil;
if Assigned(FFocused) and (FFocused.GetObject = AObject) then
FFocused := nil;
end;
function TStyledWindowBorder.GetStyleObject: TControl;
var
Obj: TFmxObject;
ResourceObject: TControl;
SB: TStyleBook;
begin
{ style }
ResourceObject := nil;
Obj := nil;
SB := GetStyleBook;
if Assigned(SB) and Assigned(SB.Style) then
Obj := TControl(SB.Style.FindStyleResource(GetStyleLookup));
if not Assigned(Obj) then
if Assigned(TStyleManager.ActiveStyleForScene(Self)) then
Obj := TControl(TStyleManager.ActiveStyleForScene(Self).FindStyleResource(GetStyleLookup));
if Assigned(Obj) and (Obj is TControl) then
begin
ResourceObject := TControl(Obj.Clone(nil));
ResourceObject.StyleName := '';
end;
Result := ResourceObject;
end;
function TStyledWindowBorder.GetSupported: Boolean;
begin
if (not (TFMXFormState.fsWasNotShown in Form.FormState)) or
(TFMXFormState.fsShowing in Form.FormState) then
ApplyStyleLookup;
Result := Assigned(Form) and Assigned(FResourceLink) and (Form.BorderStyle <> TFmxFormBorderStyle.bsNone);
end;
procedure TStyledWindowBorder.DoApplyStyle;
begin
FClientObject := TControl(FResourceLink.FindStyleResource('client'));
FTitleObject := TControl(FResourceLink.FindStyleResource('title'));
FCloseObject := TControl(FResourceLink.FindStyleResource('close'));
if FCloseObject is TCustomButton then
begin
TCustomButton(FCloseObject).Enabled := TBorderIcon.biSystemMenu in Form.BorderIcons;
TCustomButton(FCloseObject).OnClick := DoCloseClick;
end;
FMaxObject := TControl(FResourceLink.FindStyleResource('max'));
if FMaxObject is TCustomButton then
begin
TCustomButton(FMaxObject).Enabled := TBorderIcon.biMaximize in Form.BorderIcons;
TCustomButton(FMaxObject).OnClick := DoMaxClick;
end;
FMinObject := TControl(FResourceLink.FindStyleResource('min'));
if FMinObject is TCustomButton then
begin
TCustomButton(FMinObject).Enabled := TBorderIcon.biMinimize in Form.BorderIcons;
TCustomButton(FMinObject).OnClick := DoMinClick;
end;
if (FCloseObject is TCustomButton) and (FMaxObject is TCustomButton) and (FMinObject is TCustomButton) then
begin
if not TCustomButton(FCloseObject).Enabled and not TCustomButton(FMinObject).Enabled and not TCustomButton(FMaxObject).Enabled then
begin
TCustomButton(FCloseObject).Visible := False;
TCustomButton(FMinObject).Visible := False;
TCustomButton(FMaxObject).Visible := False;
end
else
begin
TCustomButton(FCloseObject).Visible := True;
TCustomButton(FMinObject).Visible := True;
TCustomButton(FMaxObject).Visible := True;
end;
end;
FResObject := TControl(FResourceLink.FindStyleResource('Res'));
if FResObject is TCustomButton then
TCustomButton(FResObject).OnClick := DoResClick;
FIconObject := TControl(FResourceLink.FindStyleResource('icon'));
FMaskObject := TControl(FResourceLink.FindStyleResource('mask'));
end;
procedure CallLoaded(const Obj: TFmxObject);
var
I: Integer;
begin
TOpenFmxObject(Obj).Loaded;
for I := 0 to Obj.ChildrenCount - 1 do
CallLoaded(Obj.Children[I]);
end;
procedure TStyledWindowBorder.ApplyStyleLookup;
var
ResourceObject: TControl;
begin
if FNeedStyleLookup then
begin
FNeedStyleLookup := False;
ResourceObject := GetStyleObject;
if Assigned(ResourceObject) then
begin
if csLoading in ResourceObject.ComponentState then
CallLoaded(ResourceObject);
FClientObject := nil;
FCloseObject := nil;
if Assigned(FResourceLink) then
FreeAndNil(FResourceLink);
ResourceObject.Align := TAlignLayout.alContents;
ResourceObject.DesignVisible := True;
AddObject(ResourceObject);
FResourceLink := ResourceObject;
{ bring to front }
RemoveObject(ResourceObject);
InsertObject(0, ResourceObject);
Realign;
{ set fields }
DoApplyStyle;
{ }
ResourceObject.Stored := False;
ResourceObject.Lock;
end
else
begin
FClientObject := nil;
FCloseObject := nil;
FreeAndNil(FResourceLink);
end;
end;
end;
procedure TStyledWindowBorder.DoCloseClick(Sender: TObject);
begin
Form.Close;
end;
procedure TStyledWindowBorder.DoMaxClick(Sender: TObject);
begin
Form.WindowState := TWindowState.wsMaximized;
end;
procedure TStyledWindowBorder.DoMinClick(Sender: TObject);
begin
Form.WindowState := TWindowState.wsMinimized;
end;
procedure TStyledWindowBorder.DoResClick(Sender: TObject);
begin
Form.WindowState := TWindowState.wsNormal;
end;
function TStyledWindowBorder.GetClientMargins: TRect;
var
R: TRect;
begin
ApplyStyleLookup;
if Assigned(FClientObject) then
begin
R := FClientObject.AbsoluteRect.Round;
Result := Rect(R.Left, R.Top, Form.Width - R.Right, Form.Height - R.Bottom);
end
else
Result := Rect(0, 0, 0, 0);
end;
function TStyledWindowBorder.ObjectAtPoint(P: TPointF): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
begin
Result := nil;
if IsSupported then
begin
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.ObjectAtPoint(P);
if Assigned(NewObj) then
begin
Result := NewObj;
Exit;
end;
end;
end;
end;
procedure TStyledWindowBorder.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
P: TPointF;
Obj: IControl;
begin
FMousePos := PointF(X, Y);
FDownPos := FMousePos;
Obj := ObjectAtPoint(FMousePos);
if Assigned(Obj) then
begin
P := Obj.ScreenToLocal(PointF(FMousePos.X, FMousePos.Y));
Obj.MouseDown(Button, Shift, P.X, P.Y);
end;
end;
procedure TStyledWindowBorder.MouseMove(Shift: TShiftState; X, Y: Single);
var
P: TPointF;
Obj: IControl;
SG: ISizeGrip;
NewCursor: TCursor;
CursorService: IFMXCursorService;
begin
NewCursor := crDefault;
TPlatformServices.Current.SupportsPlatformService(IFMXCursorService, IInterface(CursorService));
FMousePos := PointF(X, Y);
if Assigned(FCaptured) then
begin
if Assigned(CursorService) then
begin
if ((FCaptured.QueryInterface(ISizeGrip, SG) = 0) and Assigned(SG)) then
CursorService.SetCursor(crSizeNWSE)
else
CursorService.SetCursor(FCaptured.Cursor);
end;
P := FCaptured.ScreenToLocal(PointF(FMousePos.X, FMousePos.Y));
FCaptured.MouseMove(Shift, P.X, P.Y);
Exit;
end;
Obj := ObjectAtPoint(FMousePos);
if Assigned(Obj) then
begin
SetHovered(Obj);
P := Obj.ScreenToLocal(PointF(FMousePos.X, FMousePos.Y));
Obj.MouseMove(Shift, P.X, P.Y);
if ((Obj.QueryInterface(ISizeGrip, SG) = 0) and Assigned(SG)) then
NewCursor := crSizeNWSE
else
NewCursor := Obj.Cursor;
end
else
SetHovered(nil);
// set cursor
if Assigned(CursorService) then
CursorService.SetCursor(NewCursor);
FDownPos := FMousePos;
end;
procedure TStyledWindowBorder.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
P: TPointF;
Obj: IControl;
begin
if Assigned(FCaptured) then
begin
P := FCaptured.ScreenToLocal(PointF(FMousePos.X, FMousePos.Y));
FCaptured.MouseClick(Button, Shift, P.X, P.Y);
FCaptured.MouseUp(Button, Shift, P.X, P.Y);
SetCaptured(nil);
Exit;
end;
Obj := ObjectAtPoint(FMousePos);
if Assigned(Obj) then
begin
P := Obj.ScreenToLocal(PointF(FMousePos.X, FMousePos.Y));
Obj.MouseClick(Button, Shift, P.X, P.Y);
Obj.MouseUp(Button, Shift, P.X, P.Y);
end;
end;
procedure TStyledWindowBorder.MouseLeave;
begin
SetHovered(nil);
end;
{ IRoot }
function TStyledWindowBorder.GetObject: TFmxObject;
begin
Result := Self;
end;
function TStyledWindowBorder.GetActive: Boolean;
begin
Result := Form.Active
end;
function TStyledWindowBorder.GetActiveControl: IControl;
begin
Result := nil;
end;
procedure TStyledWindowBorder.SetActiveControl(const AControl: IControl);
begin
end;
procedure TStyledWindowBorder.SetCaptured(const Value: IControl);
begin
if FCaptured <> Value then
begin
if Assigned(FCaptured) then
begin
Form.ReleaseCapture;
FCaptured.RemoveFreeNotify(Self);
end;
FCaptured := Value;
if Assigned(FCaptured) then
begin
Form.MouseCapture;
FCaptured.AddFreeNotify(Self);
end;
end;
end;
function TStyledWindowBorder.NewFocusedControl(const Value: IControl): IControl;
begin
end;
procedure TStyledWindowBorder.SetFocused(const Value: IControl);
begin
end;
procedure TStyledWindowBorder.SetHovered(const Value: IControl);
begin
if (Value <> FHovered) then
begin
if Assigned(FHovered) then
begin
FHovered.DoMouseLeave;
FHovered.RemoveFreeNotify(Self);
end;
FHovered := Value;
if Assigned(FHovered) then
begin
FHovered.AddFreeNotify(Self);
FHovered.DoMouseEnter;
end;
end;
end;
procedure TStyledWindowBorder.SetStyleBook(const Value: TStyleBook);
begin
end;
procedure TStyledWindowBorder.StyleChangedHandler(const Sender: TObject; const Msg: FMX.Messages.TMessage);
begin
if Assigned(TStyleChangedMessage(Msg).Value) and (GetStyleBook <> TStyleChangedMessage(Msg).Value) then Exit;
StyleChanged;
end;
function TStyledWindowBorder.GetCaptured: IControl;
begin
Result := nil;
end;
function TStyledWindowBorder.GetFocused: IControl;
begin
Result := nil;
end;
function TStyledWindowBorder.GetBiDiMode: TBiDiMode;
begin
Result := TBiDiMode.bdLeftToRight;
end;
function TStyledWindowBorder.GetHovered: IControl;
begin
Result := nil;
end;
procedure TStyledWindowBorder.BeginInternalDrag(const Source: TObject; const ABitmap: TObject);
begin
end;
procedure TStyledWindowBorder.Deactivate;
begin
StartTriggerAnimation(Self, 'IsActive');
ApplyTriggerEffect(Self, 'IsActive');
end;
procedure TStyledWindowBorder.Activate;
begin
StartTriggerAnimation(Self, 'IsActive');
ApplyTriggerEffect(Self, 'IsActive');
end;
procedure TStyledWindowBorder.AddUpdateRect(R: TRectF);
begin
DoAddUpdateRect(R);
end;
function TStyledWindowBorder.GetCanvas: TCanvas;
begin
Result := nil;
end;
function TStyledWindowBorder.GetSceneScale: Single;
begin
Result := FWinService.GetWindowScale(Form);
end;
function TStyledWindowBorder.GetStyleBook: TStyleBook;
begin
if Assigned(Form) then
Result := (Form as IStyleBookOwner).StyleBook
else
Result := nil;
end;
function TStyledWindowBorder.GetStyleLookup: string;
begin
Result := 'windowborderstyle';
end;
function TStyledWindowBorder.GetUpdateRect(const Index: Integer): TRectF;
begin
Result := RectF(0, 0, Form.Width, Form.Height);
end;
function TStyledWindowBorder.GetUpdateRectsCount: Integer;
begin
Result := 1;
end;
procedure TStyledWindowBorder.DoAddUpdateRect(R: TRectF);
begin
if IsSupported then
if not (csDestroying in ComponentState) and not (csLoading in ComponentState) then
Invalidate;
end;
procedure TStyledWindowBorder.Invalidate;
begin
end;
function TStyledWindowBorder.LocalToScreen(P: TPointF): TPointF;
var
Offset: TPoint;
begin
Result := FWinService.ClientToScreen(Form, P);
Offset := ClientMargins.TopLeft;
Result := Result - PointF(Offset.X, Offset.Y);
end;
procedure TStyledWindowBorder.ScaleChanged;
begin
Resize;
StyleChanged;
end;
function TStyledWindowBorder.ScreenToLocal(P: TPointF): TPointF;
var
Offset: TPoint;
begin
Result := FWinService.ScreenToClient(Form, P);
Offset := ClientMargins.TopLeft;
Result := Result + PointF(Offset.X, Offset.Y);
end;
procedure TStyledWindowBorder.StyleChanged;
begin
if csLoading in ComponentState then
Exit;
if csDestroying in ComponentState then
Exit;
FNeedStyleLookup := True;
ApplyStyleLookup;
if IsSupported then
begin
StartTriggerAnimation(Self, 'IsActive');
ApplyTriggerEffect(Self, 'IsActive');
end;
end;
{ IContainerObject }
function TStyledWindowBorder.GetContainerHeight: Single;
begin
Result := Form.Width;
end;
function TStyledWindowBorder.GetContainerWidth: Single;
begin
Result := Form.Height;
end;
{ IAlignRoot }
procedure TStyledWindowBorder.ChangeScrollingState(const AControl: TControl; const Active: Boolean);
begin
end;
procedure TStyledWindowBorder.ChildrenAlignChanged;
begin
Realign;
end;
procedure TStyledWindowBorder.Realign;
var
Padding: TBounds;
begin
if Assigned(FResourceLink) and (Form.BorderStyle <> TFmxFormBorderStyle.bsNone) then
begin
Padding := TBounds.Create(RectF(0, 0, 0, 0));
try
AlignObjects(Self, Padding, Form.Width, Form.Height, FLastWidth, FLastHeight, FDisableAlign);
finally
Padding.Free;
end;
end;
end;
procedure TStyledWindowBorder.Resize;
begin
Realign;
end;
end.
|
{
@abstract(Interfaces, base classes and support classes for GMLib.)
@author(Xavier Martinez (cadetill) <cadetill@gmail.com>)
@created(August 2, 2022)
@lastmod(August 21, 2022)
The GMLib.Classes unit provides access to interfaces and base classes used into GMLib.
}
unit GMLib.Classes;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.SysUtils, System.Classes, REST.Json.Types,
{$ELSE}
SysUtils, Classes,
{$ENDIF}
GMLib.Sets;
type
{ ************************************************************************** }
{ *********************** Interfaces definition ************************** }
{ ************************************************************************** }
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.txt)
IGMAPIUrl = interface(IInterface)
['{BF91F436-B314-4128-ADA3-02147063A90C}']
// @exclude
function GetAPIUrl: string;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl: string read GetAPIUrl;
end;
// @include(..\Help\docs\GMLib.Classes.IGMToStr.txt)
IGMToStr = interface(IInterface)
['{314C6DAD-B258-4D0C-A275-229491430B65}']
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string;
end;
// @include(..\Help\docs\GMLib.Classes.IGMControlChanges.txt)
IGMControlChanges = interface(IInterface)
['{4731A754-4D4B-4AA2-978E-AF2838925A06}']
// @include(..\Help\docs\GMLib.Classes.IGMControlChanges.PropertyChanged.txt)
procedure PropertyChanged(Prop: TPersistent; PropName: string);
end;
// @include(..\Help\docs\GMLib.Classes.IGMOwnerLang.txt)
IGMOwnerLang = interface(IInterface)
['{98DE1EC1-454C-494A-893A-2B57DC4C341F}']
// @include(..\Help\docs\GMLib.Classes.IGMOwnerLang.GetOwnerLang.txt)
function GetOwnerLang: TGMLang;
end;
// @include(..\Help\docs\GMLib.Classes.IGMExecJS.txt)
IGMExecJS = interface(IInterface)
['{C1C87DC5-BDFD-4AA1-9BF7-C5FF01290339}']
// @include(..\Help\docs\GMLib.Classes.IGMExecJS.ExecuteJavaScript.txt)
procedure ExecuteJavaScript(FunctName, Params: string);
// @include(..\Help\docs\GMLib.Classes.IGMExecJS.GetJsonFromHTMLForms.txt)
function GetJsonFromHTMLForms: string;
end;
// @include(..\Help\docs\GMLib.Classes.IGMJson.txt)
IGMJson = interface
['{EA6737C1-4C53-44D5-BC98-5C13A590E084}']
// @include(..\Help\docs\GMLib.Classes.IGMJson.Serialize.txt)
function Serialize(aObject: TObject): string;
// @include(..\Help\docs\GMLib.Classes.IGMJson.Deserialize.txt)
function Deserialize(aClass: TClass; Json: string): TObject;
end;
{ ************************************************************************** }
{ ************************* classes definition *************************** }
{ ************************************************************************** }
// @include(..\Help\docs\GMLib.Classes.TGMObject.txt)
TGMObject = class(TInterfacedObject, IGMAPIUrl)
protected
// @exclude
function GetAPIUrl: string; virtual;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl: string read GetAPIUrl;
public
// @include(..\Help\docs\GMLib.Classes.TGMObject.Assign.txt)
procedure Assign(Source: TObject); virtual;
end;
// @include(..\Help\docs\GMLib.Classes.TGMJson.txt)
TGMJson = class(TGMObject, IGMJson)
public
// @include(..\Help\docs\GMLib.Classes.IGMJson.Serialize.txt)
function Serialize(aObject: TObject): string;
// @include(..\Help\docs\GMLib.Classes.IGMJson.Deserialize.txt)
function Deserialize(aClass: TClass; Json: string): TObject;
end;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedOwnedPersistent.txt)
TGMInterfacedOwnedPersistent = class(TInterfacedPersistent)
private
[JSONMarshalled(False)]
FOwner: TPersistent;
[JSONMarshalled(False)]
FOnChange: TNotifyEvent;
protected
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedOwnedPersistent.GetOwner.txt)
function GetOwner: TPersistent; override;
// @exclude
procedure ControlChanges(PropName: string); virtual;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedOwnedPersistent.OnChange.txt)
property OnChange: TNotifyEvent read FOnChange write FOnChange;
public
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedOwnedPersistent.Create.txt)
constructor Create(AOwner: TPersistent); virtual;
end;
// @include(..\Help\docs\GMLib.Classes.TGMPersistent.txt)
TGMPersistent = class(TGMInterfacedOwnedPersistent, IGMAPIUrl)
protected
// @exclude
function GetAPIUrl: string; virtual;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl: string read GetAPIUrl;
end;
// @include(..\Help\docs\GMLib.Classes.TGMPersistentStr.txt)
TGMPersistentStr = class(TGMPersistent, IGMToStr, IGMOwnerLang)
protected
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string; virtual;
// @include(..\Help\docs\GMLib.Classes.IGMOwnerLang.GetOwnerLang.txt)
function GetOwnerLang: TGMLang; virtual;
end;
// @include(..\Help\docs\GMLib.Classes.TGMComponent.txt)
TGMComponent = class(TComponent, IGMAPIUrl, IGMToStr)
private
FLanguage: TGMLang;
function GetAboutGMLib: string;
protected
// @exclude
function GetAPIUrl: string; virtual;
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string; virtual;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl: string read GetAPIUrl;
// @include(..\Help\docs\GMLib.Classes.TGMComponent.Language.txt)
property Language: TGMLang read FLanguage write FLanguage default lnEnglish;
// @include(..\Help\docs\GMLib.Classes.TGMComponent.AboutGMLib.txt)
property AboutGMLib: string read GetAboutGMLib stored False;
public
// @include(..\Help\docs\GMLib.Classes.TGMComponent.Create.txt)
constructor Create(AOwner: TComponent); override;
// @include(..\Help\docs\GMLib.Classes.TGMObject.Assign.txt)
procedure Assign(Source: TPersistent); override;
end;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollectionItem.txt)
TGMInterfacedCollectionItem = class(TCollectionItem, IGMToStr, IGMOwnerLang, IGMAPIUrl)
private
[JSONMarshalled(False)]
FOnChange: TNotifyEvent;
[JSONMarshalled(False)]
FFObject: TObject;
[JSONMarshalled(False)]
FTag: Integer;
FName: string;
protected
// @exclude
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
// @exclude
function _AddRef: Integer; virtual; stdcall;
// @exclude
function _Release: Integer; virtual; stdcall;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollectionItem.GetDisplayName.txt)
function GetDisplayName: string; override;
// @exclude
function GetAPIUrl: string; virtual;
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string; virtual;
// @include(..\Help\docs\GMLib.Classes.IGMOwnerLang.GetOwnerLang.txt)
function GetOwnerLang: TGMLang; virtual;
// @exclude
procedure ControlChanges(PropName: string); virtual;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollectionItem.OnChange.txt)
property OnChange: TNotifyEvent read FOnChange write FOnChange;
public
// @include(..\Help\docs\GMLib.Classes.TGMObject.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\Help\docs\GMLib.Classes.IGMAPIUrl.APIUrl.txt)
property APIUrl: string read GetAPIUrl;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollectionItem.FObject.txt)
property FObject: TObject read FFObject write FFObject;
published
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollectionItem.Tag.txt)
property Tag: Integer read FTag write FTag default 0;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollectionItem.Name.txt)
property Name: string read FName write FName;
end;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollection.txt)
TGMInterfacedCollection = class(TCollection, IGMControlChanges, IGMOwnerLang, IGMToStr)
private
[JSONMarshalled(False)]
FOnChange: TNotifyEvent;
[JSONMarshalled(False)]
FOwner: TPersistent;
function GetItems(I: Integer): TGMInterfacedCollectionItem;
procedure SetItems(I: Integer; const Value: TGMInterfacedCollectionItem);
protected
// @exclude
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
// @exclude
function _AddRef: Integer; virtual; stdcall;
// @exclude
function _Release: Integer; virtual; stdcall;
// @include(..\Help\docs\GMLib.Classes.IGMOwnerLang.GetOwnerLang.txt)
function GetOwnerLang: TGMLang; virtual;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollection.GetOwner.txt)
function GetOwner: TPersistent; override;
// @exclude
procedure ControlChanges(PropName: string); virtual;
// @include(..\Help\docs\GMLib.Classes.IGMControlChanges.PropertyChanged.txt)
procedure PropertyChanged(Prop: TPersistent; PropName: string);
// @include(..\Help\docs\GMLib.Classes.IGMToStr.PropToString.txt)
function PropToString: string; virtual;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollection.Add.txt)
function Add: TGMInterfacedCollectionItem;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollection.Insert.txt)
function Insert(Index: Integer): TGMInterfacedCollectionItem;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollection.Delete.txt)
procedure Delete(Index: Integer);
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollection.Move.txt)
procedure Move(CurIndex, NewIndex: Integer);
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollection.Clear.txt)
procedure Clear;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollection.OnChange.txt)
property OnChange: TNotifyEvent read FOnChange write FOnChange;
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollection.Items.txt)
property Items[I: Integer]: TGMInterfacedCollectionItem read GetItems write SetItems; default;
public
// @include(..\Help\docs\GMLib.Classes.TGMInterfacedCollection.Create.txt)
constructor Create(AOwner: TPersistent; ItemClass: TCollectionItemClass); virtual;
// @include(..\Help\docs\GMLib.Classes.TGMObject.Assign.txt)
procedure Assign(Source: TPersistent); override;
end;
implementation
uses
{$IFDEF DELPHIXE2}
System.TypInfo, Rest.Json, System.JSON, System.JSONConsts, REST.JsonReflect,
{$ELSE}
TypInfo,
{$ENDIF}
System.Generics.Collections,
GMLib.Constants;
{ TGMObject }
procedure TGMObject.Assign(Source: TObject);
begin
//
end;
function TGMObject.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference';
end;
{ TGMComponent }
procedure TGMComponent.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMComponent then
begin
Language := TGMComponent(Source).Language;
end;
end;
constructor TGMComponent.Create(AOwner: TComponent);
begin
inherited;
FLanguage := lnEnglish;
end;
function TGMComponent.GetAboutGMLib: string;
begin
Result := ctGMLib_Version;
end;
function TGMComponent.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference';
end;
function TGMComponent.PropToString: string;
begin
Result := '';
end;
{ TGMInterfacedOwnedPersistent }
procedure TGMInterfacedOwnedPersistent.ControlChanges(PropName: string);
var
Intf: IGMControlChanges;
begin
if (FOwner <> nil) and Supports(FOwner, IGMControlChanges, Intf) then
Intf.PropertyChanged(Self, Self.ClassName + '_' + PropName)
else
if Assigned(FOnChange) then FOnChange(Self);
end;
constructor TGMInterfacedOwnedPersistent.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
end;
function TGMInterfacedOwnedPersistent.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{ TGMPersistent }
function TGMPersistent.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference';
end;
{ TGMPersistentStr }
function TGMPersistentStr.GetOwnerLang: TGMLang;
var
Intf: IGMOwnerLang;
begin
Result := lnEnglish;
if not Assigned(GetOwner()) then Exit;
if not Supports(GetOwner(), IGMOwnerLang, Intf) then Exit;
Result := Intf.GetOwnerLang;
end;
function TGMPersistentStr.PropToString: string;
begin
Result := '';
end;
{ TGMInterfacedCollectionItem }
procedure TGMInterfacedCollectionItem.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMInterfacedCollectionItem then
begin
Name := TGMInterfacedCollectionItem(Source).Name;
Tag := TGMInterfacedCollectionItem(Source).Tag;
FObject := TGMInterfacedCollectionItem(Source).FObject;
end;
end;
procedure TGMInterfacedCollectionItem.ControlChanges(PropName: string);
var
Intf: IGMControlChanges;
begin
if (GetOwner <> nil) and Supports(GetOwner, IGMControlChanges, Intf) then
Intf.PropertyChanged(Self, PropName)
else
if Assigned(FOnChange) then FOnChange(Self);
end;
function TGMInterfacedCollectionItem.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference';
end;
function TGMInterfacedCollectionItem.GetDisplayName: string;
begin
if Length(FName) > 0 then
begin
if Length(FName) > 15 then
Result := Copy(FName, 0, 15) + '...'
else
Result := FName;
end
else
begin
Result := inherited GetDisplayName;
FName := Result;
end;
end;
function TGMInterfacedCollectionItem.GetOwnerLang: TGMLang;
var
Intf: IGMOwnerLang;
begin
Result := lnEnglish;
if not Assigned(Collection) then Exit;
if not Supports(Collection, IGMOwnerLang, Intf) then Exit;
Result := Intf.GetOwnerLang;
end;
function TGMInterfacedCollectionItem.PropToString: string;
begin
Result := '';
end;
function TGMInterfacedCollectionItem.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
if GetInterface(IID, Obj) then Result := S_OK
else Result := E_NOINTERFACE;
end;
function TGMInterfacedCollectionItem._AddRef: Integer;
begin
Result := -1;
end;
function TGMInterfacedCollectionItem._Release: Integer;
begin
Result := -1;
end;
{ TGMInterfacedCollection }
function TGMInterfacedCollection.Add: TGMInterfacedCollectionItem;
begin
Result := TGMInterfacedCollectionItem(inherited Add);
ControlChanges('Items');
end;
procedure TGMInterfacedCollection.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMInterfacedCollection then
FOwner := TGMInterfacedCollection(Source).FOwner;
end;
procedure TGMInterfacedCollection.Clear;
begin
inherited Clear;
ControlChanges('Items');
end;
procedure TGMInterfacedCollection.ControlChanges(PropName: string);
var
Intf: IGMControlChanges;
begin
if (GetOwner <> nil) and Supports(GetOwner, IGMControlChanges, Intf) then
Intf.PropertyChanged(Self, PropName)
else
if Assigned(FOnChange) then FOnChange(Self);
end;
constructor TGMInterfacedCollection.Create(AOwner: TPersistent;
ItemClass: TCollectionItemClass);
begin
inherited Create(ItemClass);
FOwner := AOwner;
end;
procedure TGMInterfacedCollection.Delete(Index: Integer);
begin
inherited Delete(Index);
ControlChanges('Items');
end;
function TGMInterfacedCollection.GetItems(
I: Integer): TGMInterfacedCollectionItem;
begin
Result := TGMInterfacedCollectionItem(inherited Items[I]);
end;
function TGMInterfacedCollection.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TGMInterfacedCollection.GetOwnerLang: TGMLang;
var
Intf: IGMOwnerLang;
begin
Result := lnEnglish;
if not Assigned(FOwner) then Exit;
if not Supports(FOwner, IGMOwnerLang, Intf) then Exit;
Result := Intf.GetOwnerLang;
end;
function TGMInterfacedCollection.Insert(Index: Integer): TGMInterfacedCollectionItem;
begin
Result := TGMInterfacedCollectionItem(inherited Insert(Index));
ControlChanges('Items');
end;
procedure TGMInterfacedCollection.Move(CurIndex, NewIndex: Integer);
begin
Items[CurIndex].Index := NewIndex;
ControlChanges('Items');
end;
procedure TGMInterfacedCollection.PropertyChanged(Prop: TPersistent;
PropName: string);
begin
ControlChanges(PropName);
end;
function TGMInterfacedCollection.PropToString: string;
var
i: Integer;
begin
Result := '';
for i := 0 to Count - 1 do
begin
if Result <> '' then Result := Result + ',';
Result := Result + Items[i].PropToString;
end;
end;
function TGMInterfacedCollection.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
if GetInterface(IID, Obj) then Result := S_OK
else Result := E_NOINTERFACE;
end;
procedure TGMInterfacedCollection.SetItems(I: Integer;
const Value: TGMInterfacedCollectionItem);
begin
inherited SetItem(I, Value);
end;
function TGMInterfacedCollection._AddRef: Integer;
begin
Result := -1;
end;
function TGMInterfacedCollection._Release: Integer;
begin
Result := -1;
end;
{ TGMJson }
function TGMJson.Deserialize(aClass: TClass; Json: string): TObject;
var
JSONValue: TJsonValue;
JSONObject: TJSONObject;
begin
Result := aClass.Create;
JSONValue := TJSONObject.ParseJSONValue(Json);
try
if not Assigned(JSONValue) then
Exit;
if (JSONValue is TJSONArray) then
begin
with TJSONUnMarshal.Create do
try
SetFieldArray(Result, 'Items', (JSONValue as TJSONArray));
finally
Free;
end;
Exit;
end;
if (JSONValue is TJSONObject) then
JSONObject := JSONValue as TJSONObject
else
begin
Json := Json.Trim;
if (Json = '') and not Assigned(JSONValue) or (Json <> '') and Assigned(JSONValue) and JSONValue.Null then
Exit
else
raise EConversionError.Create(SCannotCreateObject);
end;
TJson.JsonToObject(Result, JSONObject, []);
finally
JSONValue.Free;
end;
end;
function TGMJson.Serialize(aObject: TObject): string;
begin
Result := TJson.ObjectToJsonString(aObject, []);
end;
end.
|
program exer3;
var
raio,area,circ,pi : real;
begin
read(raio);
pi:=3.141592;
area:=pi*raio*raio;
circ:=2*pi*raio;
writeln('Área: ',area:0:10);
writeln('Circunferência: ',circ:0:10);
end.
//EXERCICIO: ler o raio de um circulo e escrever a sua circunferencia e area.
|
unit TBX_converters;
{Utility to convert standard TMenu to TB2K/TBX}
interface
{$I TB2Ver.inc}
uses
Windows, SysUtils, Classes, Controls, Forms, Menus, StdCtrls, ComCtrls,
TB2Item,TBX;
procedure CopyConvertMenuTB2K(const ParentItem: TTBCustomItem; Menu: TMenu);
procedure CopyConvertMenuTBX (const ParentItem: TTBCustomItem; MenuItem: TMenuItem);
procedure CopyConvertToolbarTBX (Dst: TTBXToolbar; Src: TToolbar);
implementation
procedure CopyConvertMenuTB2K(const ParentItem: TTBCustomItem; Menu: TMenu);
{originally taken from TB2DsgnConverter.pas from TB2K lib ver 2.1.6}
const
SPropNotTransferred = 'Warning: %s property not transferred on ''%s''.';
//var ConverterForm: TTBConverterForm;
procedure Log(const S: String);
begin
{ConverterForm.MessageList.Items.Add(S);
ConverterForm.MessageList.TopIndex := ConverterForm.MessageList.Items.Count-1;
ConverterForm.Update;}
end;
procedure Recurse(MenuItem: TMenuItem; TBItem: TTBCustomItem);
var
I: Integer;
Src: TMenuItem;
IsSep, IsSubmenu: Boolean;
Dst: TTBCustomItem;
N: String;
var Owner : TComponent;
begin
Owner := ParentItem.Owner;
for I := 0 to MenuItem.Count-1 do begin
Src := MenuItem[I];
IsSep := (Src.Caption = '-');
IsSubmenu := False;
if not IsSep then begin
if Src.Count > 0 then
IsSubmenu := True;
if not IsSubmenu then
Dst := TTBItem.Create(Owner)
else
Dst := TTBSubmenuItem.Create(Owner);
Dst.Action := Src.Action;
{$IFDEF JR_D6}
Dst.AutoCheck := Src.AutoCheck;
{$ENDIF}
Dst.Caption := Src.Caption;
Dst.Checked := Src.Checked;
if Src.Default then
Dst.Options := Dst.Options + [tboDefault];
Dst.Enabled := Src.Enabled;
Dst.GroupIndex := Src.GroupIndex;
Dst.HelpContext := Src.HelpContext;
Dst.ImageIndex := Src.ImageIndex;
Dst.RadioItem := Src.RadioItem;
Dst.ShortCut := Src.ShortCut;
{$IFDEF JR_D5}
Dst.SubMenuImages := Src.SubMenuImages;
{$ENDIF}
Dst.OnClick := Src.OnClick;
end
else begin
Dst := TTBSeparatorItem.Create(Owner);
end;
Dst.Hint := Src.Hint;
Dst.Tag := Src.Tag;
Dst.Visible := Src.Visible;
if not IsSep then
{ Temporarily clear the menu item's OnClick property, so that renaming
the menu item doesn't cause the function name to change }
Src.OnClick := nil;
try
{N := Src.Name;
Src.Name := N + '_OLD';
Dst.Name := N;}
Dst.Name := Src.Name;
finally
if not IsSep then
Src.OnClick := Dst.OnClick;
end;
TBItem.Add(Dst);
{$IFDEF JR_D5}
if @Src.OnAdvancedDrawItem <> nil then
Log(Format(SPropNotTransferred, ['OnAdvancedDrawItem', Dst.Name]));
{$ENDIF}
if @Src.OnDrawItem <> nil then
Log(Format(SPropNotTransferred, ['OnDrawItem', Dst.Name]));
if @Src.OnMeasureItem <> nil then
Log(Format(SPropNotTransferred, ['OnMeasureItem', Dst.Name]));
if IsSubmenu then
Recurse(Src, Dst);
end;
end;
var
// OptionsForm: TTBConvertOptionsForm;
I: Integer;
C: TComponent;
//Menu: TMenu;
begin
// Menu := nil;
//OptionsForm := TTBConvertOptionsForm.Create(Application);
{try
for I := 0 to Owner.ComponentCount-1 do begin
C := Owner.Components[I];
if (C is TMenu) and not(C is TTBPopupMenu) then
OptionsForm.MenuCombo.Items.AddObject(C.Name, C);
end;
if OptionsForm.MenuCombo.Items.Count = 0 then
raise Exception.Create('Could not find any menus on the form to convert');
OptionsForm.MenuCombo.ItemIndex := 0;
if (OptionsForm.ShowModal <> mrOK) or (OptionsForm.MenuCombo.ItemIndex < 0) then
Exit;
Menu := TMenu(OptionsForm.MenuCombo.Items.Objects[OptionsForm.MenuCombo.ItemIndex]);
finally
OptionsForm.Free;
end;}
ParentItem.SubMenuImages := Menu.Images;
{ConverterForm := TTBConverterForm.Create(Application);
ConverterForm.Show;
ConverterForm.Update;
Log(Format('Converting ''%s'', please wait...', [Menu.Name]));}
ParentItem.ViewBeginUpdate;
try
Recurse(Menu.Items, ParentItem);
finally
ParentItem.ViewEndUpdate;
end;
{Log('Done!');
ConverterForm.CloseButton.Enabled := True;
ConverterForm.CopyButton.Enabled := True;}
end;
procedure CopyConvertMenuTBX(const ParentItem: TTBCustomItem; MenuItem: TMenuItem);
{originally taken from TB2DsgnConverter.pas from TB2K lib ver 2.1.6}
const
SPropNotTransferred = 'Warning: %s property not transferred on ''%s''.';
//var ConverterForm: TTBConverterForm;
procedure Log(const S: String);
begin
{ConverterForm.MessageList.Items.Add(S);
ConverterForm.MessageList.TopIndex := ConverterForm.MessageList.Items.Count-1;
ConverterForm.Update;}
end;
procedure Recurse(MenuItem: TMenuItem; TBXItem: TTBCustomItem);
var
I: Integer;
Src: TMenuItem;
IsSep, IsSubmenu: Boolean;
Dst: TTBCustomItem;
N: String;
var Owner : TComponent;
begin
Owner := ParentItem.Owner;
for I := 0 to MenuItem.Count-1 do begin
Src := MenuItem[I];
IsSep := (Src.Caption = '-');
IsSubmenu := False;
if not IsSep then begin
if Src.Count > 0 then
IsSubmenu := True;
if not IsSubmenu then
Dst := TTBXItem.Create(Owner)
else
Dst := TTBXSubmenuItem.Create(Owner);
Dst.Action := Src.Action;
{$IFDEF JR_D6}
Dst.AutoCheck := Src.AutoCheck;
{$ENDIF}
Dst.Caption := Src.Caption;
Dst.Checked := Src.Checked;
if Src.Default then
Dst.Options := Dst.Options + [tboDefault];
Dst.Enabled := Src.Enabled;
Dst.GroupIndex := Src.GroupIndex;
Dst.HelpContext := Src.HelpContext;
Dst.ImageIndex := Src.ImageIndex;
Dst.RadioItem := Src.RadioItem;
Dst.ShortCut := Src.ShortCut;
{$IFDEF JR_D5}
Dst.SubMenuImages := Src.SubMenuImages;
{$ENDIF}
Dst.OnClick := Src.OnClick;
end
else begin
Dst := TTBXSeparatorItem.Create(Owner);
end;
Dst.Hint := Src.Hint;
Dst.Tag := Src.Tag;
Dst.Visible := Src.Visible;
if not IsSep then
{ Temporarily clear the menu item's OnClick property, so that renaming
the menu item doesn't cause the function name to change }
Src.OnClick := nil;
try
{N := Src.Name;
Src.Name := N + '_OLD';
Dst.Name := N;}
Dst.Name := Src.Name;
finally
if not IsSep then
Src.OnClick := Dst.OnClick;
end;
TBXItem.Add(Dst);
{$IFDEF JR_D5}
if @Src.OnAdvancedDrawItem <> nil then
Log(Format(SPropNotTransferred, ['OnAdvancedDrawItem', Dst.Name]));
{$ENDIF}
if @Src.OnDrawItem <> nil then
Log(Format(SPropNotTransferred, ['OnDrawItem', Dst.Name]));
if @Src.OnMeasureItem <> nil then
Log(Format(SPropNotTransferred, ['OnMeasureItem', Dst.Name]));
if IsSubmenu then
Recurse(Src, Dst);
end;
end;
var
// OptionsForm: TTBConvertOptionsForm;
I: Integer;
C: TComponent;
//Menu: TMenu;
begin
// Menu := nil;
//OptionsForm := TTBConvertOptionsForm.Create(Application);
{try
for I := 0 to Owner.ComponentCount-1 do begin
C := Owner.Components[I];
if (C is TMenu) and not(C is TTBPopupMenu) then
OptionsForm.MenuCombo.Items.AddObject(C.Name, C);
end;
if OptionsForm.MenuCombo.Items.Count = 0 then
raise Exception.Create('Could not find any menus on the form to convert');
OptionsForm.MenuCombo.ItemIndex := 0;
if (OptionsForm.ShowModal <> mrOK) or (OptionsForm.MenuCombo.ItemIndex < 0) then
Exit;
Menu := TMenu(OptionsForm.MenuCombo.Items.Objects[OptionsForm.MenuCombo.ItemIndex]);
finally
OptionsForm.Free;
end;}
ParentItem.SubMenuImages := MenuItem.GetImageList;
{ConverterForm := TTBConverterForm.Create(Application);
ConverterForm.Show;
ConverterForm.Update;
Log(Format('Converting ''%s'', please wait...', [Menu.Name]));}
ParentItem.ViewBeginUpdate;
try
Recurse(MenuItem, ParentItem);
finally
ParentItem.ViewEndUpdate;
end;
{Log('Done!');
ConverterForm.CloseButton.Enabled := True;
ConverterForm.CopyButton.Enabled := True;}
end;
procedure CopyConvertToolbarTBX (Dst: TTBXToolbar; Src: TToolbar);
{originally taken from TB2DsgnConverter.pas from TB2K lib ver 2.1.6}
const
SPropNotTransferred = 'Warning: %s property not transferred on ''%s''.';
//var ConverterForm: TTBConverterForm;
procedure Log(const S: String);
begin
{ConverterForm.MessageList.Items.Add(S);
ConverterForm.MessageList.TopIndex := ConverterForm.MessageList.Items.Count-1;
ConverterForm.Update;}
end;
procedure DoConvert();
var
I: Integer;
btn: TToolButton;
IsSep, IsSubmenu: Boolean;
Item: TTBCustomItem;
N: String;
var Owner : TComponent;
begin
Owner := Src.Owner;
for I := 0 to Src.ButtonCount-1 do
begin
btn := Src.Buttons[I];
IsSep := (btn.Style = tbsSeparator);
IsSubmenu := False;
if IsSep then
begin
Item := TTBXSeparatorItem.Create(Owner);
end
else
begin
if btn.Style = tbsDropDown then
IsSubmenu := Assigned(btn.DropdownMenu);
if not IsSubmenu then
Item := TTBXItem.Create(Owner)
else
Item := TTBXSubmenuItem.Create(Owner);
Item.Action := btn.Action;
Item.Caption := btn.Caption;
Item.Checked := btn.Down;
//if btn.Default then
//Item.Options := Item.Options + [tboDefault];
Item.Enabled := btn.Enabled;
//Item.GroupIndex := btn.GroupIndex;
Item.HelpContext := btn.HelpContext;
Item.ImageIndex := btn.ImageIndex;
//Item.RadioItem := btn.RadioItem;
//Item.ShortCut := btn.ShortCut;
{$IFDEF JR_D5}
//Item.SubMenuImages := btn.SubMenuImages;
{$ENDIF}
Item.OnClick := btn.OnClick;
end;
Item.Hint := btn.Hint;
Item.Tag := btn.Tag;
Item.Visible := btn.Visible;
if not IsSep then
{ Temporarily clear the menu item's OnClick property, so that renaming
the menu item doesn't cause the function name to change }
btn.OnClick := nil;
try
{N := Src.Name;
Src.Name := N + '_OLD';
Dst.Name := N;}
//Item.Name := btn.Name;
finally
if not IsSep then
btn.OnClick := Item.OnClick;
end;
Dst.Items.Add(Item);
if IsSubmenu then
begin
//CopyConvertMenuTBX(Item, btn.DropdownMenu.Items);
end;
end;
// Dst.BoundsRect := Src.BoundsRect;
end;
var
// OptionsForm: TTBConvertOptionsForm;
I: Integer;
C: TComponent;
begin
Dst.Images := Src.Images;
//Dst.ViewBeginUpdate;
try
DoConvert();
Dst.Left := Src.Left;
Dst.Top := Src.Top;
finally
//Dst.ViewEndUpdate;
end;
end;
end.
|
unit PrintImageUnit;
interface
uses
Windows, PrintExtension, StrUtils, SysUtils, Classes, BaseClass, Graphics,
Math;
//ABmpImageList: 图片名称列表 分隔符'|'
//APortName: 端口名称
//返回值: integer
function POS_LoadImageListExt(AComm: TMyComm;APrintName, APortName, ABmpImageList: PChar): Integer; stdcall;
{//打开端口
function POS_OpenPort(APortName: string): THandle; stdcall;
//关闭端口
function POS_ClosePort(): Integer; stdcall;
//print
function POS_Print(): Integer; stdcall; }
//IBM4610
function POS_LoadImage_IBM(AComm: TMyComm;ABmpImageList: array of PChar): Boolean;
//EPSON TM88/PT900TA/HKP600T
function POS_LoadImage_EPSON(AComm: TMyComm;APortName: PChar;ABmpImageList: array of PChar): Boolean;
//
function ParsePixel(InPixel: Integer): String;
implementation
function POS_LoadImageListExt(AComm: TMyComm;APrintName, APortName, ABmpImageList: PChar): Integer; stdcall;
var
wArrBmp: array of Pchar;
wSL: TStringList;
i: Integer;
begin
Result := -1;
// if wPOSHandle <> INVALID_HANDLE_VALUE then
//截取图像文件名
wSL := TStringList.Create;
try
// wSL.Delimiter := ';';
// wSL.DelimitedText := StrPas(ABmpImageList);
// iResult := Pos(';', ABmpImageList);
// wStr := MidStr(ABmpImageList, 1, iResult); //空格被当作一个分隔符
ExtractStrings(['|'], [], ABmpImageList, wSL);
if wSL.Count <= 0 then Exit;
//原因不详,初始化长度+1 调用新北洋动态库bmp写入传参列表+1
// SetLength(wArrBmp, wSL.Count + 1);
SetLength(wArrBmp, wSL.Count);
for i := 0 to wSL.Count - 1 do
begin
wArrBmp[i] := PChar(wSL.Strings[i]);
end;
if APrintName = 'IBM4610' then
begin
POS_LoadImage_IBM(AComm, wArrBmp);
Result := 0;
end
else if (APrintName = 'TM88') or (APrintName = 'PT900TA') or (APrintName = 'HKP600T') then
begin
POS_LoadImage_EPSON(AComm, APortName, wArrBmp);
Result := 0;
end;
// iResult := POS_PreDownloadBmpsToFlash(wArrBmp, wSL.Count);
finally
wSL.Free;
end;
end;
{function POS_OpenPort(APortName: string): THandle; stdcall;
var
iComBaudrate, iComDataBits, iComStopBits, iComParity, iParam: Integer;
begin
if Pos('COM', APortName) > 0 then
begin
iComBaudrate := 9600; //指定串口的波特率(bps)。 2400,4800,9600,19200,38400,57600,115200等。
iComDataBits := 7; //指定串口通讯时的数据位数。5 到 8。
iComStopBits := POS_COM_ONESTOPBIT; //指定串口通讯时的数据停止位数。
iComParity := POS_COM_ODDPARITY; //指定串口的奇偶校验方法。
iParam := POS_COM_RTS_CTS; //指定串口的流控制(握手)方式、或表示通讯方式。
Result := POS_Open(PChar(APortName), iComBaudrate, iComDataBits, iComStopBits,
iComParity, iParam);
end
else if Pos('LPT', APortName) > 0 then
begin
iComBaudrate := 0;
iComDataBits := 0;
iComStopBits := 0;
iComParity := 0;
iParam := POS_OPEN_PARALLEL_PORT;
Result := POS_Open(PChar(APortName), iComBaudrate, iComDataBits, iComStopBits,
iComParity, iParam);
end
else if Pos('USB', APortName) > 0 then
begin
iComBaudrate := 0;
iComDataBits := 0;
iComStopBits := 0;
iComParity :=0;
iParam := POS_OPEN_BYUSB_PORT;
Result := POS_Open(PChar(APortName), iComBaudrate, iComDataBits, iComStopBits,
iComParity, iParam);
end
else
Result := INVALID_HANDLE_VALUE;
end;
function POS_ClosePort(): Integer; stdcall;
begin
Result := POS_Close;
end;
function POS_Print(): Integer; stdcall;
var
i: Integer;
begin
Result := 0;
for i := 0 to 4 do
begin
POS_S_PrintBmpInFlash(i, 0, $00);
end;
POS_FeedLine;
POS_FeedLine;
POS_FeedLine;
POS_FeedLine;
POS_FeedLine;
POS_CutPaper($00, 0);
end;}
function POS_LoadImage_IBM(AComm: TMyComm;ABmpImageList: array of PChar): Boolean;
var
BM: TBitmap;
i, w, h, L9, b, index: integer;
s, s0, s1, Data: string;
begin
Result := False;
for index := 0 to Length(ABmpImageList) - 1 do
begin
BM := TBitmap.Create;
try
s := '';
s0 := '';
s1 := '';
BM.LoadFromFile(ABmpImageList[index]);
w := BM.Width Div 8;
h := BM.Height Div 8;
SetLength(Data, w);
for L9 := 0 to BM.Height - 1 do
begin
Move(BM.ScanLine[L9]^, Data[1], w);
for i := 1 to w do
begin
b := byte(Data[i]) xor $FF;
s := s + char(b);
end;
end;
finally
BM.Free;
end;
if AComm.OpenFlag then
begin
AComm.PutStr(Char($1D) + Char($2A) + Char(StrToInt('$' + IntToHex(index + 1, 2))) + //循环写入对应存储位
Char(StrToInt('$' + IntToHex(w, 2))) + Char(StrToInt('$' + IntToHex(h, 2))) + s);
Result := true;
end;
end;
end;
//EPSON
function POS_LoadImage_EPSON(AComm: TMyComm;APortName: PChar;ABmpImageList: array of PChar): Boolean;
var
fp: textfile;
IsLpt: Boolean;
BM: TBitmap;
i, j, k, w, h, L9, b, index: integer;
s, s0, s1, Data, sTemp: string;
ii: array of array of integer;
begin
Result := False;
sTemp := '';
for index := 0 to Length(ABmpImageList) - 1 do
begin
BM := TBitmap.Create;
try
s := '';
s0 := '';
s1 := '';
BM.LoadFromFile(ABmpImageList[index]);
w := BM.Width Div 8;
h := BM.Height Div 8;
SetLength(Data, w);
//EPSON,HISENSE
SetLength(ii, 8 * w, 8 * h);
for L9 := 0 to BM.Height - 1 do
begin
Move(BM.ScanLine[L9]^, Data[1], w);
for i := 1 to w do
begin
b := byte(Data[i]) xor $FF;
s := s + char(b);
end;
end;
//
for L9 := 0 To 8 * h - 1 Do
begin
Move(BM.ScanLine[L9]^, Data[1], w);
for i := 1 to w do
begin
b := byte(Data[i]) xor $FF;
s0 := ParsePixel(b);
for j := 1 to 8 do
begin
ii[8 * (i - 1) + j - 1, L9] := StrToInt(s0[j]);
end;
end;
end;
for i := 1 to 8 * w do
begin
for j := 1 to h do
begin
b := 0;
for k := 7 downto 0 do b := b + Trunc(IntPower(2, k)) * ii[i - 1, 8 * (j - 1) + 7 - k];
s1 := s1 + Char(StrToInt('$' + IntToHex(b, 2)));
end;
end;
//Hex 1C 71 n [xL xH yL yH d1...dk]1 ... [xL xH yL yH d1...dk]n
//https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=90
//char(strtoint('$' + inttohex(integer('['), 2)))
s1 := Char(w mod 256) + Char(w div 256) + Char(h mod 256) + Char(h div 256) + s1;
finally
BM.Free;
end;
sTemp := sTemp + s1;
end;
IsLpt := false;
if Pos('LPT', APortName) > 0 then
begin
IsLpt := True;
AssignFile(fp, PChar(APortName));
Rewrite(fp);
end;
if (not IsLpt) and AComm.OpenFlag then
begin
// if (P_PrintType = 'TM88') or (P_PrintType = 'PT900TA') or (P_PrintType = 'HKP600T') then
begin
AComm.PutStr(char($1C) + char($71) + Char(Length(ABmpImageList)) + sTemp);
Result := true;
end;
end
else if IsLpt then
begin
// if (P_PrintType = 'TM88') or (P_PrintType = 'PT900TA') or (P_PrintType = 'HKP600T') then
begin
Writeln(fp, char($1C) + char($71) + Char(Length(ABmpImageList)) + sTemp);
Result := true;
end;
end;
if IsLpt then // 并口打印机
begin
Flush(fp);
CloseFile(fp);
end;
end;
function ParsePixel(InPixel: Integer): String;
var
Bit: array[0..7] of Integer;
temp,i: Integer;
begin
Result := '00000000'; //白点
Bit[0] := 1;
Bit[1] := 2;
Bit[2] := 4;
Bit[3] := 8;
Bit[4] := 16;
Bit[5] := 32;
Bit[6] := 64;
Bit[7] := 128;
temp := InPixel;
if (temp > 0) and (temp <= 255) then
begin
while temp >= 0 do
begin
for i := 7 downto 0 do
begin
if temp >= Bit[i] then
begin
temp := temp - Bit[i];
Result := Copy(Result, 1, 7 - i) + '1' + Copy(Result, 8 - i + 1, i);
if temp = 0 then temp := -1;
Break;
end;
end;
end;
end;
end;
end.
|
unit Ti01;
{
ULTI01.DPR ================================================================
File: TI01.PAS
Library Call Demonstrated: cbTIn()
Purpose: Reads a multiplexer input channel.
Demonstration: Displays the temperature input on a MUX
channel.
Other Library Calls: cbErrHandling()
Special Requirements: Board 0 must have an A/D converter with an
attached EXP board. A thermocouple must be
attached to mux channel 0.
(c) Copyright 1995 - 2002, Measurement Computing Corp.
All rights reserved.
===========================================================================
}
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, cbw;
type
TfrmTIn = class(TForm)
tmrAIn: TTimer;
cmdStart: TButton;
cmdQuit: TButton;
MemoData: TMemo;
procedure tmrAInTimer(Sender: TObject);
procedure cmdStartClick(Sender: TObject);
procedure cmdQuitClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmTIn: TfrmTIn;
implementation
{$R *.DFM}
var
ULStat: Integer;
Options: Integer;
ADChan: Integer;
MUXChan: Integer;
Chan: Integer;
TempValue: Single;
TUnits: String[11];
ErrReporting: Integer;
ErrHandling: Integer;
RevLevel: Single;
UsesEXPs: Integer;
const
BoardNum: Integer = 0; {the number used by CB.CFG to describe this board}
procedure TfrmTIn.FormCreate(Sender: TObject);
var
InfoType: Integer;
DevNum: Integer;
ConfigItem: Integer;
begin
{declare Revision Level}
RevLevel := CURRENTREVNUM;
ULStat := cbDeclareRevision(RevLevel);
{
set up internal error handling for the Universal Library
}
ErrReporting := PRINTALL; {set Universal Library to print all errors}
ErrHandling := STOPALL; {set Universal Library to stop on errors}
ULStat := cbErrHandling(ErrReporting, ErrHandling);
{
determine via cbGetConfig if board uses expansion boards for temperature measurements
}
InfoType := BOARDINFO;
DevNum := 0;
ConfigItem := BIUSESEXPS;
UsesEXPs := 0;
ULStat := cbGetConfig(InfoType, BoardNum, DevNum, ConfigItem, UsesEXPs);
if (ULStat<>0) then UsesEXPs := 0;
MemoData.Text := 'Click Start to acquire data';
end;
procedure TfrmTIn.cmdStartClick(Sender: TObject);
begin
tmrAIn.Enabled := True;
end;
procedure TfrmTIn.tmrAInTimer(Sender: TObject);
var
Scale: Integer;
begin
{
collect the data with cbTIn()
Input values will be collected from a thermocouple into TempValue
}
MemoData.Text := 'The temperature measured is:';
MemoData.Lines.Add (' ');
for Scale := 0 to 2 do
begin
{
Parameters:
BoardNum :the number used by CB.CFG to describe this board
Chan :the input channel
Scale :temperature scale (Celsius, Fahrenheit, Kelvin)
TempValue :the temperature value collected
Options :either NOFILTER or FILTER to average data
}
Options := NOFILTER;
ADChan := 0;
MUXChan := 0;
if UsesEXPs>0 then
Chan := (ADChan + 1) * 16 + MUXChan
else
Chan := MUXChan;
ULStat := cbTIn (BoardNum, Chan, Scale, TempValue, Options);
If ULStat <> 0 then
begin
tmrAIn.Enabled := False;
exit;
end;
Case Scale of
0: TUnits := 'Celsius';
1: TUnits := 'Fahrenheit';
2: TUnits := 'Kelvin';
end;
MemoData.Lines.Add (Format
('Channel %d: %f degrees %s', [Chan, TempValue, TUnits]));
end;
end;
procedure TfrmTIn.cmdQuitClick(Sender: TObject);
begin
tmrAIn.Enabled := False;
Close;
end;
end.
|
{
НАЗНАЧЕНИЕ:
Создание объектов, участвующих в реализации протокола Modbus
ЗАВИСИМОСТИ:
- uBase
- uModbus
ПАТТЕРН:
- Builder
- Lazy Initialization
}
unit uStackBuilder;
{$mode objfpc}{$H+}
{$DEFINE DEBUG}// Альтернатива -dDEBUG
{$C+}// Альтернатива Включить Assert
interface
uses
Classes, SysUtils,
WinSock2,
uBase,
uModbus, uCommunication, uConnection, uController, uTransaction;
type
// Конкретные строители
TRtuBuilder = class;
TCnTcpBuilder = class;
TAcTcpBuilder = class;
{ TStackBuilder }
{
НАЗНАЧЕНИЕ:
Возвращает конкретный Builder из коллекции.
ОПИСАНИЕ:
Потокобезопасный контейнер Modbus Builder'ов
Используется Lazy Initialization: если требуемого Builder'а нет
в коллекции, он создается, размещается в коллекцию
}
TStackBuilderSpec = specialize TThreadSafeWrapper<TBuildersMap>;
TStackBuilder = class(TStackBuilderSpec, IStackBuilder)
private
fCapacity: byte;
protected
function GetRtuBuilder: IRtuBuilder;
function GetCnTcpBuilder: ICnTcpBuilder;
function GetAcTcpBuilder: IAcTcpBuilder;
public
constructor Create(const aCapacity: byte = 5);
destructor Destroy; override;
public
property RtuBuilder: IRtuBuilder read GetRtuBuilder;
property CnTcpBuilder: ICnTcpBuilder read GetCnTcpBuilder;
property AcTcpBuilder: IAcTcpBuilder
read GetAcTcpBuilder;
end;
TBuilder = class(TBase, IBuilder)
protected
fCapacity: byte;
fController: IController;
protected
procedure BuildController; virtual;
procedure BuildTransaction; virtual; abstract;
procedure BuildCommunication; virtual; abstract;
procedure BuildConnection; virtual; abstract;
procedure Build;
public
constructor Create(const aCapacity: byte); reintroduce;
end;
{ TRtuBuilder }
TRtuBuilder = class(TBuilder, IRtuBuilder)
private
// fRtuMbController: IRtuMbController;
fPortName: PChar;
fBaudRate: dword;
fParity: byte;
fStopBits: byte;
fByteSize: byte;
fThreeAndHalf: byte;
protected
procedure BuildController; override;
procedure BuildTransaction; override;
procedure BuildCommunication; override;
procedure BuildConnection; override;
public
function GetController(
const aPortName: PChar;
const aBaudRate: dword;
const aParity: byte;
const aStopBits: byte;
const aByteSize: byte;
const aThreeAndHalf: byte
): IController;
end;
{ TCnTcpBuilder }
TCnTcpBuilder = class(TBuilder, ICnTcpBuilder)
private
fIp: string;
fPort: word;
protected
procedure BuildController; override;
procedure BuildTransaction; override;
procedure BuildCommunication; override;
procedure BuildConnection; override;
public
function GetController(
const aIp: string;
const aPort: word
): IController;
end;
{ TAcTcpBuilder }
TAcTcpBuilder = class(TBuilder, IAcTcpBuilder)
private
fSocket: TSocket;
protected
procedure BuildController; override;
procedure BuildTransaction; override;
procedure BuildCommunication; override;
procedure BuildConnection; override;
public
function GetController(
const aSocket: TSocket
): IController;
end;
implementation
{ TStackBuilder }
constructor TStackBuilder.Create(const aCapacity: byte);
begin
inherited Create;
fT := TBuildersMap.Create;
fCapacity := aCapacity;
end;
destructor TStackBuilder.Destroy;
begin
inherited Destroy;
FreeAndNil(fT);
end;
function TStackBuilder.GetRtuBuilder: IRtuBuilder;
var
Index: Integer;
BuildersMap: TBuildersMap;
{$IFDEF DEBUG}
_RtuBuilder: IRtuBuilder;
{$ENDIF}
begin
BuildersMap := Lock;
{$IFDEF DEBUG}
Assert(BuildersMap <> nil);
{$ENDIF}
try
if not BuildersMap.Find(TTypeController.mbRtu, Index) then
Index := BuildersMap.Add(TTypeController.mbRtu, TRtuBuilder.Create(fCapacity));
{$IFDEF DEBUG}
Assert(BuildersMap.Data[Index] <> nil);
Assert(Supports(BuildersMap.Data[Index], IRtuBuilder, _RtuBuilder));
{$ENDIF}
Result := BuildersMap.Data[Index] as IRtuBuilder;
finally
Unlock;
end;
end;
function TStackBuilder.GetCnTcpBuilder: ICnTcpBuilder;
var
Index: Integer;
BuildersMap: TBuildersMap;
{$IFDEF DEBUG}
_CnTcpBuilder: ICnTcpBuilder;
{$ENDIF}
begin
BuildersMap := Lock;
{$IFDEF DEBUG}
Assert(BuildersMap <> nil);
{$ENDIF}
try
if not BuildersMap.Find(TTypeController.mbCnTcp, Index) then
Index := BuildersMap.Add(TTypeController.mbCnTcp, TCnTcpBuilder.Create(fCapacity));
{$IFDEF DEBUG}
Assert(BuildersMap.Data[Index] <> nil);
Assert(Supports(BuildersMap.Data[Index], ICnTcpBuilder, _CnTcpBuilder));
{$ENDIF}
Result := BuildersMap.Data[Index] as ICnTcpBuilder;
finally
Unlock;
end;
end;
function TStackBuilder.GetAcTcpBuilder: IAcTcpBuilder;
var
Index: Integer;
BuildersMap: TBuildersMap;
{$IFDEF DEBUG}
_AcTcpBuilder: IAcTcpBuilder;
{$ENDIF}
begin
BuildersMap := Lock;
{$IFDEF DEBUG}
Assert(BuildersMap <> nil);
{$ENDIF}
try
if not BuildersMap.Find(TTypeController.mbAcTcp, Index) then
Index := BuildersMap.Add(TTypeController.mbAcTcp, TAcTcpBuilder.Create(fCapacity));
{$IFDEF DEBUG}
Assert(BuildersMap.Data[Index] <> nil);
Assert(Supports(BuildersMap.Data[Index], IAcTcpBuilder, _AcTcpBuilder));
{$ENDIF}
Result := BuildersMap.Data[Index] as IAcTcpBuilder;
finally
Unlock;
end;
end;
{ TBuilder }
constructor TBuilder.Create(const aCapacity: byte);
begin
inherited Create;
fCapacity := aCapacity;
end;
procedure TBuilder.BuildController;
begin
fController := TController.Create(fCapacity);
end;
procedure TBuilder.Build;
begin
BuildController;
BuildTransaction;
BuildCommunication;
BuildConnection;
end;
{ TRtuBuilder }
function TRtuBuilder.GetController(const aPortName: PChar;
const aBaudRate: dword; const aParity: byte; const aStopBits: byte;
const aByteSize: byte; const aThreeAndHalf: byte): IController;
begin
fPortName := aPortName;
fBaudRate := aBaudRate;
fParity := aParity;
fStopBits := aStopBits;
fByteSize := aByteSize;
fThreeAndHalf := aThreeAndHalf;
Build;
Result := fController;
end;
procedure TRtuBuilder.BuildController;
begin
inherited BuildController;
{$IFDEF DEBUG}
Assert(fController <> nil);
{$ENDIF}
fController.TypeController := TTypeController.mbRtu;
end;
procedure TRtuBuilder.BuildTransaction;
begin
{$IFDEF DEBUG}
Assert(fController <> nil);
{$ENDIF}
fController.Transaction := TRtuTransaction.Create;
end;
procedure TRtuBuilder.BuildCommunication;
begin
{$IFDEF DEBUG}
Assert(fController <> nil);
Assert(fController.Transaction <> nil);
{$ENDIF}
fController.Transaction.Communication := TRtuCommunication.Create;
end;
procedure TRtuBuilder.BuildConnection;
var
_RtuCommunication: IRtuCommunication;
RtuStruct: TRtuStruct;
begin
{$IFDEF DEBUG}
Assert(fController <> nil);
Assert(fController.Transaction <> nil);
Assert(fController.Transaction.Communication <> nil);
Assert(Supports(fController.Transaction.Communication, IRtuCommunication,
_RtuCommunication));
{$ENDIF}
if Supports(fController.Transaction.Communication, IRtuCommunication,
_RtuCommunication) then
begin
RtuStruct.BaudRate := fBaudRate;
RtuStruct.ByteSize := fByteSize;
RtuStruct.Parity := fParity;
RtuStruct.PortName:= fPortName;
RtuStruct.StopBits:= fStopBits;
RtuStruct.ThreeAndHalf:= fThreeAndHalf;
_RtuCommunication.RtuConnection:= TRtuConnection.Create(@RtuStruct);
end;
end;
{ TCnTcpBuilder }
function TCnTcpBuilder.GetController(const aIp: string;
const aPort: word): IController;
begin
fIp := aIp;
fPort := aPort;
Build;
Result := fController;
end;
procedure TCnTcpBuilder.BuildController;
begin
inherited BuildController;
{$IFDEF DEBUG}
Assert(fController <> nil);
{$ENDIF}
fController.TypeController := TTypeController.mbCnTcp;
end;
procedure TCnTcpBuilder.BuildTransaction;
begin
{$IFDEF DEBUG}
Assert(fController <> nil);
{$ENDIF}
fController.Transaction := TTcpTransaction.Create;
end;
procedure TCnTcpBuilder.BuildCommunication;
begin
{$IFDEF DEBUG}
Assert(fController <> nil);
Assert(fController.Transaction <> nil);
{$ENDIF}
fController.Transaction.Communication := TTcpCommunication.Create;
end;
procedure TCnTcpBuilder.BuildConnection;
var
_TcpCommunication: ITcpCommunication;
begin
{$IFDEF DEBUG}
Assert(fController <> nil);
Assert(fController.Transaction <> nil);
Assert(fController.Transaction.Communication <> nil);
Assert(Supports(fController.Transaction.Communication, ITcpCommunication,
_TcpCommunication));
{$ENDIF}
if Supports(fController.Transaction.Communication, ITcpCommunication,
_TcpCommunication) then
_TcpCommunication.TcpConnection:= TCnTcpConnection.Create(fIp, fPort);
end;
{ TAcTcpBuilder }
function TAcTcpBuilder.GetController(const aSocket: TSocket
): IController;
begin
fSocket := aSocket;
Build;
Result := fController;
end;
procedure TAcTcpBuilder.BuildController;
begin
inherited BuildController;
{$IFDEF DEBUG}
Assert(fController <> nil);
{$ENDIF}
fController.TypeController := TTypeController.mbAcTcp;
end;
procedure TAcTcpBuilder.BuildTransaction;
begin
{$IFDEF DEBUG}
Assert(fController <> nil);
{$ENDIF}
fController.Transaction := TTcpTransaction.Create;
end;
procedure TAcTcpBuilder.BuildCommunication;
begin
{$IFDEF DEBUG}
Assert(fController <> nil);
Assert(fController.Transaction <> nil);
{$ENDIF}
fController.Transaction.Communication := TTcpCommunication.Create;
end;
procedure TAcTcpBuilder.BuildConnection;
var
_TcpCommunication: ITcpCommunication;
begin
{$IFDEF DEBUG}
Assert(fController <> nil);
Assert(fController.Transaction <> nil);
Assert(fController.Transaction.Communication <> nil);
Assert(Supports(fController.Transaction.Communication, ITcpCommunication,
_TcpCommunication));
{$ENDIF}
if Supports(fController.Transaction.Communication, ITcpCommunication,
_TcpCommunication) then
_TcpCommunication.TcpConnection:= TAcTcpConnection.Create(fSocket);
end;
end.
|
(*
Copyright (c) 2011, Stefan Glienke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of this library nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
unit DSharp.Core.DataConversion.Expressions;
interface
uses
DSharp.Core.DataConversion,
DSharp.Core.Expressions;
type
TExpressionConverter = class(TValueConverter)
private
FSourceToTargetExpression: IExpression;
FTargetToSourceExpression: IExpression;
public
function Convert(const Value: TValue): TValue; override;
function ConvertBack(const Value: TValue): TValue; override;
property SourceToTargetExpression: IExpression
read FSourceToTargetExpression write FSourceToTargetExpression;
property TargetToSourceExpression: IExpression
read FTargetToSourceExpression write FTargetToSourceExpression;
end;
implementation
uses
SysUtils;
{ TExpressionConverter }
function TExpressionConverter.Convert(const Value: TValue): TValue;
var
Delegate: TFunc<TValue>;
begin
if Assigned(FSourceToTargetExpression) then
begin
Delegate := FSourceToTargetExpression.Compile();
Result := Delegate();
end
else
Result := Value;
end;
function TExpressionConverter.ConvertBack(const Value: TValue): TValue;
var
Delegate: TFunc<TValue>;
begin
if Assigned(FTargetToSourceExpression) then
begin
Delegate := FTargetToSourceExpression.Compile();
Result := Delegate();
end
else
Result := Value;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.