text stringlengths 14 6.51M |
|---|
unit WinTab32;
{
WinTab interface for delphi
WinTab is standardized programming interface to digitizing tablets,
three dimensional position sensors, and other pointing devices
by a group of leading digitizer manufacturers and applications developers.
converted from wintab.h, pktdef.h from www.pointing.com
The manager part is omitted for not being widely used or supported.
Dynamic link is used so as not to prevent programs to run without a tablet installed.
Detailed documents can be downloaded from www.pointing.com.
Note: Modify definations of PACKETDATA and PACKET to define your own data format.
by LI Qingrui
emailto: the3i@sohu.com
This file is supplied "AS IS", without warranty of any kind.
Feel free to use and modify for any purpose.
Enjoy yourself.
}
interface
uses Windows, Messages;
const // Message constants
WT_DEFBASE = $7FF0;
WT_MAXOFFSET = $F;
WT_PACKET = WT_DEFBASE + 0;
WT_CTXOPEN = WT_DEFBASE + 1;
WT_CTXCLOSE = WT_DEFBASE + 2;
WT_CTXUPDATE = WT_DEFBASE + 3;
WT_CTXOVERLAP = WT_DEFBASE + 4;
WT_PROXIMITY = WT_DEFBASE + 5;
WT_INFOCHANGE = WT_DEFBASE + 6;
WT_CSRCHANGE = WT_DEFBASE + 7;
WT_MAX = WT_DEFBASE + WT_MAXOFFSET;
// Common data types
type
HCTX = THandle; // context handle
WTPKT = Longword; // packet mask
const // Packet constants
// PACKET DEFINITION
// The following definition controls what data items are requested from the Tablet during the
// "WTOpen" command. Note that while some tablets will open with all data items requested
// (i.e. X, Y, Z, and Pressure information), some tablets will not open if they do not support
// a particular data item. For example, the GTCO Sketchmaster driver will fail on "WTOpen" if
// you request Z data or Pressure data. However, the SummaSketch driver will succeed on open
// even though Z and Pressure are not supported by this tablet. In this case, 0 is returned for
// the Z and Pressure data, as you might expect.
PK_CONTEXT = $1; // reporting context
PK_STATUS = $2; // status bits
PK_TIME = $4; // time stamp
PK_CHANGED = $8; // change bit vector
PK_SERIAL_NUMBER = $10; // packet serial number
PK_CURSOR = $20; // reporting cursor
PK_BUTTONS = $40; // button information
PK_X = $80; // x axis
PK_Y = $100; // y axis
PK_Z = $200; // z axis
PK_NORMAL_PRESSURE = $400; // normal or tip pressure
PK_TANGENT_PRESSURE = $800; // tangential or barrel pressure
PK_ORIENTATION = $1000; // orientation info: tilts
PK_ROTATION = $2000; // rotation info; 1.1
// this constant is used to define PACKET record
PACKETDATA = PK_X or PK_Y or PK_NORMAL_PRESSURE;
// this constant is used to define PACKET record
PACKETMODE = 0; //This means all values are reported "absoulte"
type
// Modify this to suit your needs.
PACKET = record
// pkContext: HCTX; // PK_CONTEXT
// pkStatus: Cardinal; // PK_STATUS
// pkTime: Longword; // PK_TIME
// pkChanged: WTPKT; // PK_CHANGED
// pkSerialNumber: cardinal; // PK_SERIAL_NUMBER
// pkCursor: cardinal; // PK_CURSOR
// pkButtons: Longword; // PK_BUTTONS
pkX: LongInt; // PK_X
pkY: LongInt; // PK_Y
// pkZ: LongInt; // PK_Z
pkNormalPressure: integer; // PK_NORMAL_PRESSURE
// pkTangentPressure: integer; // PK_TANGENT_PRESSURE
// pkOrientation: ORIENTATION; // PK_ORIENTATION
// pkRotation: ROTATION; // PK_ROTATION Ver 1.1
end;
type FIX32 = Longword;
// Info data defs
const // unit specifiers
TU_NONE = 0;
TU_INCHES = 1;
TU_CENTIMETERS = 2;
TU_CIRCLE = 3;
type
AXIS = record
axMin: LongInt;
axMax: LongInt;
axUnits: Cardinal;
axResolution: FIX32;
end;
PAXIS = ^AXIS;
const // system button assignment values
SBN_NONE = $00;
SBN_LCLICK = $01;
SBN_LDBLCLICK = $02;
SBN_LDRAG = $03;
SBN_RCLICK = $04;
SBN_RDBLCLICK = $05;
SBN_RDRAG = $06;
SBN_MCLICK = $07;
SBN_MDBLCLICK = $08;
SBN_MDRAG = $09;
const // hardware capabilities
HWC_INTEGRATED = $0001;
HWC_TOUCH = $0002;
HWC_HARDPROX = $0004;
HWC_PHYSID_CURSORS = $0008; // 1.1
const // cursor capabilities
CRC_MULTIMODE = $0001; // 1.1
CRC_AGGREGATE = $0002; // 1.1
CRC_INVERT = $0004; // 1.1
const // info categories
WTI_INTERFACE = 1;
IFC_WINTABID = 1;
IFC_SPECVERSION = 2;
IFC_IMPLVERSION = 3;
IFC_NDEVICES = 4;
IFC_NCURSORS = 5;
IFC_NCONTEXTS = 6;
IFC_CTXOPTIONS = 7;
IFC_CTXSAVESIZE = 8;
IFC_NEXTENSIONS = 9;
IFC_NMANAGERS = 10;
IFC_MAX = 10;
WTI_STATUS = 2;
STA_CONTEXTS = 1;
STA_SYSCTXS = 2;
STA_PKTRATE = 3;
STA_PKTDATA = 4;
STA_MANAGERS = 5;
STA_SYSTEM = 6;
STA_BUTTONUSE = 7;
STA_SYSBTNUSE = 8;
STA_MAX = 8;
WTI_DEFCONTEXT = 3;
WTI_DEFSYSCTX = 4;
WTI_DDCTXS = 400; // 1.1
WTI_DSCTXS = 500; // 1.1
CTX_NAME = 1;
CTX_OPTIONS = 2;
CTX_STATUS = 3;
CTX_LOCKS = 4;
CTX_MSGBASE = 5;
CTX_DEVICE = 6;
CTX_PKTRATE = 7;
CTX_PKTDATA = 8;
CTX_PKTMODE = 9;
CTX_MOVEMASK = 10;
CTX_BTNDNMASK = 11;
CTX_BTNUPMASK = 12;
CTX_INORGX = 13;
CTX_INORGY = 14;
CTX_INORGZ = 15;
CTX_INEXTX = 16;
CTX_INEXTY = 17;
CTX_INEXTZ = 18;
CTX_OUTORGX = 19;
CTX_OUTORGY = 20;
CTX_OUTORGZ = 21;
CTX_OUTEXTX = 22;
CTX_OUTEXTY = 23;
CTX_OUTEXTZ = 24;
CTX_SENSX = 25;
CTX_SENSY = 26;
CTX_SENSZ = 27;
CTX_SYSMODE = 28;
CTX_SYSORGX = 29;
CTX_SYSORGY = 30;
CTX_SYSEXTX = 31;
CTX_SYSEXTY = 32;
CTX_SYSSENSX = 33;
CTX_SYSSENSY = 34;
CTX_MAX = 34;
WTI_DEVICES = 100;
DVC_NAME = 1;
DVC_HARDWARE = 2;
DVC_NCSRTYPES = 3;
DVC_FIRSTCSR = 4;
DVC_PKTRATE = 5;
DVC_PKTDATA = 6;
DVC_PKTMODE = 7;
DVC_CSRDATA = 8;
DVC_XMARGIN = 9;
DVC_YMARGIN = 10;
DVC_ZMARGIN = 11;
DVC_X = 12;
DVC_Y = 13;
DVC_Z = 14;
DVC_NPRESSURE = 15;
DVC_TPRESSURE = 16;
DVC_ORIENTATION = 17;
DVC_ROTATION = 18; // 1.1
DVC_PNPID = 19; // 1.1
DVC_MAX = 19;
WTI_CURSORS = 200;
CSR_NAME = 1;
CSR_ACTIVE = 2;
CSR_PKTDATA = 3;
CSR_BUTTONS = 4;
CSR_BUTTONBITS = 5;
CSR_BTNNAMES = 6;
CSR_BUTTONMAP = 7;
CSR_SYSBTNMAP = 8;
CSR_NPBUTTON = 9;
CSR_NPBTNMARKS = 10;
CSR_NPRESPONSE = 11;
CSR_TPBUTTON = 12;
CSR_TPBTNMARKS = 13;
CSR_TPRESPONSE = 14;
CSR_PHYSID = 15; // 1.1
CSR_MODE = 16; // 1.1
CSR_MINPKTDATA = 17; // 1.1
CSR_MINBUTTONS = 18; // 1.1
CSR_CAPABILITIES = 19; // 1.1
CSR_MAX = 19;
WTI_EXTENSIONS = 300;
EXT_NAME = 1;
EXT_TAG = 2;
EXT_MASK = 3;
EXT_SIZE = 4;
EXT_AXES = 5;
EXT_DEFAULT = 6;
EXT_DEFCONTEXT = 7;
EXT_DEFSYSCTX = 8;
EXT_CURSORS = 9;
EXT_MAX = 109; // Allow 100 cursors
// Context data defs
const
LCNAMELEN = 40;
LC_NAMELEN = 40;
// context option values
CXO_SYSTEM = $0001; // the context is a system cursor context
CXO_PEN = $0002; // the context is a PenWin context, also a system cursor context
CXO_MESSAGES = $0004; // the context sends WT_PACKET messages to its owner
CXO_MARGIN = $8000; // the margin is an area outside the input area where events will be mapped to the edge of the input area
CXO_MGNINSIDE = $4000; // the margin will be inside the specified context
CXO_CSRMESSAGES = $0008; // 1.1 sends WT_CSRCHANGE messages
// context status values
CXS_DISABLED = $0001;
CXS_OBSCURED = $0002;
CXS_ONTOP = $0004;
// context lock values
CXL_INSIZE = $0001; // the context's input size cannot be changed
CXL_INASPECT = $0002; // the context's input aspect ratio cannot be changed
CXL_SENSITIVITY = $0004; // the context's sensitivity settings for x, y, and z cannot be changed
CXL_MARGIN = $0008; // the context's margin options cannot be changed
CXL_SYSOUT = $0010; // If the context is a system cursor context, the value specifies that the system pointing control variables of the context cannot be changed
type
LOGCONTEXT = record
lcName: array[0..LCNAMELEN-1] of char; // context name string
lcOptions, // unsupported option will cause WTOpen to fail
lcStatus,
lcLocks, // specify attributes of the context that cannot be changed once the context has been opened
lcMsgBase,
lcDevice, // device whose input the context processes
lcPktRate: cardinal; // desired packet report rate in Hertz. returns the actual report rate.
lcPktData, // which optional data items will be in packets. unsupported items will cause WTOpen to fail.
lcPktMode, // whether the packet data items will be returned in absolute or relative mode
lcMoveMask: WTPKT; // which packet data items can generate move events in the context
lcBtnDnMask, // buttons for which button press events will be processed in the context
lcBtnUpMask: Longword; // buttons for which button release events will be processed in the context
lcInOrgX,
lcInOrgY,
lcInOrgZ, // origin of the context's input area in the tablet's native coordinates
lcInExtX,
lcInExtY,
lcInExtZ, // extent of the context's input area in the tablet's native coordinates
lcOutOrgX,
lcOutOrgY,
lcOutOrgZ, // origin of the context's output area in context output coordinates, absolute mode only
lcOutExtX,
lcOutExtY,
lcOutExtZ: LongInt; // extent of the context's output area in context output coordinates, absolute mode only
lcSensX,
lcSensY,
lcSensZ: FIX32; // specifies the relative-mode sensitivity factor
lcSysMode: LongBool; // system cursor tracking mode. Zero specifies absolute; non-zero means relative
lcSysOrgX,
lcSysOrgY, // the origin of the screen mapping area for system cursor tracking, in screen coordinates
lcSysExtX,
lcSysExtY: integer; // the extent of the screen mapping area for system cursor tracking, in screen coordinates
lcSysSensX,
lcSysSensY: FIX32; // specifies the system-cursor relative-mode sensitivity factor for the x and y axes
end;
PLOGCONTEXT = ^LOGCONTEXT;
// Event data defs
const // packet status values
TPS_PROXIMITY = $0001;
TPS_QUEUE_ERR = $0002;
TPS_MARGIN = $0004;
TPS_GRAB = $0008;
TPS_INVERT = $0010; // 1.1
type
ORIENTATION = record
orAzimuth: integer;
orAltitude: integer;
orTwist: integer;
end;
PORIENTATION = ^ORIENTATION;
ROTATION = record // 1.1
roPitch: integer;
roRoll: integer;
roYaw: integer;
end;
PROTATION = ^ROTATION;
const // relative buttons
TBN_NONE = 0;
TBN_UP = 1;
TBN_DOWN = 2;
// device config constants
const
WTDC_NONE = 0;
WTDC_CANCEL = 1;
WTDC_OK = 2;
WTDC_RESTART = 3;
// PREFERENCE FUNCTION CONSTANTS
const
WTP_LPDEFAULT: Pointer = Pointer(-1);
WTP_DWDEFAULT: Longword = Longword(-1);
// functions
var
// Used to read various pieces of information about the tablet.
WTInfo: function (wCategory, nIndex: Cardinal; lpOutput: Pointer): Cardinal; stdcall;
// Used to begin accessing the Tablet.
WTOpen: function (hw: HWnd; var lc: LOGCONTEXT; fEnable: LongBool): HCTX; stdcall;
// Fills the supplied structure with the current context attributes for the passed handle.
WTGet: function (hc: HCTX; var lc: LOGCONTEXT): LongBool; stdcall;
// Allows some of the context's attributes to be changed on the fly.
WTSet: function (hc: HCTX; const lc: LOGCONTEXT): LongBool; stdcall;
// Used to end accessing the Tablet.
WTClose: function (hc: HCTX): LongBool; stdcall;
// Used to poll the Tablet for input.
WTPacketsGet: function (hc: HCTX; cMaxPackets: Integer; lpPkts: Pointer): Integer; stdcall;
// Similar to WTPacketsGet but is used in a window function.
WTPacket: function (hc: HCTX; wSerial: Cardinal; lpPkts: Pointer): LongBool; stdcall;
// Visibility Functions
// Enables and Disables a Tablet Context, temporarily turning on or off the processing of packets.
WTEnable: function (hc: HCTX; fEnable: LongBool): LongBool; stdcall;
// Sends a tablet context to the top or bottom of the order of overlapping tablet contexts.
WTOverlap: function (hc: HCTX; fToTop: LongBool): LongBool; stdcall;
// Context Editing Functions
// Used to call a requestor which aids in configuring the Tablet
WTConfig: function (hc: HCTX; hw: HWnd): LongBool; stdcall;
WTExtGet: function (hc: HCTX; wExt: cardinal; lpData: Pointer): LongBool; stdcall;
WTExtSet: function (hc: HCTX; wExt: cardinal; lpData: Pointer): LongBool; stdcall;
// Fills the supplied buffer with binary save information that can be used to restore the equivalent context in a subsequent Windows session.
WTSave: function (hc: HCTX; lpSaveInfo: Pointer): LongBool; stdcall;
// Creates a tablet context from the save information returned from the WTSave function.
WTRestore: function (hw: HWnd; lpSaveInfo: Pointer; fEnable: LongBool): HCTX; stdcall;
// Advanced Packet and Queue Functions
WTPacketsPeek: function (hc: HCTX; cMaxPackets: Integer; lpPkts: Pointer): Integer; stdcall;
WTDataGet: function (hc: HCTX; wBegin, wEnding: cardinal; cMaxPackets: Integer; lpPkts: Pointer; var lpNPkts: Integer): Integer; stdcall;
WTDataPeek: function (hc: HCTX; wBegin, wEnding: cardinal; cMaxPackets: Integer; lpPkts: Pointer; var lpNPkts: Integer): Integer; stdcall;
// Returns the serial numbers of the oldest and newest packets currently in the queue.
WTQueuePacketsEx: function (hc: HCTX; var lpOld, lpNew: cardinal): LongBool; stdcall;
WTQueueSizeGet: function (hc: HCTX): Integer; stdcall;
WTQueueSizeSet: function (hc: HCTX; nPkts: Integer): LongBool; stdcall;
function IsWinTab32Available: boolean;
implementation
var lib: THandle;
function IsWinTab32Available: boolean;
begin
result := lib <> 0;
end;
function LoadWinTab32: boolean;
begin
result := true;
if lib <> 0 then Exit;
lib := LoadLibrary('wintab32.dll');
if lib = 0 then
begin
result := false;
Exit;
end;
WTInfo := GetProcAddress(lib, 'WTInfoA');
WTOpen := GetProcAddress(lib, 'WTOpenA');
WTClose := GetProcAddress(lib, 'WTClose');
WTPacketsGet := GetProcAddress(lib, 'WTPacketsGet');
WTPacket := GetProcAddress(lib, 'WTPacket');
WTEnable := GetProcAddress(lib, 'WTEnable');
WTOverlap := GetProcAddress(lib, 'WTOverlap');
WTConfig := GetProcAddress(lib, 'WTConfig');
WTGet := GetProcAddress(lib, 'WTGetA');
WTSet := GetProcAddress(lib, 'WTSetA');
WTExtGet := GetProcAddress(lib, 'WTExtGet');
WTExtSet := GetProcAddress(lib, 'WTExtSet');
WTSave := GetProcAddress(lib, 'WTSave');
WTRestore := GetProcAddress(lib, 'WTRestore');
WTPacketsPeek := GetProcAddress(lib, 'WTPacketsPeek');
WTDataGet := GetProcAddress(lib, 'WTDataGet');
WTDataPeek := GetProcAddress(lib, 'WTDataPeek');
WTQueuePacketsEx := GetProcAddress(lib, 'WTQueuePacketsEx');
WTQueueSizeGet := GetProcAddress(lib, 'WTQueueSizeGet');
WTQueueSizeSet := GetProcAddress(lib, 'WTQueueSizeSet');
end;
procedure UnloadWinTab32;
begin
if lib <> 0 then
begin
FreeLibrary(lib);
lib := 0;
WTInfo := nil;
WTOpen := nil;
WTClose := nil;
WTPacketsGet := nil;
WTPacket := nil;
WTEnable := nil;
WTOverlap := nil;
WTConfig := nil;
WTGet := nil;
WTSet := nil;
WTExtGet := nil;
WTExtSet := nil;
WTSave := nil;
WTRestore := nil;
WTPacketsPeek := nil;
WTDataGet := nil;
WTDataPeek := nil;
WTQueuePacketsEx := nil;
WTQueueSizeGet := nil;
WTQueueSizeSet := nil;
end;
end;
initialization
LoadWinTab32;
finalization
UnloadWinTab32;
end.
|
unit Form.Animation;
interface
uses
UCL.IntAnimation, UCL.IntAnimation.Helpers,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TformAnimation = class(TForm)
buttonAni: TButton;
buttonStartWithHelper: TButton;
buttonStartAnimation: TButton;
radiogroupAniKind: TRadioGroup;
radiogroupAniFunction: TRadioGroup;
groupCustomAniOptions: TGroupBox;
editStep: TLabeledEdit;
editDuration: TLabeledEdit;
editStartValue: TLabeledEdit;
editDeltaValue: TLabeledEdit;
buttonResetPosition: TButton;
procedure buttonStartAnimationClick(Sender: TObject);
procedure buttonStartWithHelperClick(Sender: TObject);
procedure buttonResetPositionClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
formAnimation: TformAnimation;
implementation
{$R *.dfm}
procedure TformAnimation.buttonStartWithHelperClick(Sender: TObject);
begin
buttonAni.AnimationFromCurrent(apTop, +100, 35, 400, akOut, afkBounce,
procedure begin buttonAni.SetFocus end);
end;
procedure TformAnimation.buttonResetPositionClick(Sender: TObject);
begin
buttonAni.Top := 20;
buttonAni.Left := 20;
end;
procedure TformAnimation.buttonStartAnimationClick(Sender: TObject);
var
Ani: TIntAni;
begin
Ani := TIntAni.Create(true, akIn, afkLinear, 20, +300,
procedure (V: Integer)
begin
buttonAni.Left:= V;
end);
Ani.AniKind := TAniKind(radiogroupAniKind.ItemIndex);
Ani.AniFunctionKind := TAniFunctionKind(radiogroupAniFunction.ItemIndex);
Ani.Step := StrToIntDef(editStep.Text, 25);
Ani.Duration := StrToIntDef(editDuration.Text, 250);
Ani.StartValue := StrToIntDef(editStartValue.Text, 20);
Ani.DeltaValue := StrToIntDef(editDeltaValue.Text, +300);
Ani.Start;
end;
end.
|
unit nsQuestionsWithChoices;
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Data\nsQuestionsWithChoices.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "nsQuestionsWithChoices" MUID: (4F9BB14900E7)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
l3IntfUses
, l3StringIDEx
, l3MessageID
;
const
{* Локализуемые строки Questions }
str_ChangedDocumentOnControl_SettingsCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangedDocumentOnControl_SettingsCaption'; rValue : 'Действие при выборе измененного документа на контроле');
{* 'Действие при выборе измененного документа на контроле' }
str_ChangedDocumentOnControl: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'ChangedDocumentOnControl'; rValue : 'В документ на контроле внесены изменения. Выберите действие:');
{* 'В документ на контроле внесены изменения. Выберите действие:' }
str_SearchUnresolvedContext: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'SearchUnresolvedContext'; rValue : 'В запросе есть слова, поиск по которым может не дать корректного результата: {color:Red}{italic:true}%s{italic}{color}.');
{* 'В запросе есть слова, поиск по которым может не дать корректного результата: [color:Red][italic:true]%s[italic][color].' }
str_DropListToList: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'DropListToList'; rValue : 'Выделенные элементы:');
{* 'Выделенные элементы:' }
str_mtNotGarantDomain: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'mtNotGarantDomain'; rValue : 'Переход по внешней ссылке');
{* 'Переход по внешней ссылке' }
str_EmptySearchResultInBaseList: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'EmptySearchResultInBaseList'; rValue : 'Поиск в базовом (сокращенном) списке не дал результатов по заданному Вами запросу. Выберите варианты для продолжения работы:');
{* 'Поиск в базовом (сокращенном) списке не дал результатов по заданному Вами запросу. Выберите варианты для продолжения работы:' }
str_AutologinDuplicate: Tl3MessageID = (rS : -1; rLocalized : false; rKey : 'AutologinDuplicate'; rValue : 'Пользователь с таким именем уже существует. Сделайте выбор:');
{* 'Пользователь с таким именем уже существует. Сделайте выбор:' }
implementation
uses
l3ImplUses
{$If NOT Defined(NoVCL)}
, Dialogs
{$IfEnd} // NOT Defined(NoVCL)
//#UC START# *4F9BB14900E7impl_uses*
//#UC END# *4F9BB14900E7impl_uses*
;
const
{* Варианты выбора для диалога ChangedDocumentOnControl }
str_ChangedDocumentOnControl_Choice_Open: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangedDocumentOnControl_Choice_Open'; rValue : 'Открыть текст документа');
{* 'Открыть текст документа' }
str_ChangedDocumentOnControl_Choice_Compare: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangedDocumentOnControl_Choice_Compare'; rValue : 'Сравнить с предыдущей редакцией');
{* 'Сравнить с предыдущей редакцией' }
{* Варианты выбора для диалога SearchUnresolvedContext }
str_SearchUnresolvedContext_Choice_Back: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'SearchUnresolvedContext_Choice_Back'; rValue : 'Вернуться в карточку и отредактировать запрос');
{* 'Вернуться в карточку и отредактировать запрос' }
str_SearchUnresolvedContext_Choice_Continue: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'SearchUnresolvedContext_Choice_Continue'; rValue : 'Продолжить поиск');
{* 'Продолжить поиск' }
{* Варианты выбора для диалога DropListToList }
str_DropListToList_Choice_Append: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DropListToList_Choice_Append'; rValue : 'Добавить в существующий список');
{* 'Добавить в существующий список' }
str_DropListToList_Choice_Copy: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'DropListToList_Choice_Copy'; rValue : 'Копировать в новый список');
{* 'Копировать в новый список' }
{* Варианты выбора для диалога mtNotGarantDomain }
str_mtNotGarantDomain_Choice_Open: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'mtNotGarantDomain_Choice_Open'; rValue : 'Перейти, открыв во внешнем браузере ');
{* 'Перейти, открыв во внешнем браузере ' }
str_mtNotGarantDomain_Choice_Stay: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'mtNotGarantDomain_Choice_Stay'; rValue : 'Не переходить');
{* 'Не переходить' }
{* Варианты выбора для диалога EmptySearchResultInBaseList }
str_EmptySearchResultInBaseList_Choice_Expand: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'EmptySearchResultInBaseList_Choice_Expand'; rValue : 'расширить базовый список до полного и произвести поиск в нем');
{* 'расширить базовый список до полного и произвести поиск в нем' }
str_EmptySearchResultInBaseList_Choice_AllBase: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'EmptySearchResultInBaseList_Choice_AllBase'; rValue : 'произвести поиск по всему информационному банку');
{* 'произвести поиск по всему информационному банку' }
{* Варианты выбора для диалога AutologinDuplicate }
str_AutologinDuplicate_Choice_Back: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'AutologinDuplicate_Choice_Back'; rValue : 'вернуться к регистрации нового пользователя, изменив регистрационные данные');
{* 'вернуться к регистрации нового пользователя, изменив регистрационные данные' }
str_AutologinDuplicate_Choice_Login: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'AutologinDuplicate_Choice_Login'; rValue : 'войти в систему с указанными регистрационными данными, использовав введенное имя пользователя');
{* 'войти в систему с указанными регистрационными данными, использовав введенное имя пользователя' }
initialization
str_ChangedDocumentOnControl_SettingsCaption.Init;
{* Инициализация str_ChangedDocumentOnControl_SettingsCaption }
str_ChangedDocumentOnControl.Init;
str_ChangedDocumentOnControl.AddChoice(str_ChangedDocumentOnControl_Choice_Open);
str_ChangedDocumentOnControl.AddChoice(str_ChangedDocumentOnControl_Choice_Compare);
str_ChangedDocumentOnControl.SetSettingsCaption(str_ChangedDocumentOnControl_SettingsCaption);
str_ChangedDocumentOnControl.SetDlgType(mtConfirmation);
{* Инициализация str_ChangedDocumentOnControl }
str_SearchUnresolvedContext.Init;
str_SearchUnresolvedContext.AddChoice(str_SearchUnresolvedContext_Choice_Back);
str_SearchUnresolvedContext.AddChoice(str_SearchUnresolvedContext_Choice_Continue);
str_SearchUnresolvedContext.SetDlgType(mtConfirmation);
{* Инициализация str_SearchUnresolvedContext }
str_DropListToList.Init;
str_DropListToList.AddChoice(str_DropListToList_Choice_Append);
str_DropListToList.AddChoice(str_DropListToList_Choice_Copy);
str_DropListToList.SetDlgType(mtConfirmation);
{* Инициализация str_DropListToList }
str_mtNotGarantDomain.Init;
str_mtNotGarantDomain.AddChoice(str_mtNotGarantDomain_Choice_Open);
str_mtNotGarantDomain.AddChoice(str_mtNotGarantDomain_Choice_Stay);
str_mtNotGarantDomain.SetDlgType(mtConfirmation);
{* Инициализация str_mtNotGarantDomain }
str_EmptySearchResultInBaseList.Init;
str_EmptySearchResultInBaseList.AddChoice(str_EmptySearchResultInBaseList_Choice_Expand);
str_EmptySearchResultInBaseList.AddChoice(str_EmptySearchResultInBaseList_Choice_AllBase);
str_EmptySearchResultInBaseList.SetDlgType(mtConfirmation);
{* Инициализация str_EmptySearchResultInBaseList }
str_AutologinDuplicate.Init;
str_AutologinDuplicate.AddChoice(str_AutologinDuplicate_Choice_Back);
str_AutologinDuplicate.AddChoice(str_AutologinDuplicate_Choice_Login);
str_AutologinDuplicate.SetDlgType(mtWarning);
{* Инициализация str_AutologinDuplicate }
str_ChangedDocumentOnControl_Choice_Open.Init;
{* Инициализация str_ChangedDocumentOnControl_Choice_Open }
str_ChangedDocumentOnControl_Choice_Compare.Init;
{* Инициализация str_ChangedDocumentOnControl_Choice_Compare }
str_SearchUnresolvedContext_Choice_Back.Init;
{* Инициализация str_SearchUnresolvedContext_Choice_Back }
str_SearchUnresolvedContext_Choice_Continue.Init;
{* Инициализация str_SearchUnresolvedContext_Choice_Continue }
str_DropListToList_Choice_Append.Init;
{* Инициализация str_DropListToList_Choice_Append }
str_DropListToList_Choice_Copy.Init;
{* Инициализация str_DropListToList_Choice_Copy }
str_mtNotGarantDomain_Choice_Open.Init;
{* Инициализация str_mtNotGarantDomain_Choice_Open }
str_mtNotGarantDomain_Choice_Stay.Init;
{* Инициализация str_mtNotGarantDomain_Choice_Stay }
str_EmptySearchResultInBaseList_Choice_Expand.Init;
{* Инициализация str_EmptySearchResultInBaseList_Choice_Expand }
str_EmptySearchResultInBaseList_Choice_AllBase.Init;
{* Инициализация str_EmptySearchResultInBaseList_Choice_AllBase }
str_AutologinDuplicate_Choice_Back.Init;
{* Инициализация str_AutologinDuplicate_Choice_Back }
str_AutologinDuplicate_Choice_Login.Init;
{* Инициализация str_AutologinDuplicate_Choice_Login }
end.
|
{-----------------------------------------------------------------------------
Unit Name: bfcore
Author: Sebastian Huetter
Date: 2007-04-08
Purpose: Core for Brainfuck. OOP here too ;)
NOTE: define FULL_OOP in Project Options to be able to assign
events to object methods!
History: 2007-04-08 initial release
[BenBE]: fixed loop issue
------------------------------------------------------------------------------
Copyright Notice: If you copy or modify this file, this block
_must_ be preserved! If you are using this code in your projects,
I would like to see a word of thanks in the About-Box or a similar place.
-----------------------------------------------------------------------------}
unit bfcore;
interface
type
TTape = array of smallint;
TStack = array of word;
TWriteEv = procedure (C:char) {$IFDEF FULL_OOP}of object{$ENDIF};
TReadNumEv = procedure (var n:word) {$IFDEF FULL_OOP}of object{$ENDIF};
TReadChrEv = procedure (var c:char) {$IFDEF FULL_OOP}of object{$ENDIF};
TStepEv = procedure (const programm:string; const prg:word; const Daten: TTape;
const ptr:word; const Stack: TStack) {$IFDEF FULL_OOP}of object{$ENDIF};
TBF = class
tmp,programm:string;
Daten: TTape;
Stack:TStack;
ptr,prg:word;
private
FOnReadChr: TReadChrEv;
FOnReadNum: TReadNumEv;
FOnWrite: TWriteEv;
FOnBeforeStep,
FOnAfterStep: TStepEv;
FCycle: integer;
{$IFDEF FULL_OOP}
procedure ReadChrEv(var c: char);
procedure ReadNumEv(var n: word);
procedure WriteEv(C: char);
{$ENDIF}
public
constructor Create;
procedure Init(APrg:string);
procedure InitFromFile(AFile:string);
procedure Run;
procedure Step;
property OnWrite : TWriteEv read FOnWrite write FOnWrite;
property OnReadNum : TReadNumEv read FOnReadNum write FOnReadNum;
property OnReadChr : TReadChrEv read FOnReadChr write FOnReadChr;
property OnBeforeStep: TStepEv read FOnBeforeStep write FOnBeforeStep;
property OnAfterStep: TStepEv read FOnAfterStep write FOnAfterStep;
property Cycle: integer read FCycle;
end;
const
TapeLength = 512;
BF_CODE_CHARS = ['.',',','#','[',']','>','<','+','-'];
implementation
procedure {$IFDEF FULL_OOP}TBF.{$ENDIF}WriteEv (C:char);
begin
Write(C);
end;
procedure {$IFDEF FULL_OOP}TBF.{$ENDIF}ReadNumEv (var n:word);
begin
Readln(n);
end;
procedure {$IFDEF FULL_OOP}TBF.{$ENDIF}ReadChrEv (var c:char);
begin
ReadLn(C);
end;
{ TBF }
constructor TBF.Create;
begin
FOnReadChr:= ReadChrEv;
FOnReadNum:= ReadNumEv;
FOnWrite:= WriteEv;
Init('');
end;
procedure TBF.Init(APrg: string);
begin
Setlength(Daten,TapeLength*2+1);
Fillchar(Daten[0],length(Daten)*sizeof(word),0);
Setlength(Stack,0);
ptr:= TapeLength;
prg:= 1;
FCycle:= 0;
programm:= APrg;
end;
procedure TBF.InitFromFile(AFile: string);
var f:TextFile;
s,p:string;
begin
Assign(F,AFile);
Reset(F);
p:= '';
while not EOF(F) do begin
Readln(F,s);
p:= p + S + #13#10;
end;
CloseFile(F);
Init(P);
end;
procedure TBF.Run;
begin
while prg<=length(programm) do begin
Step;
end;
end;
procedure TBF.Step;
var
i,j:word;
c:char;
begin
while (prg<=length(programm)) and // search for good code
not (programm[prg] in BF_CODE_CHARS) do
inc(prg);
if prg>length(programm) then exit; // nothing / end
inc(FCycle);
if @FOnBeforeStep<>nil then
FOnBeforeStep(programm,prg, Daten, ptr, Stack);
case programm[prg] of
'>' : if ptr<TapeLength shl 1 then inc(ptr);
'<' : if ptr>0 then dec(ptr);
'+' : inc(Daten[ptr]);
'-' : dec(Daten[ptr]);
'.' : FOnWrite(chr(Daten[ptr]));
',' : begin
FOnReadChr(c);
Daten[ptr]:= ord(c);
end;
'#' : begin
FOnReadNum(j);
Daten[ptr]:= j;
end;
'[' : begin
Setlength(Stack,length(Stack)+1);
Stack[high(Stack)]:= prg;
if Daten[ptr]=0 then begin
j:= 0;
for i:= prg to length(programm) do begin
case programm[i] of
'[' : inc(j);
']' : begin
dec(j);
if j=0 then begin
prg:= i;
Setlength(Stack,length(Stack)-1);
break;
end;
end;
end;
end;
end;
end;
']' : begin
if length(Stack)>0 then begin
if Daten[ptr]<>0 then
prg:= Stack[high(Stack)]-1;
Setlength(Stack,length(Stack)-1);
end;
end;
end;
inc(prg);
if @FOnAfterStep<>nil then
FOnAfterStep(programm,prg, Daten, ptr, Stack);
end;
end.
|
unit PE.Parser.Headers;
interface
uses
System.Classes,
PE.Common,
PE.Types.DOSHeader,
PE.Types.FileHeader,
PE.Types.OptionalHeader,
PE.Types.NTHeaders,
PE.Utils;
function LoadDosHeader(AStream: TStream; out AHdr: TImageDOSHeader): boolean;
function LoadFileHeader(AStream: TStream; out AHdr: TImageFileHeader): boolean; inline;
implementation
function LoadDosHeader;
begin
Result := StreamRead(AStream, AHdr, SizeOf(AHdr)) and AHdr.e_magic.IsMZ;
end;
function LoadFileHeader;
begin
Result := StreamRead(AStream, AHdr, SizeOf(AHdr));
end;
end.
|
unit ExtAINetClientOverbyte;
interface
uses
Classes, SysUtils, OverbyteIcsWSocket, WinSock;
// TCP client
type
TNotifyDataEvent = procedure(aData: pointer; aLength: cardinal) of object;
TNetClientOverbyte = class
private
fSocket: TWSocket;
fOnError: TGetStrProc;
fOnConnectSucceed: TNotifyEvent;
fOnConnectFailed: TGetStrProc;
fOnSessionDisconnected: TNotifyEvent;
fOnRecieveData: TNotifyDataEvent;
procedure NilEvents();
procedure Connected(Sender: TObject; Error: Word);
procedure Disconnected(Sender: TObject; Error: Word);
procedure DataAvailable(Sender: TObject; Error: Word);
procedure LogError(const aText: string; const aArgs: array of const);
public
constructor Create();
destructor Destroy(); override;
property OnError: TGetStrProc write fOnError;
property OnConnectSucceed: TNotifyEvent write fOnConnectSucceed;
property OnConnectFailed: TGetStrProc write fOnConnectFailed;
property OnSessionDisconnected: TNotifyEvent write fOnSessionDisconnected;
property OnRecieveData: TNotifyDataEvent write fOnRecieveData;
function MyIPString(): String;
function SendBufferEmpty(): Boolean;
procedure ConnectTo(const aAddress: String; const aPort: Word);
procedure Disconnect();
procedure SendData(aData: pointer; aLength: Cardinal);
end;
implementation
constructor TNetClientOverbyte.Create();
var
wsaData: TWSAData;
begin
Inherited Create;
fSocket := nil;
NilEvents();
Assert(WSAStartup($101, wsaData) = 0, 'Error in Network');
end;
destructor TNetClientOverbyte.Destroy();
begin
NilEvents(); // Disable callbacks before destroying socket (the app is terminating, callbacks do not have to work anymore)
fSocket.Free;
Inherited;
end;
procedure TNetClientOverbyte.NilEvents();
begin
fOnError := nil;
fOnConnectSucceed := nil;
fOnConnectFailed := nil;
fOnSessionDisconnected := nil;
fOnRecieveData := nil;
end;
function TNetClientOverbyte.MyIPString(): String;
begin
Result := '';
if (LocalIPList.Count >= 1) then
Result := LocalIPList[0]; // First address should be ours
end;
procedure TNetClientOverbyte.ConnectTo(const aAddress: String; const aPort: Word);
begin
FreeAndNil(fSocket);
fSocket := TWSocket.Create(nil);
fSocket.ComponentOptions := [wsoTcpNoDelay]; // Send packets ASAP (disables Nagle's algorithm)
fSocket.Proto := 'tcp';
fSocket.Addr := aAddress;
fSocket.Port := IntToStr(aPort);
fSocket.OnSessionClosed := Disconnected;
fSocket.OnSessionConnected := Connected;
fSocket.OnDataAvailable := DataAvailable;
try
fSocket.Connect;
except
on E: Exception do
begin
// Trap the exception and tell the user. Note: While debugging, Delphi will still stop execution for the exception, but normally the dialouge won't show.
if Assigned(fOnConnectFailed) then
fOnConnectFailed(E.Message);
end;
end;
end;
procedure TNetClientOverbyte.Disconnect();
begin
if (fSocket <> nil) then
begin
fOnRecieveData := nil;
// ShutDown(1) Works better, then Close or CloseDelayed
// With Close or CloseDelayed some data, that were sent just before disconnection could not be delivered to server.
// F.e. mkDisconnect packet
// But we can't send data into ShutDown'ed socket (we could try into Closed one, since it will have State wsClosed)
fSocket.ShutDown(1);
end;
end;
procedure TNetClientOverbyte.LogError(const aText: string; const aArgs: array of const);
begin
if Assigned(fOnError) then
fOnError(Format(aText,aArgs));
end;
procedure TNetClientOverbyte.SendData(aData: pointer; aLength: Cardinal);
begin
if (fSocket <> nil) AND (fSocket.State = wsConnected) then // Sometimes this occurs just before disconnect/reconnect
fSocket.Send(aData, aLength);
end;
function TNetClientOverbyte.SendBufferEmpty(): Boolean;
begin
Result := True;
if (fSocket <> nil) AND (fSocket.State = wsConnected) then
Result := fSocket.AllSent;
end;
procedure TNetClientOverbyte.Connected(Sender: TObject; Error: Word);
begin
if (Error <> 0) then
LogError('Error: %s (#%d)',[WSocketErrorDesc(Error), Error])
else
begin
if Assigned(fOnConnectSucceed) then
fOnConnectSucceed(Self);
fSocket.SetTcpNoDelayOption; // Send packets ASAP (disables Nagle's algorithm)
fSocket.SocketSndBufSize := 65535; // WinSock buffer should be bigger than internal buffer
fSocket.BufSize := 32768;
end;
end;
procedure TNetClientOverbyte.Disconnected(Sender: TObject; Error: Word);
begin
// Do not exit on error, because when a disconnect error occurs, the client has still disconnected
if (Error <> 0) then
LogError('Client: Disconnection error: %s (#%d)',[WSocketErrorDesc(Error), Error]);
if Assigned(fOnSessionDisconnected) then
fOnSessionDisconnected(Self);
end;
procedure TNetClientOverbyte.DataAvailable(Sender: TObject; Error: Word);
const
BufferSize = 10240; // 10kb
var
P: Pointer;
L: Integer;
begin
if (Error <> 0) then
LogError('DataAvailable. Error %s (#%d)',[WSocketErrorDesc(Error), Error])
else
begin
GetMem(P, BufferSize+1); //+1 to avoid RangeCheckError when L = BufferSize
L := TWSocket(Sender).Receive(P, BufferSize);
// L could be -1 when no data is available
if (L > 0) AND Assigned(fOnRecieveData) then
fOnRecieveData(P, Cardinal(L)) // The pointer is stored in ExtAINetClient and the memory will be freed later
else
FreeMem(P); // The pointer is NOT used and must be freed
end;
end;
end.
|
unit OutputSrch_TLB;
{ This file contains pascal declarations imported from a type library.
This file will be written during each import or refresh of the type
library editor. Changes to this file will be discarded during the
refresh process. }
{ OutputSrch Library }
{ Version 1.0 }
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
const
LIBID_OutputSrch: TGUID = '{48DB8B20-6705-11D1-A1A8-955D74A3A3E2}';
const
{ Component class GUIDs }
Class_OutputSearch: TGUID = '{48DB8B22-6705-11D1-A1A8-955D74A3A3E2}';
type
{ Forward declarations: Interfaces }
IOutputSearch = interface;
IOutputSearchDisp = dispinterface;
{ Forward declarations: CoClasses }
OutputSearch = IOutputSearch;
{ Dispatch interface for OutputSearch Object }
IOutputSearch = interface(IDispatch)
['{48DB8B21-6705-11D1-A1A8-955D74A3A3E2}']
procedure Search(const Output, World, Town, Company: WideString; Count, X, Y: Integer); safecall;
function Get_Count: Integer; safecall;
function Get_X(row: Integer): Integer; safecall;
function Get_Y(row: Integer): Integer; safecall;
function Get_K(row: Integer): Integer; safecall;
function Get_P(row: Integer): Single; safecall;
function Get_C(row: Integer): Single; safecall;
function Get_Town(row: Integer): WideString; safecall;
function Get_Company(row: Integer): WideString; safecall;
function Get_Utility(row: Integer): WideString; safecall;
function Get_SortMode: Integer; safecall;
procedure Set_SortMode(Value: Integer); safecall;
function Get_Role: Integer; safecall;
procedure Set_Role(Value: Integer); safecall;
function Get_Circuits: WideString; safecall;
procedure Set_Circuits(const Value: WideString); safecall;
function Get_Connected(index: Integer): WordBool; safecall;
property Count: Integer read Get_Count;
property X[row: Integer]: Integer read Get_X;
property Y[row: Integer]: Integer read Get_Y;
property K[row: Integer]: Integer read Get_K;
property P[row: Integer]: Single read Get_P;
property C[row: Integer]: Single read Get_C;
property Town[row: Integer]: WideString read Get_Town;
property Company[row: Integer]: WideString read Get_Company;
property Utility[row: Integer]: WideString read Get_Utility;
property SortMode: Integer read Get_SortMode write Set_SortMode;
property Role: Integer read Get_Role write Set_Role;
property Circuits: WideString read Get_Circuits write Set_Circuits;
property Connected[index: Integer]: WordBool read Get_Connected;
end;
{ DispInterface declaration for Dual Interface IOutputSearch }
IOutputSearchDisp = dispinterface
['{48DB8B21-6705-11D1-A1A8-955D74A3A3E2}']
procedure Search(const Output, World, Town, Company: WideString; Count, X, Y: Integer); dispid 1;
property Count: Integer readonly dispid 2;
property X[row: Integer]: Integer readonly dispid 3;
property Y[row: Integer]: Integer readonly dispid 4;
property K[row: Integer]: Integer readonly dispid 5;
property P[row: Integer]: Single readonly dispid 6;
property C[row: Integer]: Single readonly dispid 7;
property Town[row: Integer]: WideString readonly dispid 8;
property Company[row: Integer]: WideString readonly dispid 9;
property Utility[row: Integer]: WideString readonly dispid 10;
property SortMode: Integer dispid 11;
property Role: Integer dispid 13;
property Circuits: WideString dispid 14;
property Connected[index: Integer]: WordBool readonly dispid 15;
end;
{ OutputSearchObject }
CoOutputSearch = class
class function Create: IOutputSearch;
class function CreateRemote(const MachineName: string): IOutputSearch;
end;
implementation
uses ComObj;
class function CoOutputSearch.Create: IOutputSearch;
begin
Result := CreateComObject(Class_OutputSearch) as IOutputSearch;
end;
class function CoOutputSearch.CreateRemote(const MachineName: string): IOutputSearch;
begin
Result := CreateRemoteComObject(MachineName, Class_OutputSearch) as IOutputSearch;
end;
end.
|
unit GenericExampleUnit;
interface
uses SysUtils, BaseExampleUnit, IConnectionUnit;
type
TGenericExample = class(TBaseExample)
public
procedure Execute(Connection: IConnection);
end;
implementation
uses Route4MeManagerUnit, GenericParametersUnit, DataObjectUnit, SettingsUnit;
procedure TGenericExample.Execute(Connection: IConnection);
var
Parameters: TGenericParameters;
DataObjects: TDataObjectRouteList;
Route: TDataObjectRoute;
Uri: String;
Route4Me: TRoute4MeManager;
ErrorMessage: String;
begin
Route4Me := TRoute4MeManager.Create(Connection);
try
Parameters := TGenericParameters.Create();
try
// number of records per page
Parameters.AddParameter('limit', '10');
// the page offset starting at zero
Parameters.AddParameter('Offset', '5');
Uri := TSettings.EndPoints.Main + '/api.v4/route.php';
DataObjects := Route4Me.Connection.Get(
Uri, Parameters, TDataObjectRouteList, ErrorMessage) as TDataObjectRouteList;
try
WriteLn('');
if (DataObjects <> nil) then
begin
WriteLn(Format('GenericExample executed successfully, %d routes returned',
[DataObjects.Count]));
WriteLn('');
for Route in DataObjects do
WriteLn(Format('RouteID: %s', [Route.RouteID]));
end
else
WriteLn(Format('GenericExample error "%s"', [ErrorMessage]));
finally
FreeAndNil(DataObjects);
end;
finally
FreeAndNil(Parameters);
end;
finally
FreeAndNil(Route4Me);
end;
end;
end.
|
{ String manipulation routines.
Copyright (C) 2006 - 2012 Aleg Azarousky.
}
//VG 260717: Added ReplaceNew routine from the old Tickler sources. Can be moved to another unit
unit uStringUtils;
interface
uses Windows, Classes;
const
ListDivider = #13; // Used in DelphiToStringEx
defHumanizeDivider = '\'; // Used in StringToHumanized
defHumanizedLF = '\#10';
UnicodeLabel: array[0..2] of byte = ($EF, $BB, $BF);
// Split a string by a given divider
// Return in El - left part, in s - rest of a string
procedure SplitBy(var s: string; const divider: string; var el: string);
// Escaped string to string (based on the JEDI Code Library (JCL))
function StrEscapedToString(const S: string): string;
// Encode string to lng file string
// DividerCR - substitution for #13
// DividerCRLF - substitution for #13#10
// DividerLF - substitution for #10
function StringToLng(const s: string; Humanize: boolean; const DividerCR,
DividerCRLF, DividerLF: string): string;
// Decode lng file string to string
// DividerCR - substitution for #13
// DividerCRLF - substitution for #13#10
// DividerLF - substitution for #10
// DefaultLineBreak - used when DividerCR = DividerCRLF
function LngToString(const s: string; Humanize: boolean; const DividerCR,
DividerCRLF, DividerLF, DefaultLineBreak: string): string;
procedure ReplaceNew(var ws: String; const s: string);
implementation
uses
SysUtils, StrUtils;
procedure ReplaceNew(var ws: String; const s: string);
var
sl: TStringList;
tstr: String;
i: integer;
val: String;
begin
sl := TStringList.Create;
try
sl.Text := s;
// tstr := sl.Values[ws];
for i := 0 to sl.Count - 1 do
begin
if pos(sl.Names[i], ws) > 0 then
begin
val := sl.Values[sl.Names[i]];
tstr := StringReplace(ws, sl.Names[i], val, [rfReplaceAll, rfIgnoreCase]);
ws := tstr;
end;
end;
if tstr <> '' then
ws := tstr;
finally
sl.free;
end;
end;
{$region 'Delphi string conversions'}
procedure SplitBy(var s: string; const divider: string; var el: string);
var
i: integer;
begin
i := pos(divider, s);
if i <= 0 then begin
el := s;
s := '';
end else begin
el := copy(s, 1, i-1);
delete(s, 1, i+length(divider)-1);
end;
end;
// Encode string to delphi style string
function StringToDelphi(const s: string): string;
var
i: integer;
StrOpened: boolean;
res: string;
ch: char;
procedure SwitchStr; // '...'
begin
StrOpened := not StrOpened;
res := res + '''';
end;
begin
StrOpened := false;
if s = ''
then res := ''''''
else begin
for i := 1 to length(s) do begin
ch := s[i];
case ch of
'''': begin
if StrOpened
then res := res + ''''''
else begin
res := res + '''''''';
StrOpened := true;
end;
end;
#0..#31: begin
if StrOpened then SwitchStr;
res := res + '#' + IntToStr(ord(ch));
end;
else begin
if not StrOpened then SwitchStr;
res := res + ch;
end;
end;
end;
end;
if StrOpened then SwitchStr;
result := res;
end;
type
EDelphiToStringError = Class(Exception)
public
iBadChar: integer; // Bad character position
end;
// Decode delphi style string to string
function DelphiToString(const s: string): string;
label
Err;
var
i, iOpened: integer;
res: string;
StrOpened, CodeOpened: boolean;
ch: char;
procedure OpenStr; // '...
begin
StrOpened := true;
iOpened := i;
end;
procedure OpenCode; // #13
begin
CodeOpened := true;
iOpened := i;
end;
function CloseCode: boolean;
begin
try
res := res + char(StrToInt(copy(s, iOpened+1, i-iOpened-1)));
result := true;
CodeOpened := false;
except
result := false;
end;
end;
var
Ex: EDelphiToStringError;
begin
res := '';
StrOpened := false;
CodeOpened := false;
// 'Method ''%s'' not supported by automation object'
// 'Exception %s in module %s at %p.'#13#10'%s%s'#13#10
// '''hallo' -- 'hallo'''
// 'hal'''#13#10'lo' -- 'hallo''hallo'
for i := 1 to length(s) do begin
ch := s[i];
if StrOpened then begin
// Str opened, code closed
if ch = ''''
then StrOpened := false
else res := res + ch;
end else begin
if CodeOpened then begin
// Str closed, code opened
case ch of
'''': begin if not CloseCode then goto Err; OpenStr; end;
'#': begin if not CloseCode then goto Err; OpenCode; end;
'0'..'9':;
else goto Err;
end;
end else begin
// Str closed, code closed
case ch of
'''': begin
if (i > 1) and (s[i-1] = '''')
then res := res + '''';
OpenStr;
end;
'#': OpenCode;
else begin
result := res;
Ex := EDelphiToStringError.Create('Bad decoded string: "' + s + '"');
Ex.iBadChar := i;
raise Ex;
end;
end;
end;
end;
end;
if StrOpened then begin
Err:
raise Exception.Create('Bad decoded string: "' + s + '"');
end;
if CodeOpened then CloseCode;
result := res;
end;
// Decode delphi style string and stringlist to string
// Stringlist elements delimited by #13
function DelphiToStringEx(s: string): string;
var
res, s1: string;
procedure AddResS1;
begin
if res <> '' then
res := res + ListDivider;
res := res + S1;
end;
var
Ok: boolean;
begin
res := '';
repeat
Ok := true;
try
s1 := DelphiToString(s);
except
on E: EDelphiToStringError do begin
AddResS1;
s := Trim(copy(s, E.iBadChar+1, MaxInt));
Ok := false;
end;
end;
until Ok;
AddResS1;
result := res;
end;
{$endregion}
{$region 'Escaped string conversions'}
function StrEscapedToString(const S: string): string;
// \x041f --> wide character
procedure HandleHexEscapeSeq(const S: string; var I: integer; Len: integer; var Dest: string);
const
hexDigits = string('0123456789abcdefABCDEF');
var
startI, val, n: integer;
begin
startI := I;
val := 0;
while I < StartI + 4 do begin
n := Pos(S[I+1], hexDigits) - 1;
if n < 0 then begin
if startI = I then begin
// '\x' without hex digit following is not escape sequence
Dest := Dest + '\x';
exit;
end;
end else begin
Inc(I);
if n >= 16 then
n := n - 6;
val := val * 16 + n;
if val > Ord(High(Char)) then
raise Exception.CreateFmt('Numeric constant too large (%d) at position %d.',
[val, startI]);
end;
end;
Dest := Dest + Char(val);
end;
procedure HandleOctEscapeSeq(const S: string; var I: integer; Len: integer; var Dest: string);
const
octDigits = string('01234567');
var
startI, val, n: integer;
begin
startI := I;
// first digit
val := Pos(S[I], octDigits) - 1;
if I < Len then
begin
n := Pos(S[I + 1], octDigits) - 1;
if n >= 0 then
begin
Inc(I);
val := val * 8 + n;
end;
if I < Len then
begin
n := Pos(S[I + 1], octDigits) - 1;
if n >= 0 then
begin
Inc(I);
val := val * 8 + n;
end;
end;
end;
if val > Ord(High(Char)) then
raise Exception.CreateFmt('Numeric constant too large (%d) at position %d.',
[val, startI]);
Dest := Dest + Char(val);
end;
const
NativeBell = Char(#7);
NativeBackspace = Char(#8);
NativeTab = Char(#9);
NativeLineFeed = Char(#10);
NativeVerticalTab = Char(#11);
NativeFormFeed = Char(#12);
NativeCarriageReturn = Char(#13);
var
I, Len: integer;
begin
Result := '';
I := 1;
Len := Length(S);
while I <= Len do
begin
if not ((S[I] = '\') and (I < Len)) then
Result := Result + S[I]
else
begin
Inc(I); // Jump over escape character
case S[I] of
'a':
Result := Result + NativeBell;
'b':
Result := Result + NativeBackspace;
'f':
Result := Result + NativeFormFeed;
'n':
Result := Result + NativeLineFeed;
'r':
Result := Result + NativeCarriageReturn;
't':
Result := Result + NativeTab;
'v':
Result := Result + NativeVerticalTab;
'\':
Result := Result + '\';
'"':
Result := Result + '"';
'''':
Result := Result + ''''; // Optionally escaped
'?':
Result := Result + '?'; // Optionally escaped
'x':
if I < Len then
// Start of hex escape sequence
HandleHexEscapeSeq(S, I, Len, Result)
else
// '\x' at end of string is not escape sequence
Result := Result + '\x';
'0'..'7':
// start of octal escape sequence
HandleOctEscapeSeq(S, I, Len, Result);
else
// no escape sequence
Result := Result + '\' + S[I];
end;
end;
Inc(I);
end;
end;
{$endregion}
{$region 'Humanized string conversions'}
// Encode string to "humanized" style string
// DividerCR - substitution for #13
// DividerCRLF - substitution for #13#10
// DividerLF - substitution for #10
function StringToHumanized(const s: string; const DividerCR, DividerCRLF,
DividerLF: string): string;
begin
if (pos(DividerCR, s) > 0)
or (pos(DividerCRLF, s) > 0)
or (pos(DividerLF, s) > 0)
then
raise Exception.CreateFmt(
'String "%s" contains a humanize divider "%s", "%s" or "%s" and can''t be converted properly.'#13#10 +
'Try set a different string as the divider for this application.',
[s, DividerCR, DividerCRLF, DividerLF]);
result := StringReplace(
StringReplace(
StringReplace(s, sLineBreak, DividerCRLF, [rfReplaceAll]),
#13, DividerCR, [rfReplaceAll]),
#10, DividerLF, [rfReplaceAll]);
end;
// Decode "humanized" style string to string
// DividerCR - substitution for #13
// DividerCRLF - substitution for #13#10
// DividerLF - substitution for #10
// DefaultLineBreak - used when DividerCR = DividerCRLF
function HumanizedToString(const s: string; const DividerCR, DividerCRLF,
DividerLF, DefaultLineBreak: string): string;
begin
if DividerCR = DividerCRLF then
result := StringReplace(s, DividerCR, DefaultLineBreak, [rfReplaceAll])
else begin
result := StringReplace(s, DividerCR, #13, [rfReplaceAll]);
result := StringReplace(result, DividerCRLF, sLineBreak, [rfReplaceAll]);
end;
result := StringReplace(result, DividerLF, #10, [rfReplaceAll]);
end;
{$endregion}
{$region 'Lng file string conversions'}
function StringToLng(const s: string; Humanize: boolean; const DividerCR,
DividerCRLF, DividerLF: string): string;
begin
if Humanize then
result := StringToHumanized(s, DividerCR, DividerCRLF, DividerLF)
else
result := StringToDelphi(s);
end;
function LngToString(const s: string; Humanize: boolean; const DividerCR,
DividerCRLF, DividerLF, DefaultLineBreak: string): string;
begin
if Humanize then
result := HumanizedToString(s, DividerCR, DividerCRLF, DividerLF, DefaultLineBreak)
else
result := DelphiToStringEx(s);
end;
{$endregion}
end.
|
unit gUnitAI;
//=============================================================================
// gUnitAI.pas
//=============================================================================
//
// Responsible for managing agent AI
//
//=============================================================================
interface
uses SwinGame, gMap, sgTypes, gTypes, sysUtils, gRender, gUnit, gBuilding;
/// Handles the tick-based AI of agents
///
/// @param game The game data
procedure AITick(var game : GameData);
function FindPath(var game : GameData; var agent : UnitEntity): Integer;
implementation
// Update entity location values with sprite location
procedure UpdateEntity(var u : UnitEntity);
begin
u.loc.x := SpriteX(u.sprite);
u.loc.y := SpriteY(u.sprite);
end;
// Check whether the point 1 is close to point 2
function WithinRange(p1, p2 : Point2D): Boolean;
begin
if (p1.x > p2.x - 20)
and (p1.y > p2.y - 20)
and (p1.x < p2.x + 20)
and (p1.y < p2.y + 20) then
begin
exit (true);
end;
exit (false);
end;
// Remove node from nodearray
procedure RemoveArrayIndex(var arr : NodeArray; idx : Integer);
var
i: Integer;
begin
for i := idx to High(arr) do
begin
arr[i] := arr[i + 1];
end;
SetLength(arr, Length(arr) - 1);
end;
// Check if a node exists in a nodearray
function ClosedSetExists(closedSet : NodeArray; tile : Tile): Boolean;
var
i: Integer;
begin
for i := 0 to High(closedSet) do
begin
if VectorsEqual(closedSet[i].loc, tile.loc) then
begin
// WriteLn(PointToString(closedSet[i].loc) + ' exists!');
exit (true);
end;
end;
exit (false);
end;
// Check if a node exists in a nodearray
function ClosedSetExists(closedSet : NodeArray; node : Node): Boolean;
var
i: Integer;
begin
for i := 0 to High(closedSet) do
begin
if VectorsEqual(closedSet[i].loc, node.loc) then
begin
// WriteLn(PointToString(closedSet[i].loc) + ' exists!');
exit (true);
end;
end;
exit (false);
end;
// Search for a node in a nodearray and return its index
function SearchSet(theSet : NodeArray; node : Node): Integer;
var
i: Integer;
begin
for i := 0 to High(theSet) do
begin
if VectorsEqual(theSet[i].loc, node.loc) then
begin
// WriteLn(PointToString(closedSet[i].loc) + ' exists!');
exit (i);
end;
end;
exit (-1);
end;
// Use the A* algorithm to find a path from agent.loc to agent.destination
function FindPath(var game : GameData; var agent : UnitEntity): Integer;
var
openSet, closedSet, temp, path: NodeArray;
tempNode, lowest : Node;
start, goal : Node;
gScore, fScore, hScore, lowestVal : Double;
targetFound : Boolean;
i, j, lowestIdx, idx: Integer;
tempPt : Point2D;
neighbours : TileArray;
tentative_gScore : Double;
begin
tempNode.loc := RealToWorld(CenterPoint(agent.sprite));
start := tempNode;
SetLength(openSet, 0);
SetLength(closedSet, 0);
goal.loc := agent.destination;
// goal := tempNode;
targetFound := false;
SetLength(openSet, 1);
DebugMsg('AI: Entering Pathfinding for [START: ' + PointToString(RealToWorld(CenterPoint(agent.sprite))) + '] - [END: ' + PointToString(goal.loc) + ']');
openSet[0] := start;
openSet[0].gScore := 0;
openSet[0].hScore := MapDistance(openSet[0].loc, agent.destination);
openSet[0].fCost := openSet[0].hScore;
openSet[0].parent := -1;
repeat
lowestVal := 9999999999;
for i := 0 to High(openSet) do
begin
// WriteLn(PointToString(openSet[i].loc));
if openSet[i].fCost < lowestVal then
begin
lowest := openSet[i];
lowestVal := openSet[i].fCost;
lowestIdx := i;
end;
end;
SetLength(closedSet, Length(closedSet) + 1);
closedSet[High(closedSet)] := lowest;
RemoveArrayIndex(openSet, lowestIdx);
lowestIdx := High(closedSet);
neighbours := FindNeighbours(game, lowest.loc);
for i := 0 to High(neighbours) do
begin
FillRectangle(ColorPink, WorldToScreen(neighbours[i].loc).x, WorldToScreen(neighbours[i].loc).y, 5, 5);
// RefreshScreen();
if (((game.map[Round(neighbours[i].loc.x), Round(neighbours[i].loc.y)].tType.terrainType <> TERRAIN_ROAD) and not (VectorsEqual(neighbours[i].loc, goal.loc))) or ClosedSetExists(closedSet, neighbours[i])) then
continue;
tentative_gScore := MapDistance(start.loc, neighbours[i].loc);
if not ClosedSetExists(openSet, neighbours[i]) then
begin
SetLength(openSet, Length(openSet) + 1);
tempNode.loc := neighbours[i].loc;
// WriteLn('asdf '+IntToStr());
openSet[High(openSet)] := tempNode;
openSet[High(openSet)].parent := lowestIdx;
openSet[High(openSet)].gScore := 10;
openSet[High(openSet)].hScore := MapDistance(openSet[High(openSet)].loc, agent.destination);
openSet[High(openSet)].fCost := openSet[High(openSet)].gScore + openSet[High(openSet)].hScore;
end
else if (tentative_gScore >= openSet[High(openSet)].gScore) then
begin
openSet[High(openSet)].parent := lowestIdx;
end;
// DebugMsg('AI: No Path Found.');
// SetLength(openSet, Length(openSet) + 1);
// openSet[High(openSet)] := tempNode;
//
// Delay(500);
end;
if ClosedSetExists(closedSet, goal) then
begin
tempNode := closedSet[SearchSet(closedSet, goal)];
SetLength(path, 1);
path[0] := goal;
path[0].loc := AddVectors(goal.loc, Point(0,1));
idx := tempNode.parent;
while idx > 0 do
begin
SetLength(path, Length(path) + 1);
path[High(path)] := closedSet[idx];
path[High(path)].loc := AddVectors(path[High(path)].loc, Point(0,1));
idx := closedSet[idx].parent;
end;
DebugMsg('AI: Path found successfully.');
break;
end;
until (Length(openSet) = 0) or (Length(openSet) > 2048) or (Length(path) > 0);
if Length(path) < 2 then
begin
agent.toDelete := true;
DebugMsg('AI: Path not found!');
end;
agent.path := path;
end;
// Handle the tick-based decisions of the AI
procedure AITick(var game : GameData);
var
i, j, idx: Integer;
tDist : Double;
currMapTile, pos, old, temp : Point2D;
neighbours : Array [0..7] of Tile;
highest, active : Integer;
distance : Single;
diff : Vector;
delQueue : DeleteQueue;
doDelete : Boolean;
begin
for i := 0 to High(game.buildings) do
begin
if (Random(1000) > 995) then
begin
SpawnUnit(game, game.unitTypes[0], WorldToScreen(game.buildings[i].loc));
game.units[High(game.units)].destination := game.buildings[Random(High(game.buildings))].loc;
FindPath(game, game.units[High(game.units)]);
end;
end;
if (Random(1000) < 1) and (Length(game.buildings) > 0) then
begin
SpawnUnit(game, game.unitTypes[0], PointOfInt(165,-81));
game.units[High(game.units)].destination := game.buildings[Random(High(game.buildings))].loc;
FindPath(game, game.units[High(game.units)]);
end;
for i := 0 to High(game.units) do
begin
if (Length(game.units[i].path) <> 0) and (WithinRange(game.units[i].movingTo, SpritePosition(game.units[i].sprite))) then
begin
if (Length(game.units[i].path) > 0) then
begin
old := AddVectors(RealToWorld(game.units[i].movingTo), PointOfInt(0,1));
old.x := Round(old.x);
old.y := Round(old.y);
temp := game.units[i].path[High(game.units[i].path)].loc;
temp.x := Round(temp.x);
temp.y := Round(temp.y);
game.units[i].movingTo := WorldToScreen(game.units[i].path[High(game.units[i].path)].loc);
RemoveArrayIndex(game.units[i].path, High(game.units[i].path));
if (temp.x > old.x) and (temp.y = old.y) then
begin
DebugMsg('AI: Moving TopRight?');
SpriteShowLayer(game.units[i].sprite, 'TopRight');
active := SpriteLayerIndex(game.units[i].sprite,'TopRight');
end;
if (temp.x < old.x) and (temp.y = old.y) then
begin
DebugMsg('AI: Moving TopLeft?');
SpriteShowLayer(game.units[i].sprite, 'TopLeft');
active := SpriteLayerIndex(game.units[i].sprite,'TopLeft');
end;
if (temp.x = old.x) and (temp.y > old.y) then
begin
DebugMsg('AI: Moving BottomRight?');
SpriteShowLayer(game.units[i].sprite, 'BottomRight');
active := SpriteLayerIndex(game.units[i].sprite,'BottomRight');
end;
if (temp.x = old.x) and (temp.y < old.y) then
begin
DebugMsg('AI: Moving BottomLeft?');
SpriteShowLayer(game.units[i].sprite, 'BottomLeft');
active := SpriteLayerIndex(game.units[i].sprite,'BottomLeft');
end;
for j := 0 to SpriteLayerCount(game.units[i].sprite) - 1 do
begin
if active <> j then
SpriteHideLayer(game.units[i].sprite, j);
end;
UpdateSprite(game.units[i].sprite);
end;
end
else if (Length(game.units[i].path) = 0) and (not VectorsEqual(RealToWorld(game.units[i].loc), game.units[i].destination)) and (MapDistance(RealToWorld(game.units[i].loc), game.units[i].destination) > 2) then
begin
FindPath(game, game.units[i]);
if game.units[i].toDelete then
begin
SetLength(delQueue, Length(delQueue) + 1);
delQueue[High(delQueue)] := i;
end;
end;
if not VectorsEqual(game.units[i].movingTo, game.units[i].loc) then
begin
diff := VectorFromCenterSpriteToPoint(game.units[i].sprite, game.units[i].movingTo);
diff := VectorMultiply(diff, 0.05);
SpriteSetVelocity(game.units[i].sprite, diff);
MoveSprite(game.units[i].sprite);
end;
if WithinRange(WorldToScreen(AddVectors(game.units[i].destination, PointOfInt(0,1))), game.units[i].loc) then
begin
DebugMsg('Agent: Agent of index '+IntToStr(i) + ' arrived at destination of '+PointToString(game.units[i].destination));
doDelete := true;
for j := 0 to High(delQueue) do
begin
if delQueue[j] = i then
doDelete := false;
end;
if doDelete then
begin
SetLength(delQueue, Length(delQueue) + 1);
delQueue[High(delQueue)] := i;
end;
if game.map[Round(game.units[i].destination.x), Round(game.units[i].destination.y)].terrainType = TERRAIN_ZONE then
begin
SpawnBuilding(game, game.units[i].destination, TERRAIN_ZONE);
end;
if game.map[Round(game.units[i].destination.x), Round(game.units[i].destination.y)].terrainType = TERRAIN_COMZONE then
begin
SpawnBuilding(game, game.units[i].destination, TERRAIN_COMZONE);
end;
continue;
end;
// end;
UpdateSprite(game.units[i].sprite);
UpdateEntity(game.units[i]);
end;
for i := 0 to High(delQueue) do
begin
RemoveUnit(game, delQueue[i]);
end;
end;
end.
|
{$MODE OBJFPC}
{$DEFINE RELEASE}
{$R-,Q-,S-,I-}
{$OPTIMIZATION LEVEL2}
{$INLINE ON}
program Telecom;
uses Math;
const
InputFile = 'TELECOM.INP';
OutputFile = 'TELECOM.OUT';
maxN = 200;
maxC = 10000;
epsilon = 1E-9;
type
TPoint = packed record
case Boolean of
False: (x, y: LongInt);
True: (Code: Int64);
end;
TVector = TPoint;
var
n: Integer;
p: array[1..maxN] of TPoint;
q: array[1..maxN + 1] of TPoint;
mark: array[2..maxN - 1] of Boolean;
top: Integer;
A, B, u: TPoint;
res, finalres: Double;
resX, resY, finalX, finalY: Double;
procedure Enter;
var
f: TextFile;
i: Integer;
begin
AssignFile(f, InputFile); Reset(f);
try
ReadLn(f, n);
for i := 1 to n do
with p[i] do
ReadLn(f, x, y);
finally
CloseFile(f);
end;
end;
operator <(const a, b: TPoint): Boolean; inline;
begin
Result := (a.x < b.x) or (a.x = b.x) and (a.y < b.y);
end;
procedure Sort(L, H: Integer);
var
pivot: TPoint;
i, j: Integer;
begin
if L >= H then Exit;
i := L + Random(H - L + 1);
pivot := p[i]; p[i] := p[L];
i := L; j := H;
repeat
while (pivot < p[j]) and (i < j) do Dec(j);
if i < j then
begin
p[i] := p[j]; Inc(i);
end
else Break;
while (p[i] < pivot) and (i < j) do Inc(i);
if i < j then
begin
p[j] := p[i]; Dec(j);
end
else Break;
until i = j;
p[i] := pivot;
Sort(L, i - 1); Sort(i + 1, H);
end;
function Vector(const p, q: TPoint): TVector; inline;
begin
Result.x := q.x - p.x;
Result.y := q.y - p.y;
end;
function Distance(const u: TVector): Double; inline;
begin
Result := Sqrt(Sqr(u.x) + Sqr(u.y));
end;
function CCW(const u, v: TVector): Integer; overload; inline;
begin
Result := u.x * v.y - u.y * v.x;
end;
function CCW(const a, b, c: TPoint): Integer; overload; inline;
begin
Result := CCW(vector(a, b), vector(b, c));
end;
operator *(const u, v: TVector): Double; inline;
begin
Result := u.x * v.x + u.y * v.y;
end;
function Angle(const p, q, r: TPoint): Double;
var
u, v: TVector;
ccwres, sine: Double;
begin
u := Vector(p, q);
v := Vector(p, r);
if (Distance(u) = 0) or (Distance(v) = 0) then
Exit(0);
ccwres := CCW(u, v);
sine := EnsureRange(ccwres / (Distance(u) * Distance(v)), -1, 1);
Result := ArcSin(sine);
if u * v < 0 then
if Result > 0 then Result := Pi - Result
else Result := -Pi - Result;
end;
procedure Minimize(var target: Double; value: Double);
begin
if target > value then target := value;
end;
function Check(i, j: Integer): Boolean;
var
k, ia, ib: Integer;
alpha, beta, gamma, phi, area2, height: Double;
centerX, centerY: double;
ab: TVector;
sx, sy: Double;
temp: Integer;
begin
alpha := Pi;
beta := Pi;
for k := 1 to top do
if (k <> i) and (k <> j) then
begin
phi := Angle(q[k], q[i], q[j]);
if phi >= 0 then
Minimize(alpha, phi)
else
Minimize(beta, -phi);
end;
if (alpha + beta < Pi - epsilon) then
Exit(False);
//alpha + beta >= pi
if (alpha >= pi / 2) and (beta >= pi / 2) then
begin
res := Distance(vector(q[i], q[j])) / 2;
resX := (q[i].x + q[j].x) / 2;
resY := (q[i].y + q[j].y) / 2;
Exit(True);
end;
if alpha < beta then
gamma := 2 * alpha
else
gamma := 2 * beta;
ab := Vector(q[i], q[j]);
res := Distance(ab) / sin(gamma / 2) / 2;
area2 := res * res * Sin(gamma);
height := area2 / Distance(ab);
centerx := (q[i].x + q[j].x) / 2;
centery := (q[i].y + q[j].y) / 2;
with ab do
begin
temp := x; x := -y; y := temp;
if beta < alpha then
x := -x; y := -y;
sx := x / Distance(ab); sy := y / Distance(ab);
end;
resX := centerX + height * sx;
resY := centerY + height * sy;
Result := True;
end;
procedure Solve;
var
i, j: Integer;
begin
for i := 1 to n do
p[i] := Vector(A, p[i]);
u := p[n];
for i := 2 to n - 1 do
mark[i] := CCW(u, p[i]) >= 0;
top := 1;
q[1] := p[1];
for i := 2 to n do
if (i = n) or mark[i] then
begin
while (top >= 2) and (CCW(q[top - 1], q[top], p[i]) >= 0)
do Dec(top);
Inc(top);
q[top] := p[i];
end;
for i := n - 1 downto 1 do
if (i = 1) or not mark[i] then
begin
while (top >= 2) and (CCW(q[top - 1], q[top], p[i]) >= 0)
do Dec(top);
Inc(top);
q[top] := p[i];
end;
if top = 2 then q[top] := p[n]
else Dec(top);
finalres := 2 * maxC;
for i := 1 to top do
for j := i + 1 to top do
if Check(i, j) and (res < finalres) then
begin
finalres := res;
finalX := resX;
finalY := resY;
end;
finalX := finalX + A.x;
finalY := finalY + A.y;
end;
procedure PrintResult;
var
f: TextFile;
begin
AssignFile(f, OutputFile); Rewrite(f);
try
if Abs(finalres) < epsilon then
WriteLn(f, p[1].x + 0.0:0:6, ' ', p[1].y + 0.0:0:6, ' ', 0.0:0:6)
else
WriteLn(f, finalX:0:6, ' ', finalY:0:6, ' ', finalres:0:6);
finally
CloseFile(f);
end;
end;
begin
Enter;
Sort(1, n);
A := p[1]; B := p[n];
if A.code = B.code then
finalres := 0
else
Solve;
PrintResult;
end.
|
unit frmNoneCertifyServer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, iocp_managers, iocp_server, StdCtrls, iocp_clients, iocp_sockets,
iocp_clientBase;
type
TFormNoneCertifyServer = class(TForm)
InIOCPServer1: TInIOCPServer;
InFileManager1: TInFileManager;
Memo1: TMemo;
btnStart: TButton;
btnStop: TButton;
Button3: TButton;
Button4: TButton;
btnConnect: TButton;
InFileClient1: TInFileClient;
InConnection1: TInConnection;
procedure FormCreate(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure InIOCPServer1AfterClose(Sender: TObject);
procedure InFileManager1BeforeUpload(Sender: TObject;
Params: TReceiveParams; Result: TReturnResult);
procedure Button3Click(Sender: TObject);
procedure InFileManager1BeforeDownload(Sender: TObject;
Params: TReceiveParams; Result: TReturnResult);
procedure Button4Click(Sender: TObject);
procedure btnConnectClick(Sender: TObject);
procedure InConnection1AfterConnect(Sender: TObject);
private
{ Private declarations }
FAppDir: String;
public
{ Public declarations }
end;
var
FormNoneCertifyServer: TFormNoneCertifyServer;
implementation
uses
iocp_log, iocp_base, iocp_varis, iocp_utils;
{$R *.dfm}
procedure TFormNoneCertifyServer.btnConnectClick(Sender: TObject);
begin
InConnection1.Active := not InConnection1.Active;
end;
procedure TFormNoneCertifyServer.btnStartClick(Sender: TObject);
begin
iocp_log.TLogThread.InitLog; // 开启日志
InIOCPServer1.Active := True; // 开启服务
end;
procedure TFormNoneCertifyServer.btnStopClick(Sender: TObject);
begin
InIOCPServer1.Active := False; // 停止服务
iocp_log.TLogThread.StopLog; // 停止日志
end;
procedure TFormNoneCertifyServer.Button3Click(Sender: TObject);
begin
// 下载 S_DownloadFile
// 方法一,参数少
InFileClient1.Upload('Upload_file.txt');
// 方法二,可以加入更多参数,服务端方便操作
{ with TMessagePack.Create(InFileClient1) do
begin
AsString['path'] := 'none_certify';
LoadFromFile('Upload_file.txt'); // 不能用 FileName :=
Post(atFileUpload);
end; }
end;
procedure TFormNoneCertifyServer.Button4Click(Sender: TObject);
begin
// 下载 S_DownloadFile
// 方法一,参数少,保存到路径 InConnection1.LocalPath
InFileClient1.Download('S_DownloadFile.7z');
// 方法二,可以加入更多参数,服务端方便操作
{ with TMessagePack.Create(InFileClient1) do
begin
AsString['path'] := 'none_certify'; // 服务端路径
LocalPath := 'temp\'; // 本地存放路径
FileName := 'S_DownloadFile.7z';
Post(atFileDownload);
end; }
end;
procedure TFormNoneCertifyServer.FormCreate(Sender: TObject);
begin
// 准备工作路径
FAppDir := ExtractFilePath(Application.ExeName);
// 客户端数据存放路径
iocp_Varis.gUserDataPath := FAppDir + 'none_certify\';
MyCreateDir(FAppDir + 'log'); // 建目录
MyCreateDir(iocp_Varis.gUserDataPath); // 建目录
end;
procedure TFormNoneCertifyServer.InConnection1AfterConnect(Sender: TObject);
begin
if InConnection1.Active then
btnConnect.Caption := '断开'
else
btnConnect.Caption := '连接';
end;
procedure TFormNoneCertifyServer.InFileManager1BeforeDownload(Sender: TObject;
Params: TReceiveParams; Result: TReturnResult);
begin
// 打开文件流供下载
if (Params.AsString['path'] = '') then // 没有路径
InFileManager1.OpenLocalFile(Result, 'none_certify\' + Params.FileName)
else
InFileManager1.OpenLocalFile(Result, Params.AsString['path'] + '\' + Params.FileName);
end;
procedure TFormNoneCertifyServer.InFileManager1BeforeUpload(Sender: TObject;
Params: TReceiveParams; Result: TReturnResult);
begin
// 建文件流供上传,如果登录可以用 InFileManager1.CreateNewFile()
// 因没有登录,用以下方法:
if (Params.AsString['path'] = '') then
Params.CreateAttachment('none_certify\')
else
Params.CreateAttachment(Params.AsString['path'] + '\'); // 客户端指定的路径
end;
procedure TFormNoneCertifyServer.InIOCPServer1AfterClose(Sender: TObject);
begin
btnStart.Enabled := not InIOCPServer1.Active;
btnStop.Enabled := InIOCPServer1.Active;
end;
end.
|
unit CompWizardFile;
{
Inno Setup
Copyright (C) 1997-2010 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Compiler Script Wizard File form
$jrsoftware: issrc/Projects/CompWizardFile.pas,v 1.11 2010/03/06 22:33:02 jr Exp $
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
UIStateForm, StdCtrls, ExtCtrls, NewStaticText;
type
PWizardFile = ^TWizardFile;
TWizardFile = record
Source: String;
RecurseSubDirs: Boolean;
CreateAllSubDirs: Boolean;
DestRootDir: String;
DestRootDirIsConstant: Boolean;
DestSubDir: String;
end;
TWizardFileForm = class(TUIStateForm)
OKButton: TButton;
CancelButton: TButton;
GroupBox2: TGroupBox;
DestRootDirComboBox: TComboBox;
DestRootDirEdit: TEdit;
DestRootDirLabel: TNewStaticText;
DestSubDirEdit: TEdit;
SubDirLabel: TNewStaticText;
RequiredLabel1: TNewStaticText;
RequiredLabel2: TNewStaticText;
GroupBox1: TGroupBox;
SourceLabel: TNewStaticText;
SourceEdit: TEdit;
RecurseSubDirsCheck: TCheckBox;
CreateAllSubDirsCheck: TCheckBox;
procedure OKButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DestRootDirComboBoxChange(Sender: TObject);
procedure RecurseSubDirsCheckClick(Sender: TObject);
private
FAllowAppDestRootDir: Boolean;
FWizardFile: PWizardFile;
procedure SetWizardFile(WizardFile: PWizardFile);
procedure UpdateUI;
public
property AllowAppDestRootDir: Boolean write FAllowAppDestRootDir;
property WizardFile: PWizardFile write SetWizardFile;
end;
implementation
uses
CompMsgs, CmnFunc, CmnFunc2, CompForm;
{$R *.DFM}
type
TConstant = record
Constant, Description: String;
end;
const
DestRootDirs: array[0..8] of TConstant =
(
( Constant: '{app}'; Description: 'Application directory'),
( Constant: '{pf}'; Description: 'Program Files directory'),
( Constant: '{cf}'; Description: 'Common Files directory'),
( Constant: '{win}'; Description: 'Windows directory'),
( Constant: '{sys}'; Description: 'Windows system directory'),
( Constant: '{src}'; Description: 'Setup source directory'),
( Constant: '{sd}'; Description: 'System drive root directory'),
( Constant: '{commonstartup}'; Description: 'Common Startup folder'),
( Constant: '{userstartup}'; Description: 'User Startup folder')
);
procedure TWizardFileForm.SetWizardFile(WizardFile: PWizardFile);
var
I: Integer;
begin
FWizardFile := WizardFile;
SourceEdit.Text := WizardFile.Source;
RecurseSubDirsCheck.Checked := WizardFile.RecurseSubDirs;
CreateAllSubDirsCheck.Checked := WizardFile.CreateAllSubDirs;
if WizardFile.DestRootDirIsConstant then begin
for I := Low(DestRootDirs) to High(DestRootDirs) do begin
if DestRootDirs[I].Constant = WizardFile.DestRootDir then begin
DestRootDirComboBox.ItemIndex := I;
Break;
end;
end;
end else begin
DestRootDirComboBox.ItemIndex := DestRootDirComboBox.Items.Count-1;
DestRootDirEdit.Text := WizardFile.DestRootDir;
end;
DestSubDirEdit.Text := WizardFile.DestSubDir;
UpdateUI;
end;
{ --- }
procedure TWizardFileForm.FormCreate(Sender: TObject);
procedure MakeBold(const Ctl: TNewStaticText);
begin
Ctl.Font.Style := [fsBold];
end;
var
I: Integer;
begin
InitFormFont(Self);
MakeBold(SourceLabel);
MakeBold(DestRootDirLabel);
MakeBold(RequiredLabel1);
RequiredLabel2.Left := RequiredLabel1.Left + RequiredLabel1.Width;
for I := Low(DestRootDirs) to High(DestRootDirs) do
DestRootDirComboBox.Items.Add(DestRootDirs[I].Description);
DestRootDirComboBox.Items.Add('(Custom)');
DestRootDirComboBox.ItemIndex := 0;
end;
{ --- }
procedure TWizardFileForm.UpdateUI;
begin
CreateAllSubDirsCheck.Enabled := RecurseSubDirsCheck.Checked;
if DestRootDirComboBox.ItemIndex = DestRootDirComboBox.Items.Count-1 then begin
DestRootDirEdit.Enabled := True;
DestRootDirEdit.Color := clWindow;
end else begin
DestRootDirEdit.Enabled := False;
DestRootDirEdit.Color := clBtnFace;
end;
end;
{ --- }
procedure TWizardFileForm.RecurseSubDirsCheckClick(Sender: TObject);
begin
UpdateUI;
end;
procedure TWizardFileForm.DestRootDirComboBoxChange(Sender: TObject);
begin
UpdateUI;
if DestRootDirEdit.Enabled then
ActiveControl := DestRootDirEdit;
end;
procedure TWizardFileForm.OKButtonClick(Sender: TObject);
var
DestRootDirIndex: Integer;
begin
ModalResult := mrNone;
DestRootDirIndex := DestRootDirComboBox.ItemIndex;
if (DestRootDirIndex = DestRootDirComboBox.Items.Count-1) and (DestRootDirEdit.Text = '') then begin
MsgBox(SWizardFileDestRootDirError, '', mbError, MB_OK);
ActiveControl := DestRootDirEdit;
end else if (DestRootDirs[DestRootDirIndex].Constant = '{app}') and not FAllowAppDestRootDir then begin
MsgBox(SWizardFileAppDestRootDirError, '', mbError, MB_OK);
ActiveControl := DestRootDirComboBox;
end else
ModalResult := mrOk;
if ModalResult = mrOk then begin
FWizardFile.RecurseSubDirs := RecurseSubDirsCheck.Checked;
FWizardFile.CreateAllSubDirs := CreateAllSubDirsCheck.Checked;
if DestRootDirIndex = DestRootDirComboBox.Items.Count-1 then begin
FWizardFile.DestRootDir := DestRootDirEdit.Text;
FWizardFile.DestRootDirIsConstant := False;
end else begin
FWizardFile.DestRootDir := DestRootDirs[DestRootDirIndex].Constant;
FWizardFile.DestRootDirIsConstant := True;
end;
FWizardFile.DestSubDir := DestSubDirEdit.Text;
end;
end;
end.
|
unit TokyoScript.BuiltIn;
{
TokyoScript (c)2018 Execute SARL
http://www.execute.Fr
}
interface
uses
System.SysUtils;
type
TBuiltIn = (
bi_None,
biWrite,
biWriteLn,
biInc
);
const
BUILTINS : array[TBuiltIn] of string = (
'',
'WRITE',
'WRITELN',
'INC'
);
function GetBuiltIn(Str: string): TBuiltIn;
implementation
function GetBuiltIn(Str: string): TBuiltIn;
begin
Str := UpperCase(Str);
Result := High(TBuiltIn);
while Result > bi_None do
begin
if BUILTINS[Result] = Str then
Exit;
Dec(Result);
end;
end;
end.
|
unit nsIntegerValueMap;
{* реализация мапы "строка"-"число" }
{$Include nsDefine.inc }
interface
uses
Classes,
l3Interfaces,
l3BaseWithID,
l3ValueMap,
l3Types,
vcmExternalInterfaces,
vcmInterfaces,
L10nInterfaces
;
type
TnsIntegerValueMapRecord = record
rN: TvcmStringID;
rV: Integer;
end;//TnsIntegerValueMapRecord
TnsIntegerValueMapItem = class(Tl3BaseWithID)
private
f_Data: TnsIntegerValueMapRecord;
public
constructor Create(const aValue: TnsIntegerValueMapRecord);
reintroduce;
property StringID: TvcmStringID
read f_Data.rN;
property Value: Integer
read f_Data.rV;
end;//TnsIntegerValueMapItem
TnsIntegerValueMap = class(Tl3ValueMap, InsIntegerValueMap, InsStringsSource)
private
// Il3IntegerValueMap
function DisplayNameToValue(const aDisplayName: Il3CString): Integer;
function ValueToDisplayName(aValue: Integer): Il3CString;
// InsStringsSource
procedure FillStrings(const aStrings: IvcmStrings);
protected
procedure DoGetDisplayNames(const aList: Il3StringsEx);
override;
function GetMapSize: Integer;
override;
public
constructor Create(const aID: TnsValueMapID; const aValues: array of TnsIntegerValueMapRecord);
reintroduce;
class function Make(const aID: TnsValueMapID; const aValues: array of TnsIntegerValueMapRecord): InsIntegerValueMap;
reintroduce;
end;//TnsIntegerValueMap
function nsIntegerValueMapRecord(const aName: TvcmStringID; aValue: Integer): TnsIntegerValueMapRecord;
implementation
uses
l3Base,
l3String,
vcmBase,
vcmUtils,
nsTypes
;
function nsIntegerValueMapRecord(const aName: TvcmStringID; aValue: Integer): TnsIntegerValueMapRecord;
begin
Result.rN := aName;
Result.rV := aValue;
end;
{ TnsIntegerValueMapItem }
constructor TnsIntegerValueMapItem.Create(const aValue: TnsIntegerValueMapRecord);
begin
inherited Create(aValue.rV);
f_Data := aValue;
end;
{ TnsIntegerValueMap }
constructor TnsIntegerValueMap.Create(const aID: TnsValueMapID;
const aValues: array of TnsIntegerValueMapRecord);
var
l_Index: Integer;
l_Item: TnsIntegerValueMapItem;
begin
inherited Create(aID);
for l_index := Low(aValues) to High(aValues) do
begin
l_Item := TnsIntegerValueMapItem.Create(aValues[l_Index]);
try
Add(l_Item);
finally
l3Free(l_Item);
end;
end;
end;
function TnsIntegerValueMap.DisplayNameToValue(const aDisplayName: Il3CString): Integer;
{-}
var
l_Index : Integer;
begin
for l_Index := 0 to Count - 1 do
if l3Same(aDisplayName, vcmCStr(TnsIntegerValueMapItem(Items[l_Index]).StringID)) then
begin
Result := TnsIntegerValueMapItem(Items[l_Index]).Value;
exit;
end;//l3Same(aDisplayName,
raise El3ValueMapValueNotFound.CreateFmt('Display name %s not found in Map %s', [nsEStr(aDisplayName),rMapID.rName]);
end;
procedure TnsIntegerValueMap.FillStrings(const aStrings: IvcmStrings);
var
l_Index: Integer;
begin
aStrings.Clear;
for l_Index := 0 To Count-1 Do
aStrings.Add(vcmCStr(TnsIntegerValueMapItem(Items[l_Index]).StringID));
end;
procedure TnsIntegerValueMap.DoGetDisplayNames(const aList: Il3StringsEx);
var
l_Index: Integer;
begin
inherited;
for l_Index := 0 To Count-1 Do
aList.Add(vcmCStr(TnsIntegerValueMapItem(Items[l_Index]).StringID));
end;
class function TnsIntegerValueMap.Make(const aID: TnsValueMapID;
const aValues: array of TnsIntegerValueMapRecord): InsIntegerValueMap;
var
l_Map: TnsIntegerValueMap;
begin
l_Map := Create(aID, aValues);
try
Result := l_Map;
finally
vcmFree(l_Map);
end;
end;
function TnsIntegerValueMap.GetMapSize: Integer;
begin
Result := Count;
end;
function TnsIntegerValueMap.ValueToDisplayName(aValue: Integer): Il3CString;
var
l_Index: Integer;
begin
if FindData(aValue,l_Index,l3_siNative) then
Result := vcmCStr(TnsIntegerValueMapItem(Items[l_Index]).StringID)
else
raise El3ValueMapValueNotFound.CreateFmt('Value %d not found in Map %s',[aValue,rMapID.rName]);
end;
end.
|
unit objItem;
interface
uses System.SysUtils, FireDAC.Comp.Client, Vcl.Dialogs;
type
TItem = class(TObject)
private
Fcodigo: Integer;
Fdescricao: String;
Fvalor : Double;
Fativo : Boolean;
Fconexao : TFDConnection;
protected
function getCodigo : Integer;
function getDescricao : String;
function getValor : Double;
function getAtivo : Boolean;
procedure setCodigo(const Value: Integer);
procedure setDescricao(const Value: String);
procedure setValor(const Value: Double);
procedure setAtivo(const Value: Boolean);
public
property codigo : Integer read getCodigo write setCodigo;
property descricao : String read getDescricao write setDescricao;
property valor : Double read getValor write setValor;
property ativo : Boolean read getAtivo write setAtivo;
function Salvar : Boolean;
function Editar : Boolean;
function Excluir : Boolean;
procedure BuscarInformacoesItem;
procedure CarregarItens(var quCarregaItens : TFDQuery);
constructor Create(objConexao : TFDConnection);
destructor Destroy;
end;
implementation
{ TItem }
constructor TItem.Create(objConexao : TFDConnection);
begin
inherited Create;
Fconexao := objConexao;
end;
destructor TItem.Destroy;
begin
inherited;
end;
function TItem.getAtivo: Boolean;
begin
result := Fativo;
end;
function TItem.getCodigo: Integer;
begin
result := Fcodigo;
end;
function TItem.getDescricao: String;
begin
result := Fdescricao;
end;
function TItem.getValor: Double;
begin
result := Fvalor;
end;
procedure TItem.setAtivo(const Value: Boolean);
begin
Fativo := Value;
end;
procedure TItem.setCodigo(const Value: Integer);
begin
Fcodigo := Value;
end;
procedure TItem.setDescricao(const Value: String);
begin
Fdescricao := Value;
end;
procedure TItem.setValor(const Value: Double);
begin
Fvalor := Value;
end;
function TItem.Salvar: Boolean;
var
quInserir : TFDQuery;
begin
try
result := False;
quInserir := TFDQuery.Create(nil);
quInserir.Connection := Fconexao;
try
quInserir.Close;
quInserir.SQL.Clear;
quInserir.SQL.Add('INSERT INTO ITENS ( DESCRICAO, VALOR, ATIVO)');
quInserir.SQL.Add('VALUES (:DESCRICAO, :VALOR, :ATIVO)');
quInserir.Params.ParamByName('DESCRICAO').AsString := descricao;
quInserir.Params.ParamByName('VALOR').AsFloat := valor;
quInserir.Params.ParamByName('ATIVO').AsBoolean := ativo;
quInserir.ExecSQL;
if quInserir.RowsAffected < 1 then
raise Exception.Create('Item não inserido.');
result := True;
except
on e:Exception do
raise Exception.Create(e.Message);
end;
finally
quInserir.Close;
FreeAndNil(quInserir);
end;
end;
function TItem.Editar: Boolean;
var
quEditar : TFDQuery;
begin
try
result := False;
quEditar := TFDQuery.Create(nil);
quEditar.Connection := Fconexao;
try
quEditar.Close;
quEditar.SQL.Clear;
quEditar.SQL.Add('UPDATE ITENS');
quEditar.SQL.Add('SET DESCRICAO = :DESCRICAO,');
quEditar.SQL.Add(' VALOR = :VALOR,');
quEditar.SQL.Add(' ATIVO = :ATIVO');
quEditar.SQL.Add('WHERE CODIGO = :CODIGO');
quEditar.Params.ParamByName('DESCRICAO').AsString := descricao;
quEditar.Params.ParamByName('VALOR').AsFloat := valor;
quEditar.Params.ParamByName('ATIVO').AsBoolean := ativo;
quEditar.Params.ParamByName('CODIGO').AsInteger := codigo;
quEditar.ExecSQL;
if quEditar.RowsAffected < 1 then
raise Exception.Create('Item não alterado.');
result := True;
except
on e:Exception do
raise Exception.Create(e.Message);
end;
finally
quEditar.Close;
FreeAndNil(quEditar);
end;
end;
function TItem.Excluir: Boolean;
var
quExcluir : TFDQuery;
begin
try
result := False;
quExcluir := TFDQuery.Create(nil);
quExcluir.Connection := Fconexao;
try
quExcluir.Close;
quExcluir.SQL.Clear;
quExcluir.SQL.Add('DELETE FROM ITENS');
quExcluir.SQL.Add('WHERE CODIGO = :CODIGO');
quExcluir.Params.ParamByName('CODIGO').AsInteger := codigo;
quExcluir.ExecSQL;
if quExcluir.RowsAffected < 1 then
raise Exception.Create('Item não excluído.');
result := True;
except
on e:Exception do
raise Exception.Create(e.Message);
end;
finally
quExcluir.Close;
FreeAndNil(quExcluir);
end;
end;
procedure TItem.BuscarInformacoesItem;
var
quInformacoesItem : TFDQuery;
begin
try
quInformacoesItem := TFDQuery.Create(nil);
quInformacoesItem.Connection := Fconexao;
try
quInformacoesItem.Close;
quInformacoesItem.SQL.Clear;
quInformacoesItem.SQL.Add('SELECT DESCRICAO, VALOR, ATIVO');
quInformacoesItem.SQL.Add('FROM ITENS');
quInformacoesItem.SQL.Add('WHERE CODIGO = :CODIGO');
quInformacoesItem.Params.ParamByName('CODIGO').AsInteger := codigo;
quInformacoesItem.Open;
if quInformacoesItem.Eof then
raise Exception.Create('Informações não encontradas para o item ' + IntToStr(codigo));
descricao := quInformacoesItem.FieldByName('DESCRICAO').AsString;
valor := quInformacoesItem.FieldByName('VALOR').AsFloat;
ativo := quInformacoesItem.FieldByName('ATIVO').AsBoolean;
except
on e:Exception do
raise Exception.Create(e.Message);
end;
finally
quInformacoesItem.Close;
FreeAndNil(quInformacoesItem);
end;
end;
procedure TItem.CarregarItens(var quCarregaItens : TFDQuery);
begin
try
quCarregaItens.Close;
quCarregaItens.SQL.Clear;
quCarregaItens.SQL.Add('SELECT CODIGO, DESCRICAO, VALOR, ATIVO');
quCarregaItens.SQL.Add('FROM ITENS');
quCarregaItens.SQL.Add('WHERE ATIVO = TRUE');
quCarregaItens.SQL.Add('ORDER BY CODIGO DESC');
quCarregaItens.Open;
except
on e:Exception do
raise Exception.Create(e.Message);
end;
end;
end.
|
unit uCRUDApuracao;
interface
uses
FireDAC.Comp.Client, SysUtils, Vcl.Forms, Windows, Vcl.Controls, Data.DB,
System.Classes, Vcl.CheckLst, UFuncoesFaciliteXE8, uConstantes;
type
TCRUDApuracaoMensal = class(TObject)
private
FConexao : TFDConnection;
vloFuncoes : TFuncoesGerais;
FClasseExcept: String;
FAIMES_EMPRESA: String;
FAIMES_RECEITAALTERADA: Double;
FMensagemExcept: String;
FAIMES_IMPOSTO: String;
FAIMES_VALORIMPOSTO: Double;
FAIMES_RECEITABRUTA: Double;
FAIMES_MES: String;
FAIMES_ANO: String;
FAIMES_ALIQUOTAIMPOSTO: Double;
procedure SetAIMES_ALIQUOTAIMPOSTO(const Value: Double);
procedure SetAIMES_ANO(const Value: String);
procedure SetAIMES_EMPRESA(const Value: String);
procedure SetAIMES_IMPOSTO(const Value: String);
procedure SetAIMES_MES(const Value: String);
procedure SetAIMES_RECEITAALTERADA(const Value: Double);
procedure SetAIMES_RECEITABRUTA(const Value: Double);
procedure SetAIMES_VALORIMPOSTO(const Value: Double);
procedure SetClasseExcept(const Value: String);
procedure SetMensagemExcept(const Value: String);
public
Constructor Create(poConexao : TFDConnection);
Destructor Destroy; override;
function fncGravarApuracaoMensal: Boolean;
function fncExcluiApuracaoMensal: Boolean;
protected
published
property AIMES_EMPRESA : String read FAIMES_EMPRESA write SetAIMES_EMPRESA;
property AIMES_IMPOSTO : String read FAIMES_IMPOSTO write SetAIMES_IMPOSTO;
property AIMES_MES : String read FAIMES_MES write SetAIMES_MES;
property AIMES_ANO : String read FAIMES_ANO write SetAIMES_ANO;
property AIMES_RECEITABRUTA : Double read FAIMES_RECEITABRUTA write SetAIMES_RECEITABRUTA;
property AIMES_RECEITAALTERADA : Double read FAIMES_RECEITAALTERADA write SetAIMES_RECEITAALTERADA;
property AIMES_ALIQUOTAIMPOSTO : Double read FAIMES_ALIQUOTAIMPOSTO write SetAIMES_ALIQUOTAIMPOSTO;
property AIMES_VALORIMPOSTO : Double read FAIMES_VALORIMPOSTO write SetAIMES_VALORIMPOSTO;
property MensagemExcept : String read FMensagemExcept write SetMensagemExcept;
property ClasseExcept : String read FClasseExcept write SetClasseExcept;
end;
type
TCRUDApuracaoTrimestral = class(TObject)
private
FConexao : TFDConnection;
vloFuncoes : TFuncoesGerais;
FClasseExcept: String;
FMensagemExcept: String;
FAITRIMES_IMPOSTO: String;
FAITRIMES_VALORIMPOSTO: Double;
FAITRIMES_TRIMESTRE: Integer;
FAITRIMES_RETENCAOIMPOSTO: Double;
FAITRIMES_RECEITABRUTA: Double;
FAITRIMES_RECEITAFINANC: Double;
FAITRIMES_ALIQIMPOSTO: Double;
FAITRIMES_ADICIONALIRPJ: Double;
FAITRIMES_ANO: String;
FAITRIMES_PRESIMPOSTO: Double;
FAITRIMES_EMPRESA: String;
FAITRIMES_RECEITAALTERADA: Double;
procedure SetClasseExcept(const Value: String);
procedure SetMensagemExcept(const Value: String);
procedure SetAITRIMES_ADICIONALIRPJ(const Value: Double);
procedure SetAITRIMES_ALIQIMPOSTO(const Value: Double);
procedure SetAITRIMES_ANO(const Value: String);
procedure SetAITRIMES_EMPRESA(const Value: String);
procedure SetAITRIMES_IMPOSTO(const Value: String);
procedure SetAITRIMES_PRESIMPOSTO(const Value: Double);
procedure SetAITRIMES_RECEITAALTERADA(const Value: Double);
procedure SetAITRIMES_RECEITABRUTA(const Value: Double);
procedure SetAITRIMES_RECEITAFINANC(const Value: Double);
procedure SetAITRIMES_RETENCAOIMPOSTO(const Value: Double);
procedure SetAITRIMES_TRIMESTRE(const Value: Integer);
procedure SetAITRIMES_VALORIMPOSTO(const Value: Double);
public
Constructor Create(poConexao : TFDConnection);
Destructor Destroy; override;
function fncGravarApuracaoTrimestral: Boolean;
function fncExcluiApuracaoTrimestral: Boolean;
protected
published
property AITRIMES_EMPRESA : String read FAITRIMES_EMPRESA write SetAITRIMES_EMPRESA;
property AITRIMES_IMPOSTO : String read FAITRIMES_IMPOSTO write SetAITRIMES_IMPOSTO;
property AITRIMES_TRIMESTRE : Integer read FAITRIMES_TRIMESTRE write SetAITRIMES_TRIMESTRE;
property AITRIMES_ANO : String read FAITRIMES_ANO write SetAITRIMES_ANO;
property AITRIMES_RECEITABRUTA : Double read FAITRIMES_RECEITABRUTA write SetAITRIMES_RECEITABRUTA;
property AITRIMES_RECEITAALTERADA : Double read FAITRIMES_RECEITAALTERADA write SetAITRIMES_RECEITAALTERADA;
property AITRIMES_ALIQIMPOSTO : Double read FAITRIMES_ALIQIMPOSTO write SetAITRIMES_ALIQIMPOSTO;
property AITRIMES_PRESIMPOSTO : Double read FAITRIMES_PRESIMPOSTO write SetAITRIMES_PRESIMPOSTO;
property AITRIMES_RECEITAFINANC : Double read FAITRIMES_RECEITAFINANC write SetAITRIMES_RECEITAFINANC;
property AITRIMES_RETENCAOIMPOSTO : Double read FAITRIMES_RETENCAOIMPOSTO write SetAITRIMES_RETENCAOIMPOSTO;
property AITRIMES_ADICIONALIRPJ : Double read FAITRIMES_ADICIONALIRPJ write SetAITRIMES_ADICIONALIRPJ;
property AITRIMES_VALORIMPOSTO : Double read FAITRIMES_VALORIMPOSTO write SetAITRIMES_VALORIMPOSTO;
property MensagemExcept :String read FMensagemExcept write SetMensagemExcept;
property ClasseExcept :String read FClasseExcept write SetClasseExcept;
end;
implementation
{ TCRUDApuracaoMensal }
constructor TCRUDApuracaoMensal.Create(poConexao: TFDConnection);
begin
inherited Create;
FConexao := poConexao;
vloFuncoes := TFuncoesGerais.Create(FConexao);
end;
destructor TCRUDApuracaoMensal.Destroy;
begin
if Assigned(vloFuncoes) then
FreeAndNil(vloFuncoes);
inherited;
end;
function TCRUDApuracaoMensal.fncExcluiApuracaoMensal: Boolean;
var
FDApuracao : TFDQuery;
begin
vloFuncoes.pcdCriaFDQueryExecucao(FDApuracao, FConexao);
try
FDApuracao.SQL.Clear;
FDApuracao.SQL.Add('DELETE FROM APURAIMPOSTOMENSAL WHERE AIMES_EMPRESA = :EMPRESA AND AIMES_IMPOSTO = :IMPOSTO AND '+
' AIMES_MES = :MES AND AIMES_ANO= :ANO');
FDApuracao.ParamByName('EMPRESA').AsString := FAIMES_EMPRESA;
FDApuracao.ParamByName('IMPOSTO').AsString := FAIMES_IMPOSTO;
FDApuracao.ParamByName('MES').AsString := FAIMES_MES;
FDApuracao.ParamByName('ANO').AsString := FAIMES_ANO;
FDApuracao.Open;
if FDApuracao.RowsAffected > 0 then
begin
vloFuncoes.fncLogOperacao(FAIMES_EMPRESA, '', '', 'Apuração do período: ' + FAIMES_MES + ' - ' + FAIMES_ANO +
' para imposto ' + FAIMES_IMPOSTO + ', excluida com sucesso',
'',
OrigemLOG_ApuraImposta);
end;
finally
FreeAndNil(FDApuracao);
end;
end;
function TCRUDApuracaoMensal.fncGravarApuracaoMensal: Boolean;
var
FDApuracao : TFDQuery;
begin
Result := True;
vloFuncoes.pcdCriaFDQueryExecucao(FDApuracao, FConexao);
try
FDApuracao.SQL.Clear;
FDApuracao.SQL.Add('SELECT * FROM APURAIMPOSTOMENSAL WHERE AIMES_EMPRESA = :EMPRESA AND AIMES_IMPOSTO = :IMPOSTO AND '+
' AIMES_MES = :MES AND AIMES_ANO= :ANO');
FDApuracao.ParamByName('EMPRESA').AsString := FAIMES_EMPRESA;
FDApuracao.ParamByName('IMPOSTO').AsString := FAIMES_IMPOSTO;
FDApuracao.ParamByName('MES').AsString := FAIMES_MES;
FDApuracao.ParamByName('ANO').AsString := FAIMES_ANO;
FDApuracao.Open;
if FDApuracao.IsEmpty then
begin
FDApuracao.SQL.Clear;
FDApuracao.SQL.Add('INSERT INTO APURAIMPOSTOMENSAL (AIMES_EMPRESA, AIMES_IMPOSTO, AIMES_MES, AIMES_ANO,');
FDApuracao.SQL.Add(' AIMES_RECEITABRUTA, AIMES_RECEITAALTERADA, AIMES_ALIQUOTAIMPOSTO,');
FDApuracao.SQL.Add(' AIMES_VALORIMPOSTO)');
FDApuracao.SQL.Add('VALUES (:AIMES_EMPRESA, :AIMES_IMPOSTO, :AIMES_MES, :AIMES_ANO,');
FDApuracao.SQL.Add(' :AIMES_RECEITABRUTA, :AIMES_RECEITAALTERADA, :AIMES_ALIQUOTAIMPOSTO,');
FDApuracao.SQL.Add(' :AIMES_VALORIMPOSTO)');
FDApuracao.ParamByName('AIMES_EMPRESA').AsString := FAIMES_EMPRESA;
FDApuracao.ParamByName('AIMES_IMPOSTO').AsString := FAIMES_IMPOSTO;
FDApuracao.ParamByName('AIMES_MES').AsString := FAIMES_MES;
FDApuracao.ParamByName('AIMES_ANO').AsString := FAIMES_ANO;
FDApuracao.ParamByName('AIMES_RECEITABRUTA').AsFloat := FAIMES_RECEITABRUTA;
FDApuracao.ParamByName('AIMES_RECEITAALTERADA').AsFloat := FAIMES_RECEITAALTERADA;
FDApuracao.ParamByName('AIMES_ALIQUOTAIMPOSTO').AsFloat := FAIMES_ALIQUOTAIMPOSTO;
FDApuracao.ParamByName('AIMES_VALORIMPOSTO').AsFloat := FAIMES_VALORIMPOSTO;
try
FDApuracao.ExecSQL;
except
on E:Exception do
begin
Result := False;
FMensagemExcept := e.Message;
FClasseExcept := e.ClassName;
end;
end;
vloFuncoes.fncLogOperacao(FAIMES_EMPRESA, '', '', 'Apuração do período: ' + FAIMES_MES + ' - ' + FAIMES_ANO +
' para imposto ' + FAIMES_IMPOSTO + ', gravado com sucesso',
'',
OrigemLOG_ApuraImposta);
end
else
begin
FDApuracao.SQL.Clear;
FDApuracao.SQL.Add('UPDATE APURAIMPOSTOMENSAL');
FDApuracao.SQL.Add('SET AIMES_RECEITABRUTA = :AIMES_RECEITABRUTA,');
FDApuracao.SQL.Add(' AIMES_RECEITAALTERADA = :AIMES_RECEITAALTERADA,');
FDApuracao.SQL.Add(' AIMES_ALIQUOTAIMPOSTO = :AIMES_ALIQUOTAIMPOSTO,');
FDApuracao.SQL.Add(' AIMES_VALORIMPOSTO = :AIMES_VALORIMPOSTO');
FDApuracao.SQL.Add('WHERE (AIMES_EMPRESA = :AIMES_EMPRESA) AND (AIMES_IMPOSTO = :AIMES_IMPOSTO) AND');
FDApuracao.SQL.Add(' (AIMES_MES = :AIMES_MES) AND (AIMES_ANO = :AIMES_ANO)');
FDApuracao.ParamByName('AIMES_EMPRESA').AsString := FAIMES_EMPRESA;
FDApuracao.ParamByName('AIMES_IMPOSTO').AsString := FAIMES_IMPOSTO;
FDApuracao.ParamByName('AIMES_MES').AsString := FAIMES_MES;
FDApuracao.ParamByName('AIMES_ANO').AsString := FAIMES_ANO;
FDApuracao.ParamByName('AIMES_RECEITABRUTA').AsFloat := FAIMES_RECEITABRUTA;
FDApuracao.ParamByName('AIMES_RECEITAALTERADA').AsFloat := FAIMES_RECEITAALTERADA;
FDApuracao.ParamByName('AIMES_ALIQUOTAIMPOSTO').AsFloat := FAIMES_ALIQUOTAIMPOSTO;
FDApuracao.ParamByName('AIMES_VALORIMPOSTO').AsFloat := FAIMES_VALORIMPOSTO;
try
FDApuracao.ExecSQL;
except
on E:Exception do
begin
Result := False;
FMensagemExcept := e.Message;
FClasseExcept := e.ClassName;
end;
end;
vloFuncoes.fncLogOperacao(FAIMES_EMPRESA, '', '', 'Apuração do período: ' + FAIMES_MES + ' - ' + FAIMES_ANO +
' para imposto ' + FAIMES_IMPOSTO + ', alterada com sucesso',
'',
OrigemLOG_ApuraImposta);
end;
finally
FreeAndNil(FDApuracao);
end;
end;
procedure TCRUDApuracaoMensal.SetAIMES_ALIQUOTAIMPOSTO(const Value: Double);
begin
FAIMES_ALIQUOTAIMPOSTO := Value;
end;
procedure TCRUDApuracaoMensal.SetAIMES_ANO(const Value: String);
begin
FAIMES_ANO := Value;
end;
procedure TCRUDApuracaoMensal.SetAIMES_EMPRESA(const Value: String);
begin
FAIMES_EMPRESA := Value;
end;
procedure TCRUDApuracaoMensal.SetAIMES_IMPOSTO(const Value: String);
begin
FAIMES_IMPOSTO := Value;
end;
procedure TCRUDApuracaoMensal.SetAIMES_MES(const Value: String);
begin
FAIMES_MES := Value;
end;
procedure TCRUDApuracaoMensal.SetAIMES_RECEITAALTERADA(const Value: Double);
begin
FAIMES_RECEITAALTERADA := Value;
end;
procedure TCRUDApuracaoMensal.SetAIMES_RECEITABRUTA(const Value: Double);
begin
FAIMES_RECEITABRUTA := Value;
end;
procedure TCRUDApuracaoMensal.SetAIMES_VALORIMPOSTO(const Value: Double);
begin
FAIMES_VALORIMPOSTO := Value;
end;
procedure TCRUDApuracaoMensal.SetClasseExcept(const Value: String);
begin
FClasseExcept := Value;
end;
procedure TCRUDApuracaoMensal.SetMensagemExcept(const Value: String);
begin
FMensagemExcept := Value;
end;
{ TCRUDApuracaoTrimestral }
constructor TCRUDApuracaoTrimestral.Create(poConexao: TFDConnection);
begin
inherited Create;
FConexao := poConexao;
vloFuncoes := TFuncoesGerais.Create(FConexao);
end;
destructor TCRUDApuracaoTrimestral.Destroy;
begin
if Assigned(vloFuncoes) then
FreeAndNil(vloFuncoes);
inherited;
end;
function TCRUDApuracaoTrimestral.fncExcluiApuracaoTrimestral: Boolean;
var
FDApuracao : TFDQuery;
begin
vloFuncoes.pcdCriaFDQueryExecucao(FDApuracao, FConexao);
try
FDApuracao.SQL.Clear;
FDApuracao.SQL.Add('DELETE FROM APURAIMPOSTOTRIMESTRAL WHERE AITRIMES_EMPRESA = :EMPRESA AND '+
' AITRIMES_TRIMESTRE = :TRIMESTRE AND '+
' AITRIMES_ANO= :ANO AND '+
' AITRIMES_IMPOSTO = :IMPOSTO');
FDApuracao.ParamByName('EMPRESA').AsString := FAITRIMES_EMPRESA;
FDApuracao.ParamByName('TRIMESTRE').AsInteger := FAITRIMES_TRIMESTRE;
FDApuracao.ParamByName('ANO').AsString := FAITRIMES_ANO;
FDApuracao.ParamByName('IMPOSTO').AsString := FAITRIMES_IMPOSTO;
FDApuracao.Open;
if FDApuracao.RowsAffected > 0 then
begin
vloFuncoes.fncLogOperacao(FAITRIMES_EMPRESA, '', '', 'Apuração do trimestre: ' + IntToStr(FAITRIMES_TRIMESTRE) + ' - ' + FAITRIMES_ANO +
' para imposto ' + FAITRIMES_IMPOSTO + ', exclída com sucesso',
'',
OrigemLOG_ApuraImposta);
end;
finally
FreeAndNil(FDApuracao);
end;
end;
function TCRUDApuracaoTrimestral.fncGravarApuracaoTrimestral: Boolean;
var
FDApuracao : TFDQuery;
begin
Result := True;
vloFuncoes.pcdCriaFDQueryExecucao(FDApuracao, FConexao);
try
FDApuracao.SQL.Clear;
FDApuracao.SQL.Add('SELECT * FROM APURAIMPOSTOTRIMESTRAL WHERE AITRIMES_EMPRESA = :EMPRESA AND '+
' AITRIMES_TRIMESTRE = :TRIMESTRE AND '+
' AITRIMES_ANO= :ANO AND '+
' AITRIMES_IMPOSTO = :IMPOSTO');
FDApuracao.ParamByName('EMPRESA').AsString := FAITRIMES_EMPRESA;
FDApuracao.ParamByName('TRIMESTRE').AsInteger := FAITRIMES_TRIMESTRE;
FDApuracao.ParamByName('ANO').AsString := FAITRIMES_ANO;
FDApuracao.ParamByName('IMPOSTO').AsString := FAITRIMES_IMPOSTO;
FDApuracao.Open;
if FDApuracao.IsEmpty then
begin
FDApuracao.SQL.Clear;
FDApuracao.SQL.Add('INSERT INTO APURAIMPOSTOTRIMESTRAL (AITRIMES_EMPRESA, AITRIMES_IMPOSTO, AITRIMES_TRIMESTRE, AITRIMES_ANO,');
FDApuracao.SQL.Add(' AITRIMES_RECEITABRUTA, AITRIMES_RECEITAALTERADA, AITRIMES_ALIQIMPOSTO,');
FDApuracao.SQL.Add(' AITRIMES_PRESIMPOSTO, AITRIMES_RECEITAFINANC, AITRIMES_RETENCAOIMPOSTO,');
FDApuracao.SQL.Add(' AITRIMES_ADICIONALIRPJ, AITRIMES_VALORIMPOSTO)');
FDApuracao.SQL.Add('VALUES (:AITRIMES_EMPRESA, :AITRIMES_IMPOSTO, :AITRIMES_TRIMESTRE, :AITRIMES_ANO,');
FDApuracao.SQL.Add(' :AITRIMES_RECEITABRUTA, :AITRIMES_RECEITAALTERADA, :AITRIMES_ALIQIMPOSTO,');
FDApuracao.SQL.Add(' :AITRIMES_PRESIMPOSTO, :AITRIMES_RECEITAFINANC, :AITRIMES_RETENCAOIMPOSTO,');
FDApuracao.SQL.Add(' :AITRIMES_ADICIONALIRPJ, :AITRIMES_VALORIMPOSTO); ');
FDApuracao.ParamByName('AITRIMES_EMPRESA').AsString := FAITRIMES_EMPRESA;
FDApuracao.ParamByName('AITRIMES_IMPOSTO').AsString := FAITRIMES_IMPOSTO;
FDApuracao.ParamByName('AITRIMES_TRIMESTRE').AsInteger := FAITRIMES_TRIMESTRE;
FDApuracao.ParamByName('AITRIMES_ANO').AsString := FAITRIMES_ANO;
FDApuracao.ParamByName('AITRIMES_RECEITABRUTA').AsFloat := FAITRIMES_RECEITABRUTA;
FDApuracao.ParamByName('AITRIMES_RECEITAALTERADA').AsFloat := FAITRIMES_RECEITAALTERADA;
FDApuracao.ParamByName('AITRIMES_ALIQIMPOSTO').AsFloat := FAITRIMES_ALIQIMPOSTO;
FDApuracao.ParamByName('AITRIMES_PRESIMPOSTO').AsFloat := FAITRIMES_PRESIMPOSTO;
FDApuracao.ParamByName('AITRIMES_RECEITAFINANC').AsFloat := FAITRIMES_RECEITAFINANC;
FDApuracao.ParamByName('AITRIMES_RETENCAOIMPOSTO').AsFloat := FAITRIMES_RETENCAOIMPOSTO;
FDApuracao.ParamByName('AITRIMES_ADICIONALIRPJ').AsFloat := FAITRIMES_ADICIONALIRPJ;
FDApuracao.ParamByName('AITRIMES_VALORIMPOSTO').AsFloat := FAITRIMES_VALORIMPOSTO;
try
FDApuracao.ExecSQL;
except
on E:Exception do
begin
Result := False;
FMensagemExcept := e.Message;
FClasseExcept := e.ClassName;
end;
end;
vloFuncoes.fncLogOperacao(FAITRIMES_EMPRESA, '', '', 'Apuração do trimestre: ' + IntToStr(FAITRIMES_TRIMESTRE) + ' - ' + FAITRIMES_ANO +
' para imposto ' + FAITRIMES_IMPOSTO + ', gravado com sucesso',
'',
OrigemLOG_ApuraImposta);
end
else
begin
FDApuracao.SQL.Clear;
FDApuracao.SQL.Add('UPDATE APURAIMPOSTOTRIMESTRAL');
FDApuracao.SQL.Add('SET AITRIMES_RECEITABRUTA = :AITRIMES_RECEITABRUTA,');
FDApuracao.SQL.Add(' AITRIMES_RECEITAALTERADA = :AITRIMES_RECEITAALTERADA,');
FDApuracao.SQL.Add(' AITRIMES_ALIQIMPOSTO = :AITRIMES_ALIQIMPOSTO,');
FDApuracao.SQL.Add(' AITRIMES_PRESIMPOSTO = :AITRIMES_PRESIMPOSTO,');
FDApuracao.SQL.Add(' AITRIMES_RECEITAFINANC = :AITRIMES_RECEITAFINANC,');
FDApuracao.SQL.Add(' AITRIMES_RETENCAOIMPOSTO = :AITRIMES_RETENCAOIMPOSTO,');
FDApuracao.SQL.Add(' AITRIMES_ADICIONALIRPJ = :AITRIMES_ADICIONALIRPJ,');
FDApuracao.SQL.Add(' AITRIMES_VALORIMPOSTO = :AITRIMES_VALORIMPOSTO');
FDApuracao.SQL.Add('WHERE (AITRIMES_EMPRESA = :AITRIMES_EMPRESA) AND (AITRIMES_IMPOSTO = :AITRIMES_IMPOSTO) AND');
FDApuracao.SQL.Add(' (AITRIMES_TRIMESTRE = :AITRIMES_TRIMESTRE) AND (AITRIMES_ANO = :AITRIMES_ANO);');
FDApuracao.ParamByName('AITRIMES_EMPRESA').AsString := FAITRIMES_EMPRESA;
FDApuracao.ParamByName('AITRIMES_IMPOSTO').AsString := FAITRIMES_IMPOSTO;
FDApuracao.ParamByName('AITRIMES_TRIMESTRE').AsInteger := FAITRIMES_TRIMESTRE;
FDApuracao.ParamByName('AITRIMES_ANO').AsString := FAITRIMES_ANO;
FDApuracao.ParamByName('AITRIMES_RECEITABRUTA').AsFloat := FAITRIMES_RECEITABRUTA;
FDApuracao.ParamByName('AITRIMES_RECEITAALTERADA').AsFloat := FAITRIMES_RECEITAALTERADA;
FDApuracao.ParamByName('AITRIMES_ALIQIMPOSTO').AsFloat := FAITRIMES_ALIQIMPOSTO;
FDApuracao.ParamByName('AITRIMES_PRESIMPOSTO').AsFloat := FAITRIMES_PRESIMPOSTO;
FDApuracao.ParamByName('AITRIMES_RECEITAFINANC').AsFloat := FAITRIMES_RECEITAFINANC;
FDApuracao.ParamByName('AITRIMES_RETENCAOIMPOSTO').AsFloat := FAITRIMES_RETENCAOIMPOSTO;
FDApuracao.ParamByName('AITRIMES_ADICIONALIRPJ').AsFloat := FAITRIMES_ADICIONALIRPJ;
FDApuracao.ParamByName('AITRIMES_VALORIMPOSTO').AsFloat := FAITRIMES_VALORIMPOSTO;
try
FDApuracao.ExecSQL;
except
on E:Exception do
begin
Result := False;
FMensagemExcept := e.Message;
FClasseExcept := e.ClassName;
end;
end;
vloFuncoes.fncLogOperacao(FAITRIMES_EMPRESA, '', '', 'Apuração do trimestre: ' + IntToStr(FAITRIMES_TRIMESTRE) + ' - ' + FAITRIMES_ANO +
' para imposto ' + FAITRIMES_IMPOSTO + ', alterada com sucesso',
'',
OrigemLOG_ApuraImposta);
end;
finally
FreeAndNil(FDApuracao);
end;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_ADICIONALIRPJ(
const Value: Double);
begin
FAITRIMES_ADICIONALIRPJ := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_ALIQIMPOSTO(const Value: Double);
begin
FAITRIMES_ALIQIMPOSTO := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_ANO(const Value: String);
begin
FAITRIMES_ANO := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_EMPRESA(const Value: String);
begin
FAITRIMES_EMPRESA := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_IMPOSTO(const Value: String);
begin
FAITRIMES_IMPOSTO := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_PRESIMPOSTO(const Value: Double);
begin
FAITRIMES_PRESIMPOSTO := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_RECEITAALTERADA(
const Value: Double);
begin
FAITRIMES_RECEITAALTERADA := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_RECEITABRUTA(const Value: Double);
begin
FAITRIMES_RECEITABRUTA := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_RECEITAFINANC(
const Value: Double);
begin
FAITRIMES_RECEITAFINANC := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_RETENCAOIMPOSTO(
const Value: Double);
begin
FAITRIMES_RETENCAOIMPOSTO := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_TRIMESTRE(const Value: Integer);
begin
FAITRIMES_TRIMESTRE := Value;
end;
procedure TCRUDApuracaoTrimestral.SetAITRIMES_VALORIMPOSTO(const Value: Double);
begin
FAITRIMES_VALORIMPOSTO := Value;
end;
procedure TCRUDApuracaoTrimestral.SetClasseExcept(const Value: String);
begin
FClasseExcept := Value;
end;
procedure TCRUDApuracaoTrimestral.SetMensagemExcept(const Value: String);
begin
FMensagemExcept := Value;
end;
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uAppUserImpl.pas }
{ Описание: Реализация IAppUser }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uAppUserImpl;
interface
uses
SysUtils, Classes, uServices;
type
TAppUser = class(TInterfacedObject, IAppUser)
private
FFio: string;
FId: Variant;
FLoginName: string;
public
function ChangePassword(AOldPassword, ANewPassword: String): Boolean; virtual;
stdcall;
function GetFio: string; stdcall;
function GetId: Variant; stdcall;
function GetLoginName: string; stdcall;
function InRole(ARoleName: string): Boolean; virtual; stdcall;
procedure SetFio(const Value: string); stdcall;
procedure SetId(Value: Variant); stdcall;
procedure SetLoginName(const Value: string); stdcall;
property Fio: string read GetFio write SetFio;
property Id: Variant read GetId write SetId;
property LoginName: string read GetLoginName write SetLoginName;
end;
implementation
{
*********************************** TAppUser ***********************************
}
function TAppUser.ChangePassword(AOldPassword, ANewPassword: String): Boolean;
begin
// TODO -cMM : Interface wizard: Implement interface method
end;
function TAppUser.GetFio: string;
begin
Result := FFio;
end;
function TAppUser.GetId: Variant;
begin
Result := FId;
end;
function TAppUser.GetLoginName: string;
begin
Result := FLoginName;
end;
function TAppUser.InRole(ARoleName: string): Boolean;
begin
Result := True
end;
procedure TAppUser.SetFio(const Value: string);
begin
if FFio <> Value then
begin
FFio := Value;
end;
end;
procedure TAppUser.SetId(Value: Variant);
begin
if FId <> Value then
begin
FId := Value;
end;
end;
procedure TAppUser.SetLoginName(const Value: string);
begin
if FLoginName <> Value then
begin
FLoginName := Value;
end;
end;
end.
|
unit Eagle.Alfred.CreateCommand;
interface
uses
System.SysUtils,
System.Classes,
Winapi.Windows,
System.RegularExpressions,
Eagle.ConsoleIO,
Eagle.Alfred.DprojParser,
Eagle.Alfred.Command;
type
ECreateCommandException = class(Exception);
TCreateCommand = class(TInterfacedObject, ICommand)
private
FAppPath: string;
FCommand: string;
FModelName: string;
FModuleName: string;
FStringList: TStringList;
FDprojParser: TDprojParser;
FConsoleIO: IConsoleIO;
procedure CreateView;
procedure CreateViewModel;
procedure CreateModel;
procedure CreateRepository;
procedure CreateService;
procedure CreateTest;
procedure DoCreateModel(const SubLayer, Sufix, TemplateInterface,
TemplateClass: string);
procedure Parse;
procedure GenerateFile(const Template, UnitName, FileName: string; const HasGUID: Boolean = False);
procedure LogInfo(const Value: string);
procedure LogError(const Value: string);
procedure LogProgress(const Value: string; const NewLine: Boolean = False);
procedure RegisterForm(const UnitName, FormName, Path: string);
procedure RegisterUnit(const Name, Path: string);
procedure CreateDiretories(const Paths: array of string);
function Capitalize(const Str: string): string;
function GuidCreate: string;
public
constructor Create(const AppPath: string; ConsoleIO: IConsoleIO; DprojParser: TDprojParser);
destructor Destroy; override;
procedure Execute;
procedure Help;
end;
implementation
{ TCreateCommand }
function TCreateCommand.Capitalize(const Str: string): string;
var
flag: Boolean;
i: Byte;
s: string;
begin
flag := True;
s := Str.ToLower;
Result := EmptyStr;
for i := 1 to Length(s) do
begin
if flag then
Result := Result + AnsiUpperCase(s[i])
else
Result := Result + s[i];
flag := (s[i] in [' ', '[',']', '(', ')']);
end;
end;
constructor TCreateCommand.Create(const AppPath: string; ConsoleIO: IConsoleIO;
DprojParser: TDprojParser);
begin
FStringList := TStringList.Create;
FDprojParser := DprojParser;
FAppPath := AppPath;
FConsoleIO := ConsoleIO;
end;
procedure TCreateCommand.CreateDiretories(const Paths: array of string);
var
Path: string;
begin
for Path in Paths do
begin
if not DirectoryExists(Path) then
ForceDirectories(Path);
end;
end;
procedure TCreateCommand.CreateModel;
begin
if not TRegEx.IsMatch(FCommand, '^(m|mv|mvm|mvvm|model)$') then
Exit;
DoCreateModel('Entity', '', 'IModel.pas', 'TModel.pas');
end;
procedure TCreateCommand.CreateRepository;
begin
if not TRegEx.IsMatch(FCommand, '^(rep|repository)$') then
Exit;
DoCreateModel('Repository', 'Repository', 'IModelRepository.pas', 'TModelRepository.pas');
end;
procedure TCreateCommand.CreateService;
begin
if not TRegEx.IsMatch(FCommand, '^(sev|service)$') then
Exit;
DoCreateModel('Service', 'Service', 'IModelService.pas', 'TModelService.pas');
end;
procedure TCreateCommand.CreateTest;
begin
end;
procedure TCreateCommand.CreateView;
var
Namespace, Dir: string;
begin
if not TRegEx.IsMatch(FCommand, '^(v|mv|vvm|mvvm|view)$') then
Exit;
Namespace := 'Eagle.ERP.' + FModuleName + '.View.' + FModelName;
Dir := 'src\modulos\' + FModuleName.ToLower + '\view\';
CreateDiretories(['.\' + Dir]);
GenerateFile('View.dfm', Namespace + 'View.dfm', '.\' + Dir + Namespace + 'View.dfm');
GenerateFile('View.pas', Namespace + 'View.pas', '.\' + Dir + Namespace + 'View.pas');
RegisterForm(Namespace + 'View.pas', FModelName + 'View', '..\..\' + Dir + Namespace + 'View.pas');
end;
procedure TCreateCommand.CreateViewModel;
var
Namespace, Dir, InterfacePath, ClassPath: string;
NamespaceInterface, NamespaceClass: string;
begin
if not TRegEx.IsMatch(FCommand, '^(vm|vvm|mvm|mvvm|viewmodel)$') then
Exit;
Namespace := 'Eagle.ERP.' + FModuleName + '.ViewModel.';
Dir := 'src\modulos\' + FModuleName.ToLower + '\viewmodel\';
InterfacePath := Dir + Namespace + FModelName + 'ViewModel.pas';
ClassPath := Dir + 'impl\' + Namespace + 'Impl.' + FModelName + 'ViewModel.pas';
NamespaceInterface := Namespace + FModelName + 'ViewModel.pas';
NamespaceClass := Namespace + 'impl.' + FModelName + 'ViewModel.pas';
CreateDiretories(['.\' + Dir, '.\' + Dir + '\impl\']);
GenerateFile('IViewModel.pas', NamespaceInterface, '.\' + InterfacePath, True);
GenerateFile('TViewModel.pas', NamespaceClass, '.\' + ClassPath);
RegisterUnit(NamespaceInterface, '..\..\' + InterfacePath);
RegisterUnit(NamespaceClass, '..\..\' + ClassPath);
end;
destructor TCreateCommand.Destroy;
begin
if Assigned(FStringList) then
FStringList.Free;
inherited;
end;
procedure TCreateCommand.DoCreateModel(const SubLayer, Sufix, TemplateInterface, TemplateClass: string);
var
Namespace, Dir, InterfacePath, ClassPath, ModelNameFull: string;
NamespaceInterface, NamespaceClass: string;
begin
ModelNameFull := FModelName + Sufix;
Namespace := 'Eagle.ERP.' + FModuleName + '.Model.' + SubLayer + '.';
Dir := 'src\modulos\' + FModuleName.ToLower + '\model\' + SubLayer.ToLower + '\';
InterfacePath := Dir + Namespace + ModelNameFull + '.pas';
ClassPath := Dir + 'impl\' + Namespace + 'Impl.' + ModelNameFull + '.pas';
NamespaceInterface := Namespace + ModelNameFull + '.pas';
NamespaceClass := Namespace + 'Impl.' + ModelNameFull + '.pas';
CreateDiretories(['.\' + Dir, '.\' + Dir + '\impl\']);
GenerateFile(TemplateInterface, NamespaceInterface, '.\' + InterfacePath, True);
GenerateFile(TemplateClass, NamespaceClass, '.\' + ClassPath);
RegisterUnit(NamespaceInterface, '..\..\' + InterfacePath);
RegisterUnit(NamespaceClass, '..\..\' + ClassPath);
end;
procedure TCreateCommand.Execute;
begin
try
Parse;
CreateModel;
CreateView;
CreateViewModel;
CreateRepository;
CreateService;
CreateTest;
FDprojParser.Save;
Help;
except
on E: ECreateCommandException do
FConsoleIO.WriteError(E.Message);
end;
end;
procedure TCreateCommand.GenerateFile(const Template, UnitName, FileName: string; const HasGUID: Boolean = False);
begin
LogProgress('Gerando: ' + UnitName + '...');
FStringList.LoadFromFile(FAppPath + 'templates\' + Template);
FStringList.Text := FStringList.Text.Replace('{ModelName}', FModelName, [rfReplaceAll]);
FStringList.Text := FStringList.Text.Replace('{ModuleName}', FModuleName, [rfReplaceAll]);
if HasGUID then
FStringList.Text := FStringList.Text.Replace('{GUID}', GuidCreate, [rfReplaceAll]);
FStringList.SaveToFile(FileName);
LogProgress('Gerando: ' + UnitName + '... Done', True);
end;
function TCreateCommand.GuidCreate: string;
var
ID: TGUID;
begin
ID := TGUID.NewGuid;
Result := GUIDToString(ID);
end;
procedure TCreateCommand.Help;
begin
if not FCommand.Equals('help') then
Exit;
FConsoleIO.WriteInfo('Cria arquivos relacionados às operções de CRUD');
FConsoleIO.WriteInfo('');
FConsoleIO.WriteInfo('Para criar arquivos use:');
FConsoleIO.WriteInfo('CREATE [tipo] [nome_do_modelo] [nome_do_modulo]');
FConsoleIO.WriteInfo('');
FConsoleIO.WriteInfo('Tipos:');
FConsoleIO.WriteInfo('');
FConsoleIO.WriteInfo('View Cria um novo Form');
FConsoleIO.WriteInfo('Model Cria uma nova entidade');
FConsoleIO.WriteInfo('ViewModel Cria um novo ViewModel');
FConsoleIO.WriteInfo('Repository Cria um novo repositório');
FConsoleIO.WriteInfo('Service Cria um novo serviço');
FConsoleIO.WriteInfo('MVVM Cria os arquivos no padrão MVVM, caso não deseje gerar algum arquivo basta não informa a letra correspondente');
FConsoleIO.WriteInfo('');
end;
procedure TCreateCommand.LogError(const Value: string);
begin
if Assigned(FConsoleIO) then
FConsoleIO.WriteError(Value);
end;
procedure TCreateCommand.LogInfo(const Value: string);
begin
if Assigned(FConsoleIO) then
FConsoleIO.WriteInfo(Value);
end;
procedure TCreateCommand.LogProgress(const Value: string; const NewLine: Boolean = False);
begin
if not Assigned(FConsoleIO) then
Exit;
FConsoleIO.WriteProcess(Value);
if NewLine then
FConsoleIO.WriteInfo('');
end;
procedure TCreateCommand.Parse;
begin
FCommand := ParamStr(2).ToLower;
FModelName := Capitalize(ParamStr(3));
FModuleName := Capitalize(ParamStr(4));
end;
procedure TCreateCommand.RegisterForm(const UnitName, FormName, Path: string);
begin
LogProgress('Registrado o formulário: ' + UnitName + '...');
FDprojParser.AddForm(UnitName, FormName, Path);
LogProgress('Registrado o formulário: ' + UnitName + '... Done', True);
end;
procedure TCreateCommand.RegisterUnit(const Name, Path: string);
begin
LogProgress('Registrado a unit: ' + Name + '...');
FDprojParser.AddUnit(Name, Path);
LogProgress('Registrado a unit: ' + Name + '... Done', True);
end;
end.
|
{ 12/10/1999 10:17:34 AM > [Bill on BILL] checked out /Change tables to TTS }
unit SelectCollateralCode;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, Grids, AdvGrid, FFSAdvStringGrid, sBitBtn;
type
TfrmSelectCollateralCode = class(TForm)
grdColl: TFFSAdvStringGrid;
btnOk: TsBitBtn;
btnCancel: TsBitBtn;
procedure grdCollDblClick(Sender: TObject);
procedure grdCollMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure grdCollMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
private
{ Private declarations }
procedure LoadGrid;
public
{ Public declarations }
end;
function dlgSelectCollateralCode(var CollCode:shortstring):boolean;
implementation
uses datamod, TicklerTypes, ffsutils, TicklerGlobals;
{$R *.DFM}
function dlgSelectCollateralCode(var CollCode:shortstring):boolean;
var frmSelect : TfrmSelectCollateralCode;
begin
if daapi.CollGetCodeCount(CurrentLend.Number) = 0 then
begin
TrMsgInformation('There are not any collateral codes to choose from');
result := false;
exit;
end;
result := false;
frmSelect := TfrmSelectCollateralCode.Create(Application);
frmSelect.LoadGrid;
if frmSelect.ShowModal = mrOk then
begin
CollCode := frmSelect.grdColl.cells[0, frmSelect.grdColl.Row];
result := true;
end;
frmSelect.Free;
end;
procedure TfrmSelectCollateralCode.grdCollDblClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TfrmSelectCollateralCode.LoadGrid;
var sl : TStringList;
itemcount : integer;
x : integer;
begin
sl := TStringList.create;
try
daapi.CollGetCodeDescList(CurrentLend.Number, sl);
itemcount := sl.count;
if itemcount > 0 then grdColl.RowCount := ItemCount + 1
else grdColl.RowCount := 2;
for x := 1 to itemcount do grdColl.rows[x].CommaText := sl[x-1];
finally
sl.free;
end;
grdColl.FitLastColumn;
end;
procedure TfrmSelectCollateralCode.grdCollMouseWheelDown(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
grdColl.SetFocus;
Handled := true;
end;
procedure TfrmSelectCollateralCode.grdCollMouseWheelUp(Sender: TObject;
Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
begin
grdColl.SetFocus;
Handled := true;
end;
end.
|
{8. Un local de ropa desea analizar las ventas realizadas en el último mes. Para
ello se lee por cada día del mes, los montos de las ventas realizadas. La
lectura de montos para cada día finaliza cuando se lee el monto 0. Se asume
un mes de 31 días. Informar la cantidad de ventas por cada día, y el monto
total acumulado en ventas de todo el mes.
a) Modifique el ejercicio anterior para que además informe el día en el
que se realizó la mayor cantidad de ventas.
}
program ejercicio8;
const
Df = 31;
type
mes = 1..31;
var
dia: mes;
montoDiario, sumaDiaria, sumaTotal: Real;
i: Integer;
begin
sumaDiaria:= 0;
sumaTotal:= 0;
for i := 1 to Df do
begin
writeln('El dia del mes es: ', i);
write('Ingrese el monto de la venta: ');
readln(montoDiario);
writeln('------------------------');
while montoDiario <> 0 do
begin
sumaDiaria:= sumaDiaria + montoDiario;
write('Ingrese el mondo de la venta: ') ;
readln(montoDiario);
writeln('----------------------');
end;
writeln('El monto total del dia: ', i, ' es: ', sumaDiaria:2:2);
sumaTotal:= sumaTotal + sumaDiaria;
end;
writeln('El monto todal de ventas del mes es: ', sumaTotal:2:2);
end. |
unit eAtasOrais.Model.Configuracao;
interface
uses
eAtasOrais.Model.Interfaces;
Type
TModelConfiguracao = Class(TInterfacedObject, iModelConfiguracao)
Private
Fservidor : string;
FPastaAtas : string;
FUID : String;
FPWD : string;
FUnidade : String;
FBanco : String;
FTestes : Boolean;
Public
Constructor Create;
Destructor Destroy; Override;
Class function New: iModelConfiguracao;
Function GravaConfiguracoes : iModelConfiguracao;
Function Servidor : String; Overload;
Function Servidor (Servidor: String) : iModelConfiguracao; Overload;
Function PastaAtas : String; Overload;
Function PastaAtas (Pasta: String) : iModelConfiguracao; Overload;
Function UID : String; Overload;
Function UID (UID: String) : iModelConfiguracao; Overload;
Function PWD : String; Overload;
Function PWD (PWD: String) : iModelConfiguracao; Overload;
Function Unidade : String; Overload;
Function Unidade (Unidade: String) : iModelConfiguracao; Overload;
Function Banco : string; Overload;
Function Banco (Value: string) : iModelConfiguracao; overload;
Function Testes : Boolean; Overload;
Function Testes (Value: Boolean) : iModelConfiguracao; overload;
End;
implementation
{ TModelConfiguracao }
Uses inifiles, System.SysUtils;
function TModelConfiguracao.Banco(Value: string): iModelConfiguracao;
begin
Result := self;
FBanco := Value;
end;
function TModelConfiguracao.Banco: string;
begin
Result := FBanco;
end;
constructor TModelConfiguracao.Create;
var cfg: tinifile;
arq: string;
PastaAtas, PastaBanco : string;
begin
PastaAtas := ExtractFilePath(ParamStr(0)) + 'AtasOrais\';
PastaBanco := ExtractFilePath(ParamStr(0)) + 'BD\';
arq := Extractfilepath(ParamStr(0))+'eAtasOrais.config.ini';
cfg := TIniFile.Create(arq);
try
fservidor := cfg.ReadString('SOP', 'Servidor', '');
FUID := cfg.ReadString('SOP', 'UID', '');
FPWD := cfg.ReadString('SOP', 'PWD', '');
FPastaAtas := cfg.ReadString('Base', 'Pasta', PastaAtas);
FUnidade := cfg.ReadString('Dados', 'Unidade', 'Escola Teste');
FBanco := cfg.ReadString('Conexao', 'Banco', PastaBanco);
FTestes := cfg.ReadBool('Desenvolvimento', 'Testes', true);
finally
cfg.DisposeOf;
end;
end;
destructor TModelConfiguracao.Destroy;
begin
inherited;
end;
function TModelConfiguracao.GravaConfiguracoes: iModelConfiguracao;
var cfg: tinifile;
arq: string;
begin
Result := Self;
arq := Extractfilepath(ParamStr(0))+'eAtasOrais.config.ini';
cfg := TIniFile.Create(arq);
try
cfg.WriteString('SOP', 'Servidor', fservidor);
cfg.WriteString('SOP', 'UID', FUID);
cfg.WriteString('SOP', 'PWD', FPWD);
cfg.WriteString('Base', 'Pasta', FPastaAtas);
cfg.WriteString('Dados', 'Unidade', FUnidade);
cfg.WriteString('Conexao', 'Banco', FBanco);
cfg.WriteBool('Desenvolvimento', 'Testes', FTestes);
finally
cfg.DisposeOf;
end;
end;
class function TModelConfiguracao.New: iModelConfiguracao;
begin
Result := Self.Create;
end;
function TModelConfiguracao.PastaAtas(Pasta: String): iModelConfiguracao;
begin
Result := Self;
FPastaAtas := Pasta;
end;
function TModelConfiguracao.PastaAtas: String;
begin
Result := FPastaAtas;
end;
function TModelConfiguracao.PWD(PWD: String): iModelConfiguracao;
begin
Result := Self;
FPWD := PWD;
end;
function TModelConfiguracao.PWD: String;
begin
Result := FPWD;
end;
function TModelConfiguracao.Servidor(Servidor: String): iModelConfiguracao;
begin
Result := Self;
Fservidor := Servidor;
end;
function TModelConfiguracao.Servidor: String;
begin
Result := Fservidor;
end;
function TModelConfiguracao.Testes(Value: Boolean): iModelConfiguracao;
begin
Result := Self;
FTestes := Value;
end;
function TModelConfiguracao.Testes: Boolean;
begin
Result := FTestes;
end;
function TModelConfiguracao.UID: String;
begin
Result := FUID;
end;
function TModelConfiguracao.UID(UID: String): iModelConfiguracao;
begin
Result := Self;
FUID := UID;
end;
function TModelConfiguracao.Unidade: String;
begin
Result := FUnidade;
end;
function TModelConfiguracao.Unidade(Unidade: String): iModelConfiguracao;
begin
Result := Self;
FUnidade := Unidade;
end;
end.
|
program TESTCH01 ( INPUT , OUTPUT ) ;
//$A+
var IX : INTEGER ;
function IX_INT ( X : CHAR ; Y : CHAR ) : INTEGER ;
//**************************************************
// ermittle Index fuer internes Feld aus externem
// ab Position 26 (3. zeile) werden die Felder
// der 1. Zeile (a1, b1 bis h1) abgelegt.
// ..xxxxxxxx....yyyyyyyy....zzzzzzzz....
// das waeren also demnach die 1., 2. und 3. Zeile
// ab interner Position 24
//**************************************************
var I1 , I2 : INTEGER ;
begin (* IX_INT *)
I1 := ( ORD ( Y ) - ORD ( '1' ) ) * 12 ;
I2 := ORD ( X ) - ORD ( 'a' ) ;
IX_INT := I1 + I2 + 26 ;
end (* IX_INT *) ;
function IX_EXT ( X : INTEGER ) : STRING ;
//*****************************************************
// Rueckgabe eines Strings aus zwei Buchstaben
// z.B. a1 - oder Leerstring, wenn kein "echtes" Feld
//*****************************************************
const S1 = 'abcdefgh' ;
S2 = '12345678' ;
var S : STRING ( 2 ) ;
I1 , I2 : INTEGER ;
begin (* IX_EXT *)
S := '' ;
if X < 26 then
begin
IX_EXT := S ;
return
end (* then *) ;
I1 := X MOD 12 - 1 ;
I2 := X DIV 12 - 1 ;
if ( I1 < 1 ) or ( I1 > 8 ) or ( I2 < 1 ) or ( I2 > 8 ) then
return ;
S := S1 [ I1 ] || S2 [ I2 ] ;
IX_EXT := S ;
end (* IX_EXT *) ;
begin (* HAUPTPROGRAMM *)
TERMIN ( INPUT ) ;
TERMOUT ( OUTPUT ) ;
WRITELN ( 'bitte position eingeben (a1 = 26, ende mit 0):' ) ;
repeat
READLN ( IX ) ;
WRITELN ( IX , ' ergibt position ' , IX_EXT ( IX ) ) ;
until IX = 0
end (* HAUPTPROGRAMM *) .
|
{Pascal wrappper for proj.4 library}
{This License applies only to this wrapper and not the proj.4 itself}
{For the latest proj.4 visit https://github.com/OSGeo/proj.4}
{* Author: Giannis Giannoulas, <gg@iqsoft.gr>
*
******************************************************************************
* Copyright (c) 2016,Giannis Giannoulas
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO COORD SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*****************************************************************************}
unit proj4api;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ctypes, dynlibs, pj_prototypes, pj_types;
const
PJ_VERSION = 493;
type
{ TProj4 }
TProj4 = class(TObject)
private
{ private declarations }
LibHandle: TLibHandle;
LibFilename: string;
libVersion: string;
function geterrorstr: string;
function LoadProjLibrary: boolean;
public
{ public declarations }
{default constructor}
constructor Create; overload;
{constructor with absolute path to dynamic lib}
constructor Create(libpath: string); overload;
destructor Destroy; override;
procedure ReleaseProjLibrary;
procedure ConvertLocalToTarget(inputProj, outProj: string; out x, y: double);
property libraryVersion: string read libVersion;
property libraryFilename: string read LibFilename write LibFilename;
property GetLastError: string read geterrorstr;
function fwd(val: projLP; proj: projPJ): projXY;
function inv(val: projXY; proj: projPJ): projLP;
function fwd3d(val: projLPZ; proj: projPJ): projXYZ;
function inv3d(val: projXYZ; proj: projPJ): projLPZ;
{Transform the x/y/z points from the source coordinate system to the destination coordinate system}
function transform(src, dst: projPJ; point_count: longint; point_offset: integer; out x, y: double; z: double = 0): integer;
function datum_transform(src, dst: projPJ; point_count: longint; point_offset: integer; out x, y: double; z: double = 0): integer;
function geocentric_to_geodetic(a, es: double; point_count: longint; point_offset: integer; out x, y: double; z: double = 0): integer;
function geodetic_to_geocentric(a, es: double; point_count: longint; point_offset: integer; out x, y: double; z: double = 0): integer;
function compare_datums(srcdefn: projPJ; dstdefn: projPJ): integer;
function apply_gridshift(ctx: projCTX; c: string; i: integer; point_count: longint; point_offset: integer;
out x, y: double; z: double = 0): integer;
{Frees all resources associated with loaded and cached datum shift grids.}
procedure deallocate_grids;
procedure clear_initcache;
{Returns TRUE if the passed coordinate system is geographic (proj=latlong).}
function is_latlong(proj: projPJ): boolean;
function is_geocent(proj: projPJ): boolean;
procedure get_spheroid_defn(defn: projPJ; major_axis, eccentricity_squared: double);
procedure pr_list(proj: projPJ);
{Frees all resources associated with pj.}
procedure FreePJ(proj: projPJ);
{Install a custom function for finding init and grid shift files.}
procedure set_finder(finder: TprojFinder);
{Set a list of directories to search for init and grid shift files.}
procedure set_searchpath(Count: integer; path: string);
procedure set_searchpath(Count: integer; path: PPJ_CSTR);
function init(argc: integer; argv: string): projPJ;
{This function converts a string representation of a coordinate system definition into a projPJ object }
function init_plus(args: string): projPJ;
// function init_ctx(ctx: projCtx; argc: integer; argv: string): projPJ;
// function init_plus_ctx(ctx: projCtx; args: string): projPJ;
{Returns the PROJ.4 initialization string suitable for use with pj_init_plus()}
function get_def(proj: projPJ; i: integer): string;
{Returns a new coordinate system definition which is the geographic coordinate (lat/long) system underlying}
function latlong_from_proj(proj: projPJ): projPJ;
function malloc(size: csize_t): pointer;
procedure dalloc(ptr: pointer);
function calloc(n: csize_t; size: csize_t): pointer;
function dealloc(ptr: pointer): pointer;
{Returns the error text associated with the passed in error code.}
function strerrno(err: integer): string;
{Returns a pointer to the global pj_errno error variable.}
function get_errno_ref: integer;
{Returns an internal string describing the release version.}
function get_release: string;
// procedure acquire_lock;
// procedure release_lock;
// procedure cleanup_lock;
// function get_default_ctx: projCTX;
// function get_ctx(proj: projPJ): projCtx;
// procedure set_ctx(proj: projPJ; ctx: projCtx);
// function ctx_alloc: projCtx;
// procedure ctx_free(ctx: projCtx);
// function ctx_get_errno(ctx: projCtx): integer;
// procedure ctx_set_errno(ctx: projCtx; no: integer);
// procedure ctx_set_debug(ctx: projCtx; no: integer);
// procedure ctx_set_logger(ctx: projCtx; logger: Tprojlogger);
// procedure ctx_set_app_data(ctx: projCtx; ptr: pointer);
// function ctx_get_app_data(ctx: projCtx): pointer;
// procedure ctx_set_fileapi(ctx: projCtx; api: PprojFileAPI);
// function ctx_get_fileapi(ctx: projCtx): PprojFileAPI;
// procedure log(ctx: projCtx; level: integer; fmt: string; Args: array of const);
// procedure stderr_logger(a: Pointer; i: integer; c: string);
// function get_default_fileapi: PprojFileAPI;
// function ctx_fopen(ctx: projCtx; filename, access: string): PAFile;
// function ctx_fread(ctx: projCtx; buffer: Pointer; size, nmemb: csize_t; file_: PAFile): csize_t;
// function ctx_fseek(ctx: projCtx; file_: PAFile; offset: longint; whence: integer): integer;
// function ctx_ftell(ctx: projCtx; file_: PAFile): longint;
// procedure ctx_fclose(ctx: projCtx; file_: PAFile);
// function ctx_fgets(ctx: projCtx; line: string; size: integer; file_: PAFile): string;
// function open_lib(ctx: projCtx; Name, mode: string): PAFile;
// pj_errno: function: cint; cdecl;
end;
implementation
{ TProj4 }
function TProj4.LoadProjLibrary: boolean;
begin
Result := False;
LibHandle := LoadLibrary(ansistring(LibFilename));
if LibHandle = 0 then
RaiseLastOsError;
Pointer(pj_fwd) := GetProcAddress(LibHandle, 'pj_fwd');
Pointer(pj_inv) := GetProcAddress(LibHandle, 'pj_inv');
Pointer(pj_fwd3d) := GetProcAddress(LibHandle, 'pj_fwd3d');
Pointer(pj_inv3d) := GetProcAddress(LibHandle, 'pj_fwd3d');
Pointer(pj_transform) := GetProcAddress(LibHandle, 'pj_transform');
Pointer(pj_datum_transform) := GetProcAddress(LibHandle, 'pj_datum_transform');
Pointer(pj_geocentric_to_geodetic) := GetProcAddress(LibHandle, 'pj_geocentric_to_geodetic');
Pointer(pj_compare_datums) := GetProcAddress(LibHandle, 'pj_compare_datums');
Pointer(pj_apply_gridshift) := GetProcAddress(LibHandle, 'pj_apply_gridshift');
Pointer(pj_deallocate_grids) := GetProcAddress(LibHandle, 'pj_deallocate_grids');
Pointer(pj_clear_initcache) := GetProcAddress(LibHandle, 'pj_clear_initcache');
Pointer(pj_is_latlong) := GetProcAddress(LibHandle, 'pj_is_latlong');
Pointer(pj_is_geocent) := GetProcAddress(LibHandle, 'pj_is_geocent');
Pointer(pj_pr_list) := GetProcAddress(LibHandle, 'pj_pr_list');
Pointer(pj_free) := GetProcAddress(LibHandle, 'pj_free');
Pointer(pj_set_finder) := GetProcAddress(LibHandle, 'pj_set_finder');
Pointer(pj_set_searchpath) := GetProcAddress(LibHandle, 'pj_set_searchpath');
Pointer(pj_init) := GetProcAddress(LibHandle, 'pj_init');
Pointer(pj_init_plus) := GetProcAddress(LibHandle, 'pj_init_plus');
Pointer(pj_init_ctx) := GetProcAddress(LibHandle, 'pj_init_ctx');
Pointer(pj_init_plus_ctx) := GetProcAddress(LibHandle, 'pj_init_plus_ctx');
Pointer(pj_get_def) := GetProcAddress(LibHandle, 'pj_get_def');
Pointer(pj_latlong_from_proj) := GetProcAddress(LibHandle, 'pj_latlong_from_proj');
Pointer(pj_malloc) := GetProcAddress(LibHandle, 'pj_malloc');
Pointer(pj_dalloc) := GetProcAddress(LibHandle, 'pj_dalloc');
Pointer(pj_calloc) := GetProcAddress(LibHandle, 'pj_calloc');
Pointer(pj_dealloc) := GetProcAddress(LibHandle, 'pj_dealloc');
Pointer(pj_strerrno) := GetProcAddress(LibHandle, 'pj_strerrno');
Pointer(pj_get_release) := GetProcAddress(LibHandle, 'pj_get_release');
Pointer(pj_acquire_lock) := GetProcAddress(LibHandle, 'pj_acquire_lock');
Pointer(pj_release_lock) := GetProcAddress(LibHandle, 'pj_release_lock');
Pointer(pj_cleanup_lock) := GetProcAddress(LibHandle, 'pj_cleanup_lock');
Pointer(pj_get_default_ctx) := GetProcAddress(LibHandle, 'pj_get_default_ctx');
Pointer(pj_get_ctx) := GetProcAddress(LibHandle, 'pj_get_ctx');
Pointer(pj_set_ctx) := GetProcAddress(LibHandle, 'pj_set_ctx');
Pointer(pj_ctx_alloc) := GetProcAddress(LibHandle, 'pj_ctx_alloc');
Pointer(pj_ctx_free) := GetProcAddress(LibHandle, 'pj_ctx_free');
Pointer(pj_ctx_get_errno) := GetProcAddress(LibHandle, 'pj_ctx_get_errno');
Pointer(pj_ctx_set_errno) := GetProcAddress(LibHandle, 'pj_ctx_set_errno');
Pointer(pj_ctx_set_debug) := GetProcAddress(LibHandle, 'pj_ctx_set_debug');
Pointer(pj_ctx_set_app_data) := GetProcAddress(LibHandle, 'pj_ctx_set_app_data');
Pointer(pj_ctx_get_app_data) := GetProcAddress(LibHandle, 'pj_ctx_get_app_data');
Pointer(pj_get_spheroid_defn) := GetProcAddress(LibHandle, 'pj_get_spheroid_defn');
Pointer(pj_ctx_set_logger) := GetProcAddress(LibHandle, 'pj_ctx_set_logger');
Pointer(pj_ctx_set_fileapi) := GetProcAddress(LibHandle, 'pj_ctx_set_fileapi');
Pointer(pj_ctx_get_fileapi) := GetProcAddress(LibHandle, 'pj_ctx_get_fileapi');
Pointer(pj_log) := GetProcAddress(LibHandle, 'pj_log');
Pointer(pj_stderr_logger) := GetProcAddress(LibHandle, 'pj_stderr_logger');
Pointer(pj_ctx_fopen) := GetProcAddress(LibHandle, 'pj_ctx_fopen');
Pointer(pj_ctx_fread) := GetProcAddress(LibHandle, 'pj_ctx_fread');
Pointer(pj_ctx_fseek) := GetProcAddress(LibHandle, 'pj_ctx_fseek');
Pointer(pj_ctx_ftell) := GetProcAddress(LibHandle, 'pj_ctx_ftell');
Pointer(pj_ctx_fclose) := GetProcAddress(LibHandle, 'pj_ctx_fclose');
Pointer(pj_ctx_fgets) := GetProcAddress(LibHandle, 'pj_ctx_fgets');
Pointer(pj_open_lib) := GetProcAddress(LibHandle, 'pj_open_lib');
Pointer(pj_get_list_ref) := GetProcAddress(LibHandle, 'pj_get_list_ref');
Pointer(pj_get_errno_ref) := GetProcAddress(LibHandle, 'pj_get_errno_ref');
{
Pointer(pj_create) := GetProcAddress(LibHandle, 'pj_create');
Pointer(pj_create_argv) := GetProcAddress(LibHandle, 'pj_create_argv');
Pointer(pj_freePJ) := GetProcAddress(LibHandle, 'pj_freePJ');
Pointer(pj_error) := GetProcAddress(LibHandle, 'pj_error');
Pointer(pj_trans) := GetProcAddress(LibHandle, 'pj_trans');
Pointer(pj_roundtrip) := GetProcAddress(LibHandle, 'pj_roundtrip');
Pointer(pj_lp_dist) := GetProcAddress(LibHandle, 'pj_lp_dist');
Pointer(pj_xy_dist) := GetProcAddress(LibHandle, 'pj_xy_dist');
Pointer(pj_xyz_dist) := GetProcAddress(LibHandle, 'pj_xyz_dist');
Pointer(pj_err_level) := GetProcAddress(LibHandle, 'pj_err_level');
}
if not (Assigned(pj_fwd) and Assigned(pj_inv) and Assigned(pj_transform) and Assigned(pj_datum_transform) and
Assigned(pj_geocentric_to_geodetic) and Assigned(pj_compare_datums) and Assigned(pj_apply_gridshift) and
Assigned(pj_deallocate_grids) and Assigned(pj_is_latlong) and Assigned(pj_is_geocent) and Assigned(pj_pr_list) and
Assigned(pj_set_finder) and Assigned(pj_set_searchpath) and Assigned(pj_init) and Assigned(pj_init_plus) and
Assigned(pj_get_def) and Assigned(pj_latlong_from_proj) and Assigned(pj_malloc) and Assigned(pj_dalloc) and
Assigned(pj_strerrno) and Assigned(pj_get_release) and Assigned(pj_fwd3d) and Assigned(pj_inv3d) and
Assigned(pj_clear_initcache) and Assigned(pj_get_spheroid_defn) and Assigned(pj_init_ctx) and Assigned(pj_init_plus_ctx) and
Assigned(pj_calloc) and Assigned(pj_dealloc) and Assigned(pj_acquire_lock) and Assigned(pj_release_lock) and
Assigned(pj_cleanup_lock) and Assigned(pj_get_default_ctx) and Assigned(pj_get_ctx) and Assigned(pj_set_ctx) and
Assigned(pj_ctx_alloc) and Assigned(pj_ctx_free) and Assigned(pj_ctx_get_errno) and Assigned(pj_ctx_set_errno) and
Assigned(pj_ctx_set_debug) and Assigned(pj_ctx_set_app_data) and Assigned(pj_ctx_get_app_data) and
Assigned(pj_ctx_set_logger) and Assigned(pj_ctx_set_fileapi) and Assigned(pj_ctx_get_fileapi) and Assigned(pj_log) and
Assigned(pj_stderr_logger) and Assigned(pj_ctx_fopen) and Assigned(pj_ctx_fread) and Assigned(pj_ctx_fseek) and
Assigned(pj_ctx_ftell) and Assigned(pj_ctx_fclose) and Assigned(pj_ctx_fgets) and Assigned(pj_open_lib) and
Assigned(pj_get_list_ref) and Assigned(pj_get_errno_ref){ and
Assigned(pj_create_argv) and
Assigned(pj_freePJ) and
Assigned(pj_error) and
Assigned(pj_trans) and
Assigned(pj_roundtrip) and
Assigned(pj_lp_dist) and
Assigned(pj_xy_dist) and
Assigned(pj_xyz_dist) and
Assigned(pj_err_level)
}) then
raise Exception.Create('Unsupported proj4 library version');
Result := True;
end;
procedure TProj4.ReleaseProjLibrary;
begin
if LibHandle <> 0 then
begin
FreeLibrary(LibHandle);
LibHandle := 0;
end;
end;
function TProj4.geterrorstr: string;
begin
Result := strerrno(get_errno_ref);
end;
constructor TProj4.Create;
var
loadstat: boolean;
begin
inherited Create;
{$IF Defined(WINDOWS)}
LibFilename := 'libproj.dll';
{$ELSEIF Defined(UNIX)}
LibFilename := 'libproj.so';
{$ENDIF}
LibHandle := 0;
loadstat := LoadProjLibrary;
if loadstat then
libVersion := ansistring(pj_get_release());
end;
constructor TProj4.Create(libpath: string);
var
loadstat: boolean;
begin
inherited Create;
LibFilename := libpath;
LibHandle := 0;
loadstat := LoadProjLibrary;
if loadstat then
libVersion := ansistring(pj_get_release());
end;
destructor TProj4.Destroy;
begin
ReleaseProjLibrary;
inherited Destroy;
end;
procedure TProj4.ConvertLocalToTarget(inputProj, outProj: string; out x, y: double);
var
inp, outp: projPJ;
px, py: pcdouble;
begin
inp := nil;
outp := nil;
inp := pj_init_plus(PAnsiChar(inputProj));
outp := pj_init_plus(PAnsiChar(outProj));
if inp = nil then
begin
x := -1;
y := -1;
Exit;
end;
if outp = nil then
begin
x := -1;
y := -1;
Exit;
end;
px := @x;
py := @y;
pj_transform(inp, outp, 1, 1, px, py, nil);
x := x * RAD_TO_DEG;
y := y * RAD_TO_DEG;
pj_free(inp);
pj_free(outp);
end;
function TProj4.fwd(val: projLP; proj: projPJ): projXY;
begin
Result := pj_fwd(val, proj);
end;
function TProj4.inv(val: projXY; proj: projPJ): projLP;
begin
Result := pj_inv(val, proj);
end;
function TProj4.fwd3d(val: projLPZ; proj: projPJ): projXYZ;
begin
Result := pj_fwd3d(val, proj);
end;
function TProj4.inv3d(val: projXYZ; proj: projPJ): projLPZ;
begin
Result := pj_inv3d(val, proj);
end;
function TProj4.transform(src, dst: projPJ; point_count: longint; point_offset: integer; out x, y: double; z: double): integer;
begin
Result := pj_transform(src, dst, point_count, point_offset, @x, @y, @z);
end;
function TProj4.datum_transform(src, dst: projPJ; point_count: longint; point_offset: integer; out x, y: double; z: double): integer;
begin
Result := pj_datum_transform(src, dst, point_count, point_offset, @x, @y, @z);
end;
function TProj4.geocentric_to_geodetic(a, es: double; point_count: longint; point_offset: integer; out x, y: double; z: double): integer;
begin
Result := pj_geocentric_to_geodetic(a, es, point_count, point_offset, @x, @y, @z);
end;
function TProj4.geodetic_to_geocentric(a, es: double; point_count: longint; point_offset: integer; out x, y: double; z: double): integer;
begin
Result := pj_geodetic_to_geocentric(a, es, point_count, point_offset, @x, @y, @z);
end;
function TProj4.compare_datums(srcdefn: projPJ; dstdefn: projPJ): integer;
begin
Result := pj_compare_datums(srcdefn, dstdefn);
end;
function TProj4.apply_gridshift(ctx: projCTX; c: string; i: integer; point_count: longint; point_offset: integer;
out x, y: double; z: double): integer;
begin
Result := pj_apply_gridshift(ctx, PAnsiChar(c), i, point_count, point_offset, @x, @y, @z);
end;
procedure TProj4.deallocate_grids;
begin
pj_deallocate_grids;
end;
procedure TProj4.clear_initcache;
begin
pj_clear_initcache();
end;
function TProj4.is_latlong(proj: projPJ): boolean;
begin
Result := False;
if pj_is_latlong(proj) = 1 then
Result := True;
end;
function TProj4.is_geocent(proj: projPJ): boolean;
begin
Result := False;
if pj_is_geocent(proj) = 1 then
Result := True;
end;
procedure TProj4.get_spheroid_defn(defn: projPJ; major_axis, eccentricity_squared: double);
begin
pj_get_spheroid_defn(defn, major_axis, eccentricity_squared);
end;
procedure TProj4.pr_list(proj: projPJ);
begin
pj_pr_list(proj);
end;
procedure TProj4.FreePJ(proj: projPJ);
begin
pj_Free(proj);
end;
procedure TProj4.set_finder(finder: TprojFinder);
begin
pj_set_finder(finder);
end;
procedure TProj4.set_searchpath(Count: integer; path: string);
begin
pj_set_searchpath(Count, StringToPPChar(path, 0));
end;
procedure TProj4.set_searchpath(Count: integer; path: PPJ_CSTR);
begin
pj_set_searchpath(Count, path);
end;
function TProj4.init(argc: integer; argv: string): projPJ;
begin
Result := pj_init(argc, StringToPPChar(argv, 0));
end;
function TProj4.init_plus(args: string): projPJ;
begin
Result := pj_init_plus(PAnsiChar(args));
end;
{
function TProj4.init_ctx(ctx: projCtx; argc: integer; argv: string): projPJ;
begin
Result := pj_init_ctx(ctx, argc, StringToPPChar(argv, 0));
end;
function TProj4.init_plus_ctx(ctx: projCtx; args: string): projPJ;
begin
Result := pj_init_plus_ctx(ctx, PAnsiChar(args));
end;
}
function TProj4.get_def(proj: projPJ; i: integer): string;
begin
Result := ansistring(pj_get_def(proj, i));
end;
function TProj4.latlong_from_proj(proj: projPJ): projPJ;
begin
Result := pj_latlong_from_proj(proj);
end;
function TProj4.malloc(size: csize_t): pointer;
begin
Result := pj_malloc(size);
end;
procedure TProj4.dalloc(ptr: pointer);
begin
pj_dalloc(ptr);
end;
function TProj4.calloc(n: csize_t; size: csize_t): pointer;
begin
Result := pj_calloc(n, size);
end;
function TProj4.dealloc(ptr: pointer): pointer;
begin
Result := pj_dealloc(ptr);
end;
function TProj4.strerrno(err: integer): string;
begin
Result := ansistring(pj_strerrno(err));
end;
function TProj4.get_errno_ref: integer;
var
p: ^integer;
begin
p := @Result;
p := pj_get_errno_ref();
end;
function TProj4.get_release: string;
begin
Result := ansistring(pj_get_release());
end;
{
procedure TProj4.acquire_lock;
begin
pj_acquire_lock;
end;
procedure TProj4.release_lock;
begin
pj_release_lock;
end;
procedure TProj4.cleanup_lock;
begin
pj_cleanup_lock;
end;
function TProj4.get_default_ctx: projCTX;
begin
Result := pj_get_default_ctx;
end;
function TProj4.get_ctx(proj: projPJ): projCtx;
begin
Result := pj_get_ctx(proj);
end;
procedure TProj4.set_ctx(proj: projPJ; ctx: projCtx);
begin
pj_set_ctx(proj, ctx);
end;
function TProj4.ctx_alloc: projCtx;
begin
Result := pj_ctx_alloc;
end;
procedure TProj4.ctx_free(ctx: projCtx);
begin
pj_ctx_free(ctx);
end;
function TProj4.ctx_get_errno(ctx: projCtx): integer;
begin
Result := pj_ctx_get_errno(ctx);
end;
procedure TProj4.ctx_set_errno(ctx: projCtx; no: integer);
begin
pj_ctx_set_errno(ctx, no);
end;
procedure TProj4.ctx_set_debug(ctx: projCtx; no: integer);
begin
pj_ctx_set_debug(ctx, no);
end;
procedure TProj4.ctx_set_logger(ctx: projCtx; logger: Tprojlogger);
begin
pj_ctx_set_logger(ctx, logger);
end;
procedure TProj4.ctx_set_app_data(ctx: projCtx; ptr: pointer);
begin
pj_ctx_set_app_data(ctx, ptr);
end;
function TProj4.ctx_get_app_data(ctx: projCtx): pointer;
begin
Result := pj_ctx_get_app_data(ctx);
end;
procedure TProj4.ctx_set_fileapi(ctx: projCtx; api: PprojFileAPI);
begin
pj_ctx_set_fileapi(ctx, api);
end;
function TProj4.ctx_get_fileapi(ctx: projCtx): PprojFileAPI;
begin
Result := pj_ctx_get_fileapi(ctx);
end;
procedure TProj4.log(ctx: projCtx; level: integer; fmt: string; Args: array of const);
var
ElsArray, El: PDWORD;
I: integer;
P: PDWORD;
begin
ElsArray := nil;
if High(Args) >= 0 then
GetMem(ElsArray, (High(Args) + 1) * sizeof(Pointer));
El := ElsArray;
for I := 0 to High(Args) do
begin
P := @Args[I];
P := Pointer(P^);
El^ := DWORD(P);
Inc(El);
end;
pj_log(ctx, level, PAnsiChar(fmt), Pointer(ElsArray));
if ElsArray <> nil then
FreeMem(ElsArray);
end;
procedure TProj4.stderr_logger(a: Pointer; i: integer; c: string);
begin
pj_stderr_logger(a, i, PAnsiChar(c));
end;
function TProj4.get_default_fileapi: PprojFileAPI;
begin
Result := pj_get_default_fileapi();
end;
function TProj4.ctx_fopen(ctx: projCtx; filename, access: string): PAFile;
begin
Result := pj_ctx_fopen(ctx, PAnsiChar(filename), PAnsiChar(access));
end;
function TProj4.ctx_fread(ctx: projCtx; buffer: Pointer; size, nmemb: csize_t; file_: PAFile): csize_t;
begin
Result := pj_ctx_fread(ctx, buffer, size, nmemb, file_);
end;
function TProj4.ctx_fseek(ctx: projCtx; file_: PAFile; offset: longint; whence: integer): integer;
begin
Result := pj_ctx_fseek(ctx, file_, offset, whence);
end;
function TProj4.ctx_ftell(ctx: projCtx; file_: PAFile): longint;
begin
Result := pj_ctx_ftell(ctx, file_);
end;
procedure TProj4.ctx_fclose(ctx: projCtx; file_: PAFile);
begin
pj_ctx_fclose(ctx, file_);
end;
function TProj4.ctx_fgets(ctx: projCtx; line: string; size: integer; file_: PAFile): string;
begin
Result := ansistring(pj_ctx_fgets(ctx, PAnsiChar(line), size, file_));
end;
function TProj4.open_lib(ctx: projCtx; Name, mode: string): PAFile;
begin
Result := pj_open_lib(ctx, PAnsiChar(Name), PAnsiChar(mode));
end;
}
end.
|
unit PoliticsCache;
interface
uses
Politics, CacheAgent, KernelCache;
const
tidCachePath_Surveys = 'Surveys\';
tidCachePath_Ratings = 'Ratings\';
tidCachePath_RatingSystem = 'CampaignSystem\';
tidCachePath_Projects = 'Projects\';
tidCachePath_Campaigns = 'Campaigns\';
tidCachePath_CampaignSystem = 'CampaignSystem\';
type
TRatingCacheAgent =
class( TCacheAgent )
public
class function GetPath ( Obj : TObject; kind, info : integer ) : string; override;
class function GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache; override;
end;
TProjectCacheAgent =
class( TCacheAgent )
public
class function GetPath ( Obj : TObject; kind, info : integer ) : string; override;
class function GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache; override;
end;
TCampaignCacheAgent =
class( TCacheAgent )
public
class function GetPath ( Obj : TObject; kind, info : integer ) : string; override;
class function GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache; override;
end;
TPoliticalTownCacheAgent =
class( TTownCacheAgent )
public
class function GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache; override;
end;
procedure RegisterCachers;
implementation
uses
ModelServerCache, SysUtils, TownPolitics, Languages, Logs;
// TRatingCacheAgent
class function TRatingCacheAgent.GetPath( Obj : TObject; kind, info : integer ) : string;
begin
with TRating(Obj) do
result := System.PoliticalEntity.getCacheFolder + tidCachePath_Ratings + MetaRating.Id + '.five';
end;
class function TRatingCacheAgent.GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache;
begin
result := inherited GetCache( Obj, kind, info, update );
with TRating(Obj) do
begin
result.WriteString( 'Id', MetaRating.Id );
StoreMultiStringToCache( 'Name', MetaRating.Name_MLS, result );
result.WriteInteger( 'PeopleRating', PeopleRating );
result.WriteInteger( 'IFELRating', IFELRating );
result.WriteInteger( 'TycoonsRating', TycoonsRating );
result.WriteInteger( 'RulerPublicity', RulerPublicity );
result.WriteInteger( 'TownHallId', System.PoliticalEntity.getRDOId );
end;
end;
// TProjectCacheAgent
class function TProjectCacheAgent.GetPath( Obj : TObject; kind, info : integer ) : string;
begin
with TProject(Obj) do
result := GetObjectPath( Campaign, noKind, noInfo ) + tidCachePath_Projects + MetaProject.Id + '.five';
end;
class function TProjectCacheAgent.GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache;
begin
result := inherited GetCache( Obj, kind, info, update );
with TProject(Obj) do
begin
result.WriteString( 'Id', MetaProject.Id );
result.WriteString( 'Kind', MetaProject.Kind );
StoreMultiStringToCache( 'Name', MetaProject.Name_MLS, result );
result.WriteInteger( 'TownHallId', Campaign.System.PoliticalEntity.getRDOId );
try
StoreToCache( result );
except
end;
end;
end;
// TCampaignCacheAgent
class function TCampaignCacheAgent.GetPath( Obj : TObject; kind, info : integer ) : string;
begin
with TCampaign(Obj) do
result := System.PoliticalEntity.getCacheFolder + tidCachePath_Campaigns + Tycoon.Name + '.five\';
end;
class function TCampaignCacheAgent.GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache;
var
i : integer;
begin
result := inherited GetCache( Obj, kind, info, update );
with TCampaign(Obj) do
begin
result.WriteString( 'Tycoon', Tycoon.Name );
result.WriteInteger( 'Rating', Rating );
result.WriteInteger( 'Prestige', round(Tycoon.Prestige) );
result.WriteInteger( 'Ranking', System.Campaigns.IndexOf( Obj ) );
result.WriteInteger( 'TownHallId', System.PoliticalEntity.getRDOId );
Projects.Lock;
try
for i := 0 to pred(Projects.Count) do
CacheObject( Projects[i], noKind, noInfo ); // >> CACHE_OPTIMIZE!!
finally
Projects.Unlock;
end;
end;
end;
// TPoliticalTownCacheAgent
class function TPoliticalTownCacheAgent.GetCache( Obj : TObject; kind, info : integer; update : boolean ) : TObjectCache;
var
PTH : TPoliticalTownHall;
i : integer;
begin
Logs.Log( 'Survival', DateTimeToStr(Now) + ' Caching Town..');
result := inherited GetCache( Obj, kind, info, update );
with TPoliticalTown(Obj) do
begin
PTH := TPoliticalTownHall(TownHall.CurrBlock);
result.WriteBoolean( 'CanHaveElections', PTH.TotalPopulation > MinPopulation );
result.WriteBoolean( 'HasRuler', Mayor.SuperRole <> nil );
result.WriteString( 'ActualRuler', Mayor.MasterRole.Name );
result.WriteInteger( 'RulerPrestige', round(Mayor.Prestige) );
if Mayor.MasterRole <> nil
then result.WriteInteger( 'RulerActualPrestige', round(Mayor.MasterRole.Prestige) );
result.WriteInteger( 'YearsToElections', round(World.YearsToElections) );
result.WriteInteger( 'RulerPeriods', round(MayorPeriods) + 1); // Mandate No: 0 is not OK
result.WriteInteger( 'RulerRating', PTH.Ratings.OverallRating );
result.WriteInteger( 'IFELRating', PTH.Ratings.IFELRating );
result.WriteInteger( 'TycoonsRating', PTH.Ratings.TycoonsRating );
result.WriteInteger( 'CampaignCount', PTH.Campaigns.Campaigns.Count );
result.WriteInteger( 'TownHallId', integer(TownHall.CurrBlock) );
for i := 0 to pred(PTH.Campaigns.Campaigns.Count) do
with TCampaign(PTH.Campaigns.Campaigns[i]) do
begin
result.WriteString( 'Tycoon' + IntToStr(i), Tycoon.Name );
result.WriteInteger( 'Rating' + IntToStr(i), Rating );
result.WriteInteger( 'Prestige' + IntToStr(i), round(Tycoon.Prestige) );
result.WriteString( 'CachePath' + IntToStr(i), GetObjectPath( PTH.Campaigns.Campaigns[i], noKind, noInfo ) );
if not update
then CacheObject( PTH.Campaigns.Campaigns[i], noKind, noInfo ); // >> Cache_FIX!!
end;
if not update
then
for i := 0 to pred(PTH.Ratings.Ratings.Count) do
CacheObject( PTH.Ratings.Ratings[i], noKind, noInfo ); // >> Cache_FIX!!
end;
end;
// RegisterCachers
procedure RegisterCachers;
begin
RegisterCacher( TRating.ClassName, TRatingCacheAgent );
RegisterCacher( TProject.ClassName, TProjectCacheAgent );
RegisterCacher( TCampaign.ClassName, TCampaignCacheAgent );
RegisterCacher( TPoliticalTown.ClassName, TPoliticalTownCacheAgent );
end;
end.
|
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, uClassDef, ComCtrls;
type
TfrmMain = class(TForm)
btnLoadIntoMemory: TButton;
btnSaveToDatabase: TButton;
btnLoadFromdatabase: TButton;
btnCleanDBTables: TButton;
btnDisplayQtyRange: TButton;
btnDisplayQtyRangeElement: TButton;
tvw: TTreeView;
btnLoadTreeView: TButton;
procedure btnLoadTreeViewClick(Sender: TObject);
procedure btnLoadIntoMemoryClick(Sender: TObject);
procedure btnSaveToDatabaseClick(Sender: TObject);
procedure btnCleanDBTablesClick(Sender: TObject);
procedure btnDisplayQtyRangeClick(Sender: TObject);
procedure btnDisplayQtyRangeElementClick(Sender: TObject);
procedure btnLoadFromdatabaseClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FRangeList:TRangeList;
procedure DestroyRanges(ARangeList:TRangeList);
procedure LoadRangesTreeView(ARangeList: TRangeList);
procedure LoadRangeElementsToTreeView(RangeNode: TTreeNode;
ARange: TRange);
procedure LoadRangeSubElementsToTreeView(RangeElementNode: TTreeNode;
ARangeElement: TRangeElement);
procedure LoadDataIntoMemory(ARangeList:TRangeList);
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses
uDM;
{$R *.dfm}
//Destroys Memory Object
procedure TfrmMain.DestroyRanges(ARangeList:TRangeList);
var
ObjRange:TRange;
ObjRangeElement:TRangeElement;
iRange, iRangeElement:Integer;
begin
for iRange := ARangeList.Count-1 downto 0 do begin
ObjRange := ARangeList[iRange];
for iRangeElement := Pred(ObjRange.Elements.Count) downto 0 do begin
ObjRangeElement := ObjRange.Elements[iRangeElement];
try
if Assigned(ObjRangeElement) then
TObject(ObjRangeElement).Free;
except
end;
end;
ObjRange.Elements.Clear();
if Assigned(ObjRange) then
TObject(ObjRange).Free;
end;
ARangeList.Clear();
end;
//Loads default data into memory
procedure TfrmMain.LoadDataIntoMemory(ARangeList:TRangeList);
var
Range:TRange;
Element:TRangeElement;
begin
if (ARangeList=Nil) then
begin
raise Exception.Create('Invalid Range List Object!');
Exit;
end;
DestroyRanges(ARangeList);
//Create and Add Range to Range List Object
ARangeList.Add(TRange.Create(1, 'First Dummy Range'));
Range:= ARangeList.ItemById[1];
//Add Elements to Range
Range.Elements.Add(TRangeElement.Create(10000, 10));
Range.Elements.Add(TRangeElement.Create(10001, 11));
Range.Elements.Add(TRangeElement.Create(10002, 12));
Range.Elements.Add(TRangeElement.Create(20000, 20));
Range.Elements.Add(TRangeElement.Create(30000, 30));
//Add Sub Elements to Element 10000
Element := Range.Elements.ItemById[10000];
Element.SubElements.Add(Range.Elements.ItemById[10001]);
Element.SubElements.Add(Range.Elements.ItemById[10002]);
//Add Sub Elements to Element 30000
Element := Range.Elements.ItemById[30000];
Element.SubElements.Add(Range.Elements.ItemById[10000]);
Element.SubElements.Add(Range.Elements.ItemById[20000]);
end;
procedure TfrmMain.btnLoadIntoMemoryClick(Sender: TObject);
begin
LoadDataIntoMemory(FRangeList);
ShowMessage('Data Successfully loaded into Memroy!');
end;
procedure TfrmMain.btnSaveToDatabaseClick(Sender: TObject);
begin
if (FRangeList=nil) then
begin
ShowMessage('No Data Available to save!');
Exit;
end;
if not (DM.ConnectToDB) then
Exit;
DM.SaveToDB(FRangeList);
end;
procedure TfrmMain.btnCleanDBTablesClick(Sender: TObject);
begin
if not (DM.ConnectToDB) then
Exit;
DM.CleanDB();
end;
procedure TfrmMain.btnDisplayQtyRangeClick(Sender: TObject);
var
I:Integer;
Msg:string;
begin
if (FRangeList=nil) then
begin
ShowMessage('No Data Available to Display!');
Exit;
end;
for I:=0 to FRangeList.Count-1 do begin
Msg := 'RangeID:' + IntTOStr(FRangeList[I].Id) + ', Total Planned Quantity=' + IntToStr(FRangeList[I].GetTotalPlannedQuantity);
ShowMessage(Msg);
end;
end;
procedure TfrmMain.btnDisplayQtyRangeElementClick(Sender: TObject);
var
I:Integer;
Msg:string;
begin
if (FRangeList=nil) then
begin
ShowMessage('No Data Available to Display!');
Exit;
end;
for I:=0 to FRangeList[0].Elements.Count-1 do begin
Msg := 'Element ID:' + IntTOStr(FRangeList[0].Elements[I].Id) + ', Total Planned Quantity=' + IntToStr(FRangeList[0].Elements[I].GetTotalPlannedQuantity);
ShowMessage(Msg);
end;
end;
procedure TfrmMain.btnLoadFromdatabaseClick(Sender: TObject);
begin
if not (DM.ConnectToDB) then
Exit;
FRangeList := DM.LoadFromDB();
LoadRangesTreeView(FRangeList);
ShowMessage('Data Loaded Successfully!');
end;
procedure TfrmMain.LoadRangeSubElementsToTreeView(RangeElementNode:TTreeNode; ARangeElement:TRangeElement);
var
I:Integer;
begin
for I:=0 to ARangeElement.SubElements.Count-1 do begin
tvw.Items.AddChild(RangeElementNode, 'Sub-Element:' + IntToStr(ARangeElement.SubElements[I].Id));
end;
end;
procedure TfrmMain.LoadRangeElementsToTreeView(RangeNode:TTreeNode; ARange:TRange);
var
Node:TTreeNode;
Element:TRangeElement;
I:Integer;
begin
for I:=0 to ARange.Elements.Count-1 do begin
Element := ARange.Elements[I];
Node := tvw.Items.AddChild(RangeNode, 'Element:' + IntToStr(Element.Id));
LoadRangeSubElementsToTreeView(Node, Element);
end;
end;
procedure TfrmMain.LoadRangesTreeView(ARangeList:TRangeList);
var
RootNode, Node:TTreeNode;
Range:TRange;
I:Integer;
begin
tvw.Items.Clear();
RootNode := tvw.Items.AddChildFirst(Nil, 'Root-Ranges');
for I:=0 to ARangeList.Count-1 do begin
Range := ARangeList[I];
Node := tvw.Items.AddChild(RootNode, 'Range:' + IntToStr(Range.Id));
LoadRangeElementsToTreeView(Node, Range);
end;
tvw.FullExpand();
end;
procedure TfrmMain.btnLoadTreeViewClick(Sender: TObject);
begin
if (FRangeList=nil) then
begin
ShowMessage('No Data Available to Display!');
Exit;
end;
LoadRangesTreeView(FRangeList);
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
FRangeList := TRangeList.Create();
LoadDataIntoMemory(FRangeList);
LoadRangesTreeView(FRangeList);
DestroyRanges(FRangeList);
end;
end.
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Decorators.Repeater;
interface
uses
System.JSON,
Behavior3, Behavior3.Core.Decorator, Behavior3.Core.BaseNode, Behavior3.Core.Tick;
type
(**
* Repeater is a decorator that repeats the tick signal until the child node
* return `RUNNING` or `ERROR`. Optionally, a maximum number of repetitions
* can be defined.
*
* @module b3
* @class Repeater
* @extends Decorator
**)
TB3Repeater = class(TB3Decorator)
private
protected
public
// maxLoop** (*Integer*) Maximum number of repetitions. Default to -1 (infinite)
MaxLoop: Integer;
constructor Create; override;
(**
* Open method.
* @method open
* @param {Tick} tick A tick instance.
**)
procedure Open(Tick: TB3Tick); override;
(**
* Tick method.
* @method tick
* @param {Tick} tick A tick instance.
* @return {Constant} A state constant.
**)
function Tick(Tick: TB3Tick): TB3Status; override;
procedure Load(JsonNode: TJSONValue); override;
end;
implementation
uses
Behavior3.Helper, Behavior3.Core.BehaviorTree;
{ TB3Repeater }
constructor TB3Repeater.Create;
begin
inherited;
(**
* Node name. Default to `Repeater`.
* @property {String} name
* @readonly
**)
Name := 'Repeater';
(**
* Node title. Default to `Repeat XXx`. Used in Editor.
* @property {String} title
* @readonly
**)
Title := 'Repeat <maxLoop>x';
(**
* Node parameters.
* @property {String} parameters
* @readonly
**)
MaxLoop := -1;
end;
procedure TB3Repeater.Open(Tick: TB3Tick);
begin
Tick.Blackboard.&Set('i', 0, Tick.Tree.Id, Id);
end;
function TB3Repeater.Tick(Tick: TB3Tick): TB3Status;
var
I: Integer;
Status: TB3Status;
begin
if not Assigned(Child) then
begin
Result := Behavior3.Error;
Exit;
end;
I := Tick.Blackboard.Get('i', Tick.tree.id, Id).AsInteger;
Status := Behavior3.Success;
while (MaxLoop < 0) or (I < MaxLoop) do
begin
Status := Child._Execute(Tick);
if (Status = Behavior3.Success) or (Status = Behavior3.Failure) then
Inc(I)
else
Break;
end;
Tick.Blackboard.&Set('i', I, Tick.Tree.Id, Id);
Result := Status;
end;
procedure TB3Repeater.Load(JsonNode: TJSONValue);
begin
inherited;
MaxLoop := LoadProperty(JsonNode, 'maxLoop', MaxLoop);
end;
end.
|
unit demortti.description;
interface
type
Descriptor = class(TCustomAttribute)
private
FLanguage: String;
public
property Language: String read FLanguage;
constructor Create(const ALanguage: string);
end;
IDescription = interface
['{8CB83CF6-EE75-4B49-8CA8-DF684B0CE618}']
function Get(const AName: String): String;
end;
implementation
{ Descriptor }
constructor Descriptor.Create(const ALanguage: string);
begin
FLanguage := ALanguage;
end;
end.
|
unit WinSockRDOConnectionsServer;
interface
uses
Windows,
Classes,
SyncObjs,
SmartThreads,
SocketComp,
RDOInterfaces;
type
TQueryToService =
record
Text : string;
Socket : TCustomWinSocket;
end;
PQueryToService = ^TQueryToService;
type
TWinSockRDOConnectionsServer = class;
TServicingQueryThread =
class( TSmartThread )
private
fConnectionsServer : TWinSockRDOConnectionsServer;
fQueryToService : PQueryToService;
public
constructor Create( theConnServer : TWinSockRDOConnectionsServer );
procedure Execute; override;
public
property QueryToService : PQueryToService read fQueryToService write fQueryToService;
end;
TWinSockRDOConnectionsServer =
class( TInterfacedObject, IRDOServerConnection, IRDOConnectionsServer )
private
fQueryServer : IRDOQueryServer;
fSocketComponent : TServerSocket;
fMsgLoopThread : TSmartThread;
fEventSink : IRDOConnectionServerEvents;
fMaxQueryThreads : integer;
fQueryCount : integer;
fQueryCountLock : TCriticalSection;
fTerminateEvent : THandle;
fQueryThreads : TList;
// fQueryThreadsSem : THandle;
fNoQueryRunning : THandle;
public
constructor Create( Prt : integer );
destructor Destroy; override;
protected
procedure SetQueryServer( const QueryServer : IRDOQueryServer );
function GetMaxQueryThreads : integer;
procedure SetMaxQueryThreads( MaxQueryThreads : integer );
protected
procedure StartListening;
procedure StopListening;
function GetClientConnection( const ClientAddress : string; ClientPort : integer ) : IRDOConnection;
procedure InitEvents( const EventSink : IRDOConnectionServerEvents );
private
procedure GrowThreadCache( GrowBy : integer );
procedure ReduceThreadCache( ReduceBy : integer );
function GetFreeQueryThread : TServicingQueryThread;
private
procedure ClientConnected( Sender : TObject; Socket : TCustomWinSocket );
procedure ClientDisconnected( Sender : TObject; Socket : TCustomWinSocket );
procedure DoClientRead( Sender : TObject; Socket : TCustomWinSocket );
procedure HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer );
end;
implementation
uses
SysUtils,
WinSock,
RDOProtocol,
RDOUtils,
{$IFDEF Logs}
LogFile,
{$ENDIF}
ErrorCodes,
RDOQueryServer,
WinSockRDOServerClientConnection;
const
DefMaxQueryThreads = 5;
const
ThreadCacheDelta = 5;
type
TSocketData =
record
RDOConnection : IRDOConnection;
Buffer : string;
end;
PSocketData = ^TSocketData;
type
TMsgLoopThread =
class( TSmartThread )
private
fRDOConnServ : TWinSockRDOConnectionsServer;
public
constructor Create( RDOConnServ : TWinSockRDOConnectionsServer );
procedure Execute; override;
end;
// TServicingQueryThread
constructor TServicingQueryThread.Create( theConnServer : TWinSockRDOConnectionsServer );
begin
fConnectionsServer := theConnServer;
inherited Create( true )
end;
procedure TServicingQueryThread.Execute;
var
QueryResult : string;
begin
while not Terminated do
with fConnectionsServer do
try
fQueryCountLock.Acquire;
try
inc( fQueryCount );
if fQueryCount = 1
then
ResetEvent( fNoQueryRunning );
finally
fQueryCountLock.Release
end;
QueryResult := fQueryServer.ExecQuery( fQueryToService.Text );
if QueryResult <> ''
then
try
fQueryToService.Socket.SendText( AnswerId + QueryResult );
{$IFDEF Logs}
LogThis( 'Result : ' + QueryResult );
{$ENDIF}
except
{$IFDEF Logs}
LogThis( 'Error sending query result' )
{$ENDIF}
end
else
begin
{$IFDEF Logs}
LogThis( 'No result' )
{$ENDIF}
end
finally
Dispose( fQueryToService );
// ReleaseSemaphore( fQueryThreadsSem, 1, nil );
fQueryCountLock.Acquire;
try
dec( fQueryCount );
if fQueryCount = 0
then
SetEvent( fNoQueryRunning );
finally
fQueryCountLock.Release
end;
Suspend
end
end;
// TMsgLoopThread
constructor TMsgLoopThread.Create( RDOConnServ : TWinSockRDOConnectionsServer );
begin
fRDOConnServ := RDOConnServ;
// Priority := tpHighest;
inherited Create( false )
end;
procedure TMsgLoopThread.Execute;
var
Msg : TMsg;
begin
with fRDOConnServ do
begin
try
with fSocketComponent do
if not Active
then
Active := true
except
{$IFDEF Logs}
LogThis( 'Error establishing connection' );
{$ENDIF}
Terminate
end;
while not Terminated do
if PeekMessage( Msg, 0, 0, 0, PM_REMOVE )
then
DispatchMessage( Msg )
else
MsgWaitForMultipleObjects( 1, fTerminateEvent, false, INFINITE, QS_ALLINPUT );
with fSocketComponent do
Active := false
end
end;
// TWinSockRDOConnectionsServer
constructor TWinSockRDOConnectionsServer.Create( Prt : integer );
begin
inherited Create;
fSocketComponent := TServerSocket.Create( nil );
with fSocketComponent do
begin
Active := false;
ServerType := stNonBlocking;
Port := Prt;
OnClientConnect := ClientConnected;
OnClientDisconnect := ClientDisconnected;
OnClientRead := DoClientRead;
OnClientError := HandleError
end;
fQueryCountLock := TCriticalSection.Create;
fMaxQueryThreads := DefMaxQueryThreads;
fQueryThreads := TList.Create;
fTerminateEvent := CreateEvent( nil, true, false, nil );
fNoQueryRunning := CreateEvent( nil, true, true, nil )
end;
destructor TWinSockRDOConnectionsServer.Destroy;
begin
StopListening;
fSocketComponent.Free;
fQueryThreads.Free;
CloseHandle( fTerminateEvent );
CloseHandle( fNoQueryRunning );
inherited Destroy
end;
procedure TWinSockRDOConnectionsServer.SetQueryServer( const QueryServer : IRDOQueryServer );
begin
fQueryServer := QueryServer
end;
function TWinSockRDOConnectionsServer.GetMaxQueryThreads : integer;
begin
Result := fMaxQueryThreads
end;
procedure TWinSockRDOConnectionsServer.SetMaxQueryThreads( MaxQueryThreads : integer );
begin
fMaxQueryThreads := MaxQueryThreads
end;
procedure TWinSockRDOConnectionsServer.StartListening;
begin
ResetEvent( fTerminateEvent );
GrowThreadCache( ThreadCacheDelta );
// fQueryThreadsSem := CreateSemaphore( nil, fMaxQueryThreads, fMaxQueryThreads, nil );
fMsgLoopThread := TMsgLoopThread.Create( Self );
end;
procedure TWinSockRDOConnectionsServer.StopListening;
begin
SetEvent( fTerminateEvent );
fMsgLoopThread.Free;
fMsgLoopThread := nil;
WaitForSingleObject( fNoQueryRunning, INFINITE );
// CloseHandle( fQueryThreadsSem );
ReduceThreadCache( fQueryThreads.Count )
end;
function TWinSockRDOConnectionsServer.GetClientConnection( const ClientAddress : string; ClientPort : integer ) : IRDOConnection;
var
ConnIdx : integer;
ConnCount : integer;
FoundConn : IRDOConnection;
UseIPAddr : boolean;
CurrConn : TCustomWinSocket;
CurConnRmtAddr : string;
begin
ConnIdx := 0;
with fSocketComponent do
begin
ConnCount := Socket.ActiveConnections;
FoundConn := nil;
if inet_addr( PChar( ClientAddress ) ) = INADDR_NONE
then
UseIPAddr := false
else
UseIPAddr := true;
while ( ConnIdx < ConnCount ) and ( FoundConn = nil ) do
begin
CurrConn := Socket.Connections[ ConnIdx ];
if UseIPAddr
then
CurConnRmtAddr := CurrConn.RemoteAddress
else
CurConnRmtAddr := CurrConn.RemoteHost;
if ( CurConnRmtAddr = ClientAddress ) and ( CurrConn.RemotePort = ClientPort )
then
FoundConn := PSocketData( CurrConn.Data ).RDOConnection;
inc( ConnIdx )
end
end;
Result := FoundConn
end;
procedure TWinSockRDOConnectionsServer.InitEvents( const EventSink : IRDOConnectionServerEvents );
begin
fEventSink := EventSink
end;
procedure TWinSockRDOConnectionsServer.GrowThreadCache( GrowBy : integer );
var
ThreadCount : integer;
begin
for ThreadCount := 1 to GrowBy do
fQueryThreads.Add( TServicingQueryThread.Create( Self ) )
end;
procedure TWinSockRDOConnectionsServer.ReduceThreadCache( ReduceBy : integer );
var
ThreadIdx : integer;
ThreadCount : integer;
KilledThreads : integer;
aQueryThread : TServicingQueryThread;
begin
ThreadIdx := 0;
ThreadCount := fQueryThreads.Count;
KilledThreads := 0;
while ( KilledThreads < ReduceBy ) and ( ThreadIdx < ThreadCount ) do
begin
aQueryThread := TServicingQueryThread( fQueryThreads[ ThreadIdx ] );
if aQueryThread.Suspended
then
begin
fQueryThreads[ ThreadIdx ] := nil;
aQueryThread.Free;
inc( KilledThreads )
end;
inc( ThreadIdx )
end;
if KilledThreads > 0
then
begin
fQueryThreads.Pack;
fQueryThreads.Capacity := fQueryThreads.Count
end
end;
function TWinSockRDOConnectionsServer.GetFreeQueryThread : TServicingQueryThread;
var
ThreadIdx : integer;
ThreadCount : integer;
FreeThreadFound : boolean;
begin
FreeThreadFound := false;
ThreadIdx := 0;
ThreadCount := fQueryThreads.Count;
while ( ThreadIdx < ThreadCount ) and not FreeThreadFound do
if TServicingQueryThread( fQueryThreads[ ThreadIdx ] ).Suspended
then
FreeThreadFound := true
else
inc( ThreadIdx );
if FreeThreadFound
then
Result := TServicingQueryThread( fQueryThreads[ ThreadIdx ] )
else
begin
GrowThreadCache( ThreadCacheDelta );
Result := TServicingQueryThread( fQueryThreads[ ThreadCount ] )
end
end;
procedure TWinSockRDOConnectionsServer.ClientConnected( Sender : TObject; Socket : TCustomWinSocket );
var
SocketData : PSocketData;
begin
New( SocketData );
SocketData.RDOConnection := TWinSockRDOServerClientConnection.Create( Socket );
Socket.Data := SocketData;
if fEventSink <> nil
then
fEventSink.OnClientConnect( SocketData.RDOConnection )
end;
procedure TWinSockRDOConnectionsServer.ClientDisconnected( Sender : TObject; Socket : TCustomWinSocket );
var
SocketData : PSocketData;
begin
SocketData := PSocketData( Socket.Data );
if fEventSink <> nil
then
fEventSink.OnClientDisconnect( SocketData.RDOConnection );
Dispose( SocketData )
end;
procedure TWinSockRDOConnectionsServer.DoClientRead( Sender : TObject; Socket : TCustomWinSocket );
var
NonWSPCharIdx : integer;
QueryToService : PQueryToService;
QueryText : string;
QueryThread : TServicingQueryThread;
ReadError : boolean;
ReceivedText : string;
SocketData : PSocketData;
ServClienConn : IRDOServerClientConnection;
begin
ReadError := false;
try
ReceivedText := Socket.ReceiveText;
{$IFDEF Logs}
if ReceivedText <> ''
then
LogThis( 'Read : ' + ReceivedText )
{$ENDIF}
except
ReadError := true
end;
if not ReadError and ( fQueryServer <> nil )
then
begin
SocketData := PSocketData( Socket.Data );
SocketData.Buffer := SocketData.Buffer + ReceivedText;
QueryText := GetQueryText( SocketData.Buffer );
while QueryText <> '' do
begin
NonWSPCharIdx := 1;
SkipSpaces( QueryText, NonWSPCharIdx );
if QueryText[ NonWSPCharIdx ] = CallId
then
begin
Delete( QueryText, NonWSPCharIdx, 1 );
{$IFDEF Logs}
LogThis( 'Query : ' + QueryText );
{$ENDIF}
New( QueryToService );
QueryToService.Text := QueryText;
QueryToService.Socket := Socket;
// WaitForSingleObject( fQueryThreadsSem, INFINITE );
QueryThread := GetFreeQueryThread;
QueryThread.QueryToService := QueryToService;
QueryThread.Resume
end
else
if QueryText[ NonWSPCharIdx ] = AnswerId
then
begin
try
Delete( QueryText, NonWSPCharIdx, 1 );
ServClienConn := SocketData.RDOConnection as IRDOServerClientConnection;
ServClienConn.OnQueryResultArrival( QueryText )
except
end
end;
QueryText := GetQueryText( SocketData.Buffer )
end
end
else
{$IFDEF Logs}
LogThis( 'Error while reading from socket' )
{$ENDIF}
end;
procedure TWinSockRDOConnectionsServer.HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : Integer );
begin
ErrorCode := 0;
{$IFDEF Logs}
case ErrorEvent of
eeGeneral:
LogThis( 'General socket error' );
eeSend:
LogThis( 'Error writing to socket' );
eeReceive:
LogThis( 'Error reading from socket' );
eeConnect:
LogThis( 'Error establishing connection' );
eeDisconnect:
LogThis( 'Error closing connection' );
eeAccept:
LogThis( 'Error accepting connection' )
end
{$ENDIF}
end;
end.
|
unit ddragon3_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,m68000,main_engine,controls_engine,gfx_engine,ym_2151,rom_engine,
pal_engine,sound_engine,oki6295,qsnapshot;
function iniciar_ddragon3:boolean;
implementation
const
//Double Dragon 3
ddragon3_rom:array[0..1] of tipo_roms=(
(n:'30a14-0.ic78';l:$40000;p:1;crc:$f42fe016),(n:'30a15-0.ic79';l:$20000;p:$0;crc:$ad50e92c));
ddragon3_sound:tipo_roms=(n:'30a13-0.ic43';l:$10000;p:0;crc:$1e974d9b);
ddragon3_oki:tipo_roms=(n:'30j-8.ic73';l:$80000;p:0;crc:$c3ad40f3);
ddragon3_sprites:array[0..7] of tipo_roms=(
(n:'30j-3.ic9';l:$80000;p:0;crc:$b3151871),(n:'30a12-0.ic8';l:$10000;p:$80000;crc:$20d64bea),
(n:'30j-2.ic11';l:$80000;p:$100000;crc:$41c6fb08),(n:'30a11-0.ic10';l:$10000;p:$180000;crc:$785d71b0),
(n:'30j-1.ic13';l:$80000;p:$200000;crc:$67a6f114),(n:'30a10-0.ic12';l:$10000;p:$280000;crc:$15e43d12),
(n:'30j-0.ic15';l:$80000;p:$300000;crc:$f15dafbe),(n:'30a9-0.ic14';l:$10000;p:$380000;crc:$5a47e7a4));
ddragon3_bg:array[0..3] of tipo_roms=(
(n:'30j-7.ic4';l:$40000;p:0;crc:$89d58d32),(n:'30j-6.ic5';l:$40000;p:$1;crc:$9bf1538e),
(n:'30j-5.ic6';l:$40000;p:$80000;crc:$8f671a62),(n:'30j-4.ic7';l:$40000;p:$80001;crc:$0f74ea1c));
//Combat tribe
ctribe_rom:array[0..2] of tipo_roms=(
(n:'28a16-2.ic26';l:$20000;p:1;crc:$c46b2e63),(n:'28a15-2.ic25';l:$20000;p:$0;crc:$3221c755),
(n:'28j17-0.104';l:$10000;p:$40001;crc:$8c2c6dbd));
ctribe_sound:tipo_roms=(n:'28a10-0.ic89';l:$8000;p:0;crc:$4346de13);
ctribe_oki:array[0..1] of tipo_roms=(
(n:'28j9-0.ic83';l:$20000;p:0;crc:$f92a7f4a),(n:'28j8-0.ic82';l:$20000;p:$20000;crc:$1a3a0b39));
ctribe_sprites:array[0..7] of tipo_roms=(
(n:'28j3-0.ic77';l:$80000;p:0;crc:$1ac2a461),(n:'28a14-0.ic60';l:$10000;p:$80000;crc:$972faddb),
(n:'28j2-0.ic78';l:$80000;p:$100000;crc:$8c796707),(n:'28a13-0.ic61';l:$10000;p:$180000;crc:$eb3ab374),
(n:'28j1-0.ic97';l:$80000;p:$200000;crc:$1c9badbd),(n:'28a12-0.ic85';l:$10000;p:$280000;crc:$c602ac97),
(n:'28j0-0.ic98';l:$80000;p:$300000;crc:$ba73c49e),(n:'28a11-0.ic86';l:$10000;p:$380000;crc:$4da1d8e5));
ctribe_bg:array[0..3] of tipo_roms=(
(n:'28j7-0.ic11';l:$40000;p:0;crc:$a8b773f1),(n:'28j6-0.ic13';l:$40000;p:$1;crc:$617530fc),
(n:'28j5-0.ic12';l:$40000;p:$80000;crc:$cef0a821),(n:'28j4-0.ic14';l:$40000;p:$80001;crc:$b84fda09));
//DIP
ddragon3_dip_a:array [0..9] of def_dip=(
(mask:$3;name:'Coinage';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$1;dip_name:'2C 1C'),(dip_val:$3;dip_name:'1C 1C'),(dip_val:$2;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$10;name:'Continue Discount';number:2;dip:((dip_val:$10;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$20;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Flip Screen';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$300;name:'Difficulty';number:4;dip:((dip_val:$200;dip_name:'Easy'),(dip_val:$300;dip_name:'Normal'),(dip_val:$100;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$400;name:'Player Vs. Player Damage';number:2;dip:((dip_val:$400;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2000;name:'Stage Clear Energy';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$2000;dip_name:'50'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$4000;name:'Starting Energy';number:2;dip:((dip_val:$0;dip_name:'200'),(dip_val:$4000;dip_name:'230'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$8000;name:'Players';number:2;dip:((dip_val:$8000;dip_name:'2'),(dip_val:$0;dip_name:'3'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
ctribe_dip_a:array [0..3] of def_dip=(
(mask:$300;name:'Coinage';number:4;dip:((dip_val:$0;dip_name:'3C 1C'),(dip_val:$100;dip_name:'2C 1C'),(dip_val:$300;dip_name:'1C 1C'),(dip_val:$200;dip_name:'1C 2C'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$1000;name:'Continue Discount';number:2;dip:((dip_val:$1000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2000;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$2000;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
ctribe_dip_b:array [0..4] of def_dip=(
(mask:$300;name:'Difficulty';number:4;dip:((dip_val:$200;dip_name:'Easy'),(dip_val:$300;dip_name:'Normal'),(dip_val:$100;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$400;name:'Timer Speed';number:2;dip:((dip_val:$400;dip_name:'Normal'),(dip_val:$0;dip_name:'Fast'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$800;name:'FBI Logo';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$800;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$2000;name:'Stage Clear Energy';number:2;dip:((dip_val:$2000;dip_name:'0'),(dip_val:$0;dip_name:'50'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
ctribe_dip_c:array [0..3] of def_dip=(
(mask:$100;name:'More Stage Clear Energy';number:2;dip:((dip_val:$100;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$200;name:'Players';number:2;dip:((dip_val:$200;dip_name:'2'),(dip_val:0;dip_name:'3'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$1000;name:'Flip Screen';number:2;dip:((dip_val:$1000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
video_update_dd3:procedure;
events_update_dd3:procedure;
vreg,bg_tilebase,fg_scrollx,fg_scrolly,bg_scrollx,bg_scrolly:word;
mem_oki:array[0..$7ffff] of byte;
rom:array[0..$3ffff] of word;
bg_ram:array[0..$3ff] of word;
ram:array[0..$1fff] of word;
fg_ram,ram2:array[0..$7ff] of word;
sound_latch,vblank:byte;
procedure draw_sprites;
var
atrib,nchar,color,x,y,count:word;
f,h:byte;
{- SPR RAM Format -**
16 bytes per sprite (8-bit RAM? only every other byte is used)
---- ---- yyyy yyyy ---- ---- lllF fXYE ---- ---- nnnn nnnn ---- ---- NNNN NNNN
---- ---- ---- CCCC ---- ---- xxxx xxxx ---- ---- ---- ---- ---- ---- ---- ----
Yy = sprite Y Position
Xx = sprite X Position
C = colour bank
f = flip Y
F = flip X
l = chain sprite
E = sprite enable
Nn = Sprite Number
other bits unused}
begin
for f:=0 to $ff do begin
atrib:=buffer_sprites_w[(f*8)+1];
if (atrib and 1)<>0 then begin
x:=(buffer_sprites_w[(f*8)+5] and $00ff) or ((atrib and $0004) shl 6);
y:=(buffer_sprites_w[f*8] and $00ff) or ((atrib and $0002) shl 7);
y:=((256-y) and $1ff)-16;
count:=(atrib and $00e0) shr 5;
nchar:=((buffer_sprites_w[(f*8)+2] and $00ff) or ((buffer_sprites_w[(f*8)+3] and $00ff) shl 8)) and $7fff;
color:=buffer_sprites_w[(f*8)+4] and $000f;
for h:=0 to count do begin
put_gfx_sprite(nchar+h,color shl 4,atrib and $10<>0,atrib and $8<>0,1);
actualiza_gfx_sprite(x,y-(16*h),3,1);
end;
end; //del enable
end; //del for
end;
procedure draw_video;
var
f,x,y,nchar,atrib:word;
color:byte;
begin
for f:=$0 to $3ff do begin
x:=f and $1f;
y:=f shr 5;
//background
atrib:=bg_ram[f];
color:=(atrib and $f000) shr 12;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
nchar:=(atrib and $0fff) or ((bg_tilebase and $01) shl 12);
put_gfx_trans(x*16,y*16,nchar,(color shl 4)+512,1,0);
gfx[0].buffer[f]:=false;
end;
//fg
atrib:=fg_ram[f*2];
color:=(atrib and $f);
if (gfx[0].buffer[$400+f] or buffer_color[$10+color]) then begin
nchar:=fg_ram[(f*2)+1] and $1fff;
put_gfx_trans_flip(x*16,y*16,nchar,(color shl 4)+256,2,0,(atrib and $40)<>0,(atrib and $80)<>0);
gfx[0].buffer[$400+f]:=false;
end;
end;
fill_full_screen(3,$600);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
end;
procedure update_video_ddragon3;
begin
draw_video;
case (vreg and $60) of
$40:begin
scroll_x_y(1,3,bg_scrollx,bg_scrolly);
scroll_x_y(2,3,fg_scrollx,fg_scrolly);
draw_sprites;
end;
$60:begin
scroll_x_y(2,3,fg_scrollx,fg_scrolly);
scroll_x_y(1,3,bg_scrollx,bg_scrolly);
draw_sprites;
end;
else begin
scroll_x_y(1,3,bg_scrollx,bg_scrolly);
draw_sprites;
scroll_x_y(2,3,fg_scrollx,fg_scrolly);
end;
end;
actualiza_trozo_final(0,8,320,240,3);
end;
procedure update_video_ctribe;
begin
draw_video;
if (vreg and $8)<>0 then begin
scroll_x_y(2,3,fg_scrollx,fg_scrolly);
draw_sprites;
scroll_x_y(1,3,bg_scrollx,bg_scrolly);
end else begin
scroll_x_y(1,3,bg_scrollx,bg_scrolly);
scroll_x_y(2,3,fg_scrollx,fg_scrolly);
draw_sprites;
end;
actualiza_trozo_final(0,8,320,240,3);
end;
procedure eventos_ddragon3;
begin
if event.arcade then begin
//p1
if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or 1);
if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or 2);
if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or 4);
if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fff7) else marcade.in0:=(marcade.in0 or 8);
if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $20);
if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $ffbf) else marcade.in0:=(marcade.in0 or $40);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $ff7f) else marcade.in0:=(marcade.in0 or $80);
//p2
if arcade_input.right[1] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $100);
if arcade_input.left[1] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $200);
if arcade_input.up[1] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $400);
if arcade_input.down[1] then marcade.in0:=(marcade.in0 and $f7ff) else marcade.in0:=(marcade.in0 or $800);
if arcade_input.but0[1] then marcade.in0:=(marcade.in0 and $efff) else marcade.in0:=(marcade.in0 or $1000);
if arcade_input.but1[1] then marcade.in0:=(marcade.in0 and $dfff) else marcade.in0:=(marcade.in0 or $2000);
if arcade_input.but2[1] then marcade.in0:=(marcade.in0 and $bfff) else marcade.in0:=(marcade.in0 or $4000);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $7fff) else marcade.in0:=(marcade.in0 or $8000);
//system
if arcade_input.coin[0] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or 1);
if arcade_input.coin[1] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or 2);
end;
end;
procedure eventos_ctribe;
begin
if event.arcade then begin
//p1
if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or 1);
if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or 2);
if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or 4);
if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $fff7) else marcade.in0:=(marcade.in0 or 8);
if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ffef) else marcade.in0:=(marcade.in0 or $10);
if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ffdf) else marcade.in0:=(marcade.in0 or $20);
if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $ffbf) else marcade.in0:=(marcade.in0 or $40);
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $ff7f) else marcade.in0:=(marcade.in0 or $80);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $100);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $200);
//p2
if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or 1);
if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or 2);
if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fffb) else marcade.in1:=(marcade.in1 or 4);
if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $fff7) else marcade.in1:=(marcade.in1 or 8);
if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $10);
if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $ffdf) else marcade.in1:=(marcade.in1 or $20);
if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $ffbf) else marcade.in1:=(marcade.in1 or $40);
if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $ff7f) else marcade.in1:=(marcade.in1 or $80);
end;
end;
procedure ddragon3_principal;
var
frame_m,frame_s:single;
f:word;
begin
init_controls(false,false,false,true);
frame_m:=m68000_0.tframes;
frame_s:=z80_0.tframes;
while EmuStatus=EsRuning do begin
for f:=0 to 271 do begin
//main
m68000_0.run(frame_m);
frame_m:=frame_m+m68000_0.tframes-m68000_0.contador;
//sound
z80_0.run(frame_s);
frame_s:=frame_s+z80_0.tframes-z80_0.contador;
if ((f mod 16)=0) then m68000_0.irq[5]:=ASSERT_LINE;
case f of
7:begin
vblank:=0;
video_update_dd3;
end;
247:begin
m68000_0.irq[6]:=ASSERT_LINE;
vblank:=1;
end;
end;
end;
events_update_dd3;
video_sync;
end;
end;
procedure ddragon3_scroll_io(dir:byte;valor:word);
begin
case dir of
0:fg_scrollx:=valor;
1:fg_scrolly:=valor;
2:bg_scrollx:=valor;
3:bg_scrolly:=valor;
5:main_screen.flip_main_screen:=(valor and 1)<>0;
6:if bg_tilebase<>(valor and $1ff) then begin
bg_tilebase:=valor and $1ff;
fillchar(gfx[0].buffer,$400,1);
end;
end;
end;
procedure ddragon3_io_w(dir:byte;valor:word);
begin
case dir of
0:vreg:=valor and $ff;
1:begin
sound_latch:=valor and $ff;
z80_0.change_nmi(PULSE_LINE);
end;
2,4:m68000_0.irq[6]:=CLEAR_LINE;
3:m68000_0.irq[5]:=CLEAR_LINE;
end;
end;
function ddragon3_getword(direccion:dword):word;
begin
case direccion of
0..$7ffff:ddragon3_getword:=rom[direccion shr 1];
$80000..$80fff:ddragon3_getword:=fg_ram[(direccion and $fff) shr 1];
$82000..$827ff:ddragon3_getword:=bg_ram[(direccion and $7ff) shr 1];
$100000:ddragon3_getword:=marcade.in0;
$100002:ddragon3_getword:=marcade.in1;
$100004:ddragon3_getword:=marcade.dswa;
$100006:ddragon3_getword:=$ffff; //P3!!
$140000..$1405ff:ddragon3_getword:=buffer_paleta[(direccion and $7ff) shr 1];
$180000..$180fff:ddragon3_getword:=buffer_sprites_w[(direccion and $fff) shr 1];
$1c0000..$1c3fff:ddragon3_getword:=ram[(direccion and $3fff) shr 1];
end;
end;
procedure cambiar_color(pos,data:word);
var
color:tcolor;
begin
color.b:=pal5bit(data shr 10);
color.g:=pal5bit(data shr 5);
color.r:=pal5bit(data);
set_pal_color(color,pos);
case pos of
$100..$1ff:buffer_color[$10+((pos shr 4) and $f)]:=true;
$200..$2ff:buffer_color[(pos shr 4) and $f]:=true;
end;
end;
procedure ddragon3_putword(direccion:dword;valor:word);
begin
case direccion of
0..$7ffff:; //ROM
$80000..$80fff:if fg_ram[(direccion and $fff) shr 1]<>valor then begin
fg_ram[(direccion and $fff) shr 1]:=valor;
gfx[0].buffer[$400+((direccion and $fff) shr 2)]:=true;
end;
$82000..$827ff:if bg_ram[(direccion and $7ff) shr 1]<>valor then begin
bg_ram[(direccion and $7ff) shr 1]:=valor;
gfx[0].buffer[(direccion and $7ff) shr 1]:=true;
end;
$c0000..$c000f:ddragon3_scroll_io((direccion and $f) shr 1,valor);
$100000..$10000f:ddragon3_io_w((direccion and $f) shr 1,valor);
$140000..$1405ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin
buffer_paleta[(direccion and $7ff) shr 1]:=valor;
cambiar_color((direccion and $7ff) shr 1,valor);
end;
$180000..$180fff:buffer_sprites_w[(direccion and $fff) shr 1]:=valor;
$1c0000..$1c3fff:ram[(direccion and $3fff) shr 1]:=valor;
end;
end;
function ddragon3_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$c7ff:ddragon3_snd_getbyte:=mem_snd[direccion];
$c801:ddragon3_snd_getbyte:=ym2151_0.status;
$d800:ddragon3_snd_getbyte:=oki_6295_0.read;
$e000:ddragon3_snd_getbyte:=sound_latch;
end;
end;
procedure ddragon3_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$bfff:; //ROM
$c000..$c7ff:mem_snd[direccion]:=valor;
$c800:ym2151_0.reg(valor);
$c801:ym2151_0.write(valor);
$d800:oki_6295_0.write(valor);
$e800:copymemory(oki_6295_0.get_rom_addr,@mem_oki[(valor and 1)*$40000],$40000);
end;
end;
//Ctribe
function ctribe_getword(direccion:dword):word;
begin
case direccion of
0..$7ffff:ctribe_getword:=rom[direccion shr 1];
$80000..$80fff:ctribe_getword:=fg_ram[(direccion and $fff) shr 1];
$81000..$81fff:ctribe_getword:=buffer_sprites_w[(direccion and $fff) shr 1];
$82000..$827ff:ctribe_getword:=bg_ram[(direccion and $7ff) shr 1];
$82800..$82fff:ctribe_getword:=ram2[(direccion and $7ff) shr 1];
$c0000..$c000f:case ((direccion and $f) shr 1) of
0:ctribe_getword:=fg_scrollx;
1:ctribe_getword:=fg_scrolly;
2:ctribe_getword:=bg_scrollx;
3:ctribe_getword:=bg_scrolly;
5:ctribe_getword:=byte(main_screen.flip_main_screen);
6:ctribe_getword:=bg_tilebase;
else ctribe_getword:=0;
end;
$100000..$1005ff:ctribe_getword:=buffer_paleta[(direccion and $7ff) shr 1];
$180000:ctribe_getword:=(marcade.in0 and $e7ff) or (vblank*$800) or (marcade.dswc and $1000);
$180002:ctribe_getword:=(marcade.in1 and $ff) or (marcade.dswb and $ff00);
$180004:ctribe_getword:=$ff or (marcade.dswb and $ff00); //P3
$180006:ctribe_getword:=marcade.dswc or $1000;
$1c0000..$1c3fff:ctribe_getword:=ram[(direccion and $3fff) shr 1];
end;
end;
procedure cambiar_color_ctribe(pos,data:word);
var
color:tcolor;
begin
color.b:=pal4bit(data shr 8);
color.g:=pal4bit(data shr 4);
color.r:=pal4bit(data);
set_pal_color(color,pos);
case pos of
$100..$1ff:buffer_color[$10+((pos shr 4) and $f)]:=true;
$200..$2ff:buffer_color[(pos shr 4) and $f]:=true;
end;
end;
procedure ctribe_putword(direccion:dword;valor:word);
begin
case direccion of
0..$7ffff:; //ROM
$80000..$80fff:if fg_ram[(direccion and $fff) shr 1]<>valor then begin
fg_ram[(direccion and $fff) shr 1]:=valor;
gfx[0].buffer[$400+((direccion and $fff) shr 2)]:=true;
end;
$81000..$81fff:buffer_sprites_w[(direccion and $fff) shr 1]:=valor;
$82000..$827ff:if bg_ram[(direccion and $7ff) shr 1]<>valor then begin
bg_ram[(direccion and $7ff) shr 1]:=valor;
gfx[0].buffer[(direccion and $7ff) shr 1]:=true;
end;
$82800..$82fff:ram2[(direccion and $7ff) shr 1]:=valor;
$c0000..$c000f:ddragon3_scroll_io((direccion and $f) shr 1,valor);
$100000..$1005ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin
buffer_paleta[(direccion and $7ff) shr 1]:=valor;
cambiar_color_ctribe((direccion and $7ff) shr 1,valor);
end;
$140000..$14000f:ddragon3_io_w((direccion and $f) shr 1,valor);
$1c0000..$1c3fff:ram[(direccion and $3fff) shr 1]:=valor;
end;
end;
function ctribe_snd_getbyte(direccion:word):byte;
begin
case direccion of
0..$87ff:ctribe_snd_getbyte:=mem_snd[direccion];
$8801:ctribe_snd_getbyte:=ym2151_0.status;
$9800:ctribe_snd_getbyte:=oki_6295_0.read;
$a000:ctribe_snd_getbyte:=sound_latch;
end;
end;
procedure ctribe_snd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$7fff:; //ROM
$8000..$87ff:mem_snd[direccion]:=valor;
$8800:ym2151_0.reg(valor);
$8801:ym2151_0.write(valor);
$9800:oki_6295_0.write(valor);
end;
end;
procedure ym2151_snd_irq(irqstate:byte);
begin
z80_0.change_irq(irqstate);
end;
procedure ddragon3_sound_update;
begin
ym2151_0.update;
oki_6295_0.update;
end;
//Snapshot
procedure ddragon3_qsave(nombre:string);
var
data:pbyte;
buffer:array[0..13] of byte;
size:word;
name:string;
begin
case main_vars.tipo_maquina of
196:name:='ddragon3';
232:name:='ctribe';
end;
open_qsnapshot_save(name+nombre);
getmem(data,20000);
//CPU
size:=m68000_0.save_snapshot(data);
savedata_qsnapshot(data,size);
size:=z80_0.save_snapshot(data);
savedata_qsnapshot(data,size);
//SND
size:=ym2151_0.save_snapshot(data);
savedata_com_qsnapshot(data,size);
size:=oki_6295_0.save_snapshot(data);
savedata_com_qsnapshot(data,size);
//MEM
savedata_com_qsnapshot(@fg_ram,$800*2);
savedata_com_qsnapshot(@bg_ram,$400*2);
savedata_com_qsnapshot(@ram,$2000*2);
savedata_com_qsnapshot(@buffer_sprites_w,$800*2);
buffer[0]:=vreg and $ff;
buffer[1]:=vreg shr 8;
buffer[2]:=bg_tilebase and $ff;
buffer[3]:=bg_tilebase shr 8;
buffer[4]:=fg_scrollx and $ff;
buffer[5]:=fg_scrollx shr 8;
buffer[6]:=fg_scrolly and $ff;
buffer[7]:=fg_scrolly shr 8;
buffer[8]:=bg_scrollx and $ff;
buffer[9]:=bg_scrollx shr 8;
buffer[10]:=bg_scrolly and $ff;
buffer[11]:=bg_scrolly shr 8;
buffer[12]:=sound_latch;
buffer[13]:=vblank;
savedata_qsnapshot(@buffer,14);
savedata_com_qsnapshot(@buffer_paleta,$400*2);
freemem(data);
close_qsnapshot;
end;
procedure ddragon3_qload(nombre:string);
var
data:pbyte;
buffer:array[0..13] of byte;
f:word;
name:string;
begin
case main_vars.tipo_maquina of
196:name:='ddragon3';
232:name:='ctribe';
end;
if not(open_qsnapshot_load(name+nombre)) then exit;
getmem(data,20000);
//CPU
loaddata_qsnapshot(data);
m68000_0.load_snapshot(data);
loaddata_qsnapshot(data);
z80_0.load_snapshot(data);
//SND
loaddata_qsnapshot(data);
ym2151_0.load_snapshot(data);
loaddata_qsnapshot(data);
oki_6295_0.load_snapshot(data);
//MEM
loaddata_qsnapshot(@fg_ram);
loaddata_qsnapshot(@bg_ram);
loaddata_qsnapshot(@ram);
loaddata_qsnapshot(@buffer_sprites_w);
loaddata_qsnapshot(@buffer);
vreg:=buffer[0] or (buffer[1] shl 8);
bg_tilebase:=buffer[2] or (buffer[3] shl 8);
fg_scrollx:=buffer[4] or (buffer[5] shl 8);
fg_scrolly:=buffer[6] or (buffer[7] shl 8);
bg_scrollx:=buffer[8] or (buffer[9] shl 8);
bg_scrolly:=buffer[10] or (buffer[11] shl 8);
sound_latch:=buffer[12];
vblank:=buffer[13];
loaddata_qsnapshot(@buffer_paleta);
freemem(data);
close_qsnapshot;
//END
for f:=0 to $3ff do begin
if main_vars.tipo_maquina=196 then cambiar_color(f,buffer_paleta[f])
else cambiar_color_ctribe(f,buffer_paleta[f]);
end;
fillchar(buffer_color,$400,1);
fillchar(gfx[0].buffer,$800,1);
end;
//Main
procedure reset_ddragon3;
begin
m68000_0.reset;
z80_0.reset;
ym2151_0.reset;
oki_6295_0.reset;
reset_audio;
marcade.in0:=$ffff;
marcade.in1:=$ffff;
bg_tilebase:=0;
fg_scrollx:=0;
fg_scrolly:=0;
bg_scrollx:=0;
bg_scrolly:=0;
vreg:=0;
sound_latch:=0;
vblank:=0;
end;
function iniciar_ddragon3:boolean;
var
memoria_temp:pbyte;
const
pt_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7,
32*8+0, 32*8+1, 32*8+2, 32*8+3, 32*8+4, 32*8+5, 32*8+6, 32*8+7);
pt_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16,
16*8, 16*9, 16*10, 16*11, 16*12, 16*13, 16*14, 16*15);
ps_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7,
16*8+0, 16*8+1, 16*8+2, 16*8+3, 16*8+4, 16*8+5, 16*8+6, 16*8+7);
ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8);
begin
llamadas_maquina.bucle_general:=ddragon3_principal;
llamadas_maquina.reset:=reset_ddragon3;
llamadas_maquina.fps_max:=57.444853;
llamadas_maquina.load_qsnap:=ddragon3_qload;
llamadas_maquina.save_qsnap:=ddragon3_qsave;
iniciar_ddragon3:=false;
iniciar_audio(false);
//Pantallas
screen_init(1,512,512,true);
screen_mod_scroll(1,512,320,511,512,256,511);
screen_init(2,512,512,true);
screen_mod_scroll(2,512,320,511,512,256,511);
screen_init(3,512,512,false,true);
iniciar_video(320,240);
//Main CPU
m68000_0:=cpu_m68000.create(10000000,272);
//Sound CPU
z80_0:=cpu_z80.create(3579545,272);
z80_0.init_sound(ddragon3_sound_update);
//Sound Chips
ym2151_0:=ym2151_chip.create(3579545,0.5);
ym2151_0.change_irq_func(ym2151_snd_irq);
oki_6295_0:=snd_okim6295.Create(1056000,OKIM6295_PIN7_HIGH,1.5);
getmem(memoria_temp,$400000);
case main_vars.tipo_maquina of
196:begin //DDW 3
//Cargar ADPCM ROMS
if not(roms_load(@mem_oki,ddragon3_oki)) then exit;
copymemory(oki_6295_0.get_rom_addr,@mem_oki,$40000);
//cargar roms
m68000_0.change_ram16_calls(ddragon3_getword,ddragon3_putword);
if not(roms_load16w(@rom,ddragon3_rom)) then exit;
//cargar sonido
z80_0.change_ram_calls(ddragon3_snd_getbyte,ddragon3_snd_putbyte);
if not(roms_load(@mem_snd,ddragon3_sound)) then exit;
//convertir background
if not(roms_load16w(pword(memoria_temp),ddragon3_bg)) then exit;
init_gfx(0,16,16,$2000);
gfx[0].trans[0]:=true;
gfx_set_desc_data(4,0,64*8,8,0,$80000*8+8,$80000*8+0);
convert_gfx(0,0,memoria_temp,@pt_x,@pt_y,false,false);
//convertir sprites
if not(roms_load(memoria_temp,ddragon3_sprites)) then exit;
init_gfx(1,16,16,$8000);
gfx[1].trans[0]:=true;
gfx_set_desc_data(4,0,32*8,0,$100000*8,$100000*8*2,$100000*8*3);
convert_gfx(1,0,memoria_temp,@ps_x,@ps_y,false,false);
//DIP
marcade.dswa:=$ffff;
marcade.dswa_val:=@ddragon3_dip_a;
video_update_dd3:=update_video_ddragon3;
events_update_dd3:=eventos_ddragon3;
end;
232:begin
//Cargar ADPCM ROMS
if not(roms_load(oki_6295_0.get_rom_addr,ctribe_oki)) then exit;
//cargar roms
m68000_0.change_ram16_calls(ctribe_getword,ctribe_putword);
if not(roms_load16w(@rom,ctribe_rom)) then exit;
//cargar sonido
z80_0.change_ram_calls(ctribe_snd_getbyte,ctribe_snd_putbyte);
if not(roms_load(@mem_snd,ctribe_sound)) then exit;
//convertir background
if not(roms_load16w(pword(memoria_temp),ctribe_bg)) then exit;
init_gfx(0,16,16,$2000);
gfx[0].trans[0]:=true;
gfx_set_desc_data(4,0,64*8,8,0,$80000*8+8,$80000*8+0);
convert_gfx(0,0,memoria_temp,@pt_x,@pt_y,false,false);
//convertir sprites
if not(roms_load(memoria_temp,ctribe_sprites)) then exit;
init_gfx(1,16,16,$8000);
gfx[1].trans[0]:=true;
gfx_set_desc_data(4,0,32*8,0,$100000*8,$100000*8*2,$100000*8*3);
convert_gfx(1,0,memoria_temp,@ps_x,@ps_y,false,false);
//DIP
marcade.dswa:=$ffff;
marcade.dswa_val:=@ctribe_dip_a;
marcade.dswb:=$ffff;
marcade.dswb_val:=@ctribe_dip_b;
marcade.dswc:=$ffff;
marcade.dswc_val:=@ctribe_dip_c;
video_update_dd3:=update_video_ctribe;
events_update_dd3:=eventos_ctribe;
end;
end;
//final
freemem(memoria_temp);
reset_ddragon3;
iniciar_ddragon3:=true;
end;
end.
|
unit Rule_BDZX;
interface
uses
BaseRule,
BaseRuleData,
Rule_STD,
Rule_EMA;
type
TRule_BDZX_Price_Data = record
ParamN: Word;
ParamN_AK_EMA: WORD;
ParamN_VAR6_EMA : WORD;
ParamN_AD1_EMA : WORD;
Var2_Float: PArrayDouble;
Var5_Float: PArrayDouble;
Var6_Float: PArrayDouble;
Ret_AK_Float: PArrayDouble;
Ret_AJ: PArrayDouble;
Var3_EMA: TRule_EMA;
Var4_STD: TRule_STD;
Var6_EMA: TRule_EMA;
Ret_VAR_AK_EMA: TRule_EMA;
Ret_AD1_EMA: TRule_EMA;
end;
TRule_BDZX_Price = class(TBaseStockRule)
protected
fBDZX_Price_Data: TRule_BDZX_Price_Data;
function GetParamN: Word;
procedure SetParamN(const Value: Word);
function OnGetVar2Data(AIndex: integer): double;
function OnGetVar5Data(AIndex: integer): double;
function OnGetVar6Data(AIndex: integer): double;
function OnGetAD1Data(AIndex: integer): double;
public
constructor Create(ADataType: TRuleDataType = dtDouble); override;
destructor Destroy; override;
procedure Execute; override;
property Var2_Float: PArrayDouble read fBDZX_Price_Data.Var2_Float;
property Var3_EMA: TRule_EMA read fBDZX_Price_Data.Var3_EMA;
property Var4_STD: TRule_STD read fBDZX_Price_Data.Var4_STD;
property Var5_Float: PArrayDouble read fBDZX_Price_Data.Var5_Float;
property Var6_EMA: TRule_EMA read fBDZX_Price_Data.Var6_EMA;
property Var6_Float: PArrayDouble read fBDZX_Price_Data.Var6_Float;
property Ret_VAR_AK_EMA: TRule_EMA read fBDZX_Price_Data.Ret_VAR_AK_EMA;
property Ret_AK_Float: PArrayDouble read fBDZX_Price_Data.Ret_AK_Float;
property Ret_AD1_EMA: TRule_EMA read fBDZX_Price_Data.Ret_AD1_EMA;
property Ret_AJ: PArrayDouble read fBDZX_Price_Data.Ret_AJ;
end;
implementation
{ TRule_BDZX }
(*
VAR2:=(HIGH+LOW+CLOSE*2)/4;
VAR3:=EMA(VAR2,21);
VAR4:=STD(VAR2,21);
VAR5:=((VAR2-VAR3)/VAR4*100+200)/4;
VAR6:=(EMA(VAR5,5)-25)*1.56;
AK: EMA(VAR6,2)*1.22;
AD1: EMA(AK,2);
AJ: 3*AK-2*AD1;
org
VAR2:=(HIGH+LOW+CLOSE*2)/4;
VAR3:=EMA(VAR2,21);
VAR4:=STD(VAR2,21);
VAR5:=((VAR2-VAR3)/VAR4*100+200)/4;
VAR6:=(EMA(VAR5,5)-25)*1.56;
AK: EMA(VAR6,2)*1.22;
AD1: EMA(AK,2);
AJ: 3*AK-2*AD1;
AA:100;
BB:0;
CC:80;
Âò½ø: IF(CROSS(AK,AD1),58,20);
Âô³ö: IF(CROSS(AD1,AK),58,20);
*)
constructor TRule_BDZX_Price.Create(ADataType: TRuleDataType = dtDouble);
begin
inherited;
FillChar(fBDZX_Price_Data, SizeOf(fBDZX_Price_Data), 0);
fBDZX_Price_Data.ParamN := 21;
fBDZX_Price_Data.ParamN_VAR6_EMA := 5;
fBDZX_Price_Data.ParamN_AK_EMA := 2;
fBDZX_Price_Data.ParamN_AD1_EMA := 2;
fBDZX_Price_Data.Var3_EMA := TRule_EMA.Create(dtDouble);
fBDZX_Price_Data.Var4_STD := TRule_STD.Create(dtDouble);
fBDZX_Price_Data.Var6_EMA := TRule_EMA.Create(dtDouble);
fBDZX_Price_Data.Ret_VAR_AK_EMA := TRule_EMA.Create(dtDouble);
fBDZX_Price_Data.Ret_AD1_EMA := TRule_EMA.Create(dtDouble);
end;
destructor TRule_BDZX_Price.Destroy;
begin
CheckInArrayDouble(fBDZX_Price_Data.Var2_Float);
CheckInArrayDouble(fBDZX_Price_Data.Var5_Float);
CheckInArrayDouble(fBDZX_Price_Data.Var6_Float);
CheckInArrayDouble(fBDZX_Price_Data.Ret_AK_Float);
CheckInArrayDouble(fBDZX_Price_Data.Ret_AJ);
fBDZX_Price_Data.Var3_EMA.Free;
fBDZX_Price_Data.Var4_STD.Free;
fBDZX_Price_Data.Var6_EMA.Free;
fBDZX_Price_Data.Ret_VAR_AK_EMA.Free;
fBDZX_Price_Data.Ret_AD1_EMA.Free;
inherited;
end;
procedure TRule_BDZX_Price.Execute;
var
i: integer;
tmpDouble_Var2: double;
tmpDouble_Var5: double;
tmpDouble_AK: double;
tmpDouble_AJ: double;
begin
if Assigned(OnGetDataLength) then
begin
fBaseRuleData.DataLength := OnGetDataLength;
if fBaseRuleData.DataLength > 0 then
begin
// -----------------------------------
if fBDZX_Price_Data.Var2_Float = nil then
fBDZX_Price_Data.Var2_Float := CheckOutArrayDouble;
SetArrayDoubleLength(fBDZX_Price_Data.Var2_Float, fBaseRuleData.DataLength);
// -----------------------------------
if fBDZX_Price_Data.Var5_Float = nil then
fBDZX_Price_Data.Var5_Float := CheckOutArrayDouble;
SetArrayDoubleLength(fBDZX_Price_Data.Var5_Float, fBaseRuleData.DataLength);
// -----------------------------------
if fBDZX_Price_Data.Var6_Float = nil then
fBDZX_Price_Data.Var6_Float := CheckOutArrayDouble;
SetArrayDoubleLength(fBDZX_Price_Data.Var6_Float, fBaseRuleData.DataLength);
// -----------------------------------
if fBDZX_Price_Data.Ret_AK_Float = nil then
fBDZX_Price_Data.Ret_AK_Float := CheckOutArrayDouble;
SetArrayDoubleLength(fBDZX_Price_Data.Ret_AK_Float, fBaseRuleData.DataLength);
// -----------------------------------
if fBDZX_Price_Data.Ret_AJ = nil then
fBDZX_Price_Data.Ret_AJ := CheckOutArrayDouble;
SetArrayDoubleLength(fBDZX_Price_Data.Ret_AJ, fBaseRuleData.DataLength);
// -----------------------------------
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
// (HIGH+LOW+CLOSE*2)/4;
tmpDouble_Var2 := 2 * OnGetPriceClose(i);
tmpDouble_Var2 := tmpDouble_Var2 + OnGetPriceHigh(i);
tmpDouble_Var2 := tmpDouble_Var2 + OnGetPriceLow(i);
tmpDouble_Var2 := tmpDouble_Var2 / 4;
SetArrayDoubleValue(fBDZX_Price_Data.Var2_Float, i, tmpDouble_Var2);
end;
// -----------------------------------
fBDZX_Price_Data.Var3_EMA.ParamN := fBDZX_Price_Data.ParamN;
fBDZX_Price_Data.Var3_EMA.OnGetDataLength := Self.OnGetDataLength;
fBDZX_Price_Data.Var3_EMA.OnGetDataF := Self.OnGetVar2Data;
fBDZX_Price_Data.Var3_EMA.Execute;
// -----------------------------------
fBDZX_Price_Data.Var4_STD.ParamN := fBDZX_Price_Data.ParamN;
fBDZX_Price_Data.Var4_STD.OnGetDataLength := Self.OnGetDataLength;
fBDZX_Price_Data.Var4_STD.OnGetDataF := Self.OnGetVar2Data;
fBDZX_Price_Data.Var4_STD.Execute;
// -----------------------------------
// VAR5:=((VAR2-VAR3)/VAR4*100+200)/4;
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpDouble_Var5 := GetArrayDoubleValue(fBDZX_Price_Data.Var2_Float, i) - fBDZX_Price_Data.Var3_EMA.ValueF[i];
tmpDouble_Var5 := tmpDouble_Var5 * 100;
if fBDZX_Price_Data.Var4_STD.ValueF[i] = 0 then
begin
tmpDouble_Var5 := tmpDouble_Var5;
end else
begin
tmpDouble_Var5 := tmpDouble_Var5 / fBDZX_Price_Data.Var4_STD.ValueF[i];
end;
tmpDouble_Var5 := tmpDouble_Var5 + 200;
tmpDouble_Var5 := tmpDouble_Var5 / 4;
SetArrayDoubleValue(fBDZX_Price_Data.Var5_Float, i, tmpDouble_Var5);
end;
// -----------------------------------
//VAR6:=(EMA(VAR5,5)-25)*1.56;
fBDZX_Price_Data.Var6_EMA.ParamN := 5;
fBDZX_Price_Data.Var6_EMA.OnGetDataLength := Self.OnGetDataLength;
fBDZX_Price_Data.Var6_EMA.OnGetDataF := Self.OnGetVar5Data;
fBDZX_Price_Data.Var6_EMA.Execute;
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
SetArrayDoubleValue(fBDZX_Price_Data.Var6_Float, i, (fBDZX_Price_Data.Var6_EMA.ValueF[i] - 25) * 1.56);
end;
// -----------------------------------
// AK: EMA(VAR6,2)*1.22;
fBDZX_Price_Data.Ret_VAR_AK_EMA.ParamN := fBDZX_Price_Data.ParamN_AK_EMA;
fBDZX_Price_Data.Ret_VAR_AK_EMA.OnGetDataLength := Self.OnGetDataLength;
fBDZX_Price_Data.Ret_VAR_AK_EMA.OnGetDataF := Self.OnGetVar6Data;
fBDZX_Price_Data.Ret_VAR_AK_EMA.Execute;
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpDouble_AK := fBDZX_Price_Data.Ret_VAR_AK_EMA.valueF[i] * 1.22;
if 0 = i then
begin
fBDZX_Price_Data.Ret_AK_Float.MaxValue := tmpDouble_AK;
fBDZX_Price_Data.Ret_AK_Float.MinValue := fBDZX_Price_Data.Ret_AK_Float.MaxValue;
end else
begin
if tmpDouble_AK > fBDZX_Price_Data.Ret_AK_Float.MaxValue then
fBDZX_Price_Data.Ret_AK_Float.MaxValue := tmpDouble_AK;
if tmpDouble_AK < fBDZX_Price_Data.Ret_AK_Float.MinValue then
fBDZX_Price_Data.Ret_AK_Float.MinValue := tmpDouble_AK;
end;
SetArrayDoubleValue(fBDZX_Price_Data.Ret_AK_Float, i, tmpDouble_AK);
end;
// -----------------------------------
// AD1: EMA(AK,2);
fBDZX_Price_Data.Ret_AD1_EMA.ParamN := fBDZX_Price_Data.ParamN_AD1_EMA;
fBDZX_Price_Data.Ret_AD1_EMA.OnGetDataLength := Self.OnGetDataLength;
fBDZX_Price_Data.Ret_AD1_EMA.OnGetDataF := Self.OnGetAD1Data;
fBDZX_Price_Data.Ret_AD1_EMA.Execute;
// -----------------------------------
// AJ: 3*AK-2*AD1;
// -----------------------------------
for i := 0 to fBaseRuleData.DataLength - 1 do
begin
tmpDouble_AJ :=
3 * GetArrayDoubleValue(fBDZX_Price_Data.Ret_AK_Float, i) -
2 * fBDZX_Price_Data.Ret_AD1_EMA.valueF[i];
SetArrayDoubleValue(fBDZX_Price_Data.Ret_AJ, i, tmpDouble_AJ);
if 0 = i then
begin
fBDZX_Price_Data.Ret_AJ.MaxValue := tmpDouble_AJ;
fBDZX_Price_Data.Ret_AJ.MinValue := fBDZX_Price_Data.Ret_AJ.MaxValue;
end else
begin
if tmpDouble_AJ > fBDZX_Price_Data.Ret_AJ.MaxValue then
fBDZX_Price_Data.Ret_AJ.MaxValue := tmpDouble_AJ;
if tmpDouble_AJ < fBDZX_Price_Data.Ret_AJ.MinValue then
fBDZX_Price_Data.Ret_AJ.MinValue := tmpDouble_AJ;
end;
end;
end;
end;
end;
function TRule_BDZX_Price.GetParamN: Word;
begin
Result := fBDZX_Price_Data.ParamN;
end;
procedure TRule_BDZX_Price.SetParamN(const Value: Word);
begin
if Value > 0 then
begin
fBDZX_Price_Data.ParamN := Value;
end;
end;
function TRule_BDZX_Price.OnGetVar2Data(AIndex: integer): double;
begin
Result := GetArrayDoubleValue(fBDZX_Price_Data.Var2_Float, AIndex);
end;
function TRule_BDZX_Price.OnGetVar5Data(AIndex: integer): double;
begin
Result := GetArrayDoubleValue(fBDZX_Price_Data.Var5_Float, AIndex);
end;
function TRule_BDZX_Price.OnGetVar6Data(AIndex: integer): double;
begin
Result := GetArrayDoubleValue(fBDZX_Price_Data.Var6_Float, AIndex);
end;
function TRule_BDZX_Price.OnGetAD1Data(AIndex: integer): double;
begin
Result := GetArrayDoubleValue(fBDZX_Price_Data.Ret_AK_Float, AIndex);
end;
end.
|
unit UPatchMissingOpenURLEvent;
//This unit is a patch for a bug in XE4, XE6 unpatched: The OpenURL event doesn't get called.
// QC 115594
//The bug was fixed in XE6 SP1, so this doesn't apply for newer versions.
//This patch is applied automatically in the initialization section,
//so just including this unit in your project is enough to apply the patch.
//This unit is designed to work in Delphi XE4/XE5/XE6 (not sp1) to workaround a very specific bug:
//http://qc.embarcadero.com/wc/qcmain.aspx?d=115594
//So from XE6 SP1 or newer, we'll do nothing. You can remove the unit from your projects too.
interface
implementation
{$if CompilerVersion <= 26.0}
uses MacAPI.ObjCRuntime,
iOSapi.Foundation, SysUtils,
FMX.Platform.iOS, //This must be used, so the DelphiAppDelegate class is initialized before ours.
FMX.Platform, iOSapi.UIKit, System.Rtti;
function CallFMXOpenURLEvent(const EventContext: TiOSOpenApplicationContext): boolean;
var
AppService: IFMXApplicationService;
PlatformCocoa: TObject; //TPlatformCocoaTouch is defined in the implementation section.
c : TRttiContext;
platc: TRttiType;
HandleAppEventMethod: TRttiMethod;
DelegateResult: TValue;
begin
Result := false;
if not TPlatformServices.Current.SupportsPlatformService(IFMXApplicationService, IInterface(AppService)) then exit;
PlatformCocoa := AppService as TObject;
if PlatformCocoa = nil then exit;
c := TRttiContext.Create;
platc := c.GetType(PlatformCocoa.ClassInfo);
//We could instead get the AppDelegateProperty, and call the "application" method on it, but since application is overloaded, it is more difficult to find the right method to call.
HandleAppEventMethod := platc.GetMethod('HandleApplicationEvent');
if HandleAppEventMethod = nil then exit;
{$if CompilerVersion >= 27.0}
DelegateResult := HandleAppEventMethod.Invoke(PlatformCocoa, [TValue.From(TApplicationEvent.OpenURL), EventContext]);
{$else}
DelegateResult := HandleAppEventMethod.Invoke(PlatformCocoa, [TValue.From(TApplicationEvent.aeOpenURL), EventContext]);
{$endif}
Result := DelegateResult.AsBoolean;
end;
function applicationOpenURL(self: pointer; _cmd: pointer;
application: pointer; openURL: pointer; sourceApplication: pointer; annotation: Pointer): Boolean; cdecl;
var
sourceApp: string;
url: string;
begin
sourceApp := Utf8ToString(TNSString.Wrap(sourceApplication).UTF8String);
url:= UTF8ToString(TNSURL.Wrap(openURL).absoluteString.UTF8String);
Result := CallFMXOpenURLEvent(TiOSOpenApplicationContext.Create(sourceApp, url, annotation));
end;
//This method adds the OpenURL delegate to the DelphiAppDelegate class
//which is defined by Delphi. In XE4, they have forgotten to add this delegate,
//so we need to add it ourselves. If in a future method the delegated is
//added to Delphi, then this method will do nothing. (as it checks the method isn't already added)
procedure AddOpenURLEvent;
var
AppDelegateRef: pointer;
uid: pointer;
begin
AppDelegateRef := objc_getClass('DelphiAppDelegate');
if AppDelegateRef <> nil then
begin
uid := sel_getUid('application:openURL:sourceApplication:annotation:');
if (class_getInstanceMethod(AppDelegateRef, uid) = nil) then
begin
class_addMethod(appDelegateRef, uid, @applicationOpenURL, 'B@:@@@@');
end;
end;
end;
initialization
AddOpenURLEvent;
{$endif}
end.
|
(***********************************************************************
Slightly Modified TPMOUSE for 4HELP 4.0.
Added ManualMouseInit Procedure, which moves the mouse initialization
code from this unit to the calling program. You must call this
procedure in order to use the mouse in a program.
Scott McGrath, 11-01-91
************************************************************************)
{$S-,R-,V-,I-,B-,F+}
{$IFNDEF Ver40}
{$I OMINUS.INC}
{$ENDIF}
{*********************************************************}
{* TPMOUSE.PAS 5.11 *}
{* Copyright (c) TurboPower Software 1988. *}
{* Portions copyright (c) Sunny Hill Software 1985, 1986 *}
{* and used under license to TurboPower Software *}
{* All rights reserved. *}
{*********************************************************}
unit TpMouse;
{-Mouse interface routines. Designed for use in text mode only.}
interface
uses TpCrt;
var
MouseInstalled : Boolean;
MouseCursorOn : Boolean;
type
ButtonStatus = (
NoButton, LeftButton, RightButton, BothButtons,
{the following values are possible only on a 3-button mouse}
CenterButton, LeftAndCenterButtons, RightAndCenterButtons, All3Buttons,
{the following values are possible only on a wheel mouse}
WheelDown, LeftButtonAndWheelDown, RightButtonAndWheelDown,
BothButtonsAndWheelDown, CenterButtonAndWheelDown,
LeftAndCenterButtonsAndWheelDown, RightAndCenterButtonsAndWheelDown,
All3ButtonsAndWheelDown,
WheelUp, LeftButtonAndWheelUp, RightButtonAndWheelUp,
BothButtonsAndWheelUp, CenterButtonAndWheelUp,
LeftAndCenterButtonsAndWheelUp, RightAndCenterButtonsAndWheelUp,
All3ButtonsAndWheelUp
);
const
DisableEventHandler = $00;
MouseMoved = $01;
LeftButtonPressed = $02;
LeftButtonReleased = $04;
RightButtonPressed = $08;
RightButtonReleased = $10;
CenterButtonPressed = $20;
CenterButtonReleased = $40;
WheelMoved = $80;
AllMouseEvents = $FF;
type
MouseEventType = DisableEventHandler..AllMouseEvents;
const
DefaultScreenMask = $FFFF;
DefaultCursorMask = $7700;
type
MouseState =
record
BufSize : Word;
Buffer : array[1..400] of Byte;
end;
MouseStatePtr = ^MouseState;
var
{current window coordinates for mouse}
MouseXLo : Byte; {0-based}
MouseYLo : Byte; {0-based}
MouseXHi : Byte; {1-based}
MouseYHi : Byte; {1-based}
const
{if True, MouseKeyWord waits for the button to be released before returning
its key code}
WaitForButtonRelease : Boolean = True;
{pseudo-scan codes returned by MouseKeyWord--DO NOT CHANGE THESE}
MouseLft = $EF00; {left button}
MouseRt = $EE00; {right button}
MouseBoth = $ED00; {both buttons}
MouseCtr = $EC00; {center button}
MouseLftCtr = $EB00; {left and center buttons}
MouseRtCtr = $EA00; {right and center buttons}
MouseThree = $E900; {all three buttons}
MouseWhDn = $E800; {wheel down}
MouseLftWhDn = $E700; {left button and wheel down}
MouseRtWhDn = $E600; {right button and wheel down}
MouseBothWhDn = $E500; {both buttons and wheel down}
MouseCtrWhDn = $E400; {center button and wheel down}
MouseLftCtrWhDn = $E300; {left and center buttons and wheel down}
MouseRtCtrWhDn = $E200; {right and center buttons and wheel down}
MouseThreeWhDn = $E100; {all three buttons and wheel down}
MouseWhUp = $E000; {wheel up}
MouseLftWhUp = $DF00; {left button and wheel up}
MouseRtWhUp = $DE00; {right button and wheel up}
MouseBothWhUp = $DD00; {both buttons and wheel up}
MouseCtrWhUp = $DC00; {center button and wheel up}
MouseLftCtrWhUp = $DB00; {left and center buttons and wheel up}
MouseRtCtrWhUp = $DA00; {right and center buttons and wheel up}
MouseThreeWhUp = $D900; {all three buttons and wheel up}
var
MouseKeyWordX : Byte; {mouse coordinates at time of call to MouseKeyWord}
MouseKeyWordY : Byte;
const
MouseRoutine : Pointer = nil;
MouseRoutineEvent : MouseEventType = DisableEventHandler;
MouseEvent : MouseEventType = DisableEventHandler;
MouseStatus : ButtonStatus = NoButton;
MouseLastX : Byte = 1;
MouseLastY : Byte = 1;
function MousePressed : Boolean;
{-Return True if a mouse button is currently being pressed}
function MouseKeyWord : Word;
{-Return a pseudo-scan code based on which mouse button is being pressed}
function ReadKeyOrButton : Word;
{-Return next key or mouse button}
procedure EnableEventHandling;
{-Enable the event handler needed for MousePressed and MouseKeyWord}
procedure DisableEventHandling;
{-Disable the event handler installed by EnableEventHandling}
procedure InitializeMouse;
{-Reinitializes mouse and sets MouseInstalled}
procedure ShowMouse;
{-Show the mouse cursor.}
procedure HideMouse;
{-Hide the mouse cursor}
procedure MouseWhereXY(var MouseX, MouseY : Byte; var Status : ButtonStatus);
{-Return mouse position and button status}
function MouseWhereX : Byte;
{-Return current X coordinate for mouse}
function MouseWhereY : Byte;
{-Return current Y coordinate for mouse}
procedure MouseGotoXY(MouseX, MouseY : Byte);
{-Set mouse position}
function MouseButtonPressed(Button : ButtonStatus; var Count : Word;
var LastX, LastY : Byte) : Boolean;
{-Returns True if the Button to check has been pressed. If so, Count has the
number of times it has been pressed, and LastX/LastY have its position the
last time it was pressed.}
function MouseButtonReleased(Button : ButtonStatus; var Count : Word;
var LastX, LastY : Byte) : Boolean;
{-Returns True if the Button to check has been released. If so, Count has the
number of times it has been released, and LastX/LastY have its position the
last time it was released.}
procedure MouseWindow(XLow, YLow, XHigh, YHigh : Byte);
{-Sets window coordinates to be observed by the mouse}
procedure FullMouseWindow;
{-Sets mouse window coordinates to full screen}
function MouseInWindow(XLo, YLo, XHi, YHi : Byte) : Boolean;
{-Return True if mouse is within the specified window}
procedure SoftMouseCursor(ScreenMask, CursorMask : Word);
{-Set mouse to use a software cursor}
procedure HardMouseCursor(StartLine, EndLine : Word);
{-Set mouse to use the hardware cursor. StartLine and EndLine specify the
shape of the cursor.}
procedure NormalMouseCursor;
{-Set normal scan lines for mouse cursor based on current video mode}
procedure FatMouseCursor;
{-Set larger scan lines for mouse cursor based on current video mode}
procedure BlockMouseCursor;
{-Set scan lines for a block mouse cursor}
procedure HiddenMouseCursor;
{-Hide the mouse cursor}
procedure GetMickeyCount(var Horizontal, Vertical : Integer);
{-Returns the horizontal and vertical mickey count since the last call to
this function. Negative numbers indicate movement up or to the left;
positive numbers indicate movement down or to the right.}
procedure SetMickeyToPixelRatio(Horizontal, Vertical : Integer);
{-Sets the mickey-to-pixel ratio. Default setting is 8,16. A setting of
16,32 slows down the mouse considerably. A setting of 4,8 makes the
mouse fly.}
procedure SetMouseEventHandler(EventMask : MouseEventType; UserRoutine : Pointer);
{-Sets the address of a routine to be called when the specified mouse
events occur. TPMOUSE handles the saving of the mouse driver's registers
and sets up the DS register for the UserRoutine. Information about the
Event is passed to UserRoutine using the global variables MouseEvent,
MouseStatus, MouseLastX, and MouseLastY}
{-- The remaining routines may not be implemented by all mouse drivers!! --}
function GetMousePage : Byte;
{-Returns the video page where the mouse is being displayed}
{-- May not be implemented in all mouse drivers!! --}
procedure SetMousePage(Page : Byte);
{-Sets the video page where the mouse will be displayed}
{-- May not be implemented in all mouse drivers!! --}
{-- the following routines are intended primarily for use in TSR's --}
function MouseStateBufferSize : Word;
{-Returns amount of memory needed to save the state of the mouse driver}
procedure SaveMouseState(var MSP : MouseStatePtr; Allocate : Boolean);
{-Save the state of the mouse driver, allocating the buffer if requested.}
procedure RestoreMouseState(var MSP : MouseStatePtr; Deallocate : Boolean);
{-Restore the state of the mouse driver and Deallocate the buffer if
requested}
procedure ManualMouseInit;
{Moved Mouse Initialization code out of this unit} {!!! 4.0}
{==========================================================================}
implementation
var
SaveExitProc : Pointer;
EventHandlerInstalled : Boolean;
{$L TPMOUSE.OBJ}
procedure InitializeMouse; external;
procedure ShowMousePrim; external;
procedure HideMousePrim; external;
procedure MouseWhereXY(var MouseX, MouseY : Byte;
var Status : ButtonStatus); external;
function MouseWhereX : Byte; external;
function MouseWhereY : Byte; external;
procedure MouseGotoXY(MouseX, MouseY : Byte); external;
function MouseButtonPressed(Button : ButtonStatus; var Count : Word;
var LastX, LastY : Byte) : Boolean; external;
function MouseButtonReleased(Button : ButtonStatus; var Count : Word;
var LastX, LastY : Byte) : Boolean; external;
procedure MouseWindow(XLow, YLow, XHigh, YHigh : Byte); external;
procedure SoftMouseCursor(ScreenMask, CursorMask : Word); external;
procedure HardMouseCursor(StartLine, EndLine : Word); external;
function GetMousePage : Byte; external;
procedure SetMousePage(Page : Byte); external;
procedure GetMickeyCount(var Horizontal, Vertical : Integer); external;
procedure SetMickeyToPixelRatio(Horizontal, Vertical : Integer); external;
{these procedures, used internally, are all called FAR}
procedure MouseEventPrim(EventMask : MouseEventType; UserRoutine : Pointer); external;
procedure MouseEventHandler; external;
function GetStorageSize : Word; external;
{-Returns amount of memory needed to save state of mouse driver}
procedure SaveMouseStatePrim(var Buffer); external;
{-Save mouse state in Buffer}
procedure RestoreMouseStatePrim(var Buffer); external;
{-Restore mouse state from Buffer}
function MousePressed : Boolean;
{-Return True if a mouse button is currently being pressed}
begin
if not(MouseInstalled and EventHandlerInstalled) then
MousePressed := False
else
MousePressed := MouseStatus <> NoButton;
end;
function MouseKeyWord : Word;
{-Return a pseudo scan code based on which key is being pressed}
const
ScanTable : array[LeftButton..All3ButtonsAndWheelUp] of Word = (MouseLft,
MouseRt, MouseBoth, MouseCtr, MouseLftCtr, MouseRtCtr, MouseThree,
MouseWhDn, MouseLftWhDn, MouseRtWhDn, MouseBothWhDn, MouseCtrWhDn,
MouseLftCtrWhDn, MouseRtCtrWhDn, MouseThreeWhDn,
MouseWhUp, MouseLftWhUp, MouseRtWhUp, MouseBothWhUp, MouseCtrWhUp,
MouseLftCtrWhUp, MouseRtCtrWhUp, MouseThreeWhUp
);
BitsTable : array[ButtonStatus] of Byte = (0, 1, 1, 2, 1, 2, 2, 3,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
var
Status, TempStatus : ButtonStatus;
SaveBitsOn, BitsOn : Byte;
begin
{return bogus key code if no mouse or event handler not installed}
if not(MouseInstalled and EventHandlerInstalled) then begin
MouseKeyWord := $FFFF;
Exit;
end;
{force interrupts on}
inline($FB); {sti}
{wait for a button to be pressed}
Status := MouseStatus;
while Status = NoButton do begin
{make sure TSR's can pop up}
inline($cd/$28);
Status := MouseStatus;
end;
if WaitForButtonRelease then begin
{save the current number of buttons that are on}
SaveBitsOn := BitsTable[Status];
{wait for the button(s) now being pressed to be released}
TempStatus := MouseStatus;
while (Byte(TempStatus) and Byte(Status)) <> 0 do begin
{see if an additional button has been pressed}
BitsOn := BitsTable[TempStatus];
if BitsOn > SaveBitsOn then begin
{another button was pressed--we want it too}
Status := TempStatus;
SaveBitsOn := BitsOn;
end;
{make sure TSR's can pop up}
inline($cd/$28);
TempStatus := MouseStatus;
end;
end;
{turn interrupts off}
inline($FA);
{return pseudo-scan code}
MouseKeyWord := ScanTable[Status];
{save current mouse coordinates}
MouseKeyWordX := MouseLastX;
MouseKeyWordY := MouseLastY;
{reset wheel data}
MouseStatus := ButtonStatus(ord(MouseStatus) and 7);
{turn interrupts on}
inline($FB);
end;
procedure ShowMouse;
{-Show the mouse cursor.}
begin
if not MouseCursorOn then
ShowMousePrim;
end;
procedure HideMouse;
{-Hide the mouse cursor}
begin
if MouseCursorOn then
HideMousePrim;
end;
procedure NormalMouseCursor;
{-Set normal scan lines for mouse cursor based on current video mode}
var
ScanLines : Word;
begin
if Font8x8Selected then
ScanLines := $0507
else if CurrentMode = 7 then
ScanLines := $0B0C
else
ScanLines := $0607;
HardMouseCursor(Hi(ScanLines), Lo(ScanLines));
end;
procedure FatMouseCursor;
{-Set larger scan lines for mouse cursor based on current video mode}
var
ScanLines : Word;
begin
if Font8x8Selected then
ScanLines := $0307
else if CurrentMode = 7 then
ScanLines := $090C
else
ScanLines := $0507;
HardMouseCursor(Hi(ScanLines), Lo(ScanLines));
end;
procedure BlockMouseCursor;
{-Set scan lines for a block mouse cursor}
var
EndLine : Byte;
begin
if Font8x8Selected or (CurrentMode <> 7) then
EndLine := $07
else
EndLine := $0C;
HardMouseCursor(0, EndLine);
end;
procedure HiddenMouseCursor;
{-Hide the mouse cursor}
begin
HardMouseCursor($20, 0);
end;
procedure FullMouseWindow;
{-Sets mouse window coordinates to full screen}
begin
MouseWindow(1, 1, ScreenWidth, ScreenHeight);
end;
function MouseInWindow(XLo, YLo, XHi, YHi : Byte) : Boolean;
{-Return True if mouse is within the specified window}
var
mX, mY : Byte;
Status : ButtonStatus;
begin
{get current position of mouse and see if it's inside the window}
MouseWhereXY(mX, mY, Status);
MouseInWindow := (mX >= XLo) and (mX <= XHi) and (mY >= YLo) and (mY <= YHi);
end;
function MouseStateBufferSize : Word;
{-Returns amount of memory needed to save the state of the mouse driver}
var
I : Word;
begin
if not MouseInstalled then
MouseStateBufferSize := 0
else begin
I := GetStorageSize;
if I <> 0 then
Inc(I, SizeOf(Word));
MouseStateBufferSize := I;
end;
end;
procedure SaveMouseState(var MSP : MouseStatePtr; Allocate : Boolean);
{-Save the state of the mouse driver, allocating the buffer if requested.}
var
I : Word;
begin
if Allocate then begin
{assume failure}
MSP := nil;
{make sure a mouse is installed}
if not MouseInstalled then
Exit;
{see how much memory we need}
I := MouseStateBufferSize;
{exit if 0 was returned or insufficient memory exists}
if (I = 0) or (I > MaxAvail) then
Exit;
{allocate the MouseState record}
GetMem(MSP, I);
{fill in the MouseState record} {!!.10}
MSP^.BufSize := I; {!!.10}
end;
SaveMouseStatePrim(MSP^.Buffer);
end;
procedure RestoreMouseState(var MSP : MouseStatePtr; Deallocate : Boolean);
{-Restore the state of the mouse driver and Deallocate the buffer if
requested}
begin
{exit if MSP is nil}
if (MSP = nil) or not MouseInstalled then
Exit;
{restore the mouse state}
RestoreMouseStatePrim(MSP^.Buffer);
if Deallocate then begin
{deallocate the buffer}
FreeMem(MSP, MSP^.BufSize);
{set MSP to nil so we won't do the same thing twice}
MSP := nil;
end;
end;
procedure EnableEventHandling;
{-Enable the event handler needed for MousePressed and MouseKeyWord}
begin
if MouseInstalled and not EventHandlerInstalled then begin
MouseEventPrim(AllMouseEvents, @MouseEventHandler);
EventHandlerInstalled := True;
end;
end;
procedure SetMouseEventHandler(EventMask : MouseEventType; UserRoutine : Pointer);
{-Sets the address of a routine to be called when the specified mouse
events occur}
begin
{make sure a mouse is installed}
if not MouseInstalled then
Exit;
if EventMask = DisableEventHandler then
MouseRoutine := nil
else
MouseRoutine := UserRoutine;
if MouseRoutine = nil then
MouseRoutineEvent := DisableEventHandler
else
MouseRoutineEvent := EventMask;
{enable the event handler if it isn't already}
EnableEventHandling;
end;
procedure DisableEventHandling;
{-Disable the event handler installed by EnableEventHandling}
begin
if EventHandlerInstalled then begin
{disable the event handler}
MouseEventPrim(DisableEventHandler, nil);
{set flag to indicate that we're not installed}
EventHandlerInstalled := False;
{reset variables}
MouseRoutine := nil;
MouseRoutineEvent := DisableEventHandler;
MouseEvent := DisableEventHandler;
MouseStatus := NoButton;
end;
end;
function ReadKeyOrButton : Word;
{-Return next key or mouse button}
var
I : Word;
begin
I := $FFFF;
repeat
if KeyPressed then
I := ReadKeyWord
else if MousePressed then
I := MouseKeyWord
else
{give TSR's a chance to pop up}
inline($cd/$28);
until I <> $FFFF;
ReadKeyOrButton := I;
end;
procedure ExitHandler;
{-Reinitialize and hide mouse on exit}
begin
{restore previous exit handler}
ExitProc := SaveExitProc;
{reinitialize and hide the mouse--disables all event handlers}
InitializeMouse;
end;
procedure ManualMouseInit;
begin
{initialize the mouse if one is installed (sets MouseInstalled)}
InitializeMouse;
{no need to install exit handler if not installed}
if MouseInstalled then begin
FullMouseWindow;
SaveExitProc := ExitProc;
ExitProc := @ExitHandler;
end;
end;
begin
{INITIALIZATION CODE MOVED TO MANUALMOUSEINIT}
end.
|
// ----------------------------------------------------------------------
// | TComportDriver - A Basic Driver for the serial port |
// ----------------------------------------------------------------------
// | 1997 by Marco Cocco |
// | 1998 enhanced by Angerer Bernhard |
// | 2001 enhanced by Christophe Geers |
// ----------------------------------------------------------------------
//I removed the TTimer and inserted a thread (TTimerThread) to simulate
//the function formerly done by the TTimer.TimerEvent.
//Further more the Readstring procedure has been adjusted. As soon as
//some input on the input buffer from the serial port has been detected
//the TTimerThread is supsended until all the data from the input buffer is read
//using the ReadString procedure......well go ahead and check it out for
//yourself.
//Be sure to check out the following article:
// http://www.delphi3000.com/articles/article_809.asp
//Tested with Delphi 6 Profesionnal / Enterprise on Windows 2000.
{$A+,B-,C+,D-,E-,F-,G+,H+,I+,J+,K-,L-,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y-,Z1}
{$MINSTACKSIZE $00004000}
{$MAXSTACKSIZE $00100000}
{$IMAGEBASE $51000000}
{$APPTYPE GUI}
unit ComDrv32;
interface
uses
//Include "ExtCtrl" for the TTimer component.
Windows, Messages, SysUtils, Classes, Forms, ExtCtrls;
type
//TComPortNumber = (pnCOM1,pnCOM2,pnCOM3,pnCOM4);
TComPortBaudRate = (br110,br300,br600,br1200,br2400,br4800,br9600,
br14400,br19200,br38400,br56000,br57600,br115200);
TComPortDataBits = (db5BITS,db6BITS,db7BITS,db8BITS);
TComPortStopBits = (sb1BITS,sb1HALFBITS,sb2BITS);
TComPortParity = (ptNONE,ptODD,ptEVEN,ptMARK,ptSPACE);
TComportHwHandshaking = (hhNONE,hhRTSCTS);
TComPortSwHandshaking = (shNONE,shXONXOFF);
TTimerThread = class(TThread)
private
{ Private declarations }
FOnTimer : TThreadMethod;
FEnabled: Boolean;
protected
{ Protected declarations }
procedure Execute; override;
procedure SupRes;
public
{ Public declarations }
published
{ Published declarations }
property Enabled: Boolean read FEnabled write FEnabled;
end;
TComportDriverThread = class(TComponent)
private
{ Private declarations }
FTimer : TTimerThread;
FOnReceiveData : TNotifyEvent;
FOnSendData : TNotifyEvent;
FReceiving : Boolean;
protected
{ Protected declarations }
FComPortActive : Boolean;
FComportHandle : THandle;
FComportNumber : String;
FComportBaudRate : TComPortBaudRate;
FComportDataBits : TComPortDataBits;
FComportStopBits : TComPortStopBits;
FComportParity : TComPortParity;
FComportHwHandshaking : TComportHwHandshaking;
FComportSwHandshaking : TComPortSwHandshaking;
FComportInputBufferSize : Word;
FComportOutputBufferSize : Word;
FComportPollingDelay : Word;
FTimeOut : Integer;
FTempInputBuffer : Pointer;
procedure SetComPortActive(Value: Boolean); virtual;
procedure SetComPortNumber(AValue: String);
procedure SetComPortBaudRate(Value: TComPortBaudRate);
procedure SetComPortDataBits(Value: TComPortDataBits);
procedure SetComPortStopBits(Value: TComPortStopBits);
procedure SetComPortParity(Value: TComPortParity);
procedure SetComPortHwHandshaking(Value: TComportHwHandshaking);
procedure SetComPortSwHandshaking(Value: TComPortSwHandshaking);
procedure SetComPortInputBufferSize(Value: Word);
procedure SetComPortOutputBufferSize(Value: Word);
procedure SetComPortPollingDelay(Value: Word);
procedure ApplyComPortSettings;
procedure TimerEvent; virtual;
//procedure DoDataReceived; virtual;
//procedure DoSendData; virtual;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Connect: Boolean;
function Disconnect: Boolean;
function Connected: Boolean;
function Disconnected: Boolean;
function SendData(DataPtr: Pointer; DataSize: DWORD): Boolean;
function SendString(Input: String): Boolean;
function ReadString(var Str: string): Integer;
published
{ Published declarations }
property Active: Boolean read FComPortActive write SetComPortActive default False;
property ComPort: String read FComportNumber write SetComportNumber;
property ComPortSpeed: TComPortBaudRate read FComportBaudRate write
SetComportBaudRate default br9600;
property ComPortDataBits: TComPortDataBits read FComportDataBits write
SetComportDataBits default db8BITS;
property ComPortStopBits: TComPortStopBits read FComportStopBits write
SetComportStopBits default sb1BITS;
property ComPortParity: TComPortParity read FComportParity write
SetComportParity default ptNONE;
property ComPortHwHandshaking: TComportHwHandshaking read FComportHwHandshaking
write SetComportHwHandshaking default
hhNONE;
property ComPortSwHandshaking: TComPortSwHandshaking read FComportSwHandshaking
write SetComportSwHandshaking default
shNONE;
property ComPortInputBufferSize: Word read FComportInputBufferSize
write SetComportInputBufferSize default
2048;
property ComPortOutputBufferSize: Word read FComportOutputBufferSize
write SetComportOutputBufferSize default
2048;
property ComPortPollingDelay: Word read FComportPollingDelay write
SetComportPollingDelay default 100;
property OnReceiveData: TNotifyEvent read FOnReceiveData
write FOnReceiveData;
property OnSendData: TNotifyEvent read FOnSendData write FOnSendData;
property TimeOut: Integer read FTimeOut write FTimeOut default 30;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Self-made Components', [TComportDriverThread]);
end;
{ TComportDriver }
constructor TComportDriverThread.Create(AOwner: TComponent);
begin
try
inherited;
FReceiving := False;
FComportHandle := 0;
FComportBaudRate := br9600;
FComportDataBits := db8BITS;
FComportStopBits := sb1BITS;
FComportParity := ptNONE;
FComportHwHandshaking := hhNONE;
FComportSwHandshaking := shNONE;
FComportInputBufferSize := 2048;
FComportOutputBufferSize := 2048;
FOnReceiveData := nil;
FOnSendData := nil;
FTimeOut := 30;
FComportPollingDelay := 500;
if csDesigning in ComponentState then
Exit;
GetMem(FTempInputBuffer,FComportInputBufferSize);
FTimer := TTimerThread.Create(False);
FTimer.FOnTimer := TimerEvent;
if FComPortActive then
FTimer.Enabled := True;
FTimer.SupRes;
except
on E:Exception do
begin
//Application.MessageBox(PChar(E.Message),'',mb_ok);
end;
end;
end;
destructor TComportDriverThread.Destroy;
begin
Disconnect;
FreeMem(FTempInputBuffer,FComportInputBufferSize);
inherited Destroy;
end;
function TComportDriverThread.Connect: Boolean;
var
comName: array[0..4] of Char;
tms: TCommTimeouts;
begin
comName[0] := 'C';
comName[1] := 'O';
comName[2] := 'M';
comName[3] := FComportNumber[1];
comName[4] := #0;
FComportHandle := CreateFile(comName,GENERIC_READ OR GENERIC_WRITE,0,nil,
OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
Result := Connected;
if not Result then
Exit;
ApplyComPortSettings;
tms.ReadIntervalTimeout := 1;
tms.ReadTotalTimeoutMultiplier := 0;
tms.ReadTotalTimeoutConstant := 1;
tms.WriteTotalTimeoutMultiplier := FTimeOut;
tms.WriteTotalTimeoutConstant := FTimeOut;
SetCommTimeouts(FComportHandle,tms);
Sleep(1000);
end;
function TComportDriverThread.Connected: Boolean;
begin
Result := FComportHandle > 0;
end;
function TComportDriverThread.Disconnect: Boolean;
begin
if Connected then
begin
CloseHandle(FComportHandle);
FComportHandle := 0;
end;
if FComportHandle = 0 then
Result := True
else
Result := False;
end;
function TComportDriverThread.Disconnected: Boolean;
begin
if (FComportHandle > 0) then
Result := False
else
Result := True;
end;
const
Win32BaudRates: array[br110..br115200] of DWORD =
(CBR_110,CBR_300,CBR_600,CBR_1200,CBR_2400,CBR_4800,CBR_9600,CBR_14400,
CBR_19200,CBR_38400,CBR_56000,CBR_57600,CBR_115200);
const
dcb_Binary = $00000001;
dcb_ParityCheck = $00000002;
dcb_OutxCtsFlow = $00000004;
dcb_OutxDsrFlow = $00000008;
dcb_DtrControlMask = $00000030;
dcb_DtrControlDisable = $00000000;
dcb_DtrControlEnable = $00000010;
dcb_DtrControlHandshake = $00000020;
dcb_DsrSensitvity = $00000040;
dcb_TXContinueOnXoff = $00000080;
dcb_OutX = $00000100;
dcb_InX = $00000200;
dcb_ErrorChar = $00000400;
dcb_NullStrip = $00000800;
dcb_RtsControlMask = $00003000;
dcb_RtsControlDisable = $00000000;
dcb_RtsControlEnable = $00001000;
dcb_RtsControlHandshake = $00002000;
dcb_RtsControlToggle = $00003000;
dcb_AbortOnError = $00004000;
dcb_Reserveds = $FFFF8000;
procedure TComportDriverThread.ApplyComPortSettings;
var
//Device Control Block (= dcb)
dcb: TDCB;
begin
if not Connected then
Exit;
FillChar(dcb,sizeOf(dcb),0);
dcb.DCBlength := sizeOf(dcb);
dcb.Flags := dcb_Binary or dcb_RtsControlEnable;
dcb.BaudRate := Win32BaudRates[FComPortBaudRate];
case FComportHwHandshaking of
hhNONE : ;
hhRTSCTS:
dcb.Flags := dcb.Flags or dcb_OutxCtsFlow or dcb_RtsControlHandshake;
end;
case FComportSwHandshaking of
shNONE : ;
shXONXOFF:
dcb.Flags := dcb.Flags or dcb_OutX or dcb_Inx;
end;
dcb.XonLim := FComportInputBufferSize div 4;
dcb.XoffLim := 1;
dcb.ByteSize := 5 + ord(FComportDataBits);
dcb.Parity := ord(FComportParity);
dcb.StopBits := ord(FComportStopBits);
dcb.XonChar := #17;
dcb.XoffChar := #19;
SetCommState(FComportHandle,dcb);
SetupComm(FComportHandle,FComPortInputBufferSize,FComPortOutputBufferSize);
end;
function TComportDriverThread.ReadString(var Str: string): Integer;
var
BytesTrans, nRead: DWORD;
Buffer : String;
i : Integer;
temp : string;
begin
Str := '';
SetLength(Buffer,1);
ReadFile(FComportHandle,PChar(Buffer)^, 1, nRead, nil);
while nRead = 0 do
begin
temp := temp + PChar(Buffer);
ReadFile(FComportHandle,PChar(Buffer)^, 1, nRead, nil);
end;
//Remove the end token.
BytesTrans := Length(temp);
SetLength(str,BytesTrans-2);
for i:=0 to BytesTrans-2 do
begin
str[i] := temp[i];
end;
Result := BytesTrans;
end;
function TComportDriverThread.SendData(DataPtr: Pointer; DataSize: DWORD): Boolean;
var
nsent : DWORD;
begin
if not Active then
begin
Result := Active;
Exit;
end;
Result := WriteFile(FComportHandle,DataPtr^,DataSize,nsent,nil);
Result := Result and (nsent = DataSize);
if Assigned(FOnSendData) then
FOnSendData(Self);
end;
function TComportDriverThread.SendString(Input: String): Boolean;
begin
if not Active then
begin
Result := Active;
Exit;
end;
if not Connected then
if not Connect then
raise Exception.CreateHelp('Could not connect to COM-port !',101);
Result := SendData(PChar(Input),Length(Input));
end;
procedure TComportDriverThread.TimerEvent;
var
InQueue, OutQueue: Integer;
procedure DataInBuffer(Handle: THandle; var aInQueue, aOutQueue: Integer);
var
ComStat : TComStat;
e : Cardinal;
begin
aInQueue := 0;
aOutQueue := 0;
if ClearCommError(Handle,e,@ComStat) then
begin
aInQueue := ComStat.cbInQue;
aOutQueue := ComStat.cbOutQue;
end;
end;
begin
if csDesigning in ComponentState then
Exit;
if not Connected then
if not Connect then
raise Exception.CreateHelp('TimerEvent: Could not connect to COM-port !',101);
Application.ProcessMessages;
if Connected then
begin
DataInBuffer(FComportHandle,InQueue,OutQueue);
if InQueue = 0 then
begin
if (Assigned(FOnReceiveData)) then
begin
FReceiving := True;
FOnReceiveData(Self);
end;
end;
end;
end;
procedure TComportDriverThread.SetComportBaudRate(Value: TComPortBaudRate);
begin
FComportBaudRate := Value;
if Connected then
ApplyComPortSettings;
end;
procedure TComportDriverThread.SetComportDataBits(Value: TComPortDataBits);
begin
FComportDataBits := Value;
if Connected then
ApplyComPortSettings;
end;
procedure TComportDriverThread.SetComportHwHandshaking(Value: TComportHwHandshaking);
begin
FComportHwHandshaking := Value;
if Connected then
ApplyComPortSettings;
end;
procedure TComportDriverThread.SetComportInputBufferSize(Value: Word);
begin
FreeMem(FTempInputBuffer,FComportInputBufferSize);
FComportInputBufferSize := Value;
GetMem(FTempInputBuffer,FComportInputBufferSize);
if Connected then
ApplyComPortSettings;
end;
procedure TComportDriverThread.SetComportNumber(AValue: String);
begin
if Connected then
Disconnect;
FComportNumber := AValue;
Connect;
end;
procedure TComportDriverThread.SetComportOutputBufferSize(Value: Word);
begin
FComportOutputBufferSize := Value;
if Connected then
ApplyComPortSettings;
end;
procedure TComportDriverThread.SetComportParity(Value: TComPortParity);
begin
FComportParity := Value;
if Connected then
ApplyComPortSettings;
end;
procedure TComportDriverThread.SetComportPollingDelay(Value: Word);
begin
FComportPollingDelay := Value;
end;
procedure TComportDriverThread.SetComportStopBits(Value: TComPortStopBits);
begin
FComportStopBits := Value;
if Connected then
ApplyComPortSettings;
end;
procedure TComportDriverThread.SetComportSwHandshaking(Value: TComPortSwHandshaking);
begin
FComportSwHandshaking := Value;
if Connected then
ApplyComPortSettings;
end;
{procedure TComportDriverThread.DoDataReceived;
begin
if Assigned(FOnReceiveData) then FOnReceiveData(Self);
end;
procedure TComportDriverThread.DoSendData;
begin
if Assigned(FOnSendData) then FOnSendData(Self);
end;}
procedure TComportDriverThread.SetComPortActive(Value: Boolean);
var
DumpString : String;
begin
FComPortActive := Value;
if csDesigning in ComponentState then
Exit;
if FComPortActive then
begin
//Just dump the contents of the input buffer of the com-port.
ReadString(DumpString);
FTimer.Enabled := True;
end
else
FTimer.Enabled := False;
FTimer.SupRes;
end;
{ TTimerThread }
procedure TTimerThread.Execute;
begin
try
if not Enabled then
Exit;
Priority := tpNormal;
repeat
Sleep(500);
if Assigned(FOnTimer) then Synchronize(FOnTimer);
until Terminated;
except
on E:Exception do
SupRes;
end;
end;
procedure TTimerThread.SupRes;
begin
if not Suspended then
Suspend;
if FEnabled then
Resume;
end;
end.
|
unit GetOrdersByDateUnit;
interface
uses SysUtils, BaseExampleUnit, OrderUnit;
type
TGetOrdersByDate = class(TBaseExample)
public
procedure Execute(Date: TDate);
end;
implementation
procedure TGetOrdersByDate.Execute(Date: TDate);
var
ErrorString: String;
Orders: TOrderList;
begin
Orders := Route4MeManager.Order.Get(Date, ErrorString);
try
WriteLn('');
if (Orders.Count > 0) then
WriteLn(Format(
'GetOrderByDate executed successfully, %d orders returned', [Orders.Count]))
else
WriteLn(Format('GetOrderByDate error: "%s"', [ErrorString]));
finally
FreeAndNil(Orders);
end;
end;
end.
|
program ex;
Type
pTRoomD2=^TRoomD2;
TRoomD2=object
length,width:real; {поля: длина и ширина}
function Square:real; virtual; {метод определения площади}
constructor Init(l,w:real); {конcтруктор}
destructor Done; {деструктор}
end;
Function TRoomD2.Square:real; {тело метода определения площади}
begin
Square:=length*width;
end;
Constructor TRoomD2.Init(l,w:real); {тело конструктора}
begin
length:=l;
width:=w;
end;
Destructor TRoomD2.Done;
begin
end;
Type pTVRoomD2=^TVRoomD2;
TVRoomD2=object(TRoomD2)
h,height:real; {дополнительное поле класса}
function Square:real; virtual; {виртуальный полиморфный метод}
constructor Init(l,w:real); {конструктор}
end;
constructor TVRoomD2.Init(l,w:real);
begin
inherited Init(l,w); {инициализирует поля базового класса}
height:=h; {инициализируем собственное поле класса}
end;
Function TVRoomD2.Square:real;
begin
Square:=inherited Square+2*height*(length+width);
end;
var pA:pTRoomD2; pB:pTVRoomD2; {объявляем указатели}
begin
{объект базового класса - указатель базового класса}
pA:=New(pTRoomD2,Init(3.5,5.1)); {конструируем объект}
writeln('Plotshad= ',pA^.Square:6:2); {выведет "Площадь= 17.85"}
Dispose(pA,Done); {уничтожаем объект}
{объект производного класса - указатель производного класса}
pB:=New(pTVRoomD2,Init(3.5,5.1,2.7)); {конструируем объект}
writeln('Plotshad= ',pB^.Square:6:2); {выведет "Площадь= 96.64"}
Dispose(pB,Done); {уничтожаем объект}
{проявление полиморфных свойств:
объект производного класса - указатель базового класса}
pA:=New(pTVRoomD2,Init(3.5,5.1,2.7)); {конструируем объект}
writeln('Plotshad= ',pA^.Square:6:2); {выведет "Площадь= 94.64"}
Dispose(pA,Done); {уничтожаем объект}
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.Value.RTTI
Description : FlexValue Helper for RTTI
Author : Kike Pérez
Version : 1.0
Created : 06/05/2019
Modified : 26/06/2020
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Value.RTTI;
{$i QuickLib.inc}
interface
uses
SysUtils,
Rtti,
Quick.Value;
type
IValueTValue = interface
['{B109F5F2-32E5-4C4B-B83C-BF00BB69B2D0}']
function GetValue : TValue;
procedure SetValue(const Value : TValue);
property Value : TValue read GetValue write SetValue;
end;
TValueTValue = class(TValueData,IValueTValue)
strict private
fData : TValue;
private
function GetValue : TValue;
procedure SetValue(const Value : TValue);
public
constructor Create(const Value : TValue);
property Value : TValue read GetValue write SetValue;
end;
TRTTIFlexValue = record helper for TFlexValue
private
function CastToTValue: TValue;
procedure SetAsTValue(const Value: TValue);
public
property AsTValue : TValue read CastToTValue write SetAsTValue;
procedure FromRecord<T : record>(aRecord : T);
procedure FromArray<T>(aArray: TArray<T>);
function AsType<T : class> : T;
function AsRecord<T : record> : T;
function AsArray<T> : TArray<T>;
function AsInterfaceEx<T : IInterface> : T; overload;
end;
implementation
{ TRTTIFlexValue }
function TRTTIFlexValue.AsArray<T>: TArray<T>;
begin
if DataType <> dtArray then raise Exception.Create('DataType not supported');
Result := (Self.Data as IValueTValue).Value.AsType<TArray<T>>;
end;
function TRTTIFlexValue.AsInterfaceEx<T>: T;
begin
Result := T(Self.Data);
end;
function TRTTIFlexValue.AsRecord<T>: T;
begin
if DataType <> dtRecord then raise Exception.Create('DataType not supported');
Result := (Self.Data as IValueTValue).Value.AsType<T>;
end;
function TRTTIFlexValue.AsType<T>: T;
begin
Result := T(AsObject);
end;
function TRTTIFlexValue.CastToTValue: TValue;
begin
try
case DataType of
dtNull : Result := TValueExtended;
dtBoolean : Result := AsBoolean;
dtString : Result := AsString;
{$IFDEF MSWINDOWS}
dtAnsiString : Result := string(AsAnsiString);
dtWideString : Result := AsWideString;
{$ENDIF}
dtInteger,
dtInt64 : Result := AsInt64;
{$IFNDEF FPC}
dtVariant : Result := TValue.FromVariant(AsVariant);
dtInterface : Result := TValue.FromVariant(AsInterface);
{$ENDIF}
dtObject : Result := AsObject;
dtArray : Result := (Self.Data as IValueTValue).Value;
else raise Exception.Create('DataType not supported');
end;
except
on E : Exception do raise Exception.CreateFmt('TFlexValue conversion to TValue error: %s',[e.message]);
end;
end;
procedure TRTTIFlexValue.FromArray<T>(aArray: TArray<T>);
var
value : TValue;
begin
TValue.Make(@aArray,TypeInfo(T),value);
Self.SetAsCustom(TValueTValue.Create(value),TValueDataType.dtArray);
end;
procedure TRTTIFlexValue.FromRecord<T>(aRecord : T);
var
value : TValue;
begin
TValue.Make(@aRecord,TypeInfo(T),value);
Self.SetAsCustom(TValueTValue.Create(value),TValueDataType.dtRecord);
end;
procedure TRTTIFlexValue.SetAsTValue(const Value: TValue);
begin
Clear;
case Value.Kind of
tkInteger,
tkInt64 : AsInt64 := Value.AsInt64;
tkFloat : AsExtended := Value.AsExtended;
tkChar,
{$IFNDEF FPC}
tkString,
tkUstring,
{$ELSE}
tkAstring,
{$ENDIF}
tkWideString,
tkWideChar : AsString := Value.AsString;
tkEnumeration,
tkSet : AsInteger := Value.AsInteger;
tkClass : AsObject := Value.AsObject;
tkInterface : AsInterface := Value.AsInterface;
{$IFNDEF FPC}
tkArray,
tkDynArray : Self.SetAsCustom(TValueTValue.Create(Value),TValueDataType.dtArray);
tkRecord : Self.SetAsCustom(TValueTValue.Create(Value),TValueDataType.dtRecord);
else AsVariant := Value.AsVariant;
{$ENDIF}
end;
end;
{ TValueTValue }
constructor TValueTValue.Create(const Value: TValue);
begin
fData := Value;
end;
function TValueTValue.GetValue: TValue;
begin
Result := fData;
end;
procedure TValueTValue.SetValue(const Value: TValue);
begin
fData := Value;
end;
end.
|
{ rxapputils unit
Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team
original conception from rx library for Delphi (c)
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 with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your 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 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 Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit rxapputils;
{$I rx.inc}
interface
uses
Classes, SysUtils, Controls, IniFiles;
const
{$IFNDEF LINUX}
AllMask = '*.*';
{$ELSE}
AllMask = '*';
{$ENDIF}
var
DefCompanyName: string = '';
RegUseAppTitle: Boolean = False;
function GetDefaultSection(Component: TComponent): string;
procedure GetDefaultIniData(Control: TControl; var IniFileName,
Section: string; UseRegistry: Boolean = false);
function GetDefaultIniName: string;
type
TOnGetDefaultIniName = function: string;
const
OnGetDefaultIniName: TOnGetDefaultIniName = nil;
//Save to IniFile or TRegIniFile string value
procedure IniWriteString(IniFile: TObject; const Section, Ident,
Value: string);
function IniReadString(IniFile: TObject; const Section, Ident,
Value: string):string;
//Save to IniFile or TRegIniFile integer value
procedure IniWriteInteger(IniFile: TObject; const Section, Ident:string;
const Value: integer);
function IniReadInteger(IniFile: TObject; const Section, Ident:string;
const Value: integer):integer;
function GetDefaultIniRegKey: string;
Function RxGetAppConfigDir(Global : Boolean) : String;
implementation
uses
{$IFDEF WINDOWS}
windirs,
{$ENDIF}
Registry, Forms, FileUtil, LazUTF8;
{$IFDEF WINDOWS}
function RxGetAppConfigDir(Global: Boolean): String;
begin
If Global then
Result:=GetWindowsSpecialDir(CSIDL_COMMON_APPDATA)
else
Result:=GetWindowsSpecialDir(CSIDL_LOCAL_APPDATA);
If (Result<>'') then
begin
if VendorName<>'' then
Result:=IncludeTrailingPathDelimiter(Result+ UTF8ToSys(VendorName));
Result:=IncludeTrailingPathDelimiter(Result+UTF8ToSys(ApplicationName));
end
else
Result:=ExcludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))); //IncludeTrailingPathDelimiter(DGetAppConfigDir(Global));
end;
{$ELSE}
function RxGetAppConfigDir(Global: Boolean): String;
begin
Result:=GetAppConfigDir(Global);
end;
{$ENDIF}
function GetDefaultSection(Component: TComponent): string;
var
F: TCustomForm;
Owner: TComponent;
begin
if Component <> nil then begin
if Component is TCustomForm then Result := Component.ClassName
else begin
Result := Component.Name;
if Component is TControl then begin
F := GetParentForm(TControl(Component));
if F <> nil then Result := F.ClassName + Result
else begin
if TControl(Component).Parent <> nil then
Result := TControl(Component).Parent.Name + Result;
end;
end
else begin
Owner := Component.Owner;
if Owner is TForm then
Result := Format('%s.%s', [Owner.ClassName, Result]);
end;
end;
end
else Result := '';
end;
function GetDefaultIniName: string;
var
S:string;
begin
if Assigned(OnGetDefaultIniName) then
Result:= OnGetDefaultIniName()
else
begin
Result := ExtractFileName(ChangeFileExt(Application.ExeName, '.ini'));
S:=RxGetAppConfigDir(false);
S:=SysToUTF8(S);
ForceDirectoriesUTF8(S);
Result:=S+Result;
end;
end;
procedure GetDefaultIniData(Control: TControl; var IniFileName,
Section: string; UseRegistry: Boolean );
var
I: Integer;
begin
IniFileName := EmptyStr;
{ with Control do
if Owner is TCustomForm then
for I := 0 to Owner.ComponentCount - 1 do
if (Owner.Components[I] is TFormPropertyStorage) then
begin
IniFileName := TFormPropertyStorage(Owner.Components[I]).IniFileName;
Break;
end;}
Section := GetDefaultSection(Control);
if IniFileName = EmptyStr then
if UseRegistry then IniFileName := GetDefaultIniRegKey
else
IniFileName := GetDefaultIniName;
end;
procedure IniWriteString(IniFile: TObject; const Section, Ident,
Value: string);
var
S: string;
begin
if IniFile is TRegIniFile then
TRegIniFile(IniFile).WriteString(Section, Ident, Value)
else
begin
S := Value;
if S <> '' then
begin
if ((S[1] = '"') and (S[Length(S)] = '"')) or
((S[1] = '''') and (S[Length(S)] = '''')) then
S := '"' + S + '"';
end;
if IniFile is TIniFile then
TIniFile(IniFile).WriteString(Section, Ident, S);
end;
end;
function IniReadString(IniFile: TObject; const Section, Ident, Value: string
): string;
var
S: string;
begin
if IniFile is TRegIniFile then
Result:=TRegIniFile(IniFile).ReadString(Section, Ident, Value)
else
begin
S := Value;
if S <> '' then begin
if ((S[1] = '"') and (S[Length(S)] = '"')) or
((S[1] = '''') and (S[Length(S)] = '''')) then
S := '"' + S + '"';
end;
if IniFile is TIniFile then
Result:=TIniFile(IniFile).ReadString(Section, Ident, S);
end;
end;
procedure IniWriteInteger(IniFile: TObject; const Section, Ident: string;
const Value: integer);
begin
if IniFile is TRegIniFile then
TRegIniFile(IniFile).WriteInteger(Section, Ident, Value)
else
begin
if IniFile is TIniFile then
TIniFile(IniFile).WriteInteger(Section, Ident, Value);
end;
end;
function IniReadInteger(IniFile: TObject; const Section, Ident: string;
const Value: integer): integer;
begin
if IniFile is TRegIniFile then
Result:=TRegIniFile(IniFile).ReadInteger(Section, Ident, Value)
else
begin
if IniFile is TIniFile then
Result:=TIniFile(IniFile).ReadInteger(Section, Ident, Value);
end;
end;
function GetDefaultIniRegKey: string;
begin
if RegUseAppTitle and (Application.Title <> '') then
Result := Application.Title
else Result := ExtractFileName(ChangeFileExt(Application.ExeName, ''));
if DefCompanyName <> '' then
Result := DefCompanyName + '\' + Result;
Result := 'Software\' + Result;
end;
end.
|
unit kwForwardDeclaration;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwForwardDeclaration.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TkwForwardDeclaration" MUID: (4F4BB70D0144)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwScriptingInterfaces
, tfwDictionaryPrim
, l3Variant
, l3Interfaces
;
type
TkwForwardDeclaration = class(TtfwWord)
private
f_RealWord: TtfwWord;
protected
procedure pm_SetRealWord(aValue: TtfwWord);
procedure DoDoIt(const aCtx: TtfwContext); override;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
function pm_GetWordProducer: TtfwWord; override;
procedure pm_SetWordProducer(aValue: TtfwWord); override;
function pm_GetInnerDictionary: TtfwDictionaryPrim; override;
function pm_GetResultTypeInfo(const aCtx: TtfwContext): TtfwWordInfo; override;
public
function IsForwardDeclaration: Boolean; override;
function GetKeywordFinder(const aCtx: TtfwContext): TtfwWord; override;
function DoCheckWord(const aName: Il3CString): TtfwKeyWord; override;
function GetKeywordByName(const aName: Il3CString): Tl3PrimString; override;
function GetParentFinder: TtfwWord; override;
function WordName: Il3CString; override;
function MakeRefForCompile(const aCtx: TtfwContext;
aSNI: TtfwSuppressNextImmediate): TtfwWord; override;
function GetRefForCompare: TtfwWord; override;
public
property RealWord: TtfwWord
read f_RealWord
write pm_SetRealWord;
end;//TkwForwardDeclaration
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, SysUtils
, tfwClassRef
, kwForwardDeclarationHolder
//#UC START# *4F4BB70D0144impl_uses*
//#UC END# *4F4BB70D0144impl_uses*
;
procedure TkwForwardDeclaration.pm_SetRealWord(aValue: TtfwWord);
//#UC START# *4F4BB75C021E_4F4BB70D0144set_var*
//#UC END# *4F4BB75C021E_4F4BB70D0144set_var*
begin
//#UC START# *4F4BB75C021E_4F4BB70D0144set_impl*
aValue.SetRefTo(f_RealWord);
if (f_RealWord <> nil) then
f_RealWord.Key := Self.Key;
//#UC END# *4F4BB75C021E_4F4BB70D0144set_impl*
end;//TkwForwardDeclaration.pm_SetRealWord
procedure TkwForwardDeclaration.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_4F4BB70D0144_var*
//#UC END# *4DAEEDE10285_4F4BB70D0144_var*
begin
//#UC START# *4DAEEDE10285_4F4BB70D0144_impl*
RunnerAssert(f_RealWord <> nil,
'Предварительное определение слова не было завершено',
aCtx);
f_RealWord.DoIt(aCtx);
//#UC END# *4DAEEDE10285_4F4BB70D0144_impl*
end;//TkwForwardDeclaration.DoDoIt
procedure TkwForwardDeclaration.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4F4BB70D0144_var*
//#UC END# *479731C50290_4F4BB70D0144_var*
begin
//#UC START# *479731C50290_4F4BB70D0144_impl*
FreeAndNil(f_RealWord);
inherited;
//#UC END# *479731C50290_4F4BB70D0144_impl*
end;//TkwForwardDeclaration.Cleanup
function TkwForwardDeclaration.pm_GetWordProducer: TtfwWord;
//#UC START# *4F43C9A10139_4F4BB70D0144get_var*
//#UC END# *4F43C9A10139_4F4BB70D0144get_var*
begin
//#UC START# *4F43C9A10139_4F4BB70D0144get_impl*
if (f_RealWord = nil) then
Result := nil
else
Result := f_RealWord.WordProducer;
//#UC END# *4F43C9A10139_4F4BB70D0144get_impl*
end;//TkwForwardDeclaration.pm_GetWordProducer
procedure TkwForwardDeclaration.pm_SetWordProducer(aValue: TtfwWord);
//#UC START# *4F43C9A10139_4F4BB70D0144set_var*
//#UC END# *4F43C9A10139_4F4BB70D0144set_var*
begin
//#UC START# *4F43C9A10139_4F4BB70D0144set_impl*
f_RealWord.WordProducer := aValue;
//#UC END# *4F43C9A10139_4F4BB70D0144set_impl*
end;//TkwForwardDeclaration.pm_SetWordProducer
function TkwForwardDeclaration.IsForwardDeclaration: Boolean;
//#UC START# *4F4BB6CD0359_4F4BB70D0144_var*
//#UC END# *4F4BB6CD0359_4F4BB70D0144_var*
begin
//#UC START# *4F4BB6CD0359_4F4BB70D0144_impl*
Result := true;
//#UC END# *4F4BB6CD0359_4F4BB70D0144_impl*
end;//TkwForwardDeclaration.IsForwardDeclaration
function TkwForwardDeclaration.pm_GetInnerDictionary: TtfwDictionaryPrim;
//#UC START# *52B43311021D_4F4BB70D0144get_var*
//#UC END# *52B43311021D_4F4BB70D0144get_var*
begin
//#UC START# *52B43311021D_4F4BB70D0144get_impl*
if (f_RealWord = nil) then
Result := nil
else
Result := f_RealWord.InnerDictionary;
//#UC END# *52B43311021D_4F4BB70D0144get_impl*
end;//TkwForwardDeclaration.pm_GetInnerDictionary
function TkwForwardDeclaration.pm_GetResultTypeInfo(const aCtx: TtfwContext): TtfwWordInfo;
//#UC START# *52CFC11603C8_4F4BB70D0144get_var*
//#UC END# *52CFC11603C8_4F4BB70D0144get_var*
begin
//#UC START# *52CFC11603C8_4F4BB70D0144get_impl*
if (f_RealWord = nil) then
Result := inherited pm_GetResultTypeInfo(aCtx)
else
Result := f_RealWord.ResultTypeInfo[aCtx];
//#UC END# *52CFC11603C8_4F4BB70D0144get_impl*
end;//TkwForwardDeclaration.pm_GetResultTypeInfo
function TkwForwardDeclaration.GetKeywordFinder(const aCtx: TtfwContext): TtfwWord;
//#UC START# *52D5637A031E_4F4BB70D0144_var*
//#UC END# *52D5637A031E_4F4BB70D0144_var*
begin
//#UC START# *52D5637A031E_4F4BB70D0144_impl*
Result := f_RealWord.GetKeywordFinder(aCtx);
//#UC END# *52D5637A031E_4F4BB70D0144_impl*
end;//TkwForwardDeclaration.GetKeywordFinder
function TkwForwardDeclaration.DoCheckWord(const aName: Il3CString): TtfwKeyWord;
//#UC START# *55A7D34102A0_4F4BB70D0144_var*
//#UC END# *55A7D34102A0_4F4BB70D0144_var*
begin
//#UC START# *55A7D34102A0_4F4BB70D0144_impl*
Result := f_RealWord.DoCheckWord(aName);
//#UC END# *55A7D34102A0_4F4BB70D0144_impl*
end;//TkwForwardDeclaration.DoCheckWord
function TkwForwardDeclaration.GetKeywordByName(const aName: Il3CString): Tl3PrimString;
//#UC START# *55ACE5210310_4F4BB70D0144_var*
//#UC END# *55ACE5210310_4F4BB70D0144_var*
begin
//#UC START# *55ACE5210310_4F4BB70D0144_impl*
Result := f_RealWord.GetKeywordByName(aName);
//#UC END# *55ACE5210310_4F4BB70D0144_impl*
end;//TkwForwardDeclaration.GetKeywordByName
function TkwForwardDeclaration.GetParentFinder: TtfwWord;
//#UC START# *55ACF0F5025D_4F4BB70D0144_var*
//#UC END# *55ACF0F5025D_4F4BB70D0144_var*
begin
//#UC START# *55ACF0F5025D_4F4BB70D0144_impl*
Result := f_RealWord.GetParentFinder;
//#UC END# *55ACF0F5025D_4F4BB70D0144_impl*
end;//TkwForwardDeclaration.GetParentFinder
function TkwForwardDeclaration.WordName: Il3CString;
//#UC START# *55AFD7DA0258_4F4BB70D0144_var*
//#UC END# *55AFD7DA0258_4F4BB70D0144_var*
begin
//#UC START# *55AFD7DA0258_4F4BB70D0144_impl*
if (f_RealWord = nil) then
Result := inherited WordName
else
Result := f_RealWord.WordName;
//#UC END# *55AFD7DA0258_4F4BB70D0144_impl*
end;//TkwForwardDeclaration.WordName
function TkwForwardDeclaration.MakeRefForCompile(const aCtx: TtfwContext;
aSNI: TtfwSuppressNextImmediate): TtfwWord;
//#UC START# *55CB5B8C004E_4F4BB70D0144_var*
//#UC END# *55CB5B8C004E_4F4BB70D0144_var*
begin
//#UC START# *55CB5B8C004E_4F4BB70D0144_impl*
Result := TkwForwardDeclarationHolder.Create(Self);
//#UC END# *55CB5B8C004E_4F4BB70D0144_impl*
end;//TkwForwardDeclaration.MakeRefForCompile
function TkwForwardDeclaration.GetRefForCompare: TtfwWord;
//#UC START# *57500A22001C_4F4BB70D0144_var*
//#UC END# *57500A22001C_4F4BB70D0144_var*
begin
//#UC START# *57500A22001C_4F4BB70D0144_impl*
Result := f_RealWord;
if (Result <> nil) then
Result := Result.GetRefForCompare;
//#UC END# *57500A22001C_4F4BB70D0144_impl*
end;//TkwForwardDeclaration.GetRefForCompare
initialization
TkwForwardDeclaration.RegisterClass;
{* Регистрация TkwForwardDeclaration }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
(* MPP_SS: HDO, 2004-02-06
------
Syntax analyzer and semantic evaluator for the MiniPascal parser.
Semantic actions to be included in MPI_SS and MPC_SS.
===================================================================*)
UNIT MPC_SS;
INTERFACE
VAR
success: BOOLEAN; (*true if no syntax errros*)
PROCEDURE S; (*parses whole MiniPascal program*)
IMPLEMENTATION
USES
MP_Lex, SymTab, CodeDef, CodeGen;
FUNCTION SyIsNot(expectedSy: Symbol): BOOLEAN;
BEGIN
success:= success AND (sy = expectedSy);
SyIsNot := NOT success;
END; (*SyIsNot*)
PROCEDURE SemErr(msg: STRING);
BEGIN
WriteLn('*** Semantic error ***');
WriteLn(' ', msg);
success := FALSE;
end;
PROCEDURE MP; FORWARD;
PROCEDURE VarDecl; FORWARD;
PROCEDURE StatSeq; FORWARD;
PROCEDURE Stat; FORWARD;
PROCEDURE Expr; FORWARD;
PROCEDURE Term; FORWARD;
PROCEDURE Fact; FORWARD;
PROCEDURE S;
(*-----------------------------------------------------------------*)
BEGIN
WriteLn('parsing started ...');
success := TRUE;
MP;
IF NOT success OR SyIsNot(eofSy) THEN
WriteLn('*** Error in line ', syLnr:0, ', column ', syCnr:0)
ELSE
WriteLn('... parsing ended successfully ');
END; (*S*)
PROCEDURE MP;
BEGIN
IF SyIsNot(programSy) THEN Exit;
(* sem *)
initSymbolTable;
InitCodeGenerator;
(* endsem *)
NewSy;
IF SyIsNot(identSy) THEN Exit;
NewSy;
IF SyIsNot(semicolonSy) THEN Exit;
NewSy;
IF sy = varSy THEN BEGIN
VarDecl; IF NOT success THEN Exit;
END; (*IF*)
IF SyIsNot(beginSy) THEN Exit;
NewSy;
StatSeq; IF NOT success THEN Exit;
(* sem *)
Emit1(EndOpc);
(* endsem *)
IF SyIsNot(endSy) THEN Exit;
NewSy;
IF SyIsNot(periodSy) THEN Exit;
NewSy;
END; (*MP*)
PROCEDURE VarDecl;
var ok : BOOLEAN;
BEGIN
IF SyIsNot(varSy) THEN Exit;
NewSy;
IF SyIsNot(identSy) THEN Exit;
(* sem *)
DeclVar(identStr, ok);
NewSy;
WHILE sy = commaSy DO BEGIN
NewSy;
IF SyIsNot(identSy) THEN Exit;
(* sem *)
DeclVar(identStr, ok);
IF NOT ok THEN
SemErr('mult. decl.');
(* endsem *)
NewSy;
END; (*WHILE*)
IF SyIsNot(colonSy) THEN Exit;
NewSy;
IF SyIsNot(integerSy) THEN Exit;
NewSy;
IF SyIsNot(semicolonSy) THEN Exit;
NewSy;
END; (*VarDecl*)
PROCEDURE StatSeq;
BEGIN
Stat; IF NOT success THEN Exit;
WHILE sy = semicolonSy DO BEGIN
NewSy;
Stat; IF NOT success THEN Exit;
END; (*WHILE*)
END; (*StatSeq*)
PROCEDURE Stat;
var destId : STRING;
addr, addr1, addr2 : integer;
BEGIN
CASE sy OF
identSy: BEGIN
(* sem *)
destId := identStr;
IF NOT IsDecl(destId) then
SemErr('var. not decl.')
ELSE
Emit2(LoadAddrOpc, AddrOf(destId));
(* endsem *)
NewSy;
IF SyIsNot(assignSy) THEN Exit;
NewSy;
Expr; IF NOT success THEN Exit;
(* sem *)
IF IsDecl(destId) THEN
Emit1(StoreOpc);
(* endsem *)
END;
readSy: BEGIN
NewSy;
IF SyIsNot(leftParSy) THEN Exit;
NewSy;
IF SyIsNot(identSy) THEN Exit;
(* sem *)
IF NOT IsDecl(identStr) THEN
SemErr('var not decl.')
ELSE BEGIN
Emit2(ReadOpc,AddrOf(identStr));
END;
(* endsem *)
NewSy;
IF SyIsNot(rightParSy) THEN Exit;
NewSy;
END;
writeSy: BEGIN
NewSy;
IF SyIsNot(leftParSy) THEN Exit;
NewSy;
Expr; IF NOT success THEN Exit;
(* sem *)
Emit1(WriteOpc);
(* endsem *)
IF SyIsNot(rightParSy) THEN Exit;
NewSy;
END;
beginSy: BEGIN
newSy;
StatSeq;
IF SyIsNot(endSy) THEN Exit;
NewSy;
END;
ifSy: BEGIN
NewSy;
IF SyIsNot(identSy) THEN Exit;
(* SEM *)
IF NOT IsDecl(identStr) THEN BEGIN
SemErr('var not decl.');
END;
Emit2(LoadValOpc, AddrOf(identStr));
Emit2(JmpZOpc, 0); (*0 as dummy address*)
addr := CurAddr - 2;
(* ENDSEM *)
NewSy;
IF SyIsNot(thenSy) THEN Exit;
Stat; IF NOT success THEN Exit;
IF sy = elseSy THEN BEGIN
newSy;
(* SEM *)
Emit2(JmpOpc, 0);
FixUp(addr, CurAddr);
addr := CurAddr - 2;
(* ENDSEM *)
Stat; IF NOT success THEN Exit;
END;
(* SEM *)
FixUp(addr, CurAddr);
(* ENDSEM *)
END;
whileSy: BEGIN
NewSy;
IF SyIsNot(identSy) THEN Exit;
(* SEM *)
IF NOT IsDecl(identStr) THEN BEGIN
SemErr('var not decl.');
END;
addr1 := CurAddr;
Emit2(LoadValOpc, AddrOf(identStr));
Emit2(JmpZOpc, 0); (*0 as dummy address*)
addr2 := CurAddr - 2;
(* ENDSEM *)
NewSy;
IF SyIsNot(doSy) THEN Exit;
NewSy;
Stat;
(* SEM *)
Emit2(JmpOpc, addr1);
FixUp(addr2, CurAddr);
(* ENDSEM *)
END;
ELSE
; (*EPS*)
END; (*CASE*)
END; (*Stat*)
PROCEDURE Expr;
BEGIN
Term; IF NOT success THEN Exit;
WHILE (sy = plusSy) OR (sy = minusSy) DO BEGIN
CASE sy OF
plusSy: BEGIN
NewSy;
Term; IF NOT success THEN Exit;
(* sem *)
Emit1(AddOpc);
(* endsem *)
END;
minusSy: BEGIN
NewSy;
Term; IF NOT success THEN Exit;
(* sem *)
Emit1(SubOpc);
(* endsem *)
END;
END; (*CASE*)
END; (*WHILE*)
END; (*Expr*)
PROCEDURE Term;
BEGIN
Fact; IF NOT success THEN Exit;
WHILE (sy = timesSy) OR (sy = divSy) DO BEGIN
CASE sy OF
timesSy: BEGIN
NewSy;
Fact; IF NOT success THEN Exit;
(* sem *)
Emit1(MulOpc);
(* endsem*)
END;
divSy: BEGIN
NewSy;
Fact; IF NOT success THEN Exit;
(* sem *)
Emit1(DivOpc);
(* endsem *)
END;
END; (*CASE*)
END; (*WHILE*)
END; (*Term*)
PROCEDURE Fact;
BEGIN
CASE sy OF
identSy: BEGIN
(* sem *)
IF NOT IsDecl(identStr) THEN
SemErr('var. not decl.')
ELSE
Emit2(LoadValOpc,AddrOf(identStr));
(* endsem *)
NewSy;
END;
numberSy: BEGIN
(* sem*)
Emit2(LoadConstOpc,numberVal);
(* endsem *)
NewSy;
END;
leftParSy: BEGIN
NewSy;
Expr; IF NOT success THEN Exit;
IF SyIsNot(rightParSy) THEN Exit;
NewSy;
END;
ELSE
success := FALSE;
END; (*CASE*)
END; (*Fact*)
END. (*MPP_SS*)
|
unit vg_platform_ios;
{$mode objfpc}{$H+}
{$modeswitch objectivec1}
interface
uses
{$IFDEF DARWIN}
iPhoneAll,
CFBase, CFString,
CGContext, CGImage, CGBitmapContext, CGGeometry, CGColorSpace,
{$ENDIF}
Classes, SysUtils, Variants, TypInfo, vg_scene, vg_forms;
type
{ TvgPlatformCocoa }
TvgPlatformCocoa = class(TvgPlatform)
private
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ App }
procedure Run; override;
procedure Terminate; override;
function HandleMessage: boolean; override;
procedure WaitMessage; override;
{ Timer }
function CreateTimer(Interval: integer; TimerFunc: TvgTimerProc): THandle; override;
function DestroyTimer(Timer: THandle): boolean; override;
function GetTick: single; override;
{ Window }
function CreateWindow(AForm: TvgCustomForm): THandle; override;
procedure DestroyWindow(AForm: TvgCustomForm); override;
procedure ReleaseWindow(AForm: TvgCustomForm); override;
procedure ShowWindow(AForm: TvgCustomForm); override;
procedure HideWindow(AForm: TvgCustomForm); override;
function ShowWindowModal(AForm: TvgCustomForm): TModalResult; override;
procedure InvalidateWindowRect(AForm: TvgCustomForm; R: TvgRect); override;
procedure SetWindowRect(AForm: TvgCustomForm; ARect: TvgRect); override;
function GetWindowRect(AForm: TvgCustomForm): TvgRect; override;
function GetClientSize(AForm: TvgCustomForm): TvgPoint; override;
procedure SetWindowCaption(AForm: TvgCustomForm; ACaption: WideString); override;
procedure SetCapture(AForm: TvgCustomForm); override;
procedure ReleaseCapture(AForm: TvgCustomForm); override;
function ClientToScreen(AForm: TvgCustomForm; const Point: TvgPoint): TvgPoint; override;
function ScreenToClient(AForm: TvgCustomForm; const Point: TvgPoint): TvgPoint; override;
{ Drag and Drop }
procedure BeginDragDrop(AForm: TvgCustomForm; const Data: TvgDragObject; ABitmap: TvgBitmap); override;
{ Clipboard }
procedure SetClipboard(Value: Variant); override;
function GetClipboard: Variant; override;
{ Mouse }
function GetMousePos: TvgPoint; override;
{ International }
function GetCurrentLangID: string; override;
{ Dialogs }
function DialogOpenFiles(var FileName: WideString; AInitDir: WideString; AllowMulti: boolean): boolean; override;
{ Keyboard }
function ShowVirtualKeyboard(AControl: TvgObject): boolean; override;
function HideVirtualKeyboard: boolean; override;
end;
implementation
type
TvgHackForm = class(TvgForm);
ApplicationDelegate = objcclass(NSObject)
procedure applicationDidFinishLaunching(notification: UIApplication); message 'applicationDidFinishLaunching:';
procedure applicationWillTerminate(notification : UIApplication); message 'applicationWillTerminate:';
procedure DeviceOrientationDidChange(n: NSNotification); message 'DeviceOrientationDidChange:';
end;
var
pool: NSAutoreleasePool;
procedure ApplicationDelegate.applicationDidFinishLaunching(notification: UIApplication);
begin
Application.RealCreateForms;
NSNotificationCenter.defaultCenter.addObserver_selector_name_object(Self, objcselector(DeviceOrientationDidChange),
UIDeviceOrientationDidChangeNotification, nil);
UIDevice.currentDevice.beginGeneratingDeviceOrientationNotifications;
end;
procedure ApplicationDelegate.applicationWillTerminate(notification : UIApplication);
begin
end;
procedure ApplicationDelegate.DeviceOrientationDidChange(n: NSNotification);
var
Angle: single;
begin
case UIDevice.currentDevice.orientation of
UIDeviceOrientationUnknown: Angle := 0;
UIDeviceOrientationPortrait: Angle := 0;
UIDeviceOrientationPortraitUpsideDown: Angle := 180;
UIDeviceOrientationLandscapeLeft: Angle := 90;
UIDeviceOrientationLandscapeRight: Angle := -90;
UIDeviceOrientationFaceUp: Angle := 0;
UIDeviceOrientationFaceDown: Angle := 0;
end;
exit;
if Application.MainForm = nil then Exit;
if not (Application.MainForm is TvgForm) then Exit;
if TvgVisualObject(TvgForm(Application.MainForm).Root).Rotateangle <> Angle then
begin
TvgVisualObject(TvgForm(Application.MainForm).Root).Rotateangle := Angle;
TvgForm(Application.MainForm).RealignRoot;
end;
end;
{ TvgPlatformCocoa }
constructor TvgPlatformCocoa.Create(AOwner: TComponent);
begin
inherited;
pool := NSAutoreleasePool.new;
Application := TvgApplication.Create(nil);
end;
destructor TvgPlatformCocoa.Destroy;
begin
Application.Free;
Application := nil;
pool.release;
inherited;
end;
{ App =========================================================================}
procedure TvgPlatformCocoa.Run;
begin
ExitCode := UIApplicationMain(argc, argv, nil, NSSTR('ApplicationDelegate'));
end;
procedure TvgPlatformCocoa.Terminate;
begin
// NSApp.terminate(nil);
end;
function TvgPlatformCocoa.HandleMessage: boolean;
begin
NSRunLoop.currentRunLoop.runUntilDate(NSDate.dateWithTimeIntervalSinceNow(0.1));
Result := false;
end;
procedure TvgPlatformCocoa.WaitMessage;
begin
NSRunLoop.currentRunLoop.runMode_beforeDate(NSDefaultRunLoopMode, NSDate.date);
end;
{ Timer =======================================================================}
type
TCocoaTimerObject = objcclass(NSObject)
func : TvgTimerProc;
procedure timerEvent; message 'timerEvent';
class function initWithFunc(afunc: TvgTimerProc): TCocoaTimerObject; message 'initWithFunc:';
end;
procedure TCocoaTimerObject.timerEvent;
begin
if Assigned(@func) then func;
end;
class function TCocoaTimerObject.initWithFunc(afunc: TvgTimerProc): TCocoaTimerObject;
begin
Result:=alloc;
Result.func:=afunc;
end;
function TvgPlatformCocoa.CreateTimer(Interval: integer;
TimerFunc: TvgTimerProc): THandle;
var
timer : NSTimer;
user : TCocoaTimerObject;
begin
user := TCocoaTimerObject.initWithFunc(TimerFunc);
timer := NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats(
Interval/1000, user, objcselector(user.timerEvent), user, True);
NSRunLoop.currentRunLoop.addTimer_forMode(timer, NSDefaultRunLoopMode);
{user is retained (twice, because it's target), by the timer and }
{released (twice) on timer invalidation}
user.release;
Result := cardinal(timer);
end;
function TvgPlatformCocoa.DestroyTimer(Timer: THandle): boolean;
var
obj : NSObject;
begin
obj := NSObject(Timer);
try
Result := Assigned(obj) and obj.isKindOfClass_(NSTimer);
except
Result := false;
end;
if not Result then Exit;
NSTimer(obj).invalidate;
end;
function TvgPlatformCocoa.GetTick: single;
var
H, M, S, MS: word;
begin
DecodeTime(time, H, M, S, MS);
Result := ((((H * 60 * 60) + (M * 60) + S) * 1000) + MS) / 1000;
end;
{ Window ======================================================================}
type
TvgNSWindow = objcclass;
{ TvgNSView }
TvgNSView = objcclass(UIView)
public
NSWnd: TvgNSWindow;
Rotating: boolean;
procedure drawRect(r: CGRect); override;
procedure touchesBegan_withEvent(touches: NSSetPointer; event: UIEvent); override;
procedure touchesMoved_withEvent(touches: NSSetPointer; event: UIEvent); override;
procedure touchesEnded_withEvent(touches: NSSetPointer; event: UIEvent); override;
end;
{ TvgNSViewController }
TvgNSViewController = objcclass(UIViewController)
public
Wnd: TvgNSWindow;
procedure loadView; override;
function shouldAutorotateToInterfaceOrientation(AinterfaceOrientation: UIInterfaceOrientation): Boolean; override;
procedure willRotateToInterfaceOrientation_duration(toInterfaceOrientation: UIInterfaceOrientation; duration: NSTimeInterval); override;
procedure didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation); override;
procedure viewWillAppear(animated: Boolean); override;
procedure viewWillDisappear(animated: Boolean); override;
end;
{ TvgNSWindow }
TvgNSWindow = objcclass(UIWindow)
protected
public
Orientation: UIInterfaceOrientation;
Wnd: TvgCustomForm;
View: TvgNSView;
Controller: TvgNSViewController;
Text: UITextField;
function textField_shouldChangeCharactersInRange_replacementString(textField: UITextField; range: NSRange; string_: NSStringPointer): Boolean; message 'textField:shouldChangeCharactersInRange:replacementString:';
function textFieldShouldReturn(textField: UITextField): Boolean; message 'textFieldShouldReturn:';
function textFieldShouldClear(textField: UITextField): Boolean; message 'textFieldShouldClear:';
end;
{ TvgNSView }
function GetTouchCoord(touches: NSSetPointer; Window: UIView; var x, y: single): Boolean;
var
st : NSSet;
touch : UITouch;
p : CGPoint;
begin
Result := Assigned(touches);
if not Result then Exit;
st := NSSet(touches);
Result := st.count = 1;
if not Result then Exit;
touch := UITouch(st.anyObject);
p := touch.locationInView(Window);
x := p.x;
y := p.y;
end;
procedure TvgNSView.touchesBegan_withEvent(touches: NSSetPointer; event: UIEvent);
var
x, y : single;
begin
if not GetTouchCoord(touches, self, x, y) then Exit;
NSWnd.Wnd.MouseDown(mbLeft, [], x, y);
inherited touchesBegan_withEvent(touches, event);
end;
procedure TvgNSView.touchesMoved_withEvent(touches: NSSetPointer; event: UIEvent);
var
x, y : single;
begin
if not GetTouchCoord(touches, self, x, y) then Exit;
NSWnd.Wnd.MouseMove([ssLeft], x, y);
inherited touchesMoved_withEvent(touches, event);
end;
procedure TvgNSView.touchesEnded_withEvent(touches: NSSetPointer; event: UIEvent);
var
x, y : single;
begin
if not GetTouchCoord(touches, self, x, y) then Exit;
NSWnd.Wnd.MouseUp(mbLeft, [], x, y);
inherited touchesEnded_withEvent(touches, event);
end;
procedure TvgNSView.drawRect(r: CGRect);
begin
if NSWnd <> nil then
begin
NSWnd.Wnd.Canvas.Handle := THandle(UIGraphicsGetCurrentContext);
NSWnd.Wnd.PaintRects([vgRect(r.origin.x, r.origin.y, r.origin.x + r.size.width, r.origin.y + r.size.height)]);
{ NSWnd.Wnd.Canvas.Fill.Style := vgBrushSolid;
NSWnd.Wnd.Canvas.Fill.SolidColor := $FF000000 or random($FFFFFF);
NSWnd.Wnd.Canvas.FillRect(vgRect(0, 0, NSWnd.Wnd.Canvas.Width, NSWnd.Wnd.Canvas.Height), 15, 15, AllCorners, 1);}
NSWnd.Wnd.Canvas.Handle := 0;
end;
end;
{ TvgNSViewController }
procedure TvgNSViewController.loadView;
begin
Wnd.Orientation := InterfaceOrientation;
Wnd.View := TvgNSView.alloc.initwithFrame(CGRectMake(0, 20, Wnd.bounds.size.Width, Wnd.bounds.size.Height - 20)) ;
Wnd.View.NSWnd := Wnd;
setView(Wnd.View);
Wnd.Text := UITextField.alloc.initWithFrame(CGRectMake(0, 0, 2000, 0));
Wnd.Text.setDelegate(Wnd);
Wnd.View.addSubview(Wnd.Text);
end;
function TvgNSViewController.shouldAutorotateToInterfaceOrientation(
AinterfaceOrientation: UIInterfaceOrientation): Boolean;
begin
Result := true;
end;
procedure TvgNSViewController.willRotateToInterfaceOrientation_duration(
toInterfaceOrientation: UIInterfaceOrientation; duration: NSTimeInterval);
begin
inherited willRotateToInterfaceOrientation_duration(toInterfaceOrientation, duration);
Wnd.View.Rotating := true;
Wnd.Wnd.SetBounds(0, 0, round(view.frame.size.Width), round(view.frame.size.Height))
end;
procedure TvgNSViewController.didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation);
begin
inherited didRotateFromInterfaceOrientation(fromInterfaceOrientation);
Wnd.Orientation := InterfaceOrientation;
wnd.View.Rotating := false;
Wnd.Wnd.SetBounds(0, 0, round(view.frame.size.Width), round(view.frame.size.Height))
end;
procedure TvgNSViewController.viewWillAppear(animated: Boolean);
begin
inherited viewWillAppear(animated);
end;
procedure TvgNSViewController.viewWillDisappear(animated: Boolean);
begin
inherited viewWillDisappear(animated);
end;
{ %vgNSWindow }
function TvgNSWindow.textField_shouldChangeCharactersInRange_replacementString(
textField: UITextField; range: NSRange; string_: NSStringPointer): Boolean;
var
C: WideString;
Ch: Widechar;
K: Word;
begin
C := UTF8Decode(NSString(string_).UTF8String);
if Length(C) > 0 then
begin
K := 0;
Ch := C[1];
Wnd.KeyDown(K, Ch, []);
end
else
begin
K := 8;
Ch := #0;
Wnd.KeyDown(K, Ch, []);
end;
Result := true;
end;
function TvgNSWindow.textFieldShouldReturn(textField: UITextField): Boolean;
var
Ch: Widechar;
K: Word;
begin
K := VK_RETURN;
Ch := #0;
Wnd.KeyDown(K, Ch, []);
Result := true;
end;
function TvgNSWindow.textFieldShouldClear(textField: UITextField): Boolean;
begin
Result := true;
end;
function TvgPlatformCocoa.CreateWindow(AForm: TvgCustomForm): THandle;
begin
Result := THandle(TvgNSWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds));
AForm.Handle := Result;
TvgNSWindow(Result).Wnd := AForm;
TvgNSWindow(Result).Controller := TvgNSViewController.alloc.initWithNibName_bundle(nil, nil);
TvgNSWindow(Result).Controller.Wnd := TvgNSWindow(Result);
TvgNSWindow(Result).setAutoresizesSubviews(true);
TvgNSWindow(Result).AddSubView(TvgNSWindow(Result).Controller.View);
AForm.SetBounds(0, 0, round(TvgNSWindow(Result).View.bounds.size.Width), round(TvgNSWindow(Result).View.bounds.size.Height));
end;
procedure TvgPlatformCocoa.DestroyWindow(AForm: TvgCustomForm);
begin
TvgNSWindow(AForm.Handle).View.NSWnd := nil;
TvgNSWindow(AForm.Handle).View := nil;
TvgNSWindow(AForm.Handle).Wnd := nil;
TvgNSWindow(AForm.Handle).release;
AForm.Handle := 0;
end;
procedure TvgPlatformCocoa.ReleaseWindow(AForm: TvgCustomForm);
begin
TvgNSWindow(AForm.Handle).View.NSWnd := nil;
TvgNSWindow(AForm.Handle).View := nil;
TvgNSWindow(AForm.Handle).Wnd := nil;
AForm.Handle := 0;
end;
procedure TvgPlatformCocoa.SetWindowRect(AForm: TvgCustomForm; ARect: TvgRect);
begin
if AForm.Handle <> 0 then
begin
AForm.SetBounds(0, 0, round(TvgNSWindow(AForm.Handle).bounds.size.Width), round(TvgNSWindow(AForm.Handle).bounds.size.Height));
end;
end;
procedure TvgPlatformCocoa.InvalidateWindowRect(AForm: TvgCustomForm; R: TvgRect);
begin
TvgNSWindow(AForm.Handle).View.setNeedsDisplayInRect(CGRectMake(R.left, R.top, R.right - R.left, R.bottom - R.top));
end;
function TvgPlatformCocoa.GetWindowRect(AForm: TvgCustomForm): TvgRect;
begin
end;
procedure TvgPlatformCocoa.SetWindowCaption(AForm: TvgCustomForm; ACaption: WideString);
begin
end;
procedure TvgPlatformCocoa.ReleaseCapture(AForm: TvgCustomForm);
begin
end;
procedure TvgPlatformCocoa.SetCapture(AForm: TvgCustomForm);
begin
end;
function TvgPlatformCocoa.GetClientSize(AForm: TvgCustomForm): TvgPoint;
begin
if (TvgNSWindow(AForm.Handle).Orientation = UIInterfaceOrientationPortrait) or
(TvgNSWindow(AForm.Handle).Orientation = UIInterfaceOrientationPortraitUpsideDown) then
Result := TvgPoint(TvgNSWindow(AForm.Handle).View.frame.size)
else
with TvgNSWindow(AForm.Handle).View.frame.size do
Result := vgPoint(Height, Width);
end;
procedure TvgPlatformCocoa.HideWindow(AForm: TvgCustomForm);
begin
end;
procedure TvgPlatformCocoa.ShowWindow(AForm: TvgCustomForm);
begin
TvgNSWindow(AForm.Handle).makeKeyAndVisible;
end;
function TvgPlatformCocoa.ShowWindowModal(AForm: TvgCustomForm): TModalResult;
begin
Result := mrOk;
end;
function TvgPlatformCocoa.ClientToScreen(AForm: TvgCustomForm; const Point: TvgPoint): TvgPoint;
begin
Result := Point;
end;
function TvgPlatformCocoa.ScreenToClient(AForm: TvgCustomForm; const Point: TvgPoint): TvgPoint;
begin
Result := Point;
end;
{ Drag and Drop ===============================================================}
procedure TvgPlatformCocoa.BeginDragDrop(AForm: TvgCustomForm;
const Data: TvgDragObject; ABitmap: TvgBitmap);
begin
end;
{ Clipboard ===============================================================}
procedure TvgPlatformCocoa.SetClipboard(Value: Variant);
begin
end;
function TvgPlatformCocoa.GetClipboard: Variant;
begin
end;
{ Mouse ===============================================================}
function TvgPlatformCocoa.GetMousePos: TvgPoint;
begin
Result := vgPoint(0, 0);
end;
{ International ===============================================================}
function TvgPlatformCocoa.GetCurrentLangID: string;
begin
Result := 'en'
end;
{ Dialogs ===============================================================}
function TvgPlatformCocoa.DialogOpenFiles(var FileName: WideString;
AInitDir: WideString; AllowMulti: boolean): boolean;
begin
Result := false;
end;
{ Keyboard }
function TvgPlatformCocoa.ShowVirtualKeyboard(AControl: TvgObject): boolean;
var
W: WideString;
S: NSString;
begin
W := GetWideStrProp(AControl, 'Text');
S := NSString.alloc.initWithUTF8String(PChar(UTF8Encode(W)));
TvgNSWindow(Application.MainForm.Handle).Text.setText(S);
TvgNSWindow(Application.MainForm.Handle).Text.becomeFirstResponder;
S.release;
Result := true;
end;
function TvgPlatformCocoa.HideVirtualKeyboard: boolean;
begin
TvgNSWindow(Application.MainForm.Handle).Text.resignFirstResponder;
Result := true;
end;
initialization
DefaultPlatformClass := TvgPlatformCocoa;
GlobalDisableFocusEffect := true;
end.
|
unit RouteParametersUnit;
interface
uses
REST.Json.Types,
JSONNullableAttributeUnit,
EnumsUnit, NullableBasicTypesUnit;
type
/// <summary>
/// Route Parameters
/// </summary>
/// <remarks>
/// https://github.com/route4me/json-schemas/blob/master/RouteParameters.dtd
/// </remarks>
TRouteParameters = class
private
[JSONName('is_upload')]
[Nullable]
FIsUpload: NullableBoolean;
[JSONName('rt')]
[Nullable]
FRT: NullableBoolean;
[JSONName('disable_optimization')]
[Nullable]
FDisableOptimization: NullableBoolean;
[JSONName('route_name')]
[Nullable]
FRouteName: NullableString;
[JSONName('algorithm_type')]
[Nullable]
FAlgorithmType: NullableInteger;
[JSONName('store_route')]
[Nullable]
FStoreRoute: NullableBoolean;
[JSONName('route_date')]
[Nullable]
FRouteDate: NullableInteger;
[JSONName('route_time')]
[Nullable]
FRouteTime: NullableInteger;
[JSONName('optimize')]
[Nullable]
FOptimize: NullableString;
[JSONName('distance_unit')]
[Nullable]
FDistanceUnit: NullableString;
[JSONName('device_type')]
[Nullable]
FDeviceType: NullableString;
[JSONName('route_max_duration')]
[Nullable]
FRouteMaxDuration: NullableInteger;
[JSONName('vehicle_capacity')]
[Nullable]
FVehicleCapacity: NullableString;
[JSONName('vehicle_max_distance_mi')]
[Nullable]
FVehicleMaxDistanceMI: NullableString;
[JSONName('travel_mode')]
[Nullable]
FTravelMode: NullableString;
[JSONName('metric')]
[Nullable]
FMetric: NullableInteger;
[JSONName('parts')]
[Nullable]
FParts: NullableInteger;
[JSONName('dev_lng')]
[Nullable]
FDevLongitude: NullableDouble;
[JSONName('route_email')]
[Nullable]
FRouteEmail: NullableString;
[JSONName('dirm')]
[Nullable]
FDirm: NullableInteger;
[JSONName('dm')]
[Nullable]
FDM: NullableInteger;
[JSONName('member_id')]
[Nullable]
FMemberId: NullableString;
[JSONName('driver_id')]
[Nullable]
FDriverId: NullableString;
[JSONName('vehicle_id')]
[Nullable]
FVehicleId: NullableString;
[JSONName('routeType')]
[Nullable]
FRouteType: NullableString;
[JSONName('dev_lat')]
[Nullable]
FDevLatitude: NullableDouble;
[JSONName('ip')]
[Nullable]
FIp: NullableString;
[JSONName('device_id')]
[Nullable]
FDeviceId: NullableString;
[JSONName('lock_last')]
[Nullable]
FLockLast: NullableBoolean;
[JSONName('avoid')]
[Nullable]
FAvoid: NullableString;
[JSONName('truck_height_meters')]
[Nullable]
FTruckHeightMeters: NullableInteger;
[JSONName('truck_length_meters')]
[Nullable]
FTruckLengthMeters: NullableInteger;
[JSONName('has_trailer')]
[Nullable]
FHasTrailer: NullableBoolean;
[JSONName('max_tour_size')]
[Nullable]
FMaxTourSize: NullableInteger;
[JSONName('truck_width_meters')]
[Nullable]
FTruckWidthMeters: NullableInteger;
[JSONName('min_tour_size')]
[Nullable]
FMinTourSize: NullableInteger;
[JSONName('limited_weight_t')]
[Nullable]
FLimitedWeightT: NullableDouble;
[JSONName('optimization_quality')]
[Nullable]
FOptimizationQuality: NullableInteger;
[JSONName('trailer_weight_t')]
[Nullable]
FTrailerWeightT: NullableDouble;
[JSONName('weight_per_axle_t')]
[Nullable]
FWeightPerAxleT: NullableDouble;
function GetAlgorithmType: TAlgorithmType;
procedure SetAlgorithmType(const Value: TAlgorithmType);
function GetOptimize: TOptimize;
procedure SetOptimize(const Value: TOptimize);
function GetDistanceUnit: TDistanceUnit;
procedure SetDistanceUnit(const Value: TDistanceUnit);
function GetDeviceType: TDeviceType;
procedure SetDeviceType(const Value: TDeviceType);
function GetTravelMode: TTravelMode;
procedure SetTravelMode(const Value: TTravelMode);
function GetMetric: TMetric;
procedure SetMetric(const Value: TMetric);
function GetAvoid: TAvoid;
procedure SetAvoid(const Value: TAvoid);
public
/// <remarks>
/// Constructor with 0-arguments must be and be public.
/// For JSON-deserialization.
/// </remarks>
constructor Create;
function Equals(Obj: TObject): Boolean; override;
/// <summary>
/// Let the R4M api know if this sdk request is coming from a file upload within your environment (for analytics)
/// </summary>
property IsUpload: NullableBoolean read FIsUpload write FIsUpload;
/// <summary>
/// The tour type of this route. rt is short for round trip, the optimization engine changes its behavior for round trip routes
/// </summary>
property RT: NullableBoolean read FRT write FRT;
/// <summary>
/// By disabling optimization, the route optimization engine will not resequence the stops in your
/// </summary>
property DisableOptimization: NullableBoolean read FDisableOptimization write FDisableOptimization;
/// <summary>
/// The name of this route. this route name will be accessible in the search API, and also will be displayed on the mobile device of a user
/// </summary>
property RouteName: NullableString read FRouteName write FRouteName;
/// <summary>
/// The algorithm to be used
/// </summary>
property AlgorithmType: TAlgorithmType read GetAlgorithmType write SetAlgorithmType;
/// <summary>
/// Always true
/// </summary>
property StoreRoute: NullableBoolean read FStoreRoute write FStoreRoute;
/// <summary>
/// The route start date in UTC, unix timestamp seconds. Used to show users when the route will begin, also used for reporting and analytics
/// </summary>
property RouteDate: NullableInteger read FRouteDate write FRouteDate;
/// <summary>
/// Time when the route starts (relative to route_date) (Seconds). UTC timezone as well
/// </summary>
property RouteTime: NullableInteger read FRouteTime write FRouteTime;
/// <summary>
/// The driving directions will be generated biased for this selection. This has no impact on route sequencing
/// </summary>
property Optimize: TOptimize read GetOptimize write SetOptimize;
/// <summary>
/// The distance measurement unit for the route
/// </summary>
property DistanceUnit: TDistanceUnit read GetDistanceUnit write SetDistanceUnit;
/// <summary>
/// The type of the device that is creating this route
/// </summary>
property DeviceType: TDeviceType read GetDeviceType write SetDeviceType;
/// <summary>
/// How many seconds a route can last at most. Default is 24 hours = 86400 seconds
/// </summary>
property RouteMaxDuration: NullableInteger read FRouteMaxDuration write FRouteMaxDuration; // nullable
/// <summary>
/// How much cargo can the vehicle carry (units, e.g. cubic meters)
/// </summary>
property VehicleCapacity: NullableString read FVehicleCapacity write FVehicleCapacity;
/// <summary>
/// Max distance for a single vehicle in this route (always in miles)
/// </summary>
property VehicleMaxDistanceMI: NullableString read FVehicleMaxDistanceMI write FVehicleMaxDistanceMI;
/// <summary>
/// The mode of travel that the directions should be optimized for
/// </summary>
property TravelMode: TTravelMode read GetTravelMode write SetTravelMode;
/// <summary>
/// Integer [1, 2, 3, 4, 5]
/// 1 = ROUTE4ME_METRIC_EUCLIDEAN (use euclidean distance when computing point to point distance)
/// 2 = ROUTE4ME_METRIC_MANHATTAN (use manhattan distance (taxicab geometry) when computing point to point distance)
/// 3 = ROUTE4ME_METRIC_GEODESIC (use geodesic distance when computing point to point distance)
/// #4 is the default and suggested metric
/// 4 = ROUTE4ME_METRIC_MATRIX (use road network driving distance when computing point to point distance)
/// 5 = ROUTE4ME_METRIC_EXACT_2D (use exact rectilinear distance)
/// </summary>
property Metric: TMetric read GetMetric write SetMetric;
/// <summary>
/// Legacy feature which permits a user to request an example number of optimized routes
/// </summary>
property Parts: NullableInteger read FParts write FParts;
/// <summary>
/// A flag to indicate if the last stop in the route should be fixed
/// </summary>
property LockLast: NullableBoolean read FLockLast write FLockLast;
/// <summary>
/// Options which let the user choose which road obstacles to avoid. This has no impact on route sequencing
/// </summary>
property Avoid: TAvoid read GetAvoid write SetAvoid;
/// <summary>
/// The unique internal id of a vehicle
/// </summary>
property VehicleId: NullableString read FVehicleId write FVehicleId;
/// <summary>
/// The unique internal id of a driver
/// </summary>
property DriverId: NullableString read FDriverId write FDriverId;
/// <summary>
/// The latitude location of where a mobile device was located when it made a request to create the route
/// </summary>
property DevLatitude: NullableDouble read FDevLatitude write FDevLatitude;
/// <summary>
/// The longitude location of where a mobile device was located when it made a request to create the route
/// </summary>
property DevLongitude: NullableDouble read FDevLongitude write FDevLongitude;
/// <summary>
/// Addresses where this route was shared after completion
/// </summary>
property RouteEmail: NullableString read FRouteEmail write FRouteEmail;
/// <summary>
/// Type of route being created: ENUM(api,null)
/// </summary>
property RouteType: NullableString read FRouteType write FRouteType;
/// <summary>
/// User ID who is assigned to the route
/// </summary>
property MemberId: NullableString read FMemberId write FMemberId;
/// <summary>
/// IP Address in decimal form of user who created the route
/// </summary>
property Ip: NullableString read FIp write FIp;
/// <summary>
/// Undocumented/not publicly shown
/// </summary>
//the method to use when compute the distance between the points in a route
//1 = DEFAULT (R4M PROPRIETARY ROUTING)
//2 = DEPRECRATED
//3 = R4M TRAFFIC ENGINE
//4 = DEPRECATED
//5 = DEPRECATED
//6 = TRUCKING
property DM: NullableInteger read FDM write FDM;
/// <summary>
/// Undocumented/not publicly shown
/// </summary>
//directions method
//1 = DEFAULT (R4M PROPRIETARY INTERNAL NAVIGATION SYSTEM)
//2 = DEPRECATED
//3 = TRUCKING
//4 = DEPRECATED
property Dirm: NullableInteger read FDirm write FDirm;
/// <summary>
/// 32 Character MD5 String ID of the device that was used to plan this route
/// </summary>
property DeviceId: NullableString read FDeviceId write FDeviceId;
/// <summary>
/// if True vehicle has trailer
/// </summary>
property HasTrailer: NullableBoolean read FHasTrailer write FHasTrailer;
/// <summary>
/// If has_trailer = true, specifies the weight of the trailer (required)
/// </summary>
property TrailerWeightT: NullableDouble read FTrailerWeightT write FTrailerWeightT;
/// <summary>
/// If travel_mode = 'Trucking', specifies the truck weight (required)
/// </summary>
property LimitedWeightT: NullableDouble read FLimitedWeightT write FLimitedWeightT;
/// <summary>
/// If travel_mode = 'Trucking', specifies the weight per axle (required)
/// </summary>
property WeightPerAxleT: NullableDouble read FWeightPerAxleT write FWeightPerAxleT;
/// <summary>
/// If travel_mode = 'Trucking', specifies the truck height (required)
/// </summary>
property TruckHeightMeters: NullableInteger read FTruckHeightMeters write FTruckHeightMeters;
/// <summary>
/// If travel_mode = 'Trucking', specifies the truck width (required)
/// </summary>
property TruckWidthMeters: NullableInteger read FTruckWidthMeters write FTruckWidthMeters;
/// <summary>
/// If travel_mode = 'Trucking', specifies the truck length (required)
/// </summary>
property TruckLengthMeters: NullableInteger read FTruckLengthMeters write FTruckLengthMeters;
/// <summary>
/// Must be > 0; the minimum number of stops allowed in a subtour. null means there is no minimum
/// </summary>
//the minimum number of stops permitted per created subroute
property MinTourSize: NullableInteger read FMinTourSize write FMinTourSize;
/// <summary>
/// Must be > 0; the maximum number of stops allowed in a subtour. null means there is no maximum
/// </summary>
property MaxTourSize: NullableInteger read FMaxTourSize write FMaxTourSize;
/// <summary>
/// there are 3 types of optimization qualities that are optimizations goals
/// 1 - Generate Optimized Routes As Quickly as Possible
/// 2 - Generate Routes That Look Better On A Map
/// 3 - Generate The Shortest And Quickest Possible Routes
/// </summary>
property OptimizationQuality: NullableInteger read FOptimizationQuality write FOptimizationQuality;
end;
implementation
{ TRouteParameters }
constructor TRouteParameters.Create;
begin
FIsUpload := NullableBoolean.Null;
FRT := NullableBoolean.Null;
FDisableOptimization := NullableBoolean.Null;
FRouteName := NullableString.Null;
FAlgorithmType := NullableInteger.Null;
FStoreRoute := NullableBoolean.Null;
FRouteDate := NullableInteger.Null;
FRouteTime := NullableInteger.Null;
FOptimize := NullableString.Null;
FDistanceUnit := NullableString.Null;
FDeviceType := NullableString.Null;
FRouteMaxDuration := NullableInteger.Null;
FVehicleCapacity := NullableString.Null;
FVehicleMaxDistanceMI := NullableString.Null;
FTravelMode := NullableString.Null;
FMetric := NullableInteger.Null;
FParts := NullableInteger.Null;
FDevLongitude := NullableDouble.Null;
FRouteEmail := NullableString.Null;
FDirm := NullableInteger.Null;
FDM := NullableInteger.Null;
FMemberId := NullableString.Null;
FDriverId := NullableString.Null;
FVehicleId := NullableString.Null;
FRouteType := NullableString.Null;
FDevLatitude := NullableDouble.Null;
FIp := NullableString.Null;
FDeviceId := NullableString.Null;
FLockLast := NullableBoolean.Null;
FAvoid := NullableString.Null;
FTruckHeightMeters := NullableInteger.Null;
FTruckLengthMeters := NullableInteger.Null;
FHasTrailer := NullableBoolean.Null;
FMaxTourSize := NullableInteger.Null;
FTruckWidthMeters := NullableInteger.Null;
FMinTourSize := NullableInteger.Null;
FLimitedWeightT := NullableDouble.Null;
FOptimizationQuality := NullableInteger.Null;
FTrailerWeightT := NullableDouble.Null;
FWeightPerAxleT := NullableDouble.Null;
end;
function TRouteParameters.Equals(Obj: TObject): Boolean;
var
Other: TRouteParameters;
begin
Result := False;
if not (Obj is TRouteParameters) then
Exit;
Other := TRouteParameters(Obj);
Result :=
(FIsUpload = Other.FIsUpload) and
(FRT = Other.FRT) and
(FDisableOptimization = Other.FDisableOptimization) and
(FRouteName = Other.FRouteName) and
(FAlgorithmType = Other.FAlgorithmType) and
(FStoreRoute = Other.FStoreRoute) and
(FRouteDate = Other.FRouteDate) and
(FRouteTime = Other.FRouteTime) and
(FOptimize = Other.FOptimize) and
(FDistanceUnit = Other.FDistanceUnit) and
(FDeviceType = Other.FDeviceType) and
(FRouteMaxDuration = Other.FRouteMaxDuration) and
(FVehicleCapacity = Other.FVehicleCapacity) and
(FVehicleMaxDistanceMI = Other.FVehicleMaxDistanceMI) and
(FTravelMode = Other.FTravelMode) and
(FMetric = Other.FMetric) and
(FParts = Other.FParts) and
(FDevLatitude = Other.FDevLatitude) and
(FDevLongitude = Other.FDevLongitude) and
(FRouteEmail = Other.FRouteEmail) and
(FDirm = Other.FDirm) and
(FDM = Other.FDM) and
(FMemberId = Other.FMemberId) and
(FDriverId = Other.FDriverId) and
(FVehicleId = Other.FVehicleId) and
(FRouteType = Other.FRouteType) and
(FIp = Other.FIp) and
(FDeviceId = Other.FDeviceId) and
(FLockLast = Other.FLockLast) and
(FAvoid = Other.FAvoid) and
(FTruckHeightMeters = Other.FTruckHeightMeters) and
(FTruckLengthMeters = Other.FTruckLengthMeters) and
(FHasTrailer = Other.FHasTrailer) and
(FMaxTourSize = Other.FMaxTourSize) and
(FTruckWidthMeters = Other.FTruckWidthMeters) and
(FMinTourSize = Other.FMinTourSize) and
(FLimitedWeightT = Other.FLimitedWeightT) and
(FOptimizationQuality = Other.FOptimizationQuality) and
(FTrailerWeightT = Other.FTrailerWeightT) and
(FWeightPerAxleT = Other.FWeightPerAxleT);
end;
function TRouteParameters.GetAlgorithmType: TAlgorithmType;
begin
if FAlgorithmType.IsNull then
Result := TAlgorithmType.NoneAlgorithmType
else
Result := TAlgorithmType(FAlgorithmType.Value);
end;
function TRouteParameters.GetAvoid: TAvoid;
var
Avoid: TAvoid;
begin
Result := TAvoid.Empty;
if FAvoid.IsNotNull then
for Avoid := Low(TAvoid) to High(TAvoid) do
if (FAvoid = TAvoidDescription[Avoid]) then
Exit(Avoid);
end;
function TRouteParameters.GetDeviceType: TDeviceType;
var
DeviceType: TDeviceType;
begin
Result := TDeviceType.UnknownDevice;
if FDeviceType.IsNotNull then
for DeviceType := Low(TDeviceType) to High(TDeviceType) do
if (FDeviceType = TDeviceTypeDescription[DeviceType]) then
Exit(DeviceType);
end;
function TRouteParameters.GetDistanceUnit: TDistanceUnit;
var
DistanceUnit: TDistanceUnit;
begin
Result := TDistanceUnit.Undefinded;
if FDistanceUnit.IsNotNull then
for DistanceUnit := Low(TDistanceUnit) to High(TDistanceUnit) do
if (FDistanceUnit = TDistanceUnitDescription[DistanceUnit]) then
Exit(DistanceUnit);
end;
function TRouteParameters.GetMetric: TMetric;
begin
if FMetric.IsNull then
Result := TMetric.UndefinedMetric
else
Result := TMetric(FMetric.Value);
end;
function TRouteParameters.GetOptimize: TOptimize;
var
Optimize: TOptimize;
begin
Result := TOptimize.NoneOptimize;
if FOptimize.IsNotNull then
for Optimize := Low(TOptimize) to High(TOptimize) do
if (FOptimize = TOptimizeDescription[Optimize]) then
Exit(Optimize);
end;
function TRouteParameters.GetTravelMode: TTravelMode;
var
TravelMode: TTravelMode;
begin
Result := TTravelMode.UnknownMode;
if FTravelMode.IsNotNull then
for TravelMode := Low(TTravelMode) to High(TTravelMode) do
if (FTravelMode = TTravelModeDescription[TravelMode]) then
Exit(TravelMode);
end;
procedure TRouteParameters.SetAlgorithmType(const Value: TAlgorithmType);
begin
FAlgorithmType := Integer(Value);
end;
procedure TRouteParameters.SetAvoid(const Value: TAvoid);
begin
FAvoid := TAvoidDescription[Value];
end;
procedure TRouteParameters.SetDeviceType(const Value: TDeviceType);
begin
FDeviceType := TDeviceTypeDescription[Value];
end;
procedure TRouteParameters.SetDistanceUnit(const Value: TDistanceUnit);
begin
FDistanceUnit := TDistanceUnitDescription[Value];
end;
procedure TRouteParameters.SetMetric(const Value: TMetric);
begin
FMetric := Integer(Value);
end;
procedure TRouteParameters.SetOptimize(const Value: TOptimize);
begin
FOptimize := TOptimizeDescription[Value];
end;
procedure TRouteParameters.SetTravelMode(const Value: TTravelMode);
begin
FTravelMode := TTravelModeDescription[Value];
end;
end.
|
{$I ok_sklad.inc}
unit MetaTax;
interface
uses
MetaClass, XMLDoc, XMLIntf,
Classes;
type
TTaxMethod = (TaxMethodPercent, TaxMethodValue);
TMetaTax = class(TMetaClass)
protected
FMethod: TTaxMethod;
FValue: Extended;
function LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean;
public
constructor Create(const AParent: TMetaClass); overload;
constructor Create(const AParent: TMetaClass; const AMethod: TTaxMethod; const AValue: Extended); overload;
procedure Clear;
property Method: TTaxMethod read FMethod write FMethod;
property Value: Extended read FValue write FValue;
end;
//-----------------------------------------------------------------------
TMetaTaxList = class(TMetaClassList)
protected
function LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean;
public
constructor Create(const AParent: TMetaClass);
destructor Destroy; override;
function Add(const Value: TMetaTax): Integer; overload;
function Add(const AMethod: TTaxMethod; const AValue: Extended): Integer; overload;
// property processing
function getItem(const idx: Integer): TMetaTax;
procedure setItem(const idx: Integer; const Value: TMetaTax);
property Items[const idx: Integer]: TMetaTax read getItem write setItem; default;
end;
//==============================================================================================
//==============================================================================================
//==============================================================================================
//==============================================================================================
implementation
uses
udebug, SysUtils, StrUtils;
var
DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = '';
//==============================================================================================
constructor TMetaTax.Create(const AParent: TMetaClass);
begin
inherited;
Clear;
end;
//==============================================================================================
procedure TMetaTax.Clear;
begin
FMethod := TaxMethodPercent;
FValue := 0.0;
end;
//==============================================================================================
constructor TMetaTax.Create(const AParent: TMetaClass; const AMethod: TTaxMethod; const AValue: Extended);
begin
Create(AParent);
FMethod := AMethod;
FValue := AValue;
end;
//==============================================================================================
function TMetaTax.LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean;
var
name, data: string;
begin
Result := True;
name := AnsiLowerCase(Node.NodeName);
data := trim(Node.Text);
try
if name = 'value' then begin
FValue := StrToFloat(data);
Exit;
end;
except
Ferror := ap_err_XML_badData;
Exit;
end;
if name = 'method' then begin
data := AnsiLowerCase(data);
if data = 'percent'
then FMethod := TaxMethodPercent
else FMethod := TaxMethodValue;
Exit;
end
else Result := inherited loadXMLNode(Node, Node);
end;
//==============================================================================================
//==============================================================================================
//==============================================================================================
constructor TMetaTaxList.Create(const AParent: TMetaClass);
begin
inherited;
end;
//==============================================================================================
destructor TMetaTaxList.Destroy;
begin
Clear;
inherited;
end;
//==============================================================================================
function TMetaTaxList.Add(const Value: TMetaTax): Integer;
begin
Result := FItems.Add(Value);
Value.MetaParent := Self;
end;
//==============================================================================================
function TMetaTaxList.Add(const AMethod: TTaxMethod; const AValue: Extended): Integer;
begin
Result := FItems.Add(TMetaTax.Create(Self, AMethod, AValue));
end;
//==============================================================================================
function TMetaTaxList.getItem(const idx: Integer): TMetaTax;
begin
Result := TMetaTax(FItems[idx]);
end;
//==============================================================================================
procedure TMetaTaxList.setItem(const idx: Integer; const Value: TMetaTax);
begin
FItems[idx] := Value;
end;
//==============================================================================================
function TMetaTaxList.LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean;
var
name, data: string;
t: TMetaTax;
begin
Result := True;
name := AnsiLowerCase(Node.NodeName);
data := trim(Node.Text);
try
if name = 'tax' then begin
t := TMetaTax.Create(Self);
FItems.Add(t);
Result := t.loadXML(node);
Exit;
end;
except
Ferror := ap_err_XML_badData;
Exit;
end;
Result := inherited loadXMLNode(Node, Node);
end;
//==============================================================================================
initialization
{$IFDEF UDEBUG}
Debugging := False;
DEBUG_unit_ID := debugRegisterUnit('MetaTax', @Debugging, DEBUG_group_ID);
{$ENDIF}
//==============================================================================================
finalization
//{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF}
end.
|
unit Quick.OAuth.Utils;
interface
type
TRequestMethod = (rmGET, rmPOST);
function EncodeURL (const aURL: string): string;
procedure OpenURL (const aURL: string);
function GetDomain (const aURL: string): string;
function GetPort (const aURL: string): integer;
function GetMethodFromRequest (const aRequest: string): TRequestMethod;
function GetCleanRequest (const aRequest: string): string;
implementation
uses
{$IFDEF MSWINDOWS}
WinApi.ShellAPI,
Winapi.Windows,
{$ENDIF}
System.SysUtils,
System.Types, System.Classes, System.StrUtils;
{$I QuickLib.INC}
function EncodeURL (const aURL: string): string;
var
bArray: TBytes;
c: Char;
b: byte;
begin
result:='';
bArray := TEncoding.UTF8.GetBytes(aURL);
for b in bArray do
begin
c := Chr(b);
case c of
'A'..'Z',
'a'..'z',
'0'..'9',
'-',
'_',
'.': result := result + c
else
result:= result + '%' + IntToHex(Ord(b),2);
end;
end;
end;
procedure OpenURL (const aURL: string);
begin
{$IFDEF MSWINDOWS}
ShellExecute(0,PChar('open'),PChar(aURL),PChar(''),PChar(''), SW_NORMAL);
{$ELSE}
raise Exception.Create('OpenURL not implemented yet');
{$ENDIF}
end;
function GetDomain (const aURL: string): string;
{$IFDEF DELPHIXE3_UP}
var
parts: TStringDynArray;
begin
result:=aURL;
parts:=aURL.Split([':']);
if Length(parts) > 1 then
result:=parts[1].Replace('/', '');
{$ELSE}
begin
raise Exception.Create('Not implemented yet');
{$ENDIF}
end;
function GetPort (const aURL: string): integer;
{$IFDEF DELPHIXE3_UP}
var
parts: TStringDynArray;
begin
result:=80;
parts:=aURL.Split([':']);
if Length(parts) > 1 then
TryStrToInt(parts[High(parts)].Replace('/', ''), result);
{$ELSE}
begin
raise Exception.Create('Not implemented yet');
{$ENDIF}
end;
function GetMethodFromRequest (const aRequest: string): TRequestMethod;
begin
result:=rmGET;
if aRequest.Trim = '' then
Exit;
case IndexStr(aRequest.Split([' '])[0].ToUpper, ['GET', 'POST']) of
0: result:=rmGET;
1: result:=rmPOST;
end;
end;
function GetCleanRequest (const aRequest: string): string;
var
parts: TStringDynArray;
begin
result:=aRequest;
if aRequest.Trim = '' then
Exit;
parts:=aRequest.Split([' ']);
if Length(parts) > 1 then
result:=parts[1];
end;
end.
|
{$include lem_directives.inc}
unit GameMenuScreen;
{-------------------------------------------------------------------------------
The main menu dos screen.
-------------------------------------------------------------------------------}
interface
uses
Windows, Classes, Controls, Graphics, MMSystem, Forms,
GR32, GR32_Image, GR32_Layers,
UFastStrings,
UMisc, Dialogs,
LemCore, LemTypes, LemStrings, LemDosStructures, LemRendering, LemLevel, LemDosStyle,
LemDosGraphicSet,
SysUtils,
GameControl, GameBaseScreen, GamePreviewScreen, GameLevelCodeScreen;
type
{-------------------------------------------------------------------------------
these are the images we need for the menuscreen.
-------------------------------------------------------------------------------}
TGameMenuBitmap = (
gmbLogo,
gmbPlay, // 1st row, 1st button
gmbLevelCode, // 1st row, 2nd button
gmbMusic, // 1st row, 3d button
gmbSection, // 1st row, 4th button
gmbExit, // 2nd row, 1st button
gmbNavigation, // 2nd row, 2nd button
gmbMusicNote, // drawn in gmbMusic
gmbFXSound, // drawn in gmbMusic
gmbGameSection1, // mayhem/havoc drawn in gmbSection
gmbGameSection2, // taxing/wicked drawn in gmbSection
gmbGameSection3, // tricky/wild drawn in gmbSection
gmbGameSection4, // fun/crazy drawn in gmbSection
gmbGameSection5, // .../tame drawn in gmbSection
gmbGameSection6, // remake only
gmbGameSection7,
gmbGameSection8,
gmbGameSection9,
gmbGameSection10,
gmbGameSection11,
gmbGameSection12,
gmbGameSection13,
gmbGameSection14,
gmbGameSection15
);
const
{-------------------------------------------------------------------------------
Positions at which the images of the menuscreen are drawn
-------------------------------------------------------------------------------}
GameMenuBitmapPositions: array[TGameMenuBitmap] of TPoint = (
(X:8; Y:10), // gmbLogo
(X:72; Y:120), // gmbPlay
(X:200; Y:120), // gmbLevelCode
(X:328; Y:120), // gmbMusic
(X:456; Y:120), // gmbSection
(X:200; Y:196), // gmbExit
(X:328; Y:196), // gmbNavigation
(X:328 + 27; Y:120 + 26), // gmbMusicNote
(X:328 + 27; Y:120 + 26), // gmbFXSign,
(X:456 + 32; Y:120 + 24), // gmbSection1
(X:456 + 32; Y:120 + 24), // gmbSection2
(X:456 + 32; Y:120 + 24), // gmbSection3
(X:456 + 32; Y:120 + 24), // gmbSection4
(X:456 + 32; Y:120 + 24), // gmbSection5
(X:456 + 32; Y:120 + 24), // gmbSection6
(X:456 + 32; Y:120 + 24),
(X:456 + 32; Y:120 + 24),
(X:456 + 32; Y:120 + 24),
(X:456 + 32; Y:120 + 24),
(X:456 + 32; Y:120 + 24),
(X:456 + 32; Y:120 + 24),
(X:456 + 32; Y:120 + 24),
(X:456 + 32; Y:120 + 24),
(X:456 + 32; Y:120 + 24)
);
YPos_ProgramText = 272;
YPos_Credits = 350 - 16;
Reel_Width = 34 * 16;
Reel_Height = 16;
Font_Width = 16;
type
TStringAnimationInfo = record
end;
TGameMenuScreen = class(TGameBaseScreen)
private
{ enumerated menu bitmap elements }
BitmapElements : array[TGameMenuBitmap] of TBitmap32;
{ music }
// MusicSetting : TGameMusicSetting;
{ section }
CurrentSection : Integer; // game section
LastSection : Integer; // last game section
{ credits }
LeftLemmingAnimation : TBitmap32;
RightLemmingAnimation : TBitmap32;
Reel : TBitmap32;
ReelBuffer : TBitmap32;
CanAnimate : Boolean;
{ credits animation counters }
FrameTimeMS : Cardinal;
PrevTime : Cardinal;
ReadingPauseMS : Cardinal; //
ReelLetterBoxCount : Integer; // the number of letterboxes on the reel (34)
Pausing : Boolean;
UserPausing : Boolean;
PausingDone : Boolean; // the current text has been paused
// Credits : TStringList;
// LastCredit : Integer;
// CompleteCreditString : string;
CreditList : TStringList;
CreditIndex : Integer;
CreditString : string;
TextX : Integer;
TextPauseX : Integer; // if -1 then no pause
TextGoneX : Integer;
CurrentFrame : Integer;
// PausePosition : Integer;
ReelShift : Integer;
{ internal }
procedure DrawBitmapElement(aElement: TGameMenuBitmap);
procedure SetSoundOptions(aOptions: TGameSoundOptions);
procedure SetSection(aSection: Integer);
procedure NextSection(Forwards: Boolean);
procedure NextSoundSetting;
procedure DrawWorkerLemmings(aFrame: Integer);
procedure DrawReel;//(aReelShift, aTextX: Integer);
procedure SetNextCredit;
procedure DumpLevels;
procedure DumpImages;
{ eventhandlers }
procedure Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Form_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure Img_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
procedure Application_Idle(Sender: TObject; var Done: Boolean);
function BuildText(intxt: Array of char): String;
protected
{ overrides }
procedure PrepareGameParams(Params: TDosGameParams); override;
procedure BuildScreen; override;
procedure CloseScreen(aNextScreen: TGameScreenType); override;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
{ TGameMenuScreen }
procedure TGameMenuScreen.DrawBitmapElement(aElement: TGameMenuBitmap);
{-------------------------------------------------------------------------------
Draw bitmap at appropriate place on the screen.
-------------------------------------------------------------------------------}
var
P: TPoint;
begin
P := GameMenuBitmapPositions[aElement];
BitmapElements[aElement].DrawTo(ScreenImg.Bitmap, P.X, P.Y);
end;
procedure TGameMenuScreen.BuildScreen;
{-------------------------------------------------------------------------------
extract bitmaps from the lemmingsdata and draw
-------------------------------------------------------------------------------}
var
Mainpal: TArrayOfColor32;
Tmp: TBitmap32;
i: Integer;
begin
(* stretched := false;
// screenimg.ScaleMode := smscale;
screenimg.BitmapAlign := baCustom;
screenimg.ScaleMode := smScale;
screenimg.scale := 1.5; *)
Tmp := TBitmap32.Create;
ScreenImg.BeginUpdate;
try
MainPal := GetDosMainMenuPaletteColors32;
InitializeImageSizeAndPosition(640, 350);
ExtractBackGround;
ExtractPurpleFont;
MainDatExtractor.ExtractBitmap(BitmapElements[gmbLogo], 3, $2080, 632, 94, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbPlay], 3, $9488, 120, 61, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbLevelCode], 3, $A2D4, 120, 61, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbMusic], 3, $B120, 120, 61, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbSection], 3, $BF6C, 120, 61, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbExit], 3, $CDB8, 120, 61, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbNavigation], 3, $DC04, 120, 61, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbMusicNote], 3, $EA50, 64, 31, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbFXSound], 3, $EE30, 64, 31, 4, MainPal);
MainDatExtractor.ExtractAnimation(LeftLemmingAnimation, 4, $2A00, 48, 16, 16, 4, MainPal);
MainDatExtractor.ExtractAnimation(RightLemmingAnimation, 4, $4200, 48, 16, 16, 4, MainPal);
//@styledef
{$ifdef 15rank}
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection1], 5, 0 + (972 * 0), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection2], 5, 0 + (972 * 1), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection3], 5, 0 + (972 * 2), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection4], 5, 0 + (972 * 3), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection5], 5, 0 + (972 * 4), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection6], 5, 0 + (972 * 5), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection7], 5, 0 + (972 * 6), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection8], 5, 0 + (972 * 7), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection9], 5, 0 + (972 * 8), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection10], 5, 0 + (972 * 9), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection11], 5, 0 + (972 * 10), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection12], 5, 0 + (972 * 11), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection13], 5, 0 + (972 * 12), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection14], 5, 0 + (972 * 13), 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection15], 5, 0 + (972 * 14), 72, 27, 4, MainPal);
{$else}
//@styledef
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection1], 4, $5A80, 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection2], 4, $5E4C, 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection3], 4, $6218, 72, 27, 4, MainPal);
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection4], 4, $65E4, 72, 27, 4, MainPal);
{$ifndef fourrank}
MainDatExtractor.ExtractBitmap(BitmapElements[gmbGameSection5], 4, $65E4 + 972, 72, 27, 4, MainPal);
//BitmapElements[gmbGameSection5].LoadFromFile('d:\d7\lem\data\remake\easy.bmp');
{$endif}
{$endif}
// reel
MainDatExtractor.ExtractBitmap(Tmp, 4, $5A00, 16, 16, 4, MainPal);
// a little oversize
Reel.SetSize(ReelLetterBoxCount * 16 + 32, 16);
for i := 0 to ReelLetterBoxCount - 1 + 4 do
Tmp.DrawTo(Reel, i * 16, 0);
// make sure the reelbuffer is the right size
ReelBuffer.SetSize(ReelLetterBoxCount * 16, 16);
// background
TileBackgroundBitmap(0, 0);
BackBuffer.Assign(ScreenImg.Bitmap); // save it
// menu elements
DrawBitmapElement(gmbLogo);
DrawBitmapElement(gmbPlay);
DrawBitmapElement(gmbLevelCode);
DrawBitmapElement(gmbMusic);
DrawBitmapElement(gmbSection);
DrawBitmapElement(gmbExit);
DrawBitmapElement(gmbNavigation);
// program text
DrawPurpleTextCentered(ScreenImg.Bitmap, {$ifdef flexi}BuildText(GameParams.SysDat.PackName) + #13 + BuildText(GameParams.SysDat.SecondLine){$else}SProgramText{$endif}, YPos_ProgramText);
// credits animation
DrawWorkerLemmings(0);
DrawReel;//(0, TextX);
// a bit weird place, but here we know the bitmaps are loaded
SetSection(CurrentSection);
SetSoundOptions(GameParams.SoundOptions);
CanAnimate := True;
// ScreenImg.Bitmap.ResamplerClassName := 'TDraftResampler';
finally
ScreenImg.EndUpdate;
Tmp.Free;
end;
end;
constructor TGameMenuScreen.Create(aOwner: TComponent);
var
E: TGameMenuBitmap;
Bmp: TBitmap32;
begin
inherited Create(aOwner);
CurrentSection := 0;
// create bitmaps
for E := Low(TGameMenuBitmap) to High(TGameMenuBitmap) do
begin
Bmp := TBitmap32.Create;
BitmapElements[E] := Bmp;
if not (E in [gmbMusicNote, gmbFXSound, gmbGameSection1, gmbGameSection2, gmbGameSection3, gmbGameSection4,
gmbGameSection5, gmbGameSection6, gmbGameSection7, gmbGameSection8, gmbGameSection9, gmbGameSection10,
gmbGameSection11, gmbGameSection12, gmbGameSection13, gmbGameSection14, gmbGameSection15])
then Bmp.DrawMode := dmTransparent;
end;
LeftLemmingAnimation := TBitmap32.Create;
LeftLemmingAnimation.DrawMode := dmTransparent;
RightLemmingAnimation := TBitmap32.Create;
RightLemmingAnimation.DrawMode := dmTransparent;
Reel := TBitmap32.Create;
ReelBuffer := TBitmap32.Create;
CreditList := TStringList.Create;
// CanAnimate : Boolean;
// Credits := TStringList.Create;
FrameTimeMS := 32;
ReadingPauseMS := 1000;
// Credits.Text := SCredits;
// LastCredit := Credits.Count - 1;
// CompleteCreditString := FastReplace(SCredits, Chr(13), Chr(10));
CreditList.Text := {$ifdef flexi}''{$else}
SCredits{$endif};//CompleteCreditString;
CreditIndex := -1;
ReelLetterBoxCount := 34;
SetNextCredit;
{$ifdef flexi}CreditIndex := -1;{$endif}
//DisplayString := CreditList[0];
// windlg(currentcreditstring);
// CurrentCredit := 0;
// ScreenImg.RepaintMode := rmOptimizer;
// set eventhandlers
OnKeyDown := Form_KeyDown;
OnMouseDown := Form_MouseDown;
ScreenImg.OnMouseDown := Img_MouseDown;
Application.OnIdle := Application_Idle;
end;
destructor TGameMenuScreen.Destroy;
var
E: TGameMenuBitmap;
begin
for E := Low(TGameMenuBitmap) to High(TGameMenuBitmap) do
BitmapElements[E].Free;
LeftLemmingAnimation.Free;
RightLemmingAnimation.Free;
Reel.Free;
ReelBuffer.Free;
CreditList.Free;
inherited Destroy;
end;
procedure TGameMenuScreen.Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Shift = [] then
begin
case Key of
VK_RETURN : CloseScreen(gstPreview);
VK_F1 : CloseScreen(gstPreview);
VK_F2 : CloseScreen(gstLevelCode);
VK_F3 : NextSoundSetting;
VK_F4 : CloseScreen(gstNavigation);
VK_F5 : DumpLevels;
VK_F6 : DumpImages;
VK_ESCAPE : CloseScreen(gstExit);
VK_UP : NextSection(True);
VK_DOWN : NextSection(False);
VK_SPACE : UserPausing := not UserPausing;
end;
end;
end;
procedure TGameMenuScreen.DumpImages;
var
I: Integer;
begin
{$ifdef flexi}if GameParams.SysDat.Options3 and 4 = 0 then Exit;{$endif}
I := MessageDlg('Dump all level images? Warning: This is very slow!', mtCustom, [mbYes, mbNo], 0);
if I = mrYes then
begin
MessageDlg('The screen will go blank while dumping level images.' + CrLf + 'This is normal.', mtCustom, [mbOk], 0);
GameParams.DumpMode := true;
GameParams.WhichLevel := wlFirst;
CloseScreen(gstPreview);
end;
end;
procedure TGameMenuScreen.DumpLevels;
var
I: Integer;
begin
{$ifdef flexi}if GameParams.SysDat.Options3 and 4 = 0 then Exit;{$endif}
if not (GameParams.Style.LevelSystem is TBaseDosLevelSystem) then exit;
I := MessageDlg('Dump all level files? Warning: This may overwrite' + CrLf + 'LVL files currently present!', mtCustom, [mbYes, mbNo], 0);
if I = mrYes then
TBaseDosLevelSystem(GameParams.Style.LevelSystem).DumpAllLevels;
end;
procedure TGameMenuScreen.Form_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
CloseScreen(gstPreview);
end;
procedure TGameMenuScreen.Img_MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer;
Layer: TCustomLayer);
begin
if Button = mbLeft then
CloseScreen(gstPreview);
end;
procedure TGameMenuScreen.NextSection(Forwards: Boolean);
procedure Change;
begin
with GameParams.Info do
begin
dValid := True;
dPack := 0;
dSection := CurrentSection;
dLevel := 0;
GameParams.WhichLevel := wlFirstSection;
end;
end;
begin
case Forwards of
False:
begin
if CurrentSection > 0 then
begin
SetSection(CurrentSection - 1);
Change;
end
else
Exit;
end;
True:
begin
if CurrentSection < LastSection then
begin
SetSection(CurrentSection + 1);
Change;
end
else
Exit;
// CurrentSection := LastSection;//0;
end;
end;
end;
procedure TGameMenuScreen.NextSoundSetting;
var
Opt: TGameSoundOptions;
begin
Opt := GameParams.SoundOptions;
if Opt = [] then Include(Opt, gsoSound)
else if Opt = [gsoSound] then Include(Opt, gsoMusic)
else if Opt = [gsoMusic, gsoSound] then Opt := [];
SetSoundOptions(Opt);
end;
function TGameMenuScreen.BuildText(intxt: Array of char): String;
var
tstr : String;
x : byte;
begin
tstr := '';
for x := 0 to 35 do
begin
if (tstr <> '') or (intxt[x] <> ' ') then
begin
tstr := tstr + intxt[x];
end;
end;
Result := trim(tstr);
end;
procedure TGameMenuScreen.PrepareGameParams(Params: TDosGameParams);
var
i: integer;
k: string;
begin
inherited PrepareGameParams(Params);
CurrentSection := Params.Info.dSection;
LastSection := (Params.Style.LevelSystem as TBaseDosLevelSystem).GetSectionCount - 1;
{$ifdef flexi}
CreditList.Text := BuildText(Params.SysDat.PackName) + #13;
for i := 0 to 15 do
begin
k := BuildText(Params.SysDat.ScrollerTexts[i]);
if Trim(k) <> '' then CreditList.Text := CreditList.Text + Trim(k) + #13;
end;
CreditList.Text := CreditList.Text + SCredits;
SetNextCredit;
{$endif}
// fun, tricky, taxing, mayhem
end;
procedure TGameMenuScreen.SetSoundOptions(aOptions: TGameSoundOptions);
var
Opt: TGameSoundOptions;
begin
GameParams.SoundOptions := aOptions;
Opt := GameParams.SoundOptions;
if Opt = [] then DrawBitmapElement(gmbMusic)
else if Opt = [gsoSound] then DrawBitmapElement(gmbFXSound)
else if Opt = [gsoMusic, gsoSound] then DrawBitmapElement(gmbMusicNote);
end;
procedure TGameMenuScreen.SetSection(aSection: Integer);
begin
CurrentSection := aSection;
//@styledef
{$ifdef 15rank}
case CurrentSection of
0: DrawBitmapElement(gmbGameSection1);
1: DrawBitmapElement(gmbGameSection2);
2: DrawBitmapElement(gmbGameSection3);
3: DrawBitmapElement(gmbGameSection4);
4: DrawBitmapElement(gmbGameSection5);
5: DrawBitmapElement(gmbGameSection6);
6: DrawBitmapElement(gmbGameSection7);
7: DrawBitmapElement(gmbGameSection8);
8: DrawBitmapElement(gmbGameSection9);
9: DrawBitmapElement(gmbGameSection10);
10: DrawBitmapElement(gmbGameSection11);
11: DrawBitmapElement(gmbGameSection12);
12: DrawBitmapElement(gmbGameSection13);
13: DrawBitmapElement(gmbGameSection14);
14: DrawBitmapElement(gmbGameSection15);
end;
{$else}
{$ifdef fourrank}
case CurrentSection of
0: DrawBitmapElement(gmbGameSection4);
1: DrawBitmapElement(gmbGameSection3);
2: DrawBitmapElement(gmbGameSection2);
3: DrawBitmapElement(gmbGameSection1);
end;
{$else}
case CurrentSection of
0: DrawBitmapElement(gmbGameSection5);
1: DrawBitmapElement(gmbGameSection4);
2: DrawBitmapElement(gmbGameSection3);
3: DrawBitmapElement(gmbGameSection2);
4: DrawBitmapElement(gmbGameSection1);
end;
{$endif}
{$endif}
end;
procedure TGameMenuScreen.DrawWorkerLemmings(aFrame: Integer);
var
SrcRect, DstRect: TRect;
begin
SrcRect := CalcFrameRect(LeftLemmingAnimation, 16, aFrame);
DstRect := SrcRect;
DstRect := ZeroTopLeftRect(DstRect);
OffsetRect(DstRect, 0, YPos_Credits);
BackBuffer.DrawTo(ScreenImg.Bitmap, DstRect, DstRect);
LeftLemmingAnimation.DrawTo(ScreenImg.Bitmap, DstRect, SrcRect);
// SrcRect := CalcFrameRect(RightLemmingAnimation, 16, 0);
DstRect := SrcRect;
DstRect := ZeroTopLeftRect(DstRect);
OffsetRect(DstRect, 640 - 48, YPos_Credits);
BackBuffer.DrawTo(ScreenImg.Bitmap, DstRect, DstRect);
RightLemmingAnimation.DrawTo(ScreenImg.Bitmap, DstRect, SrcRect);
end;
procedure TGameMenuScreen.SetNextCredit;
var
TextSize: Integer;
begin
TextX := 33 * 16;
if CreditList.Count = 0 then
begin
CreditString := '';
Exit;
end;
Inc(CreditIndex);
if CreditIndex > CreditList.Count - 1 then
CreditIndex := 0;
// set new string
CreditString := CreditList[CreditIndex];
Pausing := False;
PausingDone := False;
TextSize := Length(CreditString) * Font_Width;
TextPauseX := (Reel_Width - TextSize) div 2;
TextGoneX := -TextSize;// + 10 * Font_Width;
end;
procedure TGameMenuScreen.DrawReel;//(aReelShift, aTextX: Integer);
{-------------------------------------------------------------------------------
Drawing of the moving credits. aShift = the reel shift which is wrapped every
other 16 pixels to zero.
-------------------------------------------------------------------------------}
var
// X: Integer;
R: TRect;
// S: string;
begin
// X := 48;
R := Reel.BoundsRect;
R.Left := ReelShift;
R.Right := R.Left + ReelLetterBoxCount * 16 ;
// S := Copy(CurrentCreditString, aStringShift + 1, 50);
// copy reel, draw text on it, draw to screen
// ReelBuffer.Assign(Reel);
Reel.DrawTo(ReelBuffer, ReelShift, 0);
(*
DrawPurpleText(ReelBuffer,
// Copy(CurrentCreditString, FirstChar, 50),
'1234567890123456789012345678901234',
aTextPosition, 0);//48, YPos_Credits);
*)
DrawPurpleText(ReelBuffer, CreditString, TextX, 0);
// DrawPurpleText(ReelBuffer, 'Scrolling credits...', 13 * 16, 0);
// DrawPurpleText(ReelBuffer, 'Volker Oth, ccexplore and Mindless', 0, 0);
// ReelBuffer.DrawTo(ScreenImg.Bitmap, 48, YPos_Credits, R);
ReelBuffer.DrawTo(ScreenImg.Bitmap, 48, YPos_Credits);
// ScreenImg.Update;
end;
procedure TGameMenuScreen.Application_Idle(Sender: TObject; var Done: Boolean);
{-------------------------------------------------------------------------------
Animation of credits.
- 34 characters fit into the reel.
- text scolls from right to left. when one line is centered into the reel,
scrolling is paused for a while.
-------------------------------------------------------------------------------}
var
CurrTime: Cardinal;
begin
if not CanAnimate or ScreenIsClosing then
Exit;
Sleep(1);
Done := False;
CurrTime := TimeGetTime;
if UserPausing then
Exit;
{ check end reading pause }
if Pausing then
begin
if CurrTime > PrevTime + ReadingPauseMS then
begin
PrevTime := CurrTime;
Pausing := False;
PausingDone := True; // we only pause once per text
end;
Exit;
end;
{ update frames }
if CurrTime > PrevTime + FrameTimeMS then
begin
PrevTime := CurrTime;
{ workerlemmings animation has 16 frames }
Inc(CurrentFrame);
if CurrentFrame >= 15 then
CurrentFrame := 0;
{ text + reel }
Dec(ReelShift, 4);
if ReelShift <= - 16 then
ReelShift := 0;
Dec(TextX, 4);
if TextX < TextGoneX then
begin
SetNextCredit;
//TextX := 33 * 16;
end;
if not PausingDone then
begin
// if text can be centered then pause if we are there
if TextPauseX >= 0 then
if TextX <= TextPauseX then
Pausing := True;
end;
DrawWorkerLemmings(CurrentFrame);
DrawReel;//(ReelShift, TextX);
end;
end;
procedure TGameMenuScreen.CloseScreen(aNextScreen: TGameScreenType);
begin
inherited CloseScreen(aNextScreen);
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpAsn1Object;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
SysUtils,
ClpCryptoLibTypes,
ClpIProxiedInterface,
ClpAsn1Encodable;
resourcestring
SExtraData = 'Extra Data Found After Object';
SUnRecognizedObjectStream = 'Cannot Recognise Object in Stream';
SUnRecognizedObjectByteArray = 'Cannot Recognise Object in ByteArray';
type
TAsn1Object = class abstract(TAsn1Encodable, IAsn1Object)
strict protected
function Asn1Equals(const asn1Object: IAsn1Object): Boolean;
virtual; abstract;
function Asn1GetHashCode(): Int32; virtual; abstract;
public
/// <summary>Create a base ASN.1 object from a byte array.</summary>
/// <param name="data">The byte array to parse.</param>
/// <returns>The base ASN.1 object represented by the byte array.</returns>
/// <exception cref="IOException">
/// If there is a problem parsing the data, or parsing an object did not exhaust the available data.
/// </exception>
class function FromByteArray(const data: TCryptoLibByteArray)
: IAsn1Object; static;
/// <summary>Read a base ASN.1 object from a stream.</summary>
/// <param name="inStr">The stream to parse.</param>
/// <returns>The base ASN.1 object represented by the byte array.</returns>
/// <exception cref="IOException">If there is a problem parsing the data.</exception>
class function FromStream(inStr: TStream): IAsn1Object; static;
function ToAsn1Object(): IAsn1Object; override;
procedure Encode(const derOut: TStream); virtual; abstract;
function CallAsn1Equals(const obj: IAsn1Object): Boolean;
function CallAsn1GetHashCode(): Int32;
end;
implementation
uses
// included here to avoid circular dependency :)
ClpAsn1InputStream;
{ TAsn1Object }
function TAsn1Object.CallAsn1Equals(const obj: IAsn1Object): Boolean;
begin
result := Asn1Equals(obj);
end;
function TAsn1Object.CallAsn1GetHashCode: Int32;
begin
result := Asn1GetHashCode();
end;
class function TAsn1Object.FromByteArray(const data: TCryptoLibByteArray)
: IAsn1Object;
var
asn1: TAsn1InputStream;
input: TBytesStream;
begin
try
// used TBytesStream here for one pass creation and population with byte array :)
input := TBytesStream.Create(data);
try
asn1 := TAsn1InputStream.Create(input, System.Length(data));
try
result := asn1.ReadObject();
finally
asn1.Free;
end;
if (input.Position <> input.Size) then
begin
raise EIOCryptoLibException.CreateRes(@SExtraData);
end;
finally
input.Free;
end;
except
on e: EInvalidCastCryptoLibException do
begin
raise EIOCryptoLibException.CreateRes(@SUnRecognizedObjectByteArray);
end;
end;
end;
class function TAsn1Object.FromStream(inStr: TStream): IAsn1Object;
var
asn1Stream: TAsn1InputStream;
begin
asn1Stream := TAsn1InputStream.Create(inStr);
try
try
result := asn1Stream.ReadObject();
except
on e: EInvalidCastCryptoLibException do
begin
raise EIOCryptoLibException.CreateRes(@SUnRecognizedObjectStream);
end;
end;
finally
asn1Stream.Free;
end;
end;
function TAsn1Object.ToAsn1Object: IAsn1Object;
begin
result := Self as IAsn1Object;
end;
end.
|
unit WinSockRDOServerClientConnection;
interface
uses
SmartThreads,
Classes,
ComObj,
Windows,
RDOInterfaces,
SocketComp,
SyncObjs,
RDOQueries;
type
TWinSockRDOServerClientConnection =
class(TInterfacedObject, IRDOConnection, IRDOServerClientConnection)
private
fUnsentQueries : TList;
fSentQueries : TList;
fSenderThread : TSmartThread;
fUnsentQueriesLock : TCriticalSection;
fSentQueriesLock : TCriticalSection;
fSocket : TCustomWinSocket;
fUnsentQueryWaiting : THandle;
fTerminateEvent : THandle;
fOnConnect : TRDOClientConnectEvent;
fOnDisconnect : TRDOClientDisconnectEvent;
protected
function Alive : boolean;
function SendReceive(Query : TRDOQuery; out ErrorCode : integer; TimeOut : integer) : TRDOQuery; stdcall;
procedure Send(Query : TRDOQuery); stdcall;
function GetLocalAddress : string; stdcall;
function GetLocalHost : string; stdcall;
function GetLocalPort : integer; stdcall;
function GetOnConnect : TRDOClientConnectEvent;
procedure SetOnConnect(OnConnectHandler : TRDOClientConnectEvent);
function GetOnDisconnect : TRDOClientDisconnectEvent;
procedure SetOnDisconnect(OnDisconnectHandler : TRDOClientDisconnectEvent);
protected
procedure OnQueryResultArrival(Query : TRDOQuery);
private
procedure ReleaseQueues;
public
constructor Create(Socket : TCustomWinSocket);
destructor Destroy; override;
end;
implementation
uses
SysUtils,
RDOUtils,
RDOProtocol,
{$IFDEF Logs}
LogFile,
{$ENDIF}
ErrorCodes;
// Query id generation routines and variables
var
LastQueryId : word = 0;
function GenerateQueryId : integer;
begin
Result := LastQueryId;
LastQueryId := (LastQueryId + 1) mod 65536
end;
type
PQueryToSend = ^TQueryToSend;
TQueryToSend =
record
Query : TRDOQuery;
WaitForAnsw : boolean;
Result : TRDOQuery;
Event : THandle;
ErrorCode : integer;
end;
// Delphi classes associated to the threads in charge of the connection
type
TSenderThread =
class(TSmartThread)
private
fConnection : TWinSockRDOServerClientConnection;
constructor Create(theConnection : TWinSockRDOServerClientConnection);
protected
procedure Execute; override;
end;
// TSenderThread
constructor TSenderThread.Create(theConnection : TWinSockRDOServerClientConnection);
begin
fConnection := theConnection;
inherited Create(false)
end;
procedure TSenderThread.Execute;
var
QueryToSend : PQueryToSend;
SenderThreadEvents : array [1..2] of THandle;
begin
with fConnection do
begin
SenderThreadEvents[1] := fUnsentQueryWaiting;
SenderThreadEvents[2] := fTerminateEvent;
while not Terminated do
begin
WaitForMultipleObjects(2, @SenderThreadEvents[1], false, INFINITE);
if not Terminated
then
begin
fUnsentQueriesLock.Acquire;
try
if fUnsentQueries.Count <> 0
then
begin
QueryToSend := fUnsentQueries[0];
fUnsentQueries.Delete(0)
end
else
begin
QueryToSend := nil;
ResetEvent(fUnsentQueryWaiting)
end
finally
fUnsentQueriesLock.Release
end;
end
else QueryToSend := nil;
if QueryToSend <> nil
then
if QueryToSend.WaitForAnsw
then
begin
fSentQueriesLock.Acquire;
try
fSentQueries.Add(QueryToSend)
finally
fSentQueriesLock.Release
end;
try
if fSocket.Connected
then SendQuery(QueryToSend.Query, fSocket);
except
{$IFDEF Logs}
LogThis('Error sending query');
{$ENDIF}
fSentQueriesLock.Acquire;
try
fSentQueries.Remove(QueryToSend)
finally
fSentQueriesLock.Release
end;
QueryToSend.ErrorCode := errSendError;
SetEvent(QueryToSend.Event)
end
end
else
begin
try
if fSocket.Connected
then SendQuery(QueryToSend.Query, fSocket);
except
{$IFDEF Logs}
LogThis('Error sending query');
{$ENDIF}
end;
QueryToSend.Query.Free;
dispose(QueryToSend);
end;
end
end
end;
// TWinSockRDOServerClientConnection
constructor TWinSockRDOServerClientConnection.Create(Socket : TCustomWinSocket);
begin
inherited Create;
fSocket := Socket;
fUnSentQueriesLock := TCriticalSection.Create;
fSentQueriesLock := TCriticalSection.Create;
fUnsentQueries := TList.Create;
fSentQueries := TList.Create;
//fSenderThread := TSenderThread.Create(Self);
fUnsentQueryWaiting := CreateEvent(nil, true, false, nil);
fTerminateEvent := CreateEvent(nil, true, false, nil)
end;
destructor TWinSockRDOServerClientConnection.Destroy;
begin
SetEvent(fTerminateEvent);
fSenderThread.Free;
ReleaseQueues;
fUnSentQueriesLock.Free;
fSentQueriesLock.Free;
fUnsentQueries.Free;
fSentQueries.Free;
CloseHandle(fUnsentQueryWaiting);
CloseHandle(fTerminateEvent);
inherited
end;
procedure TWinSockRDOServerClientConnection.ReleaseQueues;
var
i : integer;
QueryToSend : PQueryToSend;
begin
try
fUnsentQueriesLock.Enter;
try
for i := 0 to pred(fUnsentQueries.Count) do
TRDOQuery(fUnsentQueries[i]).Free;
fUnsentQueries.Clear;
finally
fUnsentQueriesLock.Leave;
end;
except
end;
try
fSentQueriesLock.Enter;
try
for i := 0 to pred(fSentQueries.Count) do
begin
QueryToSend := PQueryToSend(fUnsentQueries[i]);
QueryToSend.Query.Free;
QueryToSend.Result.Free;
dispose(QueryToSend);
end;
fSentQueries.Clear;
finally
fSentQueriesLock.Leave;
end;
except
end;
end;
function TWinSockRDOServerClientConnection.Alive : boolean;
begin
result := fSocket.Connected;
end;
function TWinSockRDOServerClientConnection.SendReceive(Query : TRDOQuery; out ErrorCode : integer; TimeOut : integer) : TRDOQuery;
var
theQuery : PQueryToSend;
Events : array [1..2] of THandle;
begin
result := nil;
try
new(theQuery);
try
Query.Id := GenerateQueryId;
theQuery.Query := Query;
{$IFDEF Logs}
LogThis('Sending and waiting: ' + Query.ToStr);
{$ENDIF}
theQuery.WaitForAnsw := true;
theQuery.Result := nil;
theQuery.Event := CreateEvent(nil, false, false, nil);
try
theQuery.ErrorCode := errNoError;
try
fUnsentQueriesLock.Acquire;
try
fUnsentQueries.Add(theQuery);
if fUnsentQueries.Count = 1
then SetEvent(fUnsentQueryWaiting);
// create the thread when needed
if fSenderThread = nil
then fSenderThread := TSenderThread.Create(self);
finally
fUnsentQueriesLock.Release;
end;
Events[1] := theQuery.Event;
Events[2] := fTerminateEvent;
case WaitForMultipleObjects(2, @Events[1], false, TimeOut) of
WAIT_OBJECT_0 :
begin
result := theQuery.Result;
ErrorCode := theQuery.ErrorCode;
{$IFDEF Logs}
if result <> nil
then LogThis('Result : ' + result.ToStr)
else LogThis('Result : Unknown');
{$ENDIF}
end;
WAIT_OBJECT_0 + 1 :
ErrorCode := errQueryTimedOut;
else // WAIT_TIMEOUT :
begin
{$IFDEF Logs}
LogThis('Query timed out');
{$ENDIF}
ErrorCode := errQueryTimedOut;
fSentQueriesLock.Acquire;
try
fSentQueries.Remove(theQuery)
finally
fSentQueriesLock.Release
end;
end;
end;
except
ErrorCode := errQueryQueueOverflow;
end
finally
CloseHandle(theQuery.Event)
end
finally
Dispose(theQuery)
end
except
ErrorCode := errUnknownError;
end;
end;
procedure TWinSockRDOServerClientConnection.Send(Query : TRDOQuery);
var
theQuery : PQueryToSend;
begin
New(theQuery);
theQuery.Query := Query;
{$IFDEF Logs}
LogThis('Sending : ' + Query.ToStr);
{$ENDIF}
theQuery.WaitForAnsw := false;
theQuery.Result := nil;
fUnsentQueriesLock.Acquire;
try
try
fUnsentQueries.Add(theQuery);
if fUnsentQueries.Count = 1
then
SetEvent(fUnsentQueryWaiting)
except
Dispose(theQuery)
end
finally
fUnsentQueriesLock.Release
end
end;
function TWinSockRDOServerClientConnection.GetLocalAddress : string;
begin
Result := fSocket.LocalAddress
end;
function TWinSockRDOServerClientConnection.GetLocalHost : string;
begin
Result := fSocket.LocalHost
end;
function TWinSockRDOServerClientConnection.GetLocalPort : integer;
begin
Result := fSocket.LocalPort
end;
function TWinSockRDOServerClientConnection.GetOnConnect : TRDOClientConnectEvent;
begin
result := fOnConnect;
end;
procedure TWinSockRDOServerClientConnection.SetOnConnect(OnConnectHandler : TRDOClientConnectEvent);
begin
fOnConnect := OnConnectHandler;
end;
function TWinSockRDOServerClientConnection.GetOnDisconnect : TRDOClientDisconnectEvent;
begin
result := fOnDisconnect;
end;
procedure TWinSockRDOServerClientConnection.SetOnDisconnect(OnDisconnectHandler : TRDOClientDisconnectEvent);
begin
fOnDisconnect := OnDisconnectHandler;
end;
procedure TWinSockRDOServerClientConnection.OnQueryResultArrival(Query : TRDOQuery);
function FindServicedQuery : PQueryToSend;
var
QueryIdx : integer;
SentQueries : integer;
begin
SentQueries := fSentQueries.Count;
QueryIdx := 0;
while (QueryIdx < SentQueries) and (Query.Id <> PQueryToSend(fSentQueries[QueryIdx]).Query.Id) do
inc(QueryIdx);
if QueryIdx < SentQueries
then result := PQueryToSend(fSentQueries[QueryIdx])
else result := nil;
end;
var
ServicedQuery : PQueryToSend;
begin
fSentQueriesLock.Acquire;
try
ServicedQuery := FindServicedQuery;
if ServicedQuery <> nil
then
begin
fSentQueries.Remove(ServicedQuery);
ServicedQuery.ErrorCode := GetQueryErrorCode(Query); //errNoError;
ServicedQuery.Result := Query;
SetEvent(ServicedQuery.Event);
end
else Query.Free;
finally
fSentQueriesLock.Release
end
end;
end.
|
unit CacheObjects;
interface
uses
Windows, Classes, SysUtils, FileCtrl, SpecialChars, CacheProperties;
const
UnassignedRoot = '\';
// Cache root path
function GetCacheRootPath : string;
procedure SetCacheRootPath(const aPath : string);
procedure ForceFolder(const Path : string);
const
DefaultObjectName = 'object.five';
FiveExt = '.five';
AllFiveObjects = '*.five';
LinkMarkPos = 2;
LinkMark = 'LNK';
ArchiveLinkMark = 'ALNK';
FolderLinkMark = 'FLNK';
const
onArchives = faArchive;
onFolders = faDirectory;
onBoth = onArchives or onFolders;
type
TCacheIOResult = set of (ioFileDoesntExist, ioTimeOutRead, ioTimeOutWrite, ioExpiredTTL);
TIteratorOptions = integer;
TCachedObject = class; // Image of an object stored in a file or folder.
TFolderIterator = class; // Iterator on a folder
TCachedObject =
class
public
constructor Create(const aPath : string; TheProperties : TStrings);
constructor Open(const aPath : string; Locked : boolean);
constructor Init(const aPath : string);
destructor Destroy; override;
procedure Delete;
private
procedure RemoveFolder(const ThePath : string);
private
fRelPath : string; // Relative path
fProperties : TCacheProperties;// TStrings; // List containing the pairs Prop=Value
fLocked : boolean; // Determines if the files is Locked
fStream : TStream; // File stream, nil if not locked
fIOResult : TCacheIOResult; // Result of the las file operation
fRecLinks : boolean; // Indicates whether or not this object will record the links to allow undo
public
procedure SetProperty(const Name, Value : string);
function GetProperty(const Name : string) : string;
function GetName : string;
function GetPath : string;
procedure SetPath(const aPath : string);
function GetAbsolutePath : string;
function GetErrorCode : integer;
function GetValues : TStrings;
public
property Values : TStrings read GetValues;//fProperties;
property Properties[const name : string] : string read GetProperty write SetProperty; default;
property Name : string read GetName;
property Path : string read GetPath write SetPath;
property RelPath : string read fRelPath;
property AbsolutePath : string read GetAbsolutePath;
property IOResult : TCacheIOResult read fIOResult write fIOResult;
property Locked : boolean read fLocked;
property RecLinks : boolean read fRecLinks write fRecLinks;
property ErrorCode : integer read GetErrorCode;
public
function IsArchive : boolean;
function IsFolder : boolean;
function CreateFolder(const FolderName : string) : boolean;
function ContainsFolder(const FolderName : string) : boolean;
function GetFolderIterator(const FolderName : string) : TFolderIterator;
procedure Flush;
procedure Lock;
procedure Unlock;
procedure UpdateProperties(Props : TStrings);
procedure ActivateDictionary(Activate: WordBool);
private
function CreateLink(const aPath : string) : boolean;
function DeleteLink(const aPath : string) : boolean;
public
procedure CreateLinks;
procedure DeleteLinks;
procedure DeleteFolders;
procedure ClearProperties;
protected
function GetTargetPath(const aPath : string) : string;
function GetObjectLinkName : string;
procedure InitProperties;
function LoadProperties : boolean;
function SaveProperties : boolean;
end;
TFolderIterator =
class
public
constructor Create(const aPath, TheWildCards : string; TheOptions : integer);
destructor Destroy; override;
private
fPath : string; // Absolute path
fWildCards : string; // *.?.* etc.
fCurrent : string; // Name of the current file or folder
fOptions : TIteratorOptions; // Kind of files to iterate on
fSearchRec : TSearchRec; // Search struct
fEmpty : boolean; // True if no file was found
public
procedure Reset;
function Next : boolean;
function IsFolder : boolean;
private
procedure SetOptions(Options : TIteratorOptions);
function GetFullPath : string;
public
property Options : TIteratorOptions read fOptions write SetOptions;
property Empty : boolean read fEmpty;
property Current : string read fCurrent;
property FullPath : string read GetFullPath;
end;
function RemoveFullPath(const Path : string) : boolean;
implementation
uses
ShellAPI, CacheNameUtils, SyncObjs, CompStringsParser, CacheCommon,
CacheRegistryData, CacheLinks;
const
WriteFailTimeOut = 25; // 5 seconds
ReadFailTimeOut = 25; // 5 seconds
DeleteFailTimeOut = 15; // 5 seconds
NoIndex = -1;
var
CacheRootPath : string = UnassignedRoot;
function GetCacheRootPath : string;
begin
if CacheRootPath = UnassignedRoot
then SetCacheRootPath(CacheRegistryData.ReadCacheValue('', 'RootPath'));
result := CacheRootPath;
end;
procedure SetCacheRootPath(const aPath : string);
begin
if aPath[length(aPath)] = '\'
then CacheRootPath := aPath
else CacheRootPath := aPath + '\';
end;
procedure ForceFolder(const Path : string);
begin
if not DirectoryExists(Path)
then ForceDirectories(Path);
end;
function RemoveFullPath(const Path : string) : boolean;
var
FileOp : TSHFileOpStruct;
tmp : array[0..MAX_PATH] of char;
begin
fillchar(tmp, sizeof(tmp), 0);
strpcopy(tmp, Path);
// If Path is a folder the last '\' must be removed.
if Path[length(Path)] = '\'
then tmp[length(Path)-1] := #0;
with FileOp do
begin
wFunc := FO_DELETE;
Wnd := 0;
pFrom := tmp;
pTo := nil;
fFlags := FOF_NOCONFIRMATION or FOF_SILENT or FOF_NOERRORUI;
hNameMappings := nil;
end;
try
if DirectoryExists(Path)
then result := SHFileOperation( FileOp ) = 0
else result := true;
except
result := false;
end;
end;
procedure CloseSearch(var Search : TSearchRec);
begin
if Search.FindHandle <> INVALID_HANDLE_VALUE
then
begin
FindClose(Search);
Search.FindHandle := INVALID_HANDLE_VALUE
end;
end;
// TCachedObject
constructor TCachedObject.Create(const aPath : string; TheProperties : TStrings);
var
AbsPath : string;
refLnks : boolean;
begin
inherited Create;
fRelPath := aPath;
if FileExists(Path)
then
begin
fProperties := TCacheProperties.Create;//TStringList.Create;
InitProperties;
refLnks := fProperties.Values[ppRefLinks] <> '';
if (TheProperties = nil) or (refLnks and (CompareText(fProperties.Values[LinkName], TheProperties.Values[LinkName]) <> 0))
then DeleteLinks;
fProperties.Free;
end
else
begin
AbsPath := AbsolutePath;
ForceFolder(ExtractFilePath(AbsPath));
end;
if TheProperties <> nil
then
begin
fProperties := TCacheProperties.Create;
fProperties.AssignProperties(TheProperties) // := TheProperties
end
else fProperties := TCacheProperties.Create;//TStringList.Create;
{if TheProperties <> nil
then fProperties := TheProperties
else fProperties := TStringList.Create;}
end;
constructor TCachedObject.Open(const aPath : string; Locked : boolean);
begin
inherited Create;
fLocked := Locked;
fProperties := TCacheProperties.Create;//TStringList.Create;
SetPath(aPath);
end;
constructor TCachedObject.Init(const aPath : string);
begin
inherited Create;
fProperties := TCacheProperties.Create;//TStringList.Create;
fRelPath := GetTargetPath(aPath);
end;
destructor TCachedObject.Destroy;
begin
fProperties.Free;
fStream.Free;
inherited;
end;
procedure TCachedObject.Delete;
var
DelFails : integer;
FullPath : string;
begin
try
FullPath := AbsolutePath;
if IsFolder
then
begin
if DirectoryExists(FullPath)
then RemoveFolder(FullPath)
end
else
if FileExists(FullPath)
then
begin
DelFails := 0;
while (DelFails < DeleteFailTimeOut) and not DeleteFile(FullPath) do
begin
inc(DelFails);
Sleep(10); // Sleep 0.01 seconds. This might not occur
end;
end;
DeleteLinks;
DeleteFolders;
finally
Destroy;
end;
end;
procedure TCachedObject.RemoveFolder(const ThePath : string);
var
DelFails : integer;
begin
DelFails := 0;
while (DelFails < DeleteFailTimeOut) and not RemoveFullPath(ThePath) do
begin
inc(DelFails);
Sleep(10); // Sleep 0.01 seconds. This might not occur
end;
end;
procedure TCachedObject.CreateLinks;
var
Links : string;
p : integer;
s : string;
link : string;
begin
if fProperties <> nil
then
begin
Links := fProperties.Values[LinkName];
if Links <> ''
then
begin
p := 1;
s := GetNextStringUpTo(Links, p, LinkSep);
link := '';
while s <> '' do
begin
if s[length(s)] = '\'
then
begin
if link = ''
then link := GetObjectLinkName;
CreateLink(s + link);
end
else CreateLink(s);
s := GetNextStringUpTo(Links, p, LinkSep);
end;
end;
end;
end;
procedure TCachedObject.DeleteLinks;
var
Links : string;
p : integer;
s : string;
begin
if fProperties <> nil
then
begin
Links := fProperties.Values[LinkName];
if Links <> ''
then
begin
p := 1;
s := GetNextStringUpTo(Links, p, LinkSep);
while s <> '' do
begin
DeleteLink(s);
s := GetNextStringUpTo(Links, p, LinkSep);
end;
end;
end;
end;
procedure TCachedObject.DeleteFolders;
var
Folders : string;
p : integer;
s : string;
begin
if fProperties <> nil
then
begin
Folders := fProperties.Values[DelPName];
if Folders <> ''
then
begin
p := 1;
s := GetNextStringUpTo(Folders, p, LinkSep);
while s <> '' do
begin
RemoveFullPath(CacheRootPath + s);
s := GetNextStringUpTo(Folders, p, LinkSep);
end;
end;
end;
end;
function TCachedObject.CreateLink(const aPath : string) : boolean;
var
ActPath : string;
FPath : string;
flName : string;
flInfo : string;
i : integer;
cnt : integer;
len : integer;
begin
ActPath := CacheRootPath + aPath;
FPath := ExtractFilePath(ActPath);
flName := ExtractFileName(ActPath);
flInfo := '';
if UpperCase(copy(flName, 1, 3)) = 'MAP'
then
begin
i := 1;
cnt := 0;
len := length(flName);
while (i <= len) and (cnt < 2) do
begin
if flName[i] = BackSlashChar
then inc(cnt);
inc(i);
end;
if cnt = 2
then
begin
flInfo := copy(flName, i, len - i + 1);
flName := copy(flName, 4, i - 4);
end;
end;
ForceFolder(FPath);
FPath := FPath + flName;
if CacheLinks.CreateLink(FPath, flInfo, 5) and fRecLinks
then
begin
CacheLinks.RecordLinks(FPath, false);
result := true;
end
else result := false;
end;
function TCachedObject.DeleteLink(const aPath : string) : boolean;
var
link : string;
ActPath : string;
FPath : string;
flName : string;
i : integer;
cnt : integer;
len : integer;
begin
if aPath[length(aPath)] <> '\' //Worlds\Zyrane\Map\256}320\MAP315}364}Companies}Gaba Inc.five}Chemical Plant 7{315{364.five}
then
begin
ActPath := CacheRootPath + aPath;
FPath := ExtractFilePath(ActPath); //Worlds\Zyrane\Map\256}320\
flName := ExtractFileName(ActPath); //MAP315}364}Companies}Gaba Inc.five}Chemical Plant 7{315{364.five}
if UpperCase(copy(flName, 1, 3)) = 'MAP'
then
begin
i := 1;
cnt := 0;
len := length(flName);
while (i <= len) and (cnt < 2) do
begin
if flName[i] = BackSlashChar
then inc(cnt);
inc(i);
end;
if cnt = 2
then flName := copy(flName, 4, i - 4);
link := FPath + flName;
end
else link := ActPath;
end
else link := CacheRootPath + aPath + GetObjectLinkName;
result := CacheLinks.DeleteLink(link, 5);
end;
procedure TCachedObject.ClearProperties;
begin
fProperties.Clear;
end;
function TCachedObject.GetName : string;
var
len : integer;
aux : pchar;
tmp : string;
eps : integer;
begin
len := length(Path);
if len > 0
then
begin
aux := pchar(pchar(Path) + len - 1);
if aux[0] = '\'
then dec(aux);
while (aux >= pchar(Path)) and (aux[0] <> '\') do
dec(aux);
tmp := pchar(aux + 1);
eps := pos(FiveExt, tmp);
if eps = 0
then result := tmp
else result := copy(tmp, 1, eps - 1);
end
else result := '';
end;
function TCachedObject.GetPath : string;
begin
if IsFolder
then result := AbsolutePath + DefaultObjectName
else result := AbsolutePath;
end;
procedure TCachedObject.SetPath(const aPath : string);
begin
fRelPath := GetTargetPath(aPath);
if not IsFolder and DirectoryExists(AbsolutePath)
then fRelPath := fRelPath + '\';
fProperties.Clear;
fStream.Free;
fStream := nil;
fIOResult := [];
InitProperties;
end;
function TCachedObject.GetAbsolutePath : string;
begin
result := GetCacheRootPath + fRelPath;
end;
function TCachedObject.GetErrorCode : integer;
begin
result := 0;
if ioFileDoesntExist in fIOResult
then result := result or 1;
if ioTimeOutRead in fIOResult
then result := result or 2;
if ioTimeOutWrite in fIOResult
then result := result or 4;
if ioExpiredTTL in fIOResult
then result := result or 8;
end;
function TCachedObject.IsArchive : boolean;
begin
result := (fRelPath <> '') and (fRelPath[length(fRelPath)] <> '\');
end;
function TCachedObject.IsFolder : boolean;
begin
result := (fRelPath <> '') and (fRelPath[length(fRelPath)] = '\');
end;
function TCachedObject.CreateFolder(const FolderName : string) : boolean;
var
FullPath : string;
begin
if IsFolder
then
begin
FullPath := AbsolutePath + FolderName;
ForceFolder(FullPath);
result := DirectoryExists(FullPath);
end
else result := false;
end;
function TCachedObject.ContainsFolder(const FolderName : string) : boolean;
begin
result := IsFolder and DirectoryExists(AbsolutePath + FolderName);
end;
function TCachedObject.GetFolderIterator(const FolderName : string) : TFolderIterator;
begin
if ContainsFolder(FolderName)
then result := TFolderIterator.Create(AbsolutePath + FolderName, AllFiveObjects, onBoth)
else result := nil;
end;
function TCachedObject.GetValues: TStrings;
begin
Result := fProperties.StringList;
end;
procedure TCachedObject.SetProperty(const Name, Value : string);
begin
fProperties.Values[Name] := Value;
end;
function TCachedObject.GetProperty(const Name : string) : string;
begin
result := fProperties.Values[Name];
end;
procedure TCachedObject.Flush;
var
WriteFails : integer;
begin
WriteFails := 0;
while (WriteFails < WriteFailTimeOut) and not SaveProperties do
begin
Sleep(10); // Sleep 0.01 seconds
inc(WriteFails);
end;
if WriteFails = WriteFailTimeOut
then fIOResult := fIOResult + [ioTimeOutWrite];
CreateLinks;
end;
procedure TCachedObject.Lock;
begin
fLocked := true;
try
if fStream = nil
then fStream := TFileStream.Create(Path, fmOpenReadWrite or fmShareExclusive);
except
end;
end;
procedure TCachedObject.Unlock;
begin
fLocked := false;
fStream.Free;
fStream := nil;
end;
procedure TCachedObject.ActivateDictionary(Activate: WordBool);
begin
if Activate
then
fProperties.ActivateDictionary
else
fProperties.DeactivateDictionary
end;
procedure TCachedObject.UpdateProperties(Props : TStrings);
var
i : integer;
//index : integer;
Name : string;
P : integer;
begin
for i := 0 to pred(Props.Count) do
begin
Name := Props.Names[i];
if fProperties.Values[Name] <> ''
then
begin
P := AnsiPos('=',Props[i]);
fProperties.Values[Name]:= copy(Props[i],P+1,MaxInt);
end
else
begin
fProperties.Add(Props[i]);
end;
{Name := Props.Names[i];
index := fProperties.IndexOfName(Name);
if index <> NoIndex
then fProperties[index] := Props[i]
else fProperties.Add(Props[i]);}
end;
end;
function TCachedObject.GetTargetPath(const aPath : string) : string;
var
FileName : string;
Link : string;
begin
FileName := ExtractFileName(aPath);
if pos(LinkMark, FileName) = LinkMarkPos
then
begin
Link := copy(FileName, length(FolderLinkMark) + 1, length(FileName) - length(LinkMark));
TranslateChars(Link, BackSlashChar, '\');
if (FileName[1] = 'F') or (FileName[1] = 'f')
then result := Link + '\'
else result := Link;
end
else result := aPath;
end;
function TCachedObject.GetObjectLinkName : string;
begin
if IsFolder
then result := FolderLinkMark + copy(fRelPath, 1, length(fRelPath)-1)
else result := ArchiveLinkMark + fRelPath;
TranslateChars(result, '\', BackSlashChar);
end;
procedure TCachedObject.InitProperties;
var
ReadFails : integer;
begin
if FileExists(Path)
then
begin
ReadFails := 0;
while (ReadFails < ReadFailTimeOut) and not LoadProperties do
begin
inc(ReadFails);
Sleep(100); // Sleep 0.05 seconds
end;
if ReadFails = ReadFailTimeOut
then fIOResult := fIOResult + [ioTimeOutRead];
end
else fIOResult := fIOResult + [ioFileDoesntExist];
end;
function TCachedObject.LoadProperties : boolean;
var
TmpPath : string;
begin
TmpPath := Path;
try
if fLocked
then fStream := TFileStream.Create(TmpPath, fmOpenReadWrite or fmShareExclusive)
else fStream := TFileStream.Create(TmpPath, fmOpenRead);
try
fProperties.Clear;
fProperties.LoadFromStream(fStream);
result := true;
finally
if not fLocked
then
begin
fStream.Free;
fStream := nil;
end;
end;
except
result := false;
end
end;
function TCachedObject.SaveProperties : boolean;
var
aux : string;
begin
try
aux := Path;
if fStream <> nil
then fStream.Seek(soFromBeginning, 0)
else
begin
ForceFolder(ExtractFilePath(aux));
fStream := TFileStream.Create(aux, fmCreate or fmShareExclusive);
end;
try
fProperties.SaveToStream(fStream);
result := true;
finally
fStream.Free;
fStream := nil;
end;
except
result := false;
end;
end;
// TFolderIterator
constructor TFolderIterator.Create(const aPath, TheWildCards : string; TheOptions : integer);
begin
inherited Create;
fWildCards := TheWildCards;
if aPath[length(aPath)] = '\'
then fPath := aPath
else fPath := aPath + '\';
fOptions := TheOptions;
fSearchRec.FindHandle := INVALID_HANDLE_VALUE; // Uuuf!!
Reset;
end;
destructor TFolderIterator.Destroy;
begin
CloseSearch(fSearchRec);
inherited;
end;
procedure TFolderIterator.Reset;
begin
CloseSearch(fSearchRec);
fEmpty := FindFirst(fPath + fWildCards, fOptions, fSearchRec) <> 0;
if not fEmpty
then
begin
fCurrent := fSearchRec.Name;
if (fSearchRec.Attr and fOptions = 0) or ((Lowercase(fCurrent) = DefaultObjectName) or (fCurrent = '.') or (fCurrent = '..'))
then fEmpty := not Next;
end
else
begin
fCurrent := '';
CloseSearch(fSearchRec);
end;
end;
function TFolderIterator.Next : boolean;
begin
if FindNext(fSearchRec) = 0
then
begin
fCurrent := fSearchRec.Name;
if (fSearchRec.Attr and fOptions = 0) or ((Lowercase(fCurrent) = DefaultObjectName) or (fCurrent = '.') or (fCurrent = '..'))
then result := Next
else result := true;
end
else
begin
fCurrent := '';
result := false;
end;
if not result
then CloseSearch(fSearchRec);
end;
function TFolderIterator.IsFolder : boolean;
begin
result := fSearchRec.Attr = onFolders;
end;
procedure TFolderIterator.SetOptions(Options : TIteratorOptions);
begin
fOptions := Options;
Reset;
end;
function TFolderIterator.GetFullPath : string;
begin
if fSearchRec.Attr = onFolders
then result := fPath + fCurrent + '\'
else result := fPath + fCurrent;
end;
end.
|
{*********************************************************************** }
{ File: VTCheckList.pas }
{ }
{ Purpose: }
{ source file to demonstrate how to get started with VT (2) }
{ <-- Generic CheckListbox selection Form - no node data used --> }
{ }
{ Module Record: }
{ }
{ -------- -- -------------------------------------- }
{ 05-Nov-2002 TC Created (tomc@gripsystems.com) }
{**********************************************************************}
unit VTCheckList;
{$mode delphi}
{$H+}
interface
uses
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, VirtualTrees, ImgList, ExtCtrls, StdCtrls, Buttons, LResources;
type
TfrmVTCheckList =
class(TForm)
Panel1 : TPanel;
VT : TVirtualStringTree;
panBase : TPanel;
btnOk: TButton;
btnCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure VTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
procedure VTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: String);
procedure VTInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure btnOkClick(Sender: TObject);
private
FCaptions : TStringList;
function GetSelections : string;
end;
procedure DoVTCheckListExample;
function DoVTCheckList( sl : TStringList; var sSelections : string ) : boolean;
implementation
{.$R *.dfm}
procedure DoVTCheckListExample;
var
sl : TStringList;
sSelections : string;
begin
sl := TStringList.Create;
try
sl.Add( 'Willy Wonka' );
sl.Add( 'Bill Gates' );
sl.Add( 'Silly Billy' );
sl.Add( 'Homer Simpson' );
sl.Add( 'Harry Potty' );
sl.Add( 'Dilbert' );
sl.Add( 'Gandalf' );
sl.Add( 'Darth Laugh' );
sl.Add( 'Tim nice-but-dim' );
if DoVTCheckList( sl, sSelections ) then
ShowMessage( Format( 'You selected: %s', [sSelections] ));
finally
sl.Free;
end;
end;
function DoVTCheckList( sl : TStringList; var sSelections : string ) : boolean;
begin
Result := False;
with TfrmVTCheckList.Create(Application) do
begin
try
FCaptions.Assign(sl);
if (ShowModal=mrOk) then
begin
Result := True;
sSelections := GetSelections;
end;
finally
Release;
end;
end;
end;
procedure TfrmVTCheckList.FormCreate(Sender: TObject);
begin
{set up root values + turn on checklist support}
FCaptions := TStringList.Create;
VT.TreeOptions.MiscOptions := VT.TreeOptions.MiscOptions + [toCheckSupport];
end;
procedure TfrmVTCheckList.FormDestroy(Sender: TObject);
begin
FCaptions .Free;
end;
procedure TfrmVTCheckList.FormActivate(Sender: TObject);
begin
VT.RootNodeCount := FCaptions.Count;
end;
procedure TfrmVTCheckList.VTGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
begin
NodeDataSize := 0; {note *** no node data used *** }
end;
procedure TfrmVTCheckList.VTInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
begin
Node.CheckType := ctCheckBox; {we will have checkboxes throughout}
end;
procedure TfrmVTCheckList.VTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: String);
begin
Celltext := FCaptions[Node.Index]; {top-level}
end;
procedure TfrmVTCheckList.btnOkClick(Sender: TObject);
begin
if GetSelections <> '' then
ModalResult := mrOk
else
ShowMessage( 'Please select 1 or more options' );
end;
function TfrmVTCheckList.GetSelections : string;
var
node : PVirtualNode;
begin
Result:= '';
node := VT.RootNode;
while Assigned(Node) do
begin
if node.CheckState in [ csCheckedNormal, csMixedPressed ] then
Result := Result + IntToStr( Node.Index ) + ',';
node := VT.GetNext(node);
end;
{-------------------------------------------------------------
example using 'selected' instead of testing for 'checked'
Node := VT.GetFirstSelected;
while Assigned(Node) do
begin
Result := Result + ',' + IntToStr( Node.Index );
Node := VT.GetNextSelected(Node);
end;
------------------------------------------------------------}
end;
initialization
{$I VTCheckList.lrs}
end.
|
unit untPages;
interface
Uses
// VCL
Windows, Classes, Controls, ExtCtrls,
// This
SizeableForm, TestManager;
type
TPage = class;
TPageClass = class of TPage;
{ TPages }
TPages = class
private
FList: TList;
FPage: TPage;
procedure Clear;
function GetCount: Integer;
procedure InsertItem(AItem: TPage);
procedure RemoveItem(AItem: TPage);
function GetItem(Index: Integer): TPage;
public
constructor Create;
destructor Destroy; override;
procedure ShowPage(APage: TPage);
property Count: Integer read GetCount;
property Page: TPage read FPage write FPage;
property Items[Index: Integer]: TPage read GetItem; default;
end;
{ TPage }
TPage = class(TSizeableForm)
private
FOwner: TPages;
FPages: TPages;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure UpdatePage; virtual;
procedure UpdateObject; virtual;
procedure SetOwner(AOwner: TPages);
function LoadDefaults: Boolean; virtual;
procedure EnableButtons(Value: Boolean); override;
procedure ExecuteCommand(var ResultCode, Count: Integer); virtual;
property Pages: TPages read FPages;
end;
implementation
{ TPages }
constructor TPages.Create;
begin
inherited Create;
FList := TList.Create;
end;
destructor TPages.Destroy;
begin
Clear;
FList.Free;
inherited Destroy;
end;
procedure TPages.Clear;
begin
while Count > 0 do
Items[0].Free;
end;
function TPages.GetCount: Integer;
begin
Result := FList.Count;
end;
function TPages.GetItem(Index: Integer): TPage;
begin
Result := FList[Index];
end;
procedure TPages.InsertItem(AItem: TPage);
begin
FList.Add(AItem);
AItem.FOwner := Self;
end;
procedure TPages.RemoveItem(AItem: TPage);
begin
AItem.FOwner := nil;
FList.Remove(AItem);
end;
procedure TPages.ShowPage(APage: TPage);
// Спрятать страницу и всех ее родителей
procedure HidePageTree(Page: TWinControl);
begin
if Page <> nil then
begin
if (Page is TPage) or (Page is TPanel) then
begin
Page.Visible := False;
if Page is TPage then
TPage(Page).UpdateObject;
if (Page.Parent is TPage) or (Page.Parent is TPanel) then
HidePageTree(Page.Parent);
end;
end;
end;
// Показать страницу и всех ее родителей
procedure ShowPageTree(Page: TWinControl);
begin
if Page <> nil then
begin
if (Page is TPage) or (Page is TPanel) then
begin
Page.Visible := True;
Page.Align := alClient;
if Page is TPage then
(Page as TPage).UpdateObject;
if (Page.Parent is TPage) or (Page.Parent is TPanel) then
begin
ShowPageTree(Page.Parent);
// Предполагается, что дочерняя страничка всегда помещается
// на панель TPanel родительской страницы
if (Page is TPage) and (Page.Parent.Parent is TPage) then
begin
// Сообщаем родительской страничке указатель на текущую
// дочернюю страничку
(Page.Parent.Parent as TPage).Pages.Page := Page as TPage;
end;
end;
end;
end;
end;
begin
if APage <> FPage then
begin
HidePageTree(FPage);
ShowPageTree(APage);
FPage := APage;
end;
end;
{ TPage }
constructor TPage.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPages := TPages.Create;
end;
destructor TPage.Destroy;
begin
SetOwner(nil);
FPages.Free;
inherited Destroy;
end;
procedure TPage.SetOwner(AOwner: TPages);
begin
if FOwner <> nil then FOwner.RemoveItem(Self);
if AOwner <> nil then AOwner.InsertItem(Self);
end;
procedure TPage.UpdatePage;
begin
end;
procedure TPage.UpdateObject;
begin
end;
procedure TPage.EnableButtons(Value: Boolean);
begin
inherited EnableButtons(Value);
if Value then
DriverManager.StopTest
else
DriverManager.StartTest;
end;
function TPage.LoadDefaults: Boolean;
begin
Result := True;
end;
procedure TPage.ExecuteCommand(var ResultCode, Count: Integer);
begin
Count := 0;
ResultCode := 0;
end;
end.
|
{$I tdl_dire.inc}
unit tdl_inde;
{
Indexing routines for working with the files we've copied over.
Also contains structures for working with title metadata, such as favorites.
}
interface
uses
DOS,
objects,
tdl_glob,
tdl_conf;
const
{Metadata bitflags:}
numMetaFlags=2;
m_favorite=1;
m_unpacked=2;
m_reserved=4;
type
{base class for indexes in general}
PIndex=^TIndex;
TIndex=object(TObject)
PUBLIC
entries:word;
{cached:boolean;}
data:PStream;
Constructor Init(fpath:PathStr;caching:boolean); {caching=are we allowed to}
Destructor Done; VIRTUAL;
Function verify:boolean; VIRTUAL;
end;
PFileIndex=^TFileIndex;
TFileIndex=object(TIndex)
Constructor Init(fpath:PathStr;caching:boolean);
Destructor Done; VIRTUAL;
{retrieval functions return a pointer because we might have the data
cached in memory already}
Function retrieve(i:word;var d:pFileStruct):boolean;
Function verify:boolean; VIRTUAL;
PRIVATE
tmpdata:PFileStruct;
end;
PTitleIndex=^TTitleIndex;
TTitleIndex=object(TIndex)
Constructor Init(fpath:PathStr;caching:boolean);
Destructor Done; VIRTUAL;
Function retrieve(i:word;var d:pTitleStruct):boolean;
Function retrieve1c(i:word):char; {first char of title returned}
Function verify:boolean; VIRTUAL;
PRIVATE
tmpdata:PTitleStruct;
headerCached:boolean;
headerCache:PTitleOffsets;
headerCacheSize:word;
end;
{
Not yet written:
Mapping index (contains what titles contain which search words)
}
PMetadataArray=^TMetadataArray;
TMetadataArray=array[0..maxTitles-1] of byte;
PMetadata=^TMetadata;
TMetadata=object(TObject)
PUBLIC
numEntries:word;
metaFlags:pMetadataArray;
changed:boolean;
Constructor Init(favcache:PathStr;ne:word);
Destructor Done; VIRTUAL;
(*
Procedure FileExport(fname:PathStr);
Procedure FileImport(fname:PathStr);
*)
function Flush:boolean;
function Used:word; {returns how entries are in use}
function getFlag(tid:word;flag:byte):boolean; {returns if a title has a certain flag set}
function setFlag(tid:word;flag:byte):boolean; {sets a flag for a title}
function clearFlag(tid:word;flag:byte):boolean; {sets a flag for a title}
function toggleFlag(tid:word;flag:byte):boolean; {flips a flag bit}
function countFlag(flag:byte):word; {counts how many titles have a certain set}
PRIVATE
fname:string;
fhandle:file;
end;
procedure stCheck(st:PStream);
var
Files:PFileIndex; {holds all fileIDs and their 8.4 filenames}
Titles:PTitleIndex; {holds all titleIDs and their full title strings}
implementation
uses
support,
streams;
const
{Leave these values alone. Reducing these values may cause breakage.
Increasing these values will not significantly speed anything up.}
minReadSize=sizeof(TTitleStruct); {minimum size of bytes to read from title stream}
indexMinRAM=4096; {minimum size of RAM bytes to preload a stream}
procedure stCheck(st:PStream);
begin
case st^.status of
stError :fatalerror(21,'Access error');
stInitError :fatalerror(22,'Cannot initialize stream');
stReadError :fatalerror(23,'Read beyond end of stream');
stWriteError:fatalerror(24,'Cannot expand stream');
stGetError :fatalerror(25,'Get of unregistered object type');
stPutError :fatalerror(26,'Put of unregistered object type');
end;
end;
Constructor TIndex.Init;
var
odata:PBufStream;
l:longint;
begin
if not Inherited Init then fail;
if config=nil then fail;
if not fileexists(fpath) then fail;
{register index as a stream on disk}
odata:=new(pbufstream,init(fpath,stOpenRead,indexMinRAM));
{If we have no EMS or XMS, and if stream is > than RAM,
disable caching to speed up program initialization.}
if (ems_memavail=0)
and (xms_memavail=0)
and (odata^.getsize > maxavail)
then caching:=false;
if caching then begin
{create a new RAM-based stream and copy index into it}
l:=indexMinRAM;
{if index is tiny, just load entire thing}
if l > odata^.getsize then l:=odata^.getsize;
data:=TempStream(l,odata^.getsize,ForSpeed);
if data=nil
then fatalerror(16,'Caching '+fpath+' failed during init');
{Copy disk-based stream into memory-based stream.
Do size-efficient copy if index is loaded into lower DOS RAM,
as we might not have enough low RAM for FastCopy's 64K temp buffer.}
if typeof(data^) = typeof(TMemoryStream)
then data^.copyfrom(odata^,odata^.getsize)
else FastCopy(odata^,data^,odata^.GetSize);
if data^.status <> stOK
then fatalerror(16,'Caching '+fpath+' failed during copy');
dispose(odata,done);
end else begin
{Just use the stream on disk as-is. Slow, but low RAM usage.}
data:=odata;
end;
data^.seek(0);
end;
Destructor TIndex.Done;
begin
{close our index file handle}
dispose(data,done);
Inherited Done;
end;
Function TIndex.verify:boolean;
begin
if data=nil then fatalerror(3,'Index not initialized');
end;
Constructor TFileIndex.Init;
begin
if not Inherited Init(fpath,caching) then fail;
data^.read(entries,2);
config^.NumTitles:=entries;
getmem(tmpdata,sizeof(tfilestruct));
end;
Destructor TFileIndex.done;
begin
freemem(tmpdata,sizeof(tfilestruct));
Inherited Done;
end;
Function TFileIndex.Retrieve(i:word;var d:pFileStruct):boolean;
begin
{find offset in stream header, then grab the data into temporary buffer}
data^.seek(2+longint(i)*sizeof(TFileStruct));
data^.read(tmpdata^,sizeof(TFileStruct));
d:=tmpdata;
retrieve:=(data^.status=stOK);
end;
Function TFileIndex.Verify:boolean;
const
err_lengthuneven=1;
err_wronglength=2;
err_outoforder=4;
var
calcedEntries,w,numf:word;
mangled:word;
begin
Verify:=false;
mangled:=0;
{verify length is correct}
if ((data^.GetSize-2) mod (2+12)) <> 0
then mangled:=mangled OR err_lengthuneven;
{verify Entries is correct}
calcedEntries:=((data^.GetSize-2) div (2+12));
if calcedEntries<>entries
then mangled:=mangled OR err_wronglength;
{verify all fileIDs are correct}
data^.seek(2);
for numf:=0 to Entries-1 do begin
data^.read(w,2);
if w<>numf then begin
mangled:=mangled OR err_outoforder;
break;
end;
data^.seek(data^.GetPos+12);
end;
if mangled<>0 then begin
writeln('File index errors found: ');
if (mangled AND err_lengthuneven)=err_lengthuneven
then writeln('Index wrong length; expected ',(14*entries),' but length is ',data^.GetSize-2);
if (mangled AND err_wronglength)=err_wronglength
then writeln('Expected ',entries,' entries but index appears to contain ',calcedEntries);
if (mangled AND err_outoforder)=err_outoforder
then writeln('Wrong fileID found; expected ',numf,', found ',w);
writeln('Hit enter when done reviewing');
readln;
end else begin
{if we get here, we didn't detect anything wrong}
Verify:=true;
end
end;
Constructor TTitleIndex.Init;
begin
if not Inherited Init(fpath,caching) then fail;
data^.read(entries,2);
headerCached:=false;
{We can eliminate nearly half of all seeks if we cache the header offsets in RAM}
if caching and (entries<maxCacheableTitles) then begin
headerCacheSize:=entries*4;
if maxavail>headerCacheSize then begin;
getmem(headerCache,headerCacheSize);
data^.read(headerCache^,headerCacheSize);
headerCached:=true;
end;
end;
getmem(tmpdata,minReadSize);
end;
Destructor TTitleIndex.done;
begin
freemem(tmpdata,minReadSize);
if headerCached
then freemem(headerCache,headerCacheSize);
Inherited Done;
end;
Function TTitleIndex.retrieve(i:word;var d:pTitleStruct):boolean;
{
Seeks are costly on slow I/O systems. Normally we would seek to the title
length, read it, then read only the title characters we need. To remove
one seek per retrieval, we are just going to read 256 bytes. This will
always dip into the next record, but the extra junk won't be visible
to the calling program.
}
var
l:longint;
status:integer;
b:byte;
begin
{find offset in stream header, then grab the data into temporary buffer}
if headerCached then begin
l:=headerCache^[i];
end else begin
data^.seek(2+(longint(i)*sizeof(longint)));
data^.read(l,sizeof(longint));
end;
data^.seek(l);
data^.read(tmpdata^,minReadSize);
{Our speed optimization of reading minReadSize can go past the end of the
stream. If we do this, we'll fall back to slower but 100% accurate reading.}
if data^.status<>stOK then begin
data^.status:=stOK;
data^.seek(l);
data^.read(tmpdata^.id,sizeof(tmpdata^.id)+sizeof(tmpdata^.hash));
{get exact length of title}
data^.read(b,1);
data^.seek(data^.getpos-1);
data^.read(tmpdata^.title,b+1);
end;
{$IFDEF DEBUG}
{If still getting an error, fatal abort with the reason}
if data^.status<>stOK then stCheck(data);
{$ENDIF}
d:=tmpdata;
retrieve:=(data^.status=stOK);
end;
Function TTitleIndex.retrieve1c(i:word):char;
{
Retrieves only the first character of the title. Used for title binary search.
}
const
tcofs=2+16+1;
var
l:longint;
c:char;
begin
{find offset in stream header, then grab the data into temporary buffer}
if headerCached then begin
{l:=headerCache^[i];
data^.seek(l+tcofs);}
data^.seek(headerCache^[i]+tcofs);
end else begin
data^.seek(2+(longint(i)*sizeof(longint)));
data^.read(l,sizeof(longint));
data^.seek(l+tcofs);
end;
data^.read(c,1);
retrieve1c:=c;
end;
Function TTItleIndex.Verify:boolean;
var
w,tmpid:word;
l,oldpos:longint;
begin
Verify:=false;
{check to see if we have same number of entries as filenames}
if entries <> config^.numTitles then exit;
{verify title offsets and titleIDs are correct}
data^.seek(2);
for w:=0 to config^.numTitles-1 do begin
if headerCached then begin
data^.seek(headerCache^[w]);
data^.read(tmpid,2);
end else begin
oldpos:=data^.GetPos;
data^.read(l,4);
data^.seek(l);
data^.read(tmpid,2);
data^.seek(oldpos+4);
end;
if tmpid <> w
then exit;
end;
{Verifying md5 hash is beyond the scope of slow vintage computers.}
{Verifying title strings isn't possible without end-of-string markers.}
{if we get here, we didn't detect anything wrong}
Verify:=true;
end;
Constructor TMetadata.init;
var
makeNewCache:boolean;
begin
Inherited Init;
numEntries:=ne;
fname:=favcache;
changed:=false;
getmem(metaFlags,numEntries);
fillchar(metaFlags^,numEntries,0);
if fname<>'' then begin {if '' then read-only filesystem, can't work with files}
makeNewCache:=false;
if not fileexists(fname)
then begin
makeNewCache:=true
end else begin
if sizeoffile(fname)<>ne {if size doesn't match our index files, invalidate the cache}
then makeNewCache:=true;
end;
assign(fhandle,fname);
if makeNewCache then begin
rewrite(fhandle,1);
blockwrite(fhandle,metaFlags^,numEntries);
end else begin
reset(fhandle,1);
blockread(fhandle,metaFlags^,numEntries);
end;
close(fhandle);
end;
end;
Destructor TMetadata.done;
begin
freemem(metaFlags,numEntries);
Inherited Done;
end;
function TMetadata.Used;
var
w,count:word;
begin
count:=0;
for w:=0 to numEntries-1 do
if metaFlags^[w]<>0
then inc(count);
Used:=count;
end;
function TMetadata.countFlag;
var
w,count:word;
begin
count:=0;
for w:=0 to numEntries-1 do
if (metaFlags^[w] AND flag)=flag
then inc(count);
countFlag:=count;
end;
function TMetadata.setFlag;
var
rc:boolean;
begin
rc:=false;
if tid<numEntries then begin
metaFlags^[tid] := metaFlags^[tid] OR flag;
rc:=true;
end;
setFlag:=rc;
end;
function TMetadata.clearFlag;
var
rc:boolean;
begin
rc:=false;
if tid<numEntries then begin
metaFlags^[tid] := metaFlags^[tid] AND NOT flag;
rc:=true;
end;
clearFlag:=rc;
end;
function TMetadata.toggleFlag;
var
rc:boolean;
begin
rc:=false;
if tid<numEntries then begin
metaFlags^[tid] := metaFlags^[tid] XOR flag;
rc:=true;
end;
toggleFlag:=rc;
end;
function TMetadata.getFlag;
var
rc:boolean;
begin
rc:=false;
if (metaFlags^[tid] AND flag) = flag
then rc:=true;
getFlag:=rc;
end;
function TMetadata.Flush;
begin
if (fname<>'') and changed then begin
assign(fhandle,fname);
rewrite(fhandle,1);
blockwrite(fhandle,metaFlags^,numEntries);
close(fhandle);
changed:=false;
end;
end;
end.
|
{ Subroutine SST_W_C_INTRINSIC (INTR)
*
* Write out one of the symbols the C back end treats as if are intrinsic,
* but that really do need to be declared. This routine first makes sure
* the appropriate declarations is made, if needed, and then writes the
* symbol at the current writing position.
}
module sst_w_c_INTRINSIC;
define sst_w_c_intrinsic;
%include 'sst_w_c.ins.pas';
procedure sst_w_c_intrinsic ( {write name of intrinsic symbol}
in intr: intr_k_t); {selects symbol, will be declared if needed}
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
begin
case intr of {which intrinsic symbol is requested ?}
intr_nil_k: begin {NIL pointer value}
sst_w_c_declare (decl_nil_k);
sst_w.appendn^ ('nil', 3);
end;
intr_true_k: begin {logical TRUE}
sst_w_c_declare (decl_true_k);
sst_w.appendn^ ('true', 4);
end;
intr_false_k: begin {logical FALSE}
sst_w_c_declare (decl_false_k);
sst_w.appendn^ ('false', 5);
end;
intr_nullset_k: begin {empty set value}
sst_w_c_declare (decl_nullset_k);
sst_w.appendn^ ('nullset', 7);
end;
intr_unspec_int_k: begin
sst_w_c_declare (decl_unspec_int_k);
sst_w.appendn^ ('unspec_int', 10);
end;
intr_unspec_enum_k: begin
sst_w_c_declare (decl_unspec_enum_k);
sst_w.appendn^ ('unspec_enum', 11);
end;
intr_unspec_float_k: begin
sst_w_c_declare (decl_unspec_float_k);
sst_w.appendn^ ('unspec_float', 12);
end;
intr_unspec_bool_k: begin
sst_w_c_declare (decl_unspec_bool_k);
sst_w.appendn^ ('unspec_bool', 11);
end;
intr_unspec_char_k: begin
sst_w_c_declare (decl_unspec_char_k);
sst_w.appendn^ ('unspec_char', 11);
end;
intr_unspec_set_k: begin
sst_w_c_declare (decl_unspec_set_k);
sst_w.appendn^ ('unspec_set', 10);
end;
intr_unspec_pnt_k: begin
sst_w_c_declare (decl_unspec_pnt_k);
sst_w.appendn^ ('unspec_pnt', 10);
end;
{
* Integer math functions.
}
intr_abs_k: begin {absolute value, integer}
sst_w_c_declare (decl_stdlib_k);
sst_w.appendn^ ('abs', 3);
end;
{
* Floating point math intrinsics.
}
intr_atan_k: begin {arctangent, one argument}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('atan', 4);
end;
intr_atan2_k: begin {arctangent, two arguments}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('atan2', 5);
end;
intr_ceil_k: begin {to integer, round toward +infinity}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('ceil', 4);
end;
intr_cos_k: begin {cosine}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('cos', 3);
end;
intr_exp_k: begin {E ** arg}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('exp', 3);
end;
intr_fabs_k: begin {absolute value, floating point}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('fabs', 4);
end;
intr_floor_k: begin {to integer, round toward -infinity}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('floor', 5);
end;
intr_log_k: begin {natural log}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('log', 3);
end;
intr_pow_k: begin {arg1 ** arg2}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('pow', 3);
end;
intr_sin_k: begin {sine}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('sin', 3);
end;
intr_sqrt_k: begin {square root}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('sqrt', 4);
end;
intr_tan_k: begin {tangent}
sst_w_c_declare (decl_math_k);
sst_w.appendn^ ('tan', 3);
end;
otherwise
sys_msg_parm_int (msg_parm[1], ord(intr));
sys_message_bomb ('sst_c_write', 'intrinsic_symbol_id_bad', msg_parm, 1);
end;
end;
|
Unit TERRA_INI;
{$I terra.inc}
Interface
Uses TERRA_String, TERRA_Utils, TERRA_Math, TERRA_Stream;
Type
TokenFormat=(tkInteger, tkCardinal, tkFloat,
tkBoolean, tkByte, tkString,
tkColor, tkVector, tkKey
);
PINIToken=^INIToken;
INIToken=Record
Name:TERRAString;
Default:TERRAString;
Format:TokenFormat;
Data:Pointer;
Found:Boolean;
End;
INIParser = Class(TERRAObject)
Protected
_TokenList:Array Of INIToken;
_TokenCount:Integer;
Public
ParseCommas:Boolean;
Constructor Create;
Procedure Release; Override;
Procedure AddToken(Token:TERRAString; Format:TokenFormat; Data:Pointer; Default:TERRAString='');
Function GetToken(Token:TERRAString):PINIToken;
Procedure DiscardTokens;
Procedure Load(Source:Stream; IgnoreWarnings:Boolean=False);Overload;
Procedure Load(Filename:TERRAString; IgnoreWarnings:Boolean=False);Overload;
Procedure LoadFromString(S:TERRAString; IgnoreWarnings:Boolean=False);
Function SaveToString(IgnoreDefaults:Boolean=True):TERRAString;
Procedure Save(Dest:Stream; IgnoreDefaults:Boolean=True);Overload;
Procedure Save(Filename:TERRAString; IgnoreDefaults:Boolean=True);Overload;
End;
Procedure ConvertFromToken(Source:TERRAString; Dest:Pointer; Format:TokenFormat);
Function ConvertToToken(Source:Pointer; Format:TokenFormat):TERRAString;
Implementation
Uses TERRA_Error, TERRA_FileStream, TERRA_MemoryStream, TERRA_Log, TERRA_Application,
TERRA_Color, TERRA_Vector3D, TERRA_InputManager;
// LINIParser
Constructor INIParser.Create;
Begin
SetLength(_TokenList,0);
_TokenCount:=0;
End;
Procedure INIParser.Release;
Begin
SetLength(_TokenList,0);
End;
Procedure INIParser.AddToken(Token:TERRAString; Format:TokenFormat; Data:Pointer; Default:TERRAString='');
Begin
If Assigned(GetToken(Token)) Then
Exit;
SetLength(_TokenList,Succ(_TokenCount));
_TokenList[_TokenCount].Name:=Token;
_TokenList[_TokenCount].Format:=Format;
_TokenList[_TokenCount].Data:=Data;
_TokenList[_TokenCount].Default:=Default;
_TokenList[_TokenCount].Found:=False;
Inc(_TokenCount);
End;
Function INIParser.GetToken(Token:TERRAString): PINIToken;
Var
I:Integer;
Begin
Result:=Nil;
Token:=StringUpper(Token);
For I:=0 To Pred(_TokenCount) Do
If StringUpper(_TokenList[I].Name)=Token Then
Begin
Result:=@(_TokenList[I]);
Break;
End;
End;
Procedure ConvertFromToken(Source:TERRAString; Dest:Pointer; Format:TokenFormat);
Begin
Case Format Of
tkInteger: PInteger(Dest)^ := StringToInt(Source);
tkCardinal: PCardinal(Dest)^ := StringToCardinal(Source);
tkFloat: PSingle(Dest)^ := StringToFloat(Source);
tkBoolean: PBoolean(Dest)^ := StringToBool(StringUpper(Source));
tkByte: PByte(Dest)^ := StringToInt(Source);
tkString: PString(Dest)^ := Source;
tkColor: If (Source<>'') And (Source[1]='#') Then
Begin
PColor(Dest)^ := ColorCreateFromString(Source);
End Else
Begin
PColor(Dest).R := StringToInt(StringGetNextSplit(Source, Ord('\')));
PColor(Dest).G := StringToInt(StringGetNextSplit(Source, Ord('\')));
PColor(Dest).B := StringToInt(StringGetNextSplit(Source, Ord('\')));
If Source<>'' Then
PColor(Dest).A := StringToInt(Source)
Else
PColor(Dest).A := 255;
End;
tkVector: Begin
PVector3D(Dest).X := StringToFloat(StringGetNextSplit(Source, Ord('\')));
PVector3D(Dest).Y := StringToFloat(StringGetNextSplit(Source, Ord('\')));
PVector3D(Dest).Z := StringToFloat(Source);
End;
tkKey: PInteger(Dest)^ := GetKeyByName(Source);
Else
RaiseError('Invalid token format.['+CardinalToString(Cardinal(Format))+']');
End;
End;
Function ConvertToToken(Source:Pointer; Format:TokenFormat):TERRAString;
Begin
Case Format Of
tkInteger: Result:=IntToString(PInteger(Source)^);
tkCardinal: Result:=CardinalToString(PCardinal(Source)^);
tkFloat: Result:=FloatToString(PSingle(Source)^);
tkBoolean: Result:=StringLower(BoolToString(PBoolean(Source)^));
tkByte: Result:=IntToString(PByte(Source)^);
tkString: Result:=PString(Source)^;
tkColor: Result:=ColorToString(PColor(Source)^);
tkVector: Begin
Result:= FloatToString(PVector3D(Source).X)+'\'+
FloatToString(PVector3D(Source).Y)+'\'+
FloatToString(PVector3D(Source).Z);
End;
tkKey: Result := GetKeyName(PInteger(Source)^);
Else
Begin
Result := '';
RaiseError('Invalid token format.['+CardinalToString(Cardinal(Format))+']');
End;
End;
End;
Procedure INIParser.DiscardTokens;
Begin
_TokenCount:=0;
SetLength(_TokenList, _TokenCount);
End;
Procedure INIParser.Load(Source:Stream; IgnoreWarnings:Boolean=False);
Var
Token,S,SK:TERRAString;
Info:PINIToken;
I:Integer;
Begin
While Source.Position<Source.Size Do
Begin
Source.ReadLine(SK);
I:=Pos('//',SK);
If I>0 Then
SK:=Copy(SK,1,Pred(I)); // Strip comments from line
While SK<>'' Do
Begin
If ParseCommas Then
I:=Pos(',',SK)
Else
I:=0;
If I>0 Then
Begin
S:=Copy(SK,1,Pred(I));
SK := StringTrim(StringCopy(SK, Succ(I), MaxInt));
End Else
Begin
S:=SK;
SK:='';
End;
I:=Pos('=',S);
If I<=0 Then Break;
Token := StringUpper(Copy(S,1,Pred(I)));
Token := StringTrim(Token);
S := StringCopy(S, Succ(I), MaxInt); // Get Token and Value
S := StringTrim(S);
Info := GetToken(Token);
If Not Assigned(Info) Then
Begin
If Not IgnoreWarnings Then
Log(logWarning,'INI','Invalid Token.['+Token+']');
Continue;
End;
Info.Found := True;
ConvertFromToken(S, Info.Data, Info.Format);
End;
End;
For I:=0 To Pred(_TokenCount) Do
With _TokenList[I] Do
If (Not Found) And (Default<>'') Then
ConvertFromToken(Default, Data, Format);
End;
Function INIParser.SaveToString(IgnoreDefaults:Boolean=True):TERRAString;
Var
Dest:MemoryStream;
Begin
Dest := MemoryStream.Create(1024);
Save(Dest, IgnoreDefaults);
SetLength(Result, Pred(Dest.Position));
Move(Dest.Buffer^, Result[1], Pred(Dest.Position));
ReleaseObject(Dest);
End;
Procedure INIParser.Save(Dest:Stream; IgnoreDefaults:Boolean=True);
Var
S:TERRAString;
I:Integer;
Info:PINIToken;
Begin
For I:=0 To Pred(_TokenCount) Do
Begin
Info:=@(_TokenList[I]);
S:=ConvertToToken(Info.Data, Info.Format);
If (Not IgnoreDefaults) Or (StringUpper(S)<>StringUpper(Info.Default)) Then
Dest.WriteLine(Info.Name+'='+S);
End;
End;
Procedure INIParser.Load(Filename:TERRAString; IgnoreWarnings:Boolean=False);
Var
Source:Stream;
Begin
If Not FileStream.Exists(FileName) Then
Begin
RaiseError('File not found ['+FileName+']');
Exit;
End;
Source := FileStream.Open(FileName);
Load(Source, IgnoreWarnings);
ReleaseObject(Source);
End;
Procedure INIParser.LoadFromString(S:TERRAString; IgnoreWarnings:Boolean=False);
Var
Source:MemoryStream;
Begin
If S='' Then
Exit;
Source := MemoryStream.Create(Length(S), @S[1]);
Load(Source, IgnoreWarnings);
ReleaseObject(Source);
End;
Procedure INIParser.Save(Filename:TERRAString; IgnoreDefaults:Boolean=True);
Var
Dest:Stream;
Begin
Dest := FileStream.Create(FileName);
Save(Dest, IgnoreDefaults);
ReleaseObject(Dest);
End;
End.
|
unit UPryvDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
FMX.StdCtrls, FMX.TMSCloudBase, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomPryv,
FMX.TMSCloudPryv, FMX.Objects, FMX.Layouts, FMX.TreeView, FMX.Edit,
FMX.ListBox, FMX.Grid, FMX.TMSCloudListView, FMX.TMSCloudImage, FMX.Memo,
FMX.ExtCtrls;
type
TForm1175 = class(TForm)
Panel1: TPanel;
btConnect: TButton;
Image1: TImage;
TMSFMXCloudPryv1: TTMSFMXCloudPryv;
btRemove: TButton;
Panel2: TPanel;
Label1: TLabel;
btStreams: TButton;
TreeView1: TTreeView;
Label13: TLabel;
edStreamName: TEdit;
cbSubStream: TCheckBox;
btAddStream: TButton;
btDeleteStream: TButton;
btUpdateStream: TButton;
Panel3: TPanel;
Label2: TLabel;
btEvents: TButton;
Label3: TLabel;
cbEventCount: TComboBox;
cbStream: TCheckBox;
TMSFMXCloudListView1: TTMSFMXCloudListView;
Label4: TLabel;
cbEventType: TComboBox;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
btAddEvent: TButton;
btDeleteEvent: TButton;
btUpdateEvent: TButton;
edTags: TEdit;
cbUnit: TComboEdit;
edLongitude: TEdit;
edLatitude: TEdit;
Label10: TLabel;
meValue: TMemo;
meDescription: TMemo;
Label11: TLabel;
Label12: TLabel;
TMSFMXCloudImage1: TTMSFMXCloudImage;
OpenDialog1: TOpenDialog;
btDownload: TButton;
dpDate: TCalendarEdit;
procedure btConnectClick(Sender: TObject);
procedure TMSFMXCloudPryv1ReceivedAccessToken(Sender: TObject);
procedure btRemoveClick(Sender: TObject);
procedure btStreamsClick(Sender: TObject);
procedure TreeView1Change(Sender: TObject);
procedure btAddStreamClick(Sender: TObject);
procedure btDeleteStreamClick(Sender: TObject);
procedure btUpdateStreamClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btEventsClick(Sender: TObject);
procedure cbEventTypeChange(Sender: TObject);
procedure btAddEventClick(Sender: TObject);
procedure btDeleteEventClick(Sender: TObject);
procedure btUpdateEventClick(Sender: TObject);
procedure TMSFMXCloudListView1Change(Sender: TObject);
procedure btDownloadClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Connected: boolean;
InitLV: boolean;
IsUploading: boolean;
IsDownloading: boolean;
procedure ToggleControls;
procedure ToggleControlsText;
procedure ToggleControlsPicture;
procedure ToggleControlsPosition;
procedure ToggleControlsValue;
procedure FillStreams;
procedure FillEvents;
end;
var
Form1175: TForm1175;
implementation
{$R *.fmx}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// PryvAppkey = 'xxxxxxxxx';
{$I APPIDS.INC}
procedure TForm1175.btAddStreamClick(Sender: TObject);
var
it: TPryvStreamItem;
si: TPryvStreamItem;
begin
it := TMSFMXCloudPryv1.Streams.Add;
if cbSubStream.IsChecked then
begin
if not Assigned(TreeView1.Selected) then
begin
ShowMessage('Please select a Stream first.');
exit;
end;
si := TPryvStreamItem(TTMSFMXCloudTreeViewItem(TreeView1.Selected).DataObject);
it.ParentID := si.ID;
end;
it.Summary := edStreamName.Text;
TMSFMXCloudPryv1.AddStream(it);
FillStreams;
end;
procedure TForm1175.btAddEventClick(Sender: TObject);
var
text: TPryvText;
pic: TPryvPicture;
pos: TPryvPosition;
val: TPryvValue;
si: TPryvStreamItem;
begin
if not Assigned(TreeView1.Selected) then
begin
ShowMessage('Please select a Stream first.');
exit;
end;
si := TPryvStreamItem(TTMSFMXCloudTreeViewItem(TreeView1.Selected).DataObject);
if cbEventType.ItemIndex = 0 then
begin
text := TPryvText.Create;
TMSFMXCloudPryv1.Events.Add(text);
text.Content := meValue.Text;
text.StreamID := si.ID;
text.DateTime := dpDate.Date;
text.Tags.CommaText := edTags.Text;
text.Description := meDescription.Text;
TMSFMXCloudPryv1.AddEvent(text);
end
else if cbEventType.ItemIndex = 1 then
begin
if OpenDialog1.Execute then
begin
IsUploading := true;
pic := TPryvPicture.Create;
TMSFMXCloudPryv1.Events.Add(pic);
pic.StreamID := si.ID;
pic.DateTime := dpDate.Date;
pic.Tags.CommaText := edTags.Text;
pic.Description := meDescription.Text;
TMSFMXCloudPryv1.AddEvent(pic, OpenDialog1.FileName);
IsUploading := false;
end;
end
else if cbEventType.ItemIndex = 2 then
begin
pos := TPryvPosition.Create;
TMSFMXCloudPryv1.Events.Add(pos);
pos.Latitude := StrToFloat(edLatitude.Text);
pos.Longitude := StrToFloat(edLongitude.Text);
pos.StreamID := si.ID;
pos.DateTime := dpDate.Date;
pos.Tags.CommaText := edTags.Text;
pos.Description := meDescription.Text;
TMSFMXCloudPryv1.AddEvent(pos);
end
else if cbEventType.ItemIndex = 3 then
begin
val := TPryvValue.Create;
TMSFMXCloudPryv1.Events.Add(val);
val.Content := meValue.Text;
val.StreamID := si.ID;
val.UnitValue := cbUnit.Text;
val.DateTime := dpDate.Date;
val.Tags.CommaText := edTags.Text;
val.Description := meDescription.Text;
TMSFMXCloudPryv1.AddEvent(val);
end;
FillEvents;
end;
procedure TForm1175.btConnectClick(Sender: TObject);
var
acc: boolean;
begin
TMSFMXCloudPryv1.App.Key := PryvAppKey;
if TMSFMXCloudPryv1.App.Key <> '' then
begin
TMSFMXCloudPryv1.PersistTokens.Location := plIniFile;
TMSFMXCloudPryv1.PersistTokens.Key := ExtractFilePath(Paramstr(0)) + 'pryv.ini';
TMSFMXCloudPryv1.PersistTokens.Section := 'tokens';
TMSFMXCloudPryv1.LoadTokens;
acc := TMSFMXCloudPryv1.TestTokens;
if not acc then
TMSFMXCloudPryv1.DoAuth
else
begin
Connected := true;
ToggleControls;
end;
end
else
ShowMessage('Please provide a valid application ID for the client component');
end;
procedure TForm1175.btDeleteStreamClick(Sender: TObject);
var
si: TPryvStreamItem;
begin
if not Assigned(TreeView1.Selected) then
begin
ShowMessage('Please select a Stream first.');
exit;
end;
si := TPryvStreamItem(TTMSFMXCloudTreeViewItem(TreeView1.Selected).DataObject);
TreeView1.RemoveObject(TreeView1.Selected);
TMSFMXCloudPryv1.DeleteStream(si);
FillStreams;
end;
procedure TForm1175.btDownloadClick(Sender: TObject);
var
o: TPryvObject;
sv: TSaveDialog;
begin
if TMSFMXCloudListView1.ItemIndex < 0 then
Exit;
o := TMSFMXCloudPryv1.Events[TMSFMXCloudListView1.ItemIndex];
if o is TPryvPicture then
begin
sv := TSaveDialog.Create(Self);
sv.FileName := (o as TPryvPicture).FileName;
if sv.Execute then
begin
IsDownloading := true;
TMSFMXCloudPryv1.Download(o as TPryvPicture,sv.FileName);
IsDownloading := false;
ShowMessage('File ' + (o as TPryvPicture).FileName + ' downloaded');
end;
sv.Free;
end;
end;
procedure TForm1175.btDeleteEventClick(Sender: TObject);
begin
TMSFMXCloudPryv1.DeleteEvent(TMSFMXCloudPryv1.Events[TMSFMXCloudListView1.ItemIndex]);
FillEvents;
end;
procedure TForm1175.btEventsClick(Sender: TObject);
begin
FillEvents;
end;
procedure TForm1175.btRemoveClick(Sender: TObject);
begin
TMSFMXCloudPryv1.ClearTokens;
Connected := false;
ToggleControls;
end;
procedure TForm1175.btUpdateStreamClick(Sender: TObject);
var
si: TPryvStreamItem;
begin
if not Assigned(TreeView1.Selected) then
begin
ShowMessage('Please select a Stream first.');
exit;
end;
si := TPryvStreamItem(TTMSFMXCloudTreeViewItem(TreeView1.Selected).DataObject);
si.Summary := edStreamName.Text;
TMSFMXCloudPryv1.UpdateStream(si);
FillStreams;
end;
procedure TForm1175.btUpdateEventClick(Sender: TObject);
var
text: TPryvText;
pic: TPryvPicture;
pos: TPryvPosition;
val: TPryvValue;
begin
if cbEventType.ItemIndex = 0 then
begin
text := TMSFMXCloudPryv1.Events[TMSFMXCloudListView1.ItemIndex] as TPryvText;
text.Content := meValue.Text;
text.DateTime := dpDate.Date;
text.Tags.CommaText := edTags.Text;
text.Description := meDescription.Text;
TMSFMXCloudPryv1.UpdateEvent(text);
end
else if cbEventType.ItemIndex = 1 then
begin
pic := TMSFMXCloudPryv1.Events[TMSFMXCloudListView1.ItemIndex] as TPryvPicture;
pic.DateTime := dpDate.Date;
pic.Tags.CommaText := edTags.Text;
pic.Description := meDescription.Text;
TMSFMXCloudPryv1.UpdateEvent(pic);
end
else if cbEventType.ItemIndex = 2 then
begin
pos := TMSFMXCloudPryv1.Events[TMSFMXCloudListView1.ItemIndex] as TPryvPosition;
pos.Latitude := StrToFloat(edLatitude.Text);
pos.Longitude := StrToFloat(edLongitude.Text);
pos.DateTime := dpDate.Date;
pos.Tags.CommaText := edTags.Text;
pos.Description := meDescription.Text;
TMSFMXCloudPryv1.UpdateEvent(pos);
end
else if cbEventType.ItemIndex = 3 then
begin
val := TMSFMXCloudPryv1.Events[TMSFMXCloudListView1.ItemIndex] as TPryvValue;
val.Content := meValue.Text;
val.DateTime := dpDate.Date;
val.UnitValue := cbUnit.Text;
val.Tags.CommaText := edTags.Text;
val.Description := meDescription.Text;
TMSFMXCloudPryv1.UpdateEvent(val);
end;
FillEvents;
end;
procedure TForm1175.cbEventTypeChange(Sender: TObject);
begin
if cbEventType.ItemIndex = 0 then
ToggleControlsText
else if cbEventType.ItemIndex = 1 then
ToggleControlsPicture
else if cbEventType.ItemIndex = 2 then
ToggleControlsPosition
else if cbEventType.ItemIndex = 3 then
ToggleControlsValue;
btUpdateEvent.Enabled := false;
end;
procedure TForm1175.btStreamsClick(Sender: TObject);
begin
FillStreams;
end;
procedure TForm1175.FillEvents;
var
I: integer;
o: TPryvObject;
li: TListItem;
si: TPryvStreamItem;
sa: TStringArray;
begin
InitLV := true;
meValue.Text := '';
edTags.Text := '';
edLatitude.Text := '';
edLongitude.Text := '';
cbUnit.Text := '';
meDescription.Text := '';
TMSFMXCloudImage1.URL := '';
btUpdateEvent.Enabled := true;
TMSFMXCloudListView1.Items.Clear;
if cbStream.isChecked then
begin
if Assigned(TreeView1.Selected) then
begin
si := TPryvStreamItem(TTMSFMXCloudTreeViewItem(TreeView1.Selected).DataObject);
SetLength(sa, 1);
sa[0] := si.ID;
TMSFMXCloudPryv1.GetEvents(sa,nil,StrToInt(cbEventCount.Selected.Text));
end;
end
else
TMSFMXCloudPryv1.GetEvents(StrToInt(cbEventCount.Selected.Text));
for I := 0 to TMSFMXCloudPryv1.Events.Count - 1 do
begin
o := TMSFMXCloudPryv1.Events[I];
li := TMSFMXCloudListView1.Items.Add;
if o is TPryvValue then
begin
li.Text := (o as TPryvValue).Content;
li.SubItems.Add((o as TPryvValue).UnitValue);
end
else
begin
if o is TPryvText then
begin
li.Text := (o as TPryvText).Content;
li.SubItems.Add('Text')
end
else if o is TPryvPicture then
begin
li.Text := '';
li.SubItems.Add('Picture')
end
else if o is TPryvPosition then
begin
li.Text := '';
li.SubItems.Add('Position');
end;
end;
li.SubItems.Add(o.Description);
li.SubItems.Add(DateTimeToStr(o.DateTime));
si := TMSFMXCloudPryv1.Streams.FindStreamById(o.StreamID);
if Assigned(si) then
li.SubItems.Add(si.Summary);
end;
InitLV := false;
end;
procedure TForm1175.FillStreams;
begin
TMSFMXCloudPryv1.GetStreams;
TMSFMXCloudPryv1.FillTreeView(TreeView1);
end;
procedure TForm1175.FormCreate(Sender: TObject);
begin
InitLV := false;
IsUploading := false;
Connected := false;
ToggleControls;
dpDate.Date := Now;
end;
procedure TForm1175.TMSFMXCloudListView1Change(Sender: TObject);
var
o: TPryvObject;
begin
if (InitLV) or (TMSFMXCloudListView1.ItemIndex < 0 )then
Exit;
btUpdateEvent.Enabled := true;
meValue.Text := '';
edTags.Text := '';
edLatitude.Text := '';
edLongitude.Text := '';
cbUnit.Text := '';
meDescription.Text := '';
TMSFMXCloudImage1.URL := '';
o := TMSFMXCloudPryv1.Events[TMSFMXCloudListView1.ItemIndex];
meDescription.Text := o.Description;
edTags.Text := o.Tags.CommaText;
dpDate.Date := o.DateTime;
if (o is TPryvValue) then
begin
cbEventType.ItemIndex := 3;
ToggleControlsValue;
cbUnit.Text := (o as TPryvValue).UnitValue;
end
else if (o is TPryvText) then
begin
cbEventType.ItemIndex := 0;
ToggleControlsText;
meValue.Text := (o as TPryvText).Content;
end
else if (o is TPryvPicture) then
begin
cbEventType.ItemIndex := 1;
ToggleControlsPicture;
TMSFMXCloudImage1.URL := (o as TPryvPicture).ImageURL;
end
else if (o is TPryvPosition) then
begin
cbEventType.ItemIndex := 2;
ToggleControlsPosition;
edLatitude.Text := FloatToStr((o as TPryvPosition).Latitude);
edLongitude.Text := FloatToStr((o as TPryvPosition).Longitude);
end;
end;
procedure TForm1175.TMSFMXCloudPryv1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudPryv1.SaveTokens;
Connected := true;
ToggleControls;
end;
procedure TForm1175.ToggleControls;
begin
btConnect.Enabled := not Connected;
btRemove.Enabled := Connected;
btStreams.Enabled := Connected;
btEvents.Enabled := Connected;
btAddEvent.Enabled := Connected;
btAddStream.Enabled := Connected;
btDeleteEvent.Enabled := Connected;
btDeleteStream.Enabled := Connected;
btUpdateEvent.Enabled := Connected;
btUpdateStream.Enabled := Connected;
TMSFMXCloudListView1.Enabled := Connected;
TreeView1.Enabled := Connected;
edStreamName.Enabled := Connected;
edTags.Enabled := Connected;
edLatitude.Enabled := Connected;
edLongitude.Enabled := Connected;
cbUnit.Enabled := Connected;
meValue.Enabled := Connected;
meDescription.Enabled := Connected;
cbEventCount.Enabled := Connected;
cbEventType.Enabled := Connected;
cbStream.Enabled := Connected;
cbSubStream.Enabled := Connected;
dpDate.Enabled := Connected;
btDownload.Enabled := Connected;
end;
procedure TForm1175.ToggleControlsPicture;
begin
edLatitude.Enabled := false;
edLongitude.Enabled := false;
cbUnit.Enabled := false;
meValue.Enabled := false;
btDownload.Enabled := true;
end;
procedure TForm1175.ToggleControlsPosition;
begin
edLatitude.Enabled := true;
edLongitude.Enabled := true;
cbUnit.Enabled := false;
meValue.Enabled := false;
btDownload.Enabled := false;
end;
procedure TForm1175.ToggleControlsText;
begin
edLatitude.Enabled := false;
edLongitude.Enabled := false;
cbUnit.Enabled := false;
meValue.Enabled := true;
btDownload.Enabled := false
end;
procedure TForm1175.ToggleControlsValue;
begin
edLatitude.Enabled := false;
edLongitude.Enabled := false;
cbUnit.Enabled := true;
meValue.Enabled := true;
btDownload.Enabled := false;
end;
procedure TForm1175.TreeView1Change(Sender: TObject);
var
si: TPryvStreamItem;
begin
if Assigned(TreeView1.Selected) then
begin
si := TPryvStreamItem(TTMSFMXCloudTreeViewItem(TreeView1.Selected).DataObject);
edStreamName.Text := si.Summary;
end;
end;
end.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, clTcpClient, clTcpClientTls, clMC, clImap4, ImgList, clCertificate,
clMailMessage, clTcpCommandClient, clOAuth, DemoBaseFormUnit, ExtCtrls;
type
TForm1 = class(TclDemoBaseForm)
Label4: TLabel;
edtUser: TEdit;
btnLogin: TButton;
btnLogout: TButton;
tvFolders: TTreeView;
lvMessages: TListView;
Label6: TLabel;
Label7: TLabel;
edtFrom: TEdit;
edtSubject: TEdit;
memBody: TMemo;
Label8: TLabel;
Label9: TLabel;
clImap: TclImap4;
Images: TImageList;
clMailMessage: TclMailMessage;
clOAuth1: TclOAuth;
procedure btnLoginClick(Sender: TObject);
procedure btnLogoutClick(Sender: TObject);
procedure tvFoldersChange(Sender: TObject; Node: TTreeNode);
procedure lvMessagesClick(Sender: TObject);
private
FChanging: Boolean;
procedure FillFolderList;
procedure AddFolderToList(AName: string);
function GetFolderName(Node: TTreeNode): string;
procedure FillMessages;
procedure FillMessage(AItem: TListItem);
procedure ClearMessage;
procedure EnableControls(AEnabled: Boolean);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnLoginClick(Sender: TObject);
begin
if clImap.Active then Exit;
clOAuth1.AuthUrl := 'https://accounts.google.com/o/oauth2/auth';
clOAuth1.TokenUrl := 'https://accounts.google.com/o/oauth2/token';
clOAuth1.RedirectUrl := 'http://localhost';
clOAuth1.ClientID := '421475025220-6khpgoldbdsi60fegvjdqk2bk4v19ss2.apps.googleusercontent.com';
clOAuth1.ClientSecret := '_4HJyAVUmH_iVrPB8pOJXjR1';
clOAuth1.Scope := 'https://mail.google.com/';
clImap.Server := 'imap.gmail.com';
clImap.Port := 993;
clImap.UseTLS := ctImplicit;
clImap.UserName := edtUser.Text;
clImap.Authorization := clOAuth1.GetAuthorization();
clImap.Open();
FillFolderList();
end;
procedure TForm1.FillFolderList;
var
i: integer;
list: TStrings;
begin
list := TStringList.Create();
try
tvFolders.Items.BeginUpdate();
tvFolders.Items.Clear();
clImap.GetMailBoxes(list);
for i := 0 to list.Count - 1 do
begin
AddFolderToList(list[i]);
end;
finally
tvFolders.Items.EndUpdate();
list.Free();
end;
end;
procedure TForm1.AddFolderToList(AName: string);
var
Papa, N: TTreeNode;
S: string;
i: Integer;
begin
Papa := nil;
N := tvFolders.Items.GetFirstNode();
if AName[1] = clImap.MailBoxSeparator then
begin
Delete(AName, 1, 1);
end;
while True do
begin
i := Pos(clImap.MailBoxSeparator, AName);
if (i = 0) then
begin
Papa := tvFolders.Items.AddChild(Papa, AName);
Papa.ImageIndex := 0;
Papa.SelectedIndex := 0;
Break;
end else
begin
S := Copy(AName, 1, i - 1);
Delete(AName, 1, i);
while ((N <> nil) and (N.Text <> S)) do
begin
N := N.getNextSibling;
end;
if (N = nil) then
begin
Papa := tvFolders.Items.AddChild(Papa, S);
end else
begin
Papa := N;
end;
N := Papa.GetFirstChild();
end;
end;
end;
procedure TForm1.btnLogoutClick(Sender: TObject);
begin
clImap.Close();
tvFolders.Items.Clear();
lvMessages.Clear();
edtFrom.Text := '';
edtSubject.Text := '';
memBody.Clear();
end;
procedure TForm1.tvFoldersChange(Sender: TObject; Node: TTreeNode);
begin
if (FChanging) then Exit;
FChanging := True;
try
EnableControls(False);
if clImap.Active and Assigned(tvFolders.Selected) then
begin
clImap.SelectMailBox(GetFolderName(tvFolders.Selected));
end;
FillMessages();
finally
FChanging := False;
EnableControls(True);
end;
end;
function TForm1.GetFolderName(Node: TTreeNode): string;
begin
if (Node = nil) then
begin
Result := ''
end else
begin
Result := Node.Text;
while (Node.Parent <> nil) do
begin
Node := Node.Parent;
Result := Node.Text + clImap.MailBoxSeparator + Result;
end;
end;
end;
procedure TForm1.FillMessages;
var
i: Integer;
Item: TListItem;
begin
lvMessages.Items.Clear();
ClearMessage();
if not clImap.Active then Exit;
for i := 1 to clImap.CurrentMailBox.ExistsMessages do
begin
Item := lvMessages.Items.Add();
Item.Data := Pointer(i);
FillMessage(Item);
end;
end;
procedure TForm1.FillMessage(AItem: TListItem);
var
Index: Integer;
begin
Index := Integer(AItem.Data);
clImap.RetrieveHeader(Index, clMailMessage);
AItem.Caption := clMailMessage.Subject;
AItem.SubItems.Clear();
AItem.SubItems.Add(clMailMessage.From.FullAddress);
AItem.SubItems.Add(DateTimeToStr(clMailMessage.Date));
AItem.SubItems.Add(IntToStr(clImap.GetMessageSize(Index)));
end;
procedure TForm1.ClearMessage;
begin
edtFrom.Text := '';
edtSubject.Text := '';
memBody.Lines.Clear();
end;
procedure TForm1.lvMessagesClick(Sender: TObject);
begin
if (FChanging) then Exit;
FChanging := True;
try
EnableControls(False);
if clImap.Active and (lvMessages.Selected <> nil) then
begin
clImap.RetrieveMessage(Integer(lvMessages.Selected.Data), clMailMessage);
edtFrom.Text := clMailMessage.From.FullAddress;
edtSubject.Text := clMailMessage.Subject;
memBody.Lines := clMailMessage.MessageText;
end else
begin
ClearMessage();
end;
finally
FChanging := False;
EnableControls(True);
end;
end;
procedure TForm1.EnableControls(AEnabled: Boolean);
begin
btnLogin.Enabled := AEnabled;
btnLogout.Enabled := AEnabled;
tvFolders.Enabled := AEnabled;
lvMessages.Enabled := AEnabled;
edtFrom.Enabled := AEnabled;
edtSubject.Enabled := AEnabled;
memBody.Enabled := AEnabled;
if (AEnabled) then
begin
Cursor := crArrow;
end else
begin
Cursor := crHourGlass;
end;
end;
end.
|
{
MIT License
Copyright (c) 2017 Marcos Douglas B. Santos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
unit James.Tests.Clss;
{$include james.inc}
interface
uses
Classes, SysUtils,
James.Data,
James.IO,
James.IO.Clss;
type
TJamesTestsTemplateFile = class sealed(TInterfacedObject, IFile)
private
FFile: IFile;
public
constructor Create(const FileName: string);
class function New(const FileName: string): IFile;
class function New: IFile;
function Path: string;
function Name: string;
function FileName: string;
function Stream: IDataStream;
end;
implementation
{ TJamesTestsTemplateFile }
constructor TJamesTestsTemplateFile.Create(const FileName: string);
begin
inherited Create;
FFile := TFile.New(FileName);
end;
class function TJamesTestsTemplateFile.New(const FileName: string): IFile;
begin
Result := Create(FileName);
end;
class function TJamesTestsTemplateFile.New: IFile;
begin
Result := Create('james.tests.template.xml');
end;
function TJamesTestsTemplateFile.Path: string;
begin
Result := FFile.Path;
end;
function TJamesTestsTemplateFile.Name: string;
begin
Result := FFile.Name;
end;
function TJamesTestsTemplateFile.FileName: string;
begin
Result := FFile.FileName;
end;
function TJamesTestsTemplateFile.Stream: IDataStream;
begin
Result := FFile.Stream;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, TypInfo,
ComDrv32;
type
TCheque = record
Banco: Integer;
Agencia: string;
Conta: string;
NroCheque: integer;
Valor: currency;
Data: TDateTime;
Nominal: string;
Cidade: string;
Observacao: TStrings;
end;
TConfigSerial = record
Porta: string;
Velocidade: Integer;
BitsDados: Integer;
BitsParadas: Integer;
Paridade: Integer;
end;
TForm1 = class(TForm)
private
drvSerial: TCommPortDriver;
procedure ConfigurarImpressora(const AConfiguracao: TConfigSerial);
procedure ImprimirCheque(const ACheque: TCheque; const AConfiguracao: TConfigSerial);
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.ImprimirCheque(const ACheque: TCheque; const AConfiguracao: TConfigSerial);
var
I : Integer;
begin
try
ConfigurarImpressora(AConfiguracao);
drvSerial.Connect;
drvSerial.SendString(Chr(27) + 'B' + IntToStr(ACheque.Banco));
drvSerial.SendString(Chr(27) + 'F' + ACheque.Nominal + '$');
drvSerial.SendString(Chr(27) + 'C' + ACheque.Cidade + '$');
drvSerial.SendString(Chr(27) + 'D' + FormatDateTime('dd/mm/yy', ACheque.Data));
drvSerial.SendString(Chr(27) + 'V' + FormatFloat('00000000000000', ACheque.Valor * 100));
//drvSerial.SendString(Chr(27) + Chr(176));
drvSerial.Disconnect;
if ACheque.Observacao.Count > 0 then
if Application.MessageBox('Vire o cheque e tecle Ok para inciar impressão do histórico do cheque.', 'Atenção', mb_OkCancel + mb_IconWarning) = id_Ok then
begin
drvSerial.Connect;
drvSerial.SendString(Replicate(' ', 10) + Chr(13) + Chr(10));
drvSerial.SendString(Replicate(' ', 10) + 'CHEQUE........: ' + FormatFloat('000000', ACheque.NroCheque) + Chr(13) + Chr(10));
drvSerial.SendString(Replicate(' ', 10) + 'CONTA CORRENTE: ' + IntToStr(ACheque.Banco) + '.' + ACheque.Agencia) + '.' + ACheque.Conta) + Chr(13) + Chr(10));
drvSerial.SendString(Replicate(' ', 10) + Chr(13) + Chr(10));
for I := 0 to (ACheque.Observacao.Count - 1) do
drvSerial.SendString(Replicate(' ', 10) + ACheque.Observacao[I] + Chr(13) + Chr(10));
drvSerial.Disconnect;
end;
except
Application.MessageBox('Problemas de comunicação entre computador e impressora. Verifique!', 'Erro', mb_Ok + mb_IconError);
end;
end;
procedure TForm1.ConfigurarImpressora(const AConfiguracao: TConfigSerial);
begin
//s := GetEnumName(TypeInfo(TProgrammerType), integer(tpDelphi)) ;
//TProgrammerType(GetEnumValue(TypeInfo(TProgrammerType),s)) ;
drvSerial := TCommPortDriver.Create(Application);
drvSerial.ComPort := TComPortNumber(GetEnumValue(TypeInfo(TComPortNumber), 'pn' + AConfiguracao.Porta)) ;
drvSerial.ComPortSpeed := TComPortBaudRate(GetEnumValue(TypeInfo(TComPortBaudRate), 'br' + IntToStr(AConfiguracao.Velocidade))) ;
drvSerial.ComPortDataBits := TComPortDataBits(GetEnumValue(TypeInfo(TComPortDataBits), 'db' + IntToStr(AConfiguracao.BitsDados) + 'Bits')) ;
drvSerial.ComPortStopBits := TComPortStopBits(GetEnumValue(TypeInfo(TComPortStopBits), 'sb' + IntToStr(AConfiguracao.BitsParadas) + 'Bits')) ;
case AConfiguracao.Paridade of
0: drvSerial.ComPortParity := ptNone;
1: drvSerial.ComPortParity := ptOdd;
2: drvSerial.ComPortParity := ptEven;
3: drvSerial.ComPortParity := ptMARK;
4: drvSerial.ComPortParity := ptSPACE;
end;
end;
end.
|
unit uMainForm;
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.ListView.Types, FMX.ListView.Appearances,
FMX.ListView.Adapters.Base, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.DApt, REST.Backend.EMSServices, IPPeerClient,
REST.Backend.EMSProvider, REST.Backend.EMSFireDAC, FireDAC.Comp.Client,
Data.DB, FireDAC.Comp.DataSet, FMX.ListView, FireDAC.UI.Intf,
FireDAC.FMXUI.Wait, FireDAC.Stan.StorageJSON, FireDAC.Comp.UI, System.Rtti,
System.Bindings.Outputs, FMX.Bind.Editors, Data.Bind.EngExt,
FMX.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, FMXTee.Engine,
FMXTee.Series, FMXTee.Procs, FMXTee.Chart, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteVDataSet;
type
TMainForm = class(TForm)
ToolBar1: TToolBar;
SpeedButton1: TSpeedButton;
lstResult: TListView;
FDMemTable1: TFDMemTable;
FDTableAdapter1: TFDTableAdapter;
FDSchemaAdapter1: TFDSchemaAdapter;
EMSFireDACClient1: TEMSFireDACClient;
EMSProvider1: TEMSProvider;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
FDMemTable1VBELN: TWideStringField;
FDMemTable1AUDAT: TSQLTimeStampField;
FDMemTable1VKORG: TWideStringField;
FDMemTable1NETWR: TFloatField;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
LinkFillControlToField1: TLinkFillControlToField;
StyleBook1: TStyleBook;
chartResult: TChart;
FDConnection1: TFDConnection;
FDLocalSQL1: TFDLocalSQL;
FDQuery1: TFDQuery;
Series1: TPieSeries;
SpeedButton2: TSpeedButton;
procedure SpeedButton1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
{$R *.LgXhdpiPh.fmx ANDROID}
{$R *.iPad.fmx IOS}
{$R *.Windows.fmx MSWINDOWS}
procedure TMainForm.FormCreate(Sender: TObject);
begin
chartResult.Series[0].Clear;
end;
procedure TMainForm.SpeedButton1Click(Sender: TObject);
var
i: integer;
MyThread: TThread;
begin
EMSFireDACClient1.GetData;
FDMemTable1.Open;
FDConnection1.Open;
FDQuery1.Open;
MyThread := TThread.CreateAnonymousThread(
procedure
begin
while not FDQuery1.Eof do
begin
TThread.Synchronize(MyThread,
procedure
begin
chartResult.Series[0].Add(FDQuery1.FieldByName('TOTAL').AsFloat,
FDQuery1.FieldByName('VKORG').AsString);
end);
FDQuery1.Next;
end;
end);
MyThread.Start;
end;
procedure TMainForm.SpeedButton2Click(Sender: TObject);
begin
Application.Terminate;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpIDerInteger;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpIProxiedInterface,
ClpCryptoLibTypes,
ClpBigInteger;
type
IDerInteger = interface(IAsn1Object)
['{B968152A-5A16-4C1D-95E1-3B5F416D2C75}']
function GetBytes: TCryptoLibByteArray;
function GetPositiveValue: TBigInteger;
function GetValue: TBigInteger;
function ToString(): String;
property value: TBigInteger read GetValue;
property PositiveValue: TBigInteger read GetPositiveValue;
property bytes: TCryptoLibByteArray read GetBytes;
end;
implementation
end.
|
unit steCommon;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
ESTEParserError = class(Exception);
const
steWhiteSpaceChars = [ #0..' ' ];
steSCR = #13;
steSLF = #10;
function STEGetSourceLineNumber(const source : string; srcPos: integer): integer;
implementation
function STEGetSourceLineNumber(const source : string; srcPos: integer): integer;
var
i, maxPos : integer;
lnEnd : char;
begin
lnEnd := char(string(LineEnding)[1]);
Result := 1;
maxPos := Length( source );
if srcPos > maxPos then
Exit
else
maxPos := srcPos;
for i := 1 to maxPos do begin
if (char(source[i]) = lnEnd) then begin
inc(Result);
end;
end;
end;
end.
|
{
Uma empresa deve desenvolver um programa para controlar o salário de todos os seus funcionários. As informações
que ela mantém sobre cada funcionário são: registro_funcionario, nome, cargo e salario
Esta estrutura de dados deve ser armazenada em um vetor de registro onde cada posição contém um funcionário.
Pede-se:
- Definir este vetor de registro com 20 posições.
- Um procedimento para ler funcionários.
- Um procedimento para imprimir todos os funcionários.
- Um procedimento para imprimir os funcionários que ganham acima de 5000,00 reais .
- Um programa principal para a chamada de cada procedimento
}
Program Exc1;
uses Crt;
Type
reg_funcionario = record
n_registro: integer;
nome: string;
cargo: string;
salario: real;
end;
vet_funcs = array[1..20] of reg_funcionario;
Procedure lerFuncionario(var vet: vet_funcs);
var
i: integer;
begin
for i := 1 to 20 do
begin
vet[i].n_registro := i;
write('Nome do funcionário ', i, ': ');
readln(vet[i].nome);
write('Cargo do funcionário ', i, ': ');
readln(vet[i].cargo);
write('Salário do funcionário ', i, ': ');
readln(vet[i].salario);
end;
end;
Procedure imprimir(vet: vet_funcs);
var
i: integer;
begin
ClrScr;
writeln('--------------------------------------');
writeln('Funcionários cadastrados');
writeln('--------------------------------------');
for i := 1 to 20 do
begin
writeln('Registro do funcionário ', i, ': ', vet[i].n_registro);
writeln('Nome do funcionário ', i, ': ', vet[i].nome);
writeln('Cargo do funcionário ', i, ': ', vet[i].cargo);
writeln('Salário do funcionário ', i, ': ', vet[i].salario:6:2);
end;
end;
Procedure imprimir5000(vet: vet_funcs);
var
i: integer;
begin
writeln('--------------------------------------');
writeln('Funcionários que recebem acima de 5000');
writeln('--------------------------------------');
for i := 1 to 20 do
begin
if(vet[i].salario > 5000.00) then
begin
writeln('Registro do funcionário ', i, ': ', vet[i].n_registro);
writeln('Nome do funcionário ', i, ': ', vet[i].nome);
writeln('Cargo do funcionário ', i, ': ', vet[i].cargo);
writeln('Salário do funcionário ', i, ': ', vet[i].salario:6:2);
end;
end;
end;
Var
vet: vet_funcs;
Begin
lerFuncionario(vet);
imprimir(vet);
imprimir5000(vet);
End.
|
unit fmxSASLCrypt;
interface
uses classes, sysutils,IdCoderMIME, IdGlobal,IdHashMessageDigest, strutils, system.IOUtils;
//Decode jabber SASL message for authentification
function GetSASLResponse(AStr: string; AUsername,APassword,AServer : string): string;
implementation
// convert string to commatext
procedure parseNameValues(list: TStringlist; str: String);
begin
str := AnsiReplaceStr(str,'"','');
str := AnsiReplaceStr(str,',','","');
str := '"'+str+'"';
list.CommaText := str;
end;
//Get SASL RESPONSE (as described in the jabber protocole)
function GetSASLResponse(AStr: string; AUsername,APassword,AServer : string): string;
var
_hasher: TIdHashMessageDigest5;
_decoder: TIdDecoderMime;
_encoder: TIdEncoderMime;
_nc: integer;
_realm: string;
_nonce: string;
_cnonce: string;
// -------
azjid: string;
resp, pass, serv, uname, uri, az, dig, a2, p1, p2, e, c: string;
a1: String;
pairs: TStringlist;
a1s: TMemoryStream;
tmpstr: string;
tmp: TIdBytes;
wa1Bytes : TIdBytes;
i : integer;
begin
uname := AUserName;
serv := AServer;
pass := APassword;
_decoder := TIdDecoderMIME.Create(nil);
c := _decoder.DecodeString(AStr);
freeandnil(_decoder);
pairs := TStringlist.Create();
parseNameValues(pairs, c);
_nc := 1;
_realm := pairs.Values['realm'];
_nonce := pairs.Values['nonce'];
tmpstr := copy(c, 1, 7);
if tmpstr = 'rspauth' then begin
Result := '';
Exit
end;
_realm := serv;
// Start the insanity.............
e := '1234567890123456789012345678930';
_encoder := TIdEncoderMIME.Create(nil);
e := _encoder.Encode(e);
_hasher := TIdHashMessageDigest5.Create;
_cnonce := Lowercase(_hasher.HashStringAsHex(e));
azjid := uname + '@' + serv;
uri := 'xmpp/' + serv;
resp := 'username="' + uname + '",';
resp := resp + 'realm="' + _realm + '",';
resp := resp + 'nonce="' + _nonce + '",';
resp := resp + 'cnonce="' + _cnonce + '",';
resp := resp + 'nc=' + Format('%8.8d', [_nc]) + ',';
resp := resp + 'qop=auth,';
resp := resp + 'digest-uri="' + uri + '",';
resp := resp + 'charset=utf-8,';
// actually calc the response...
e := uname + ':' + _realm + ':' + pass;
tmp := _hasher.HashString(e);
// NB: H(A1) is just 16 bytes, not HEX(H(A1))
a1s := TMemoryStream.Create();
a1s.Write(tmp[0], 16);
if (az <> '') then
a1 := ':' + _nonce + ':' + _cnonce + ':' + az
else
a1 := ':' + _nonce + ':' + _cnonce;
// a1 := tmp + a1;
SetLength(wa1Bytes, Length(a1));
for i := 0 to Length(wa1Bytes) -1 do
begin
{$ifdef WIN32}
wa1Bytes[i] := Ord(a1[i+1]);
{$ELSE}
wa1Bytes[i] := Ord(a1[i]);
{$ENDIF}
end;
a1s.Write(Pointer(wa1Bytes)^, Length(wa1Bytes));
a1s.Seek(0, soFromBeginning);
// ha1 := _hasher.HashValue(a1s);
a1s.SaveToFile(TPath.Combine(TPath.GetSharedDownloadsPath , 'test.bin'));
a2 := 'AUTHENTICATE:' + uri;
p1 := Lowercase(_hasher.HashStreamAsHex(a1s));
FreeAndNil(a1s);
p2 := Lowercase(_hasher.HashStringAsHex(a2));
e := p1 + ':' + _nonce + ':' + Format('%8.8d', [_nc]) + ':' + _cnonce + ':auth:' +
p2;
dig := Lowercase(_hasher.HashStringAsHex(e));
if (az <> '') then
resp := resp + 'authzid="' + az + '",';
resp := resp + 'response=' + dig;
Result := _encoder.Encode(resp);
FreeAndNil(_encoder);
FreeAndNil(_hasher);
end;
end.
|
{ Mark Sattolo 428500
CSI-1100A DGD-1 TA: Chris Lankester
Assignment 7, Question 1(b) }
program GetFrequent (input,output);
const
MaxSize = 25;
tab = ' ';
type
WordArray = array[1..MaxSize] of string;
{ ************************************************************************ }
procedure ListWords(WordString, Separator : string; var Words : WordArray;
var NumWords : integer);
{ Given a string of words separated by a common separator, return an array of the words and
an integer with the number of words in the string. }
{ Data Dictionary
Givens: WordString, Separator - WordString is a string of words separated by Separator.
Results: Words, NumWords - Words is the array of the words from WordString
and NumWords is the number of elements in Words.
Intermediates: tmp - keeps track of the various positions of Separator in the loop.
J - an index for Words.
Uses: Delete, Copy, Pos, Length }
var
tmp, J : integer;
begin { procedure ListWords }
NumWords := 0;
J := 1;
tmp := pos(Separator, WordString);
while tmp <> 0 do
begin
Words[J] := copy(WordString, 1, tmp-1);
Delete(WordString, 1, tmp);
NumWords := NumWords + 1;
tmp := pos(Separator, WordString);
J := J + 1
end; { while tmp <>0 }
if length(WordString) > 0 then
begin
NumWords := NumWords + 1;
Words[J] := WordString
end; { if length(WordString) > 0 }
end; { procedure ListWords }
{ ************************************************************************ }
procedure CountNumTimes(Words: WordArray; NumWords: integer; W: string;
var NumTimes: integer);
{ Count the number of times word W occurs in an array of words.}
{ Data Dictionary:
Givens: Words, NumWords - Words is an array of NumWords strings.
W - a string.
Results: NumTimes - the number of times W occurs in the array Words.
Intermediates: I - an index for Words. }
var
I : integer;
begin { procedure CountNumTimes }
NumTimes := 0;
For I := 1 to NumWords do
If Words[I] = W then
inc(NumTimes);
{endif}
{endfor}
end; { procedure CountNumTimes }
{ ************************************************************************ }
{ Main Program: Find the most frequently occurring word in a string. }
{ Data Dictionary
Givens: S - a string consisting of words separated by single spaces.
Intermediates: Words - an array filled with the individual words in S.
NumWords - the number of words in Words.
NumTimes - the number of times each word appears in Words.
k - an index for Words.
Freq - keeps track of the highest value of NumTimes.
Results: FreqWord - the most frequently occurring word in S.
Uses: ListWords, CountNumTimes. }
var
S, FreqWord : string;
Words : WordArray;
Freq, k, NumWords, NumTimes : integer;
begin
{ Read in the program's givens. }
writeln('Please enter a string consisting of words separated by single spaces:');
readln(S);
{ body }
ListWords(S, tab, Words, NumWords);
Freq := 0;
for k := 1 to NumWords do
begin
CountNumTimes(Words, NumWords, Words[k], NumTimes);
if NumTimes > Freq then
begin
Freq := NumTimes;
FreqWord := Words[k]
end; { if NumTimes > Freq }
end; { for k := 1 to NumWords }
{ write out the results }
writeln;
writeln('**************************************************');
writeln('Mark Sattolo 428500');
writeln('CSI-1100A DGD-1 TA: Chris Lankester');
writeln('Assignment 7, Question 1b');
writeln('**************************************************');
writeln;
writeln('The most frequently occurring word in your string is "', FreqWord, '".');
writeln('"', FreqWord, '" appears ', Freq, ' times in your string.');
end.
|
unit htDataConverter;
// Модуль: "w:\common\components\rtl\Garant\HT\htDataConverter.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "ThtDataConverter" MUID: (55599B5C014A)
{$Include w:\common\components\rtl\Garant\HT\htDefineDA.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, htInterfaces
, HT_Const
, daTypes
, l3Date
, daInterfaces
;
type
ThtDataConverter = class(Tl3ProtoObject, IhtDataConverter)
private
function MakeString(aData: Pointer;
const aDesc: OPEL): AnsiString;
protected
function AllocateParamBuffer(const aDescription: IdaParamDescription): Pointer;
procedure ParamToDataBase(const aDescription: IdaParamDescription;
ClientBufferFormat: TdaDataType;
aClientBuffer: Pointer;
var aServerBuffer: Pointer);
procedure ParamFromDataBase(const aDescription: IdaParamDescription;
ClientBufferFormat: TdaDataType;
aServerBuffer: Pointer;
aClientBuffer: Pointer);
procedure FreeParamBuffer(const aDescription: IdaParamDescription;
aBuffer: Pointer);
function ToLargeInt(aData: Pointer;
const aDesc: OPEL): LargeInt;
function ToInteger(aData: Pointer;
const aDesc: OPEL): Integer;
function ToStDate(aData: Pointer;
const aDesc: OPEL): TStDate;
function ToStTime(aData: Pointer;
const aDesc: OPEL): TStTime;
function ToString(aData: Pointer;
const aDesc: OPEL): AnsiString;
function ToByte(aData: Pointer;
const aDesc: OPEL): Byte;
public
constructor Create; reintroduce;
class function Make: IhtDataConverter; reintroduce;
end;//ThtDataConverter
implementation
uses
l3ImplUses
, l3Base
, l3String
, SysUtils
//#UC START# *55599B5C014Aimpl_uses*
//#UC END# *55599B5C014Aimpl_uses*
;
constructor ThtDataConverter.Create;
//#UC START# *55599D240026_55599B5C014A_var*
//#UC END# *55599D240026_55599B5C014A_var*
begin
//#UC START# *55599D240026_55599B5C014A_impl*
inherited Create;
//#UC END# *55599D240026_55599B5C014A_impl*
end;//ThtDataConverter.Create
class function ThtDataConverter.Make: IhtDataConverter;
var
l_Inst : ThtDataConverter;
begin
l_Inst := Create;
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//ThtDataConverter.Make
function ThtDataConverter.MakeString(aData: Pointer;
const aDesc: OPEL): AnsiString;
//#UC START# *562E1BAB0090_55599B5C014A_var*
//#UC END# *562E1BAB0090_55599B5C014A_var*
begin
//#UC START# *562E1BAB0090_55599B5C014A_impl*
if aDesc.nType = ET_CHAR then
Result := l3ArrayToString(aData^, aDesc.wLen)
else
Result := '';
//#UC END# *562E1BAB0090_55599B5C014A_impl*
end;//ThtDataConverter.MakeString
function ThtDataConverter.AllocateParamBuffer(const aDescription: IdaParamDescription): Pointer;
//#UC START# *555995210007_55599B5C014A_var*
//#UC END# *555995210007_55599B5C014A_var*
begin
//#UC START# *555995210007_55599B5C014A_impl*
case aDescription.DataType of
da_dtChar:
l3System.GetLocalMem(Result, aDescription.Size + 1);
da_dtByte:
l3System.GetLocalMem(Result, SizeOf(Byte));
da_dtDWord:
l3System.GetLocalMem(Result, SizeOf(LongInt));
da_dtQWord:
l3System.GetLocalMem(Result, SizeOf(LargeInt));
da_dtDate:
l3System.GetLocalMem(Result, SizeOf(TStDate));
da_dtTime:
l3System.GetLocalMem(Result, SizeOf(TStTime));
da_dtWord:
l3System.GetLocalMem(Result, SizeOf(Word));
da_dtInteger:
l3System.GetLocalMem(Result, SizeOf(Integer));
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
else
Assert(False);
end;
//!! !!! Needs to be implemented !!!
//#UC END# *555995210007_55599B5C014A_impl*
end;//ThtDataConverter.AllocateParamBuffer
procedure ThtDataConverter.ParamToDataBase(const aDescription: IdaParamDescription;
ClientBufferFormat: TdaDataType;
aClientBuffer: Pointer;
var aServerBuffer: Pointer);
//#UC START# *5559955500DF_55599B5C014A_var*
//#UC END# *5559955500DF_55599B5C014A_var*
begin
//#UC START# *5559955500DF_55599B5C014A_impl*
case aDescription.DataType of
da_dtChar:
case ClientBufferFormat of
da_dtDWord:
StrPLCopy(PAnsiChar(aServerBuffer), PAnsiChar(IntToStr(PLongWord(aClientBuffer)^)), aDescription.Size);
da_dtQWord:
StrPLCopy(PAnsiChar(aServerBuffer), PAnsiChar(IntToStr(PLargeInt(aClientBuffer)^)), aDescription.Size);
da_dtChar:
StrPLCopy(PAnsiChar(aServerBuffer), PAnsiChar(PAnsiString(aClientBuffer)^), aDescription.Size);
da_dtDate:
StrPLCopy(PAnsiChar(aServerBuffer), PAnsiChar(IntToStr(PStDate(aClientBuffer)^)), aDescription.Size);
da_dtTime:
StrPLCopy(PAnsiChar(aServerBuffer), PAnsiChar(IntToStr(PStTime(aClientBuffer)^)), aDescription.Size);
da_dtWord:
StrPLCopy(PAnsiChar(aServerBuffer), PAnsiChar(IntToStr(PWord(aClientBuffer)^)), aDescription.Size);
da_dtInteger:
StrPLCopy(PAnsiChar(aServerBuffer), PAnsiChar(IntToStr(PInteger(aClientBuffer)^)), aDescription.Size);
da_dtByte:
StrPLCopy(PAnsiChar(aServerBuffer), PAnsiChar(IntToStr(PByte(aClientBuffer)^)), aDescription.Size);
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtDWord
da_dtDWord:
case ClientBufferFormat of
da_dtDWord:
PLongWord(aServerBuffer)^ := PLongWord(aClientBuffer)^;
da_dtQWord:
PLongWord(aServerBuffer)^ := PLargeInt(aClientBuffer)^;
da_dtChar:
PLongWord(aServerBuffer)^ := StrToInt(PAnsiString(aClientBuffer)^);
da_dtDate:
PLongWord(aServerBuffer)^ := PStDate(aClientBuffer)^;
da_dtTime:
PLongWord(aServerBuffer)^ := PStTime(aClientBuffer)^;
da_dtWord:
PLongWord(aServerBuffer)^ := PWord(aClientBuffer)^;
da_dtInteger:
PLongWord(aServerBuffer)^ := PInteger(aClientBuffer)^;
da_dtByte:
PLongWord(aServerBuffer)^ := PByte(aClientBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtDWord
da_dtQWord:
case ClientBufferFormat of
da_dtDWord:
PLargeInt(aServerBuffer)^ := PLongWord(aClientBuffer)^;
da_dtQWord:
PLargeInt(aServerBuffer)^ := PLargeInt(aClientBuffer)^;
da_dtChar:
PLargeInt(aServerBuffer)^ := StrToInt64(PAnsiString(aClientBuffer)^);
da_dtDate:
PLargeInt(aServerBuffer)^ := PStDate(aClientBuffer)^;
da_dtTime:
PLargeInt(aServerBuffer)^ := PStTime(aClientBuffer)^;
da_dtWord:
PLargeInt(aServerBuffer)^ := PWord(aClientBuffer)^;
da_dtInteger:
PLargeInt(aServerBuffer)^ := PInteger(aClientBuffer)^;
da_dtByte:
PLargeInt(aServerBuffer)^ := PByte(aClientBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtQWord
da_dtDate:
case ClientBufferFormat of
da_dtDWord:
PStDate(aServerBuffer)^ := PLongWord(aClientBuffer)^;
da_dtQWord:
PStDate(aServerBuffer)^ := PLargeInt(aClientBuffer)^;
da_dtChar:
PStDate(aServerBuffer)^ := StrToInt(PAnsiString(aClientBuffer)^);
da_dtDate:
PStDate(aServerBuffer)^ := PStDate(aClientBuffer)^;
da_dtTime:
PStDate(aServerBuffer)^ := PStTime(aClientBuffer)^;
da_dtWord:
PStDate(aServerBuffer)^ := PWord(aClientBuffer)^;
da_dtInteger:
PStDate(aServerBuffer)^ := PInteger(aClientBuffer)^;
da_dtByte:
PStDate(aServerBuffer)^ := PByte(aClientBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtQWord
da_dtTime:
case ClientBufferFormat of
da_dtDWord:
PStTime(aServerBuffer)^ := PLongWord(aClientBuffer)^;
da_dtQWord:
PStTime(aServerBuffer)^ := PLargeInt(aClientBuffer)^;
da_dtChar:
PStTime(aServerBuffer)^ := StrToInt(PAnsiString(aClientBuffer)^);
da_dtDate:
PStTime(aServerBuffer)^ := PStDate(aClientBuffer)^;
da_dtTime:
PStTime(aServerBuffer)^ := PStTime(aClientBuffer)^;
da_dtWord:
PStTime(aServerBuffer)^ := PWord(aClientBuffer)^;
da_dtInteger:
PStTime(aServerBuffer)^ := PInteger(aClientBuffer)^;
da_dtByte:
PStTime(aServerBuffer)^ := PByte(aClientBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end;
da_dtWord:
case ClientBufferFormat of
da_dtDWord:
PWord(aServerBuffer)^ := PLongWord(aClientBuffer)^;
da_dtQWord:
PWord(aServerBuffer)^ := PLargeInt(aClientBuffer)^;
da_dtChar:
PWord(aServerBuffer)^ := StrToInt(PAnsiString(aClientBuffer)^);
da_dtDate:
PWord(aServerBuffer)^ := PStDate(aClientBuffer)^;
da_dtTime:
PWord(aServerBuffer)^ := PStTime(aClientBuffer)^;
da_dtWord:
PWord(aServerBuffer)^ := PWord(aClientBuffer)^;
da_dtInteger:
PWord(aServerBuffer)^ := PInteger(aClientBuffer)^;
da_dtByte:
PWord(aServerBuffer)^ := PByte(aClientBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtQWord
da_dtInteger:
case ClientBufferFormat of
da_dtDWord:
PInteger(aServerBuffer)^ := PLongWord(aClientBuffer)^;
da_dtQWord:
PInteger(aServerBuffer)^ := PLargeInt(aClientBuffer)^;
da_dtChar:
PInteger(aServerBuffer)^ := StrToInt(PAnsiString(aClientBuffer)^);
da_dtDate:
PInteger(aServerBuffer)^ := PStDate(aClientBuffer)^;
da_dtTime:
PInteger(aServerBuffer)^ := PStTime(aClientBuffer)^;
da_dtWord:
PInteger(aServerBuffer)^ := PWord(aClientBuffer)^;
da_dtInteger:
PInteger(aServerBuffer)^ := PInteger(aClientBuffer)^;
da_dtByte:
PInteger(aServerBuffer)^ := PByte(aClientBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtQWord
da_dtByte:
case ClientBufferFormat of
da_dtDWord:
PByte(aServerBuffer)^ := PLongWord(aClientBuffer)^;
da_dtQWord:
PByte(aServerBuffer)^ := PLargeInt(aClientBuffer)^;
da_dtChar:
PByte(aServerBuffer)^ := StrToInt(PAnsiString(aClientBuffer)^);
da_dtDate:
PByte(aServerBuffer)^ := PStDate(aClientBuffer)^;
da_dtTime:
PByte(aServerBuffer)^ := PStTime(aClientBuffer)^;
da_dtWord:
PByte(aServerBuffer)^ := PWord(aClientBuffer)^;
da_dtInteger:
PByte(aServerBuffer)^ := PInteger(aClientBuffer)^;
da_dtByte:
PByte(aServerBuffer)^ := PByte(aClientBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtQWord
(* da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
else
Assert(False);
end;
//!! !!! Needs to be implemented !!!
//#UC END# *5559955500DF_55599B5C014A_impl*
end;//ThtDataConverter.ParamToDataBase
procedure ThtDataConverter.ParamFromDataBase(const aDescription: IdaParamDescription;
ClientBufferFormat: TdaDataType;
aServerBuffer: Pointer;
aClientBuffer: Pointer);
//#UC START# *55599596005B_55599B5C014A_var*
//#UC END# *55599596005B_55599B5C014A_var*
begin
//#UC START# *55599596005B_55599B5C014A_impl*
case ClientBufferFormat of
da_dtChar:
case aDescription.DataType of
da_dtChar:
PString(aClientBuffer)^ := StrPas(PAnsiChar(aServerBuffer));
da_dtDWord:
PString(aClientBuffer)^ := IntToStr(PLongWord(aServerBuffer)^);
da_dtQWord:
PString(aClientBuffer)^ := IntToStr(PLargeInt(aServerBuffer)^);
da_dtDate:
PAnsiString(aClientBuffer)^ := IntToStr(PStDate(aServerBuffer)^);
da_dtTime:
PAnsiString(aClientBuffer)^ := IntToStr(PStTime(aServerBuffer)^);
da_dtWord:
PAnsiString(aClientBuffer)^ := IntToStr(PWord(aServerBuffer)^);
da_dtInteger:
PAnsiString(aClientBuffer)^ := IntToStr(PInteger(aServerBuffer)^);
da_dtByte:
PAnsiString(aClientBuffer)^ := IntToStr(PByte(aServerBuffer)^);
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtDWord
da_dtDWord:
case aDescription.DataType of
da_dtChar:
PLongWord(aClientBuffer)^ := StrToInt(PAnsiChar(aServerBuffer)^);
da_dtDWord:
PLongWord(aClientBuffer)^ := PLongWord(aServerBuffer)^;
da_dtQWord:
PLongWord(aClientBuffer)^ := PLargeInt(aServerBuffer)^;
da_dtDate:
PLongWord(aClientBuffer)^ := PStDate(aServerBuffer)^;
da_dtTime:
PLongWord(aClientBuffer)^ := PStTime(aServerBuffer)^;
da_dtWord:
PLongWord(aClientBuffer)^ := PWord(aServerBuffer)^;
da_dtInteger:
PLongWord(aClientBuffer)^ := PInteger(aServerBuffer)^;
da_dtByte:
PLongWord(aClientBuffer)^ := PByte(aServerBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtDWord
da_dtQWord:
case ClientBufferFormat of
da_dtChar:
PLargeInt(aClientBuffer)^ := StrToInt64(PAnsiChar(aServerBuffer)^);
da_dtDWord:
PLargeInt(aClientBuffer)^ := PLongWord(aServerBuffer)^;
da_dtQWord:
PLargeInt(aClientBuffer)^ := PLargeInt(aServerBuffer)^;
da_dtDate:
PLargeInt(aClientBuffer)^ := PStDate(aServerBuffer)^;
da_dtTime:
PLargeInt(aClientBuffer)^ := PStTime(aServerBuffer)^;
da_dtWord:
PLargeInt(aClientBuffer)^ := PWord(aServerBuffer)^;
da_dtInteger:
PLargeInt(aClientBuffer)^ := PInteger(aServerBuffer)^;
da_dtByte:
PLargeInt(aClientBuffer)^ := PByte(aServerBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtQWord
da_dtDate:
case ClientBufferFormat of
da_dtChar:
PStDate(aClientBuffer)^ := StrToInt(PAnsiChar(aServerBuffer)^);
da_dtDWord:
PStDate(aClientBuffer)^ := PLongWord(aServerBuffer)^;
da_dtQWord:
PStDate(aClientBuffer)^ := PLargeInt(aServerBuffer)^;
da_dtDate:
PStDate(aClientBuffer)^ := PStDate(aServerBuffer)^;
da_dtTime:
PStDate(aClientBuffer)^ := PStTime(aServerBuffer)^;
da_dtWord:
PStDate(aClientBuffer)^ := PWord(aServerBuffer)^;
da_dtInteger:
PStDate(aClientBuffer)^ := PInteger(aServerBuffer)^;
da_dtByte:
PStDate(aClientBuffer)^ := PByte(aServerBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtQWord
da_dtTime:
case ClientBufferFormat of
da_dtChar:
PStTime(aClientBuffer)^ := StrToInt(PAnsiChar(aServerBuffer)^);
da_dtDWord:
PStTime(aClientBuffer)^ := PLongWord(aServerBuffer)^;
da_dtQWord:
PStTime(aClientBuffer)^ := PLargeInt(aServerBuffer)^;
da_dtDate:
PStTime(aClientBuffer)^ := PStDate(aServerBuffer)^;
da_dtTime:
PStTime(aClientBuffer)^ := PStTime(aServerBuffer)^;
da_dtWord:
PStTime(aClientBuffer)^ := PWord(aServerBuffer)^;
da_dtInteger:
PStTime(aClientBuffer)^ := PInteger(aServerBuffer)^;
da_dtByte:
PStTime(aClientBuffer)^ := PByte(aServerBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end;
da_dtWord:
case ClientBufferFormat of
da_dtChar:
PWord(aClientBuffer)^ := StrToInt(PAnsiChar(aServerBuffer)^);
da_dtDWord:
PWord(aClientBuffer)^ := PLongWord(aServerBuffer)^;
da_dtQWord:
PWord(aClientBuffer)^ := PLargeInt(aServerBuffer)^;
da_dtDate:
PWord(aClientBuffer)^ := PStDate(aServerBuffer)^;
da_dtTime:
PWord(aClientBuffer)^ := PStTime(aServerBuffer)^;
da_dtWord:
PWord(aClientBuffer)^ := PWord(aServerBuffer)^;
da_dtInteger:
PWord(aClientBuffer)^ := PInteger(aServerBuffer)^;
da_dtByte:
PWord(aClientBuffer)^ := PByte(aServerBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtQWord
da_dtInteger:
case ClientBufferFormat of
da_dtChar:
PInteger(aClientBuffer)^ := StrToInt(PAnsiChar(aServerBuffer)^);
da_dtDWord:
PInteger(aClientBuffer)^ := PLongWord(aServerBuffer)^;
da_dtQWord:
PInteger(aClientBuffer)^ := PLargeInt(aServerBuffer)^;
da_dtDate:
PInteger(aClientBuffer)^ := PStDate(aServerBuffer)^;
da_dtTime:
PInteger(aClientBuffer)^ := PStTime(aServerBuffer)^;
da_dtWord:
PInteger(aClientBuffer)^ := PWord(aServerBuffer)^;
da_dtInteger:
PInteger(aClientBuffer)^ := PInteger(aServerBuffer)^;
da_dtByte:
PInteger(aClientBuffer)^ := PByte(aServerBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtQWord
da_dtByte:
case ClientBufferFormat of
da_dtChar:
PByte(aClientBuffer)^ := StrToInt(PAnsiChar(aServerBuffer)^);
da_dtDWord:
PByte(aClientBuffer)^ := PLongWord(aServerBuffer)^;
da_dtQWord:
PByte(aClientBuffer)^ := PLargeInt(aServerBuffer)^;
da_dtDate:
PByte(aClientBuffer)^ := PStDate(aServerBuffer)^;
da_dtTime:
PByte(aClientBuffer)^ := PStTime(aServerBuffer)^;
da_dtWord:
PByte(aClientBuffer)^ := PWord(aServerBuffer)^;
da_dtInteger:
PByte(aClientBuffer)^ := PInteger(aServerBuffer)^;
da_dtByte:
PByte(aClientBuffer)^ := PByte(aServerBuffer)^;
(*
++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
end; // Client case da_dtQWord
(*++ da_dtChar
++ , da_dtByte
++ , da_dtDate
++ , da_dtTime
++ , da_dtDWord
++ , da_dtWord
++ , da_dtInteger
, da_dtBoolean
++ , da_dtQWord*)
else
Assert(False);
end;
//!! !!! Needs to be implemented !!!
//#UC END# *55599596005B_55599B5C014A_impl*
end;//ThtDataConverter.ParamFromDataBase
procedure ThtDataConverter.FreeParamBuffer(const aDescription: IdaParamDescription;
aBuffer: Pointer);
//#UC START# *5559D14D02D1_55599B5C014A_var*
//#UC END# *5559D14D02D1_55599B5C014A_var*
begin
//#UC START# *5559D14D02D1_55599B5C014A_impl*
l3System.FreeLocalMem(aBuffer);
//#UC END# *5559D14D02D1_55599B5C014A_impl*
end;//ThtDataConverter.FreeParamBuffer
function ThtDataConverter.ToLargeInt(aData: Pointer;
const aDesc: OPEL): LargeInt;
//#UC START# *55C89B830012_55599B5C014A_var*
//#UC END# *55C89B830012_55599B5C014A_var*
begin
//#UC START# *55C89B830012_55599B5C014A_impl*
Result := 0;
case aDesc.nType of
ET_CHAR:
Result := StrToInt64(MakeString(aData, aDesc));
// ET_ARRA = 1; (* Массив байтов заданной длины *)
ET_BYTE:
Result := PByte(aData)^; (* Элемент - короткое целое (1 байт) без знака *)
ET_INTR:
Result := PSmallInt(aData)^; (* Элемент - целое со знаком *)
ET_WORD:
Result := PWord(aData)^; (* Элемент - целое без знака *)
// ET_DATE = 5; (* Дата - целое без знака *)
// ET_NMBR = 6; (* Номер - 3-х байтовое целое без знака *)
ET_LONG:
Result := PLongWord(aData)^; (* Элемент - длинное целое со знаком *)
ET_DWRD:
Result := PLongWord(aData)^; (* Элемент - длинное целое без знака *)
// ET_FLOA = 9; (* Элемент - single *)
// ET_CURR =10; (* Деньги - double *)
// ET_DFLT =11; (* Элемент - double *)
else
Assert(False);
end;
//#UC END# *55C89B830012_55599B5C014A_impl*
end;//ThtDataConverter.ToLargeInt
function ThtDataConverter.ToInteger(aData: Pointer;
const aDesc: OPEL): Integer;
//#UC START# *55C89BB40093_55599B5C014A_var*
//#UC END# *55C89BB40093_55599B5C014A_var*
begin
//#UC START# *55C89BB40093_55599B5C014A_impl*
Result := 0;
case aDesc.nType of
ET_CHAR:
Result := StrToInt(MakeString(aData, aDesc));
// ET_ARRA = 1; (* Массив байтов заданной длины *)
ET_BYTE:
Result := PByte(aData)^; (* Элемент - короткое целое (1 байт) без знака *)
ET_INTR:
Result := PSmallInt(aData)^; (* Элемент - целое со знаком *)
ET_WORD:
Result := PWord(aData)^; (* Элемент - целое без знака *)
// ET_DATE = 5; (* Дата - целое без знака *)
// ET_NMBR = 6; (* Номер - 3-х байтовое целое без знака *)
ET_LONG:
Result := PLongWord(aData)^; (* Элемент - длинное целое со знаком *)
ET_DWRD:
Result := PLongWord(aData)^; (* Элемент - длинное целое без знака *)
// ET_FLOA = 9; (* Элемент - single *)
// ET_CURR =10; (* Деньги - double *)
// ET_DFLT =11; (* Элемент - double *)
else
Assert(False);
end;
//#UC END# *55C89BB40093_55599B5C014A_impl*
end;//ThtDataConverter.ToInteger
function ThtDataConverter.ToStDate(aData: Pointer;
const aDesc: OPEL): TStDate;
//#UC START# *55C89BC8017D_55599B5C014A_var*
//#UC END# *55C89BC8017D_55599B5C014A_var*
begin
//#UC START# *55C89BC8017D_55599B5C014A_impl*
Result := 0;
case aDesc.nType of
ET_CHAR:
Result := StrToInt(MakeString(aData, aDesc));
// ET_ARRA = 1; (* Массив байтов заданной длины *)
ET_BYTE:
Result := PByte(aData)^; (* Элемент - короткое целое (1 байт) без знака *)
ET_INTR:
Result := PSmallInt(aData)^; (* Элемент - целое со знаком *)
ET_WORD:
Result := PWord(aData)^; (* Элемент - целое без знака *)
// ET_DATE = 5; (* Дата - целое без знака *)
// ET_NMBR = 6; (* Номер - 3-х байтовое целое без знака *)
ET_LONG:
Result := PLongWord(aData)^; (* Элемент - длинное целое со знаком *)
ET_DWRD:
Result := PLongWord(aData)^; (* Элемент - длинное целое без знака *)
// ET_FLOA = 9; (* Элемент - single *)
// ET_CURR =10; (* Деньги - double *)
// ET_DFLT =11; (* Элемент - double *)
else
Assert(False);
end;
//#UC END# *55C89BC8017D_55599B5C014A_impl*
end;//ThtDataConverter.ToStDate
function ThtDataConverter.ToStTime(aData: Pointer;
const aDesc: OPEL): TStTime;
//#UC START# *55C89BDC012F_55599B5C014A_var*
//#UC END# *55C89BDC012F_55599B5C014A_var*
begin
//#UC START# *55C89BDC012F_55599B5C014A_impl*
Result := 0;
case aDesc.nType of
ET_CHAR:
Result := StrToInt(MakeString(aData, aDesc));
// ET_ARRA = 1; (* Массив байтов заданной длины *)
ET_BYTE:
Result := PByte(aData)^; (* Элемент - короткое целое (1 байт) без знака *)
ET_INTR:
Result := PSmallInt(aData)^; (* Элемент - целое со знаком *)
ET_WORD:
Result := PWord(aData)^; (* Элемент - целое без знака *)
// ET_DATE = 5; (* Дата - целое без знака *)
// ET_NMBR = 6; (* Номер - 3-х байтовое целое без знака *)
ET_LONG:
Result := PLongWord(aData)^; (* Элемент - длинное целое со знаком *)
ET_DWRD:
Result := PLongWord(aData)^; (* Элемент - длинное целое без знака *)
// ET_FLOA = 9; (* Элемент - single *)
// ET_CURR =10; (* Деньги - double *)
// ET_DFLT =11; (* Элемент - double *)
else
Assert(False);
end;
//#UC END# *55C89BDC012F_55599B5C014A_impl*
end;//ThtDataConverter.ToStTime
function ThtDataConverter.ToString(aData: Pointer;
const aDesc: OPEL): AnsiString;
//#UC START# *55FA9B9301D7_55599B5C014A_var*
//#UC END# *55FA9B9301D7_55599B5C014A_var*
begin
//#UC START# *55FA9B9301D7_55599B5C014A_impl*
Result := '';
case aDesc.nType of
ET_CHAR:
Result := MakeString(aData, aDesc);
// ET_ARRA = 1; (* Массив байтов заданной длины *)
ET_BYTE:
Result := IntToStr(PByte(aData)^); (* Элемент - короткое целое (1 байт) без знака *)
ET_INTR:
Result := IntToStr(PSmallInt(aData)^); (* Элемент - целое со знаком *)
ET_WORD:
Result := IntToStr(PWord(aData)^); (* Элемент - целое без знака *)
// ET_DATE = 5; (* Дата - целое без знака *)
// ET_NMBR = 6; (* Номер - 3-х байтовое целое без знака *)
ET_LONG:
Result := IntToStr(PLongWord(aData)^); (* Элемент - длинное целое со знаком *)
ET_DWRD:
Result := IntToStr(PLongWord(aData)^); (* Элемент - длинное целое без знака *)
// ET_FLOA = 9; (* Элемент - single *)
// ET_CURR =10; (* Деньги - double *)
// ET_DFLT =11; (* Элемент - double *)
else
Assert(False);
end;
//#UC END# *55FA9B9301D7_55599B5C014A_impl*
end;//ThtDataConverter.ToString
function ThtDataConverter.ToByte(aData: Pointer;
const aDesc: OPEL): Byte;
//#UC START# *562E0F8F02F3_55599B5C014A_var*
//#UC END# *562E0F8F02F3_55599B5C014A_var*
begin
//#UC START# *562E0F8F02F3_55599B5C014A_impl*
Result := 0;
case aDesc.nType of
ET_CHAR:
Result := StrToInt(MakeString(aData, aDesc));
// ET_ARRA = 1; (* Массив байтов заданной длины *)
ET_BYTE:
Result := PByte(aData)^; (* Элемент - короткое целое (1 байт) без знака *)
ET_INTR:
Result := PSmallInt(aData)^; (* Элемент - целое со знаком *)
ET_WORD:
Result := PWord(aData)^; (* Элемент - целое без знака *)
// ET_DATE = 5; (* Дата - целое без знака *)
// ET_NMBR = 6; (* Номер - 3-х байтовое целое без знака *)
ET_LONG:
Result := PLongWord(aData)^; (* Элемент - длинное целое со знаком *)
ET_DWRD:
Result := PLongWord(aData)^; (* Элемент - длинное целое без знака *)
// ET_FLOA = 9; (* Элемент - single *)
// ET_CURR =10; (* Деньги - double *)
// ET_DFLT =11; (* Элемент - double *)
else
Assert(False);
end;
//#UC END# *562E0F8F02F3_55599B5C014A_impl*
end;//ThtDataConverter.ToByte
end.
|
Unit Unit6;
Interface
Uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBTables, db_STORE, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
Data.fireTables;
Type
TForm6 = Class(TForm)
Button1: TButton;
ALQuery1: TALQuery;
LabeledEdit1: TLabeledEdit;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
DBGrid1: TDBGrid;
DataSource1: TDataSource;
Button2: TButton;
Procedure FormCreate(Sender : TObject);
Procedure Button1Click(Sender : TObject);
Procedure BitBtn1Click(Sender : TObject);
Procedure BitBtn2Click(Sender : TObject);
procedure ALQuery1BeforeOpen(DataSet: TDataSet);
procedure Button2Click(Sender: TObject);
Private
FDatabasename: string;
procedure SetDatabasename(const Value: string);
{ Private declarations }
Public
{ Public declarations }
property Databasename:string read FDatabasename write SetDatabasename;
End;
Var
Form6: TForm6;
Implementation
{$R *.dfm}
Uses data.db_store_types, iniFiles, mFunctions;
procedure TForm6.ALQuery1BeforeOpen(DataSet: TDataSet);
begin
// exemplo como altera os parametros antes de abrir a tabela.
// alquery1.DatabaseName := FDatabasename;
end;
Procedure TForm6.BitBtn1Click(Sender : TObject);
Begin
With createQuery('Estoque', 'ctgrupo', 'grupo=:grupo') Do
Try
paramByName('grupo').asString := '001';
open;
Finally
free;
End;
LabeledEdit1.text := intToStr(Session.DatabaseCount);
ALQuery1.ReOpen;
End;
Procedure TForm6.BitBtn2Click(Sender : TObject);
Var qry: TALQuery;
Begin
qry := createQuery('Estoque', 'ctgrupo', 'grupo=:codigogrupo');
Try
qry.ActiveSqlUpdate('ctgrupo', 'grupo'); // cria links TUpdateSQL
qry.paramByName('codigogrupo').asString := '001'; // inicia o parametro grupo
qry.open; // abre a tabela
qry.edit; // abre o registor
qry.FieldByName('nome').asString := 'TESTE '+DateTimeToStr(now);
// antes do post;
qry.StartTransaction; // inicia transacao
Try
qry.post; // envia o Update para o Banco
qry.CommitTransaction; // commit na transaçao
Except
qry.RollBackTransaction;
End;
Finally
qry.free; // nao pode esquecer deste....
End;
ALQuery1.reopen;
End;
Procedure TForm6.Button1Click(Sender : TObject);
Var bd: TDatabaseBASE;
Begin
// cria uma conexao para SQLEstoque com base na configuracao d Estoque.ini
bd := ConnectDataBaseFromIni('SQLEstoque', 'Estoque', 'estoque.ini', True);
// bd.Connected := true; // nao precisa faze a conexao no codigo, o componente faz automatico.
// cria uma conexao para SQLSupervisor.
ConnectDatabaseFromIni('SQLSupervisor', 'Supervisor', 'supervisor.ini', False);
// LEMBRETE...!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// se o banco for o mesmo para os dois alias,
// a conexão podera ser reproveitada e os dois alias apontar para a mesma conexao;
LabeledEdit1.text := intToStr(Session.DatabaseCount);
// se precisar do Usuario / Senha do Banco de dados...
okDlg('Usuario do BD: ' + DBLoginDoUsuario + ' Senha: ' + DBSenhaDoUsuario);
End;
procedure TForm6.Button2Click(Sender: TObject);
Var qry: TALQuery;
Begin
qry := createQuery('Estoque', 'ctgrupo', 'grupo=:codigogrupo');
Try
//qry.AutoTransction := true;
qry.ActiveSqlUpdate('ctgrupo', 'grupo'); // cria links TUpdateSQL
qry.paramByName('codigogrupo').asString := '001'; // inicia o parametro grupo
qry.open; // abre a tabela
qry.edit; // abre o registor
qry.FieldByName('nome').asString := 'TESTE '+DateTimeToStr(now);
// antes do post;
qry.post; // envia o Update para o Banco
Finally
//qry.free; // nao pode esquecer deste....
End;
//ALQuery1.reopen;
end;
Procedure TForm6.FormCreate(Sender : TObject);
Var ini: TIniFile;
rt: String;
Begin
databasename := 'Estoque';
LabeledEdit1.text := intToStr(Session.DatabaseCount);
// sem usar variavel
With TIniFile.create('Supervisor.ini') Do
Try
rt := readString('Config', 'Usuario', '');
Finally
free; // nao pode esquecer de liberar a memoria (jamais)
End;
// inicializando objeto com uma variavel associado
ini := TIniFile.create('estoque.ini');
Try
rt := ini.readString('Config', 'Usuario', '');
Finally
freeAndNil(ini);
ini := Nil; // corrige bug no delphi 2007 que nao poe NIL usando FreeAndNil
End;
// uso misto de variavel e acesso de memoria direto
ini := TIniFile.create('estoque.ini');
With ini Do
Try
rt := readString('Config', 'Usuario', '');
Finally
free;
ini := Nil;
End;
End;
procedure TForm6.SetDatabasename(const Value: string);
begin
FDatabasename := Value;
// troca os Databasename de todos dos TQuery que estao no FORM (desiging)
DataBaseNameChange(self,value);
end;
End.
|
{ Subroutine SST_R_PAS_SMENT_CONST
*
* Process the CONST_STATEMENT syntax.
}
module sst_r_pas_SMENT_CONST;
define sst_r_pas_sment_const;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_sment_const; {process CONST_STATEMENT syntax}
var
tag: sys_int_machine_t; {tag number from .syn file}
str_h: syo_string_t; {handle to string for current tag}
sym_p: sst_symbol_p_t; {scratch pointer to symbol table entry}
stat: sys_err_t;
begin
syo_level_down; {down into CONST_STATEMENT syntax}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'const_bad', nil, 0);
while tag <> syo_tag_end_k do begin {once for each constant declared}
if tag <> 1 then begin {complain if unexpected TAG value}
syo_error_tag_unexp (tag, str_h);
end;
sst_symbol_new {create new symbol for constant name}
(str_h, syo_charcase_down_k, sym_p, stat);
syo_error_abort (stat, str_h, '', '', nil, 0);
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'const_bad', nil, 0); {expression tag}
if tag <> 1 then begin {complain if unexpected TAG value}
syo_error_tag_unexp (tag, str_h);
end;
sst_r_pas_exp (str_h, true, sym_p^.const_exp_p); {build expression descriptor}
sym_p^.flags := sym_p^.flags + {symbol is defined and has a value}
[sst_symflag_def_k];
sym_p^.symtype := sst_symtype_const_k; {this symbol is a constant}
syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'const_bad', nil, 0); {next const name}
end; {back and process new constant}
syo_level_up; {up from CONST_STATMENT syntax}
end;
|
(*
libltc - en+decode linear timecode
Copyright (C) 2005 Maarten de Boer <mdeboer@iua.upf.es>
Copyright (C) 2006-2012 Robin Gareus <robin@gareus.org>
Copyright (C) 2008-2009 Jan <jan@geheimwerk.de>
Binary constant generator macro for endianess conversion
by Tom Torfs - donated to the public domain
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library.
If not, see <http://www.gnu.org/licenses/>.
Conversion to Pascal Copyright 2015 (c) Oleksandr Nazaruk <support@freehand.com.ua>
based on libltc-1.1.4
*)
unit FH.LIBLTC.DECODER;
interface
uses
System.SysUtils, System.Types, System.Generics.Collections, Math, FH.LIBLTC.LTC, FH.LIBLTC.TIMECODE;
{$M+}
type
TLTCDecoder = class
private
FQueue : TQueue<TLTCFrameExt>;
FQueue_Len : integer;
FBiphase_state : byte;
FBiphase_prev : byte;
FSnd_to_biphase_state : byte;
FSnd_to_biphase_cnt : int64; ///< counts the samples in the current period
FSnd_to_biphase_lmt : integer; ///< specifies when a state-change is considered biphase-clock or 2*biphase-clock
fSnd_to_biphase_period: Single; ///< track length of a period - used to set snd_to_biphase_lmt
FSnd_to_biphase_min : ltcsnd_sample_t;
FSnd_to_biphase_max : ltcsnd_sample_t;
FDecoder_sync_word : word;
FLtc_frame : TLTCFrameRAW;
FBit_cnt : integer;
FFrame_start_off : ltc_off_t;
FFrame_start_prev : ltc_off_t;
FBiphase_tics : array[0..LTC_FRAME_BIT_COUNT-1] of Single;
FBiphase_tic : integer;
function GetBiphaseTics(index: integer): Single;
procedure SetBiphaseTics(index: integer; const Value: Single);
procedure SetAPV(value: integer);
protected
property biphase_tics[index: integer]: Single read GetBiphaseTics write SetBiphaseTics;
public
constructor create(); overload;
destructor Destroy; override;
procedure Write(buf: array of ltcsnd_sample_t; size : size_t; posinfo : ltc_off_t);
function Read(var frame: TLTCFrameExt): boolean;
property Queue: TQueue<TLTCFrameExt> read FQueue write FQueue;
property queue_len: integer read FQueue_len write FQueue_len;
property decoder_sync_word : word read FDecoder_sync_word write FDecoder_sync_word;
property frame_start_off : ltc_off_t read FFrame_start_off write FFrame_start_off;
property frame_start_prev : ltc_off_t read FFrame_start_prev write FFrame_start_prev;
property ltc_frame : TLTCFrameRAW read FLtc_frame write FLtc_frame;
property biphase_prev : byte read FBiphase_prev write FBiphase_prev;
property biphase_state : byte read FBiphase_state write FBiphase_state;
property biphase_tic : integer read FBiphase_tic write FBiphase_tic;
property bit_cnt : integer read FBit_cnt write FBit_cnt;
property snd_to_biphase_period : Single read fSnd_to_biphase_period write fSnd_to_biphase_period;
property snd_to_biphase_lmt : integer read FSnd_to_biphase_lmt write FSnd_to_biphase_lmt;
property snd_to_biphase_cnt : int64 read FSnd_to_biphase_cnt write FSnd_to_biphase_cnt;
property snd_to_biphase_state : byte read FSnd_to_biphase_state write FSnd_to_biphase_state;
property snd_to_biphase_min : ltcsnd_sample_t read FSnd_to_biphase_min write FSnd_to_biphase_min;
property snd_to_biphase_max : ltcsnd_sample_t read FSnd_to_biphase_max write FSnd_to_biphase_max;
property apv: integer write SetAPV;
end;
function calc_volume_db(d : TLTCDecoder): Single;
Procedure parse_ltc(d : TLTCDecoder; bit: byte; offset: integer; posinfo: ltc_off_t);
procedure biphase_decode2(d : TLTCDecoder; offset : integer; pos: ltc_off_t); inline;
function decode_ltc(d: TLTCDecoder; sound: array of ltcsnd_sample_t; size: size_t; posinfo: ltc_off_t): integer;
implementation
(* OK *)
function calc_volume_db(d : TLTCDecoder): Single;
begin
if (d.snd_to_biphase_max <= d.snd_to_biphase_min) then
begin
result:= NegInfinity;
exit;
end;
result:= (20.0 * log10((d.snd_to_biphase_max - d.snd_to_biphase_min) / 255.0));
end;
(* OK *)
Procedure parse_ltc(d : TLTCDecoder; bit: byte; offset: integer; posinfo: ltc_off_t);
var
bit_num, bit_set, byte_num : integer;
k : integer;
bi , bo : byte;
bc : integer;
temp_Queue: TLTCFrameExt;
btc : integer;
byte_num_max : integer;
begin
if (d.bit_cnt = 0) then
begin
fillchar(addr(d.ltc_frame)^, sizeof(TLTCFrameRAW), #0);
if (d.frame_start_prev < 0) then
begin
d.frame_start_off := trunc(posinfo - d.snd_to_biphase_period);
{$IfDef OnDebug}
d.DoDebug(format('parse_ltc -> d.frame_start_off = %d',[d.frame_start_off, posinfo, d.snd_to_biphase_period]));
{$EndIf}
end
else
d.frame_start_off := d.frame_start_prev;
end;
d.frame_start_prev := ltc_off_t(offset + posinfo);
if (d.bit_cnt >= LTC_FRAME_BIT_COUNT) then
begin
byte_num_max := LTC_FRAME_BIT_COUNT shr 3;
(* shift bits backwards *)
for k:=0 to byte_num_max-1 do
begin
bi := PByte(addr(d.ltc_frame))[k];
bo := 0;
if (bi and $80)>0 then
bo := bo or $40
else
bo := bo or $0;
if (bi and $40)>0 then
bo := bo or $20
else
bo := bo or $0;
if (bi and $20)>0 then
bo := bo or $10
else
bo := bo or $0;
if (bi and $10)>0 then
bo := bo or $08
else
bo := bo or $0;
if (bi and $08)>0 then
bo := bo or $04
else
bo := bo or $0;
if (bi and $04)>0 then
bo := bo or $02
else
bo := bo or $0;
if (bi and $02)>0 then
bo := bo or $01
else
bo := bo or $0;
if (k+1 < byte_num_max) then
begin
if (PByte(@d.ltc_frame)[k+1] and $01)>0 then
bo := bo or $80
else
bo := bo or $0;
end;
PByte(@d.ltc_frame)[k] := bo;
{$IfDef OnDebug}
d.DoDebug(format('parse_ltc -> d.ltc_frame[%d]= %d',[k, bo]));
{$EndIf}
end;
d.frame_start_off := d.frame_start_off+ceil(d.snd_to_biphase_period);
{$IfDef OnDebug}
d.DoDebug(format('parse_ltc -> d.frame_start_off = %d (frame_start_off - %f)',[d.frame_start_off, d.snd_to_biphase_period]));
{$EndIf}
d.bit_cnt:=d.bit_cnt-1;
end;
(* corrected:2013-01-12,
+ "and $FF" - range check error
*)
d.decoder_sync_word := word(d.decoder_sync_word shl $0001) ;
if bit>0 then
begin
d.decoder_sync_word := d.decoder_sync_word or $0001;
if ((d.bit_cnt < LTC_FRAME_BIT_COUNT) and (d.bit_cnt>=0)) then
begin
// Isolating the lowest three bits: the location of this bit in the current byte
bit_num := (d.bit_cnt and $7);
// Using the bit number to define which of the eight bits to set
bit_set := $01 shl bit_num;
// Isolating the higher bits: the number of the byte/char the target bit is contained in
byte_num := d.bit_cnt shr 3;
PByte(@(d.ltc_frame))[byte_num] := PByte(@(d.ltc_frame))[byte_num] or bit_set;
{$IfDef OnDebug}
d.DoDebug(format('parse_ltc -> d.ltc_frame[%d]= %d bit_set=%d',[byte_num, PByte(@(d.ltc_frame))[byte_num], bit_set]));
{$EndIf}
end;
end;
d.bit_cnt:=d.bit_cnt+1;
if (d.decoder_sync_word = $3ffd (*LTC Sync Word 0x3ffd*)) then
begin
if (d.bit_cnt = LTC_FRAME_BIT_COUNT) then
begin
move(d.ltc_frame, temp_Queue.ltc, sizeof(TLTCFrameRAW));
for bc := 0 to LTC_FRAME_BIT_COUNT-1 do
begin
btc := (d.biphase_tic + bc ) mod LTC_FRAME_BIT_COUNT;
temp_Queue.biphase_tics[bc] := d.biphase_tics[btc];
end;
temp_Queue.off_start := d.frame_start_off;
temp_Queue.off_end := posinfo + offset - 1;
temp_Queue.reverse := 0;
temp_Queue.volume := calc_volume_db(d);
temp_Queue.sample_min := d.snd_to_biphase_min;
temp_Queue.sample_max := d.snd_to_biphase_max;
{$IfDef OnDebug}
d.DoDebug(format('parse_ltc -> temp_Queue.off_start = %d (%d 16 * %f)',[temp_Queue.off_start, d.frame_start_off, d.snd_to_biphase_period]));
d.DoDebug(format('parse_ltc -> temp_Queue.off_end = %d (%d + %d -1 - 16 * %f)',[temp_Queue.off_end, posinfo, offset, d.snd_to_biphase_period]));
d.DoDebug(format('parse_ltc -> temp_Queue.reverse = %d (%d 8 * %f)',[temp_Queue.reverse, (LTC_FRAME_BIT_COUNT shr 3), d.snd_to_biphase_period]));
{$EndIf}
d.queue.Enqueue(temp_Queue);
if d.queue.Count>d.queue_len then d.queue.Dequeue;
{d.queue[d.queue_write_off]:=temp_Queue;
d.queue_write_off := d.queue_write_off + 1;
if (d.queue_write_off = d.queue_len) then d.queue_write_off := 0; }
end;
d.bit_cnt := 0;
end;
if (d.decoder_sync_word = $BFFC (*LTC Sync Word 0xBFFC*)) then
begin
if (d.bit_cnt = LTC_FRAME_BIT_COUNT) then
begin
byte_num_max := LTC_FRAME_BIT_COUNT shr 3;
(* swap bits *)
for k:=0 to byte_num_max-1 do
begin
bi := PByte(addr(d.ltc_frame))[k];
bo := 0;
if (bi and $80)>0 then
bo := bo or $01
else
bo := bo or $0;
if (bi and $40)>0 then
bo := bo or $02
else
bo := bo or $0;
if (bi and $20)>0 then
bo := bo or $04
else
bo := bo or $0;
if (bi and $10)>0 then
bo := bo or $08
else
bo := bo or $0;
if (bi and $08)>0 then
bo := bo or $10
else
bo := bo or $0;
if (bi and $04)>0 then
bo := bo or $20
else
bo := bo or $0;
if (bi and $02)>0 then
bo := bo or $40
else
bo := bo or $0;
if (bi and $01)>0 then
bo := bo or $80
else
bo := bo or $0;
PByte(@d.ltc_frame)[k] := bo;
end;
(* swap bytes *)
byte_num_max := byte_num_max - 2; // skip sync-word
for k:=0 to (byte_num_max-1) div 2 do
begin
bi := PByte(addr(d.ltc_frame))[k];
PByte(addr(d.ltc_frame))[k] := PByte(addr(d.ltc_frame))[byte_num_max-1-k];
PByte(addr(d.ltc_frame))[byte_num_max-1-k] := bi;
end;
move(d.ltc_frame, temp_Queue.ltc, sizeof(TLTCFrameRAW));
for bc := 0 to LTC_FRAME_BIT_COUNT-1 do
begin
btc := (d.biphase_tic + bc ) mod LTC_FRAME_BIT_COUNT;
temp_Queue.biphase_tics[bc] := d.biphase_tics[btc];
end;
temp_Queue.off_start := trunc(d.frame_start_off - 16 * d.snd_to_biphase_period);
temp_Queue.off_end := trunc(posinfo + offset - 1 - 16 * d.snd_to_biphase_period);
temp_Queue.reverse := trunc((LTC_FRAME_BIT_COUNT shr 3) * 8 * d.snd_to_biphase_period);
temp_Queue.volume := calc_volume_db(d);
temp_Queue.sample_min := d.snd_to_biphase_min;
temp_Queue.sample_max := d.snd_to_biphase_max;
{$IfDef OnDebug}
d.DoDebug(format('parse_ltc -> temp_Queue.off_start = %d (%d 16 * %f)',[temp_Queue.off_start, d.frame_start_off, d.snd_to_biphase_period]));
d.DoDebug(format('parse_ltc -> temp_Queue.off_end = %d (%d + %d -1 - 16 * %f)',[temp_Queue.off_end, posinfo, offset, d.snd_to_biphase_period]));
d.DoDebug(format('parse_ltc -> temp_Queue.reverse = %d (%d 8 * %f)',[temp_Queue.reverse, (LTC_FRAME_BIT_COUNT shr 3), d.snd_to_biphase_period]));
{$EndIf}
d.queue.Enqueue(temp_Queue);
if d.queue.Count>d.queue_len then d.queue.Dequeue;
{d.queue[d.queue_write_off]:=temp_Queue;
d.queue_write_off := d.queue_write_off + 1;
if (d.queue_write_off = d.queue_len) then d.queue_write_off := 0; }
end;
d.bit_cnt := 0;
end;
end;
(* OK *)
procedure biphase_decode2(d : TLTCDecoder; offset : integer; pos: ltc_off_t); inline;
begin
d.biphase_tics[d.biphase_tic] := d.snd_to_biphase_period;
d.biphase_tic := (d.biphase_tic + 1) Mod LTC_FRAME_BIT_COUNT;
{$IfDef OnDebug}
d.DoDebug(format('biphase_decode2 -> d->biphase_tic = %d',[d.biphase_tic]));
{$EndIf}
if (d.snd_to_biphase_cnt <= 2 * d.snd_to_biphase_period) then
begin
(*
var
OldRM: TRoundingMode;
OldRM := GetRoundMode; { Save the original setting for the Round Mode }
SetRoundMode(rmDown);
pos := pos - (ceil(roundto(d.snd_to_biphase_period, -4)) - d.snd_to_biphase_cnt);
SetRoundMode(OldRM); { Restore the original Rounding Mode }
*)
pos := pos - (round(d.snd_to_biphase_period) - d.snd_to_biphase_cnt);
{$IfDef OnDebug}
d.DoDebug(format('biphase_decode2 -> pos = %d (%.10f - %d)',[pos, d.snd_to_biphase_period, d.snd_to_biphase_cnt]));
{$EndIf}
end;
if (d.snd_to_biphase_state = d.biphase_prev) then
begin
d.biphase_state := 1;
parse_ltc(d, 0, offset, pos);
end else
begin
d.biphase_state := 1 - d.biphase_state;
if (d.biphase_state = 1) then
parse_ltc(d, 1, offset, pos);
end;
d.biphase_prev := d.snd_to_biphase_state;
end;
(* OK *)
function decode_ltc(d: TLTCDecoder; sound: array of ltcsnd_sample_t; size: size_t; posinfo: ltc_off_t): integer;
var
i : size_t;
max_threshold, min_threshold : ltcsnd_sample_t;
begin
result:=0;
for I := 0 to size-1 do
begin
(* track minimum and maximum values *)
d.snd_to_biphase_min := SAMPLE_CENTER - round(((SAMPLE_CENTER - d.snd_to_biphase_min) * 15) div 16);
d.snd_to_biphase_max := SAMPLE_CENTER + round(((d.snd_to_biphase_max - SAMPLE_CENTER) * 15) div 16);
if (sound[i] < d.snd_to_biphase_min) then
d.snd_to_biphase_min := sound[i];
if (sound[i] > d.snd_to_biphase_max) then
d.snd_to_biphase_max := sound[i];
(* set the thresholds for hi/lo state tracking *)
min_threshold := SAMPLE_CENTER - round(((SAMPLE_CENTER - d.snd_to_biphase_min) * 8) div 16);
max_threshold := SAMPLE_CENTER + round(((d.snd_to_biphase_max - SAMPLE_CENTER) * 8) div 16);
{$IfDef OnDebug}
d.DoDebug(format('decode_ltc -> d.snd_to_biphase_min = %d ',[d.snd_to_biphase_min]));
d.DoDebug(format('decode_ltc -> d.snd_to_biphase_max = %d ',[d.snd_to_biphase_max]));
d.DoDebug(format('decode_ltc -> min_threshold = %d ',[min_threshold]));
d.DoDebug(format('decode_ltc -> max_threshold = %d ',[max_threshold]));
{$EndIf}
(* Check for a biphase state change *)
if (((d.snd_to_biphase_state>0) and (sound[i] > max_threshold)) // Check for a biphase state change
or ((d.snd_to_biphase_state<=0) and (sound[i] < min_threshold))) then
begin
// There is a state change at sound[i]
// If the sample count has risen above the biphase length limit
if (d.snd_to_biphase_cnt > d.snd_to_biphase_lmt) then
begin
(* single state change within a biphase priod. decode to a 0 *)
biphase_decode2(d, i, posinfo);
biphase_decode2(d, i, posinfo);
end else
begin
(* "short" state change covering half a period
* together with the next or previous state change decode to a 1
*)
d.snd_to_biphase_cnt := d.snd_to_biphase_cnt * 2;
biphase_decode2(d, i, posinfo);
end;
if (d.snd_to_biphase_cnt > (d.snd_to_biphase_period * 4)) then
begin
(* "long" silence in between
* -> reset parser, don't use it for phase-tracking
*)
d.bit_cnt := 0;
end else
begin
(* track speed variations
* As this is only executed at a state change,
* d->snd_to_biphase_cnt is an accurate representation of the current period length.
*)
d.snd_to_biphase_period := (d.snd_to_biphase_period * 3.0 + d.snd_to_biphase_cnt) / 4.0;
(* This limit specifies when a state-change is
* considered biphase-clock or 2*biphase-clock.
* The relation with period has been determined
* empirically through trial-and-error *)
d.snd_to_biphase_lmt := trunc((d.snd_to_biphase_period * 3) / 4);
end;
d.snd_to_biphase_cnt := 0;
d.snd_to_biphase_state := not d.snd_to_biphase_state;
end;
d.snd_to_biphase_cnt:=d.snd_to_biphase_cnt+1;
end;
end;
(* TLTCDecoder *)
constructor TLTCDecoder.create();
begin
FQueue_Len := 32;
FQueue:= TQueue<TLTCFrameExt>.create;
FBiphase_state := 1;
SetAPV(44100 div 25);
FSnd_to_biphase_min := SAMPLE_CENTER;
FSnd_to_biphase_max := SAMPLE_CENTER;
FFrame_start_prev := -1;
FBiphase_tic := 0;
end;
destructor TLTCDecoder.Destroy;
begin
FQueue.Clear;
FreeAndNil(FQueue);
inherited Destroy;
end;
procedure TLTCDecoder.Write(buf: array of ltcsnd_sample_t; size : size_t; posinfo : ltc_off_t);
begin
decode_ltc(Self, buf, size, posinfo);
end;
function TLTCDecoder.Read(var frame: TLTCFrameExt ): boolean;
begin
result:=false;
if FQueue.Count>0 then
begin
frame:=FQueue.Dequeue;
result:=true;
end;
end;
function TLTCDecoder.GetBiphaseTics(index: integer): Single;
begin
result:=FBiphase_tics[index];
end;
procedure TLTCDecoder.SetBiphaseTics(index: integer; const Value: Single);
begin
FBiphase_tics[index]:=Value;
end;
procedure TLTCDecoder.SetAPV(value: integer);
begin
FSnd_to_biphase_period := value / 80;
FSnd_to_biphase_lmt := trunc((FSnd_to_biphase_period * 3) / 4);
end;
end.
|
unit List_Module;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "View"
// Модуль: "List_Module.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: VCMFormsPack::Class Shared Delphi Sand Box$UC::List::View::List::List
//
// Список
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{$Include w:\common\components\SandBox\VCM\sbDefine.inc}
interface
uses
vcmExternalInterfaces {a},
vcmInterfaces {a},
vcmModule {a}
;
type
TListModule = {formspack} class(TvcmModule)
{* Список }
public
// public methods
class function ListPrintAndExportDefaultSetting: Boolean;
{* Метод для получения значения настройки "Печать и экспорт"."Использовать для экспорта и печати размер шрифта, отображаемого на экране" }
class function ListPrintAndExportCustomSetting: Boolean;
{* Метод для получения значения настройки "Печать и экспорт"."Использовать для экспорта и печати следующий размер шрифта" }
class function ListPrintAndExportFontSizeSetting: Integer;
{* Метод для получения значения настройки "Использовать для экспорта и печати следующий размер шрифта" }
class procedure WriteListPrintAndExportFontSizeSetting(aValue: Integer);
{* Метод для записи значения настройки "Использовать для экспорта и печати следующий размер шрифта" }
end;//TListModule
implementation
uses
afwFacade,
ListPrintAndExportSettingRes,
ListPrintAndExportFontSizeSettingRes,
stListPrintAndExportFontSizeItem,
vcmFormSetFactory {a},
StdRes {a}
;
// start class TListModule
class function TListModule.ListPrintAndExportDefaultSetting: Boolean;
{-}
begin
if (afw.Settings = nil) then
Result := false
else
Result := afw.Settings.LoadBoolean(pi_List_PrintAndExport_Default, false);
end;//TListModule.ListPrintAndExportDefaultSetting
class function TListModule.ListPrintAndExportCustomSetting: Boolean;
{-}
begin
if (afw.Settings = nil) then
Result := false
else
Result := afw.Settings.LoadBoolean(pi_List_PrintAndExport_Custom, false);
end;//TListModule.ListPrintAndExportCustomSetting
class function TListModule.ListPrintAndExportFontSizeSetting: Integer;
{-}
begin
if (afw.Settings = nil) then
Result := dv_List_PrintAndExportFontSize
else
Result := afw.Settings.LoadInteger(pi_List_PrintAndExportFontSize, dv_List_PrintAndExportFontSize);
end;//TListModule.ListPrintAndExportFontSizeSetting
class procedure TListModule.WriteListPrintAndExportFontSizeSetting(aValue: Integer);
{-}
begin
if (afw.Settings <> nil) then
afw.Settings.SaveInteger(pi_List_PrintAndExportFontSize, aValue);
end;//TListModule.WriteListPrintAndExportFontSizeSetting
end. |
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpPCGRandomNumberGenerator;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
ClpCryptoLibTypes,
ClpPcgRandomMinimal,
ClpIPCGRandomNumberGenerator,
ClpRandomNumberGenerator;
type
TPCGRandomNumberGenerator = class sealed(TRandomNumberGenerator,
IPCGRandomNumberGenerator)
public
constructor Create();
procedure GetBytes(const data: TCryptoLibByteArray); override;
procedure GetNonZeroBytes(const data: TCryptoLibByteArray); override;
end;
implementation
{ TPCGRandomNumberGenerator }
constructor TPCGRandomNumberGenerator.Create;
begin
inherited Create();
end;
procedure TPCGRandomNumberGenerator.GetBytes(const data: TCryptoLibByteArray);
var
i: Int64;
begin
i := System.Length(data);
while i > 0 do
begin
data[i - 1] := Byte(TPcg.NextInt(System.Low(Int32), System.High(Int32)));
System.Dec(i);
end;
end;
procedure TPCGRandomNumberGenerator.GetNonZeroBytes(const data: TCryptoLibByteArray);
var
i: Int64;
val: Byte;
begin
i := System.Length(data);
while i > 0 do
begin
repeat
val := Byte(TPcg.NextUInt32(System.Low(UInt32), System.High(UInt32)));
until (not(val = 0));
data[i - 1] := val;
System.Dec(i);
end;
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpCfbBlockCipher;
{$I ..\..\Include\CryptoLib.inc}
interface
uses
SysUtils,
ClpIBlockCipher,
ClpICfbBlockCipher,
ClpICipherParameters,
ClpIParametersWithIV,
ClpCryptoLibTypes;
resourcestring
SInputBufferTooShort = 'Input Buffer too Short';
SOutputBufferTooShort = 'Output Buffer too Short';
type
/// <summary>
/// implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
/// </summary>
TCfbBlockCipher = class sealed(TInterfacedObject, ICfbBlockCipher,
IBlockCipher)
strict private
var
FIV, FcfbV, FcfbOutV: TCryptoLibByteArray;
FblockSize: Int32;
Fcipher: IBlockCipher;
Fencrypting: Boolean;
/// <summary>
/// return the algorithm name and mode.
/// </summary>
/// <returns>
/// return the name of the underlying algorithm followed by "/CFB"
/// </returns>
function GetAlgorithmName: String; inline;
function GetIsPartialBlockOkay: Boolean; inline;
/// <summary>
/// Do the appropriate processing for CFB mode encryption.
/// </summary>
/// <param name="input">
/// the array containing the data to be encrypted.
/// </param>
/// <param name="inOff">
/// offset into the in array the data starts at.
/// </param>
/// <param name="outBytes">
/// the array the encrypted data will be copied into.
/// </param>
/// <param name="outOff">
/// the offset into the out array the output will start at.
/// </param>
/// <returns>
/// the number of bytes processed and produced.
/// </returns>
/// <exception cref="EDataLengthCryptoLibException">
/// if there isn't enough data in input, or space in output.
/// </exception>
/// <exception cref="EInvalidOperationCryptoLibException">
/// if the cipher isn't initialised.
/// </exception>
function EncryptBlock(const input: TCryptoLibByteArray; inOff: Int32;
const outBytes: TCryptoLibByteArray; outOff: Int32): Int32;
/// <summary>
/// Do the appropriate chaining step for CBC mode decryption.
/// </summary>
/// <param name="input">
/// the array containing the data to be decrypted.
/// </param>
/// <param name="inOff">
/// offset into the in array the data starts at.
/// </param>
/// <param name="outBytes">
/// the array the decrypted data will be copied into.
/// </param>
/// <param name="outOff">
/// the offset into the out array the output will start at.
/// </param>
/// <returns>
/// the number of bytes processed and produced.
/// </returns>
/// <exception cref="EDataLengthCryptoLibException">
/// if there isn't enough data in input, or space in output.
/// </exception>
/// <exception cref="EInvalidOperationCryptoLibException">
/// if the cipher isn't initialised.
/// </exception>
function DecryptBlock(const input: TCryptoLibByteArray; inOff: Int32;
const outBytes: TCryptoLibByteArray; outOff: Int32): Int32;
public
/// <summary>
/// Basic constructor.
/// </summary>
/// <param name="cipher">
/// the block cipher to be used as the basis of the feedback mode.
/// </param>
/// <param name="bitBlockSize">
/// the block size in bits (note: a multiple of 8)
/// </param>
constructor Create(const cipher: IBlockCipher; bitBlockSize: Int32);
/// <summary>
/// return the underlying block cipher that we are wrapping.
/// </summary>
/// <returns>
/// return the underlying block cipher that we are wrapping.
/// </returns>
function GetUnderlyingCipher(): IBlockCipher;
/// <summary>
/// Initialise the cipher and, possibly, the initialisation vector (IV). <br />
/// If an IV isn't passed as part of the parameter, the IV will be all
/// zeros.
/// An IV which is too short is handled in FIPS compliant fashion.
/// </summary>
/// <param name="forEncryption">
/// forEncryption if true the cipher is initialised for encryption, if
/// false for decryption.
/// </param>
/// <param name="parameters">
/// the key and other data required by the cipher.
/// </param>
procedure Init(forEncryption: Boolean; const parameters: ICipherParameters);
/// <summary>
/// return the block size we are operating at.
/// </summary>
/// <returns>
/// the block size we are operating at (in bytes).
/// </returns>
function GetBlockSize(): Int32; inline;
/// <summary>
/// Process one block of input from the input array and write it to the
/// output array.
/// </summary>
/// <param name="input">
/// the array containing the input data.
/// </param>
/// <param name="inOff">
/// offset into the input array the data starts at.
/// </param>
/// <param name="output">
/// the array the output data will be copied into.
/// </param>
/// <param name="outOff">
/// the offset into the output array the data starts at.
/// </param>
/// <returns>
/// the number of bytes processed and produced.
/// </returns>
/// <exception cref="EDataLengthCryptoLibException">
/// if there isn't enough data in input, or space in output.
/// </exception>
/// <exception cref="EInvalidOperationCryptoLibException">
/// if the cipher isn't initialised.
/// </exception>
function ProcessBlock(const input: TCryptoLibByteArray; inOff: Int32;
const output: TCryptoLibByteArray; outOff: Int32): Int32;
/// <summary>
/// reset the chaining vector back to the IV and reset the underlying
/// cipher.
/// </summary>
procedure Reset(); inline;
/// <summary>
/// return the algorithm name and mode.
/// </summary>
/// <value>
/// return the name of the underlying algorithm followed by "/CFB"
/// </value>
property AlgorithmName: String read GetAlgorithmName;
property IsPartialBlockOkay: Boolean read GetIsPartialBlockOkay;
end;
implementation
{ TCfbBlockCipher }
constructor TCfbBlockCipher.Create(const cipher: IBlockCipher;
bitBlockSize: Int32);
begin
inherited Create();
Fcipher := cipher;
FblockSize := bitBlockSize div 8;
System.SetLength(FIV, Fcipher.GetBlockSize);
System.SetLength(FcfbV, Fcipher.GetBlockSize);
System.SetLength(FcfbOutV, Fcipher.GetBlockSize);
end;
function TCfbBlockCipher.DecryptBlock(const input: TCryptoLibByteArray;
inOff: Int32; const outBytes: TCryptoLibByteArray; outOff: Int32): Int32;
var
I, count: Int32;
begin
if ((inOff + FblockSize) > System.length(input)) then
begin
raise EDataLengthCryptoLibException.CreateRes(@SInputBufferTooShort);
end;
if ((outOff + FblockSize) > System.length(outBytes)) then
begin
raise EDataLengthCryptoLibException.CreateRes(@SOutputBufferTooShort);
end;
Fcipher.ProcessBlock(FcfbV, 0, FcfbOutV, 0);
//
// change over the input block.
//
count := (System.length(FcfbV) - FblockSize) * System.SizeOf(Byte);
if count > 0 then
begin
System.Move(FcfbV[FblockSize], FcfbV[0], count);
end;
System.Move(input[inOff], FcfbV[(System.length(FcfbV) - FblockSize)],
FblockSize * System.SizeOf(Byte));
// XOR the FcfbV with the ciphertext producing the plaintext
for I := 0 to System.Pred(FblockSize) do
begin
outBytes[outOff + I] := Byte(FcfbOutV[I] xor input[inOff + I]);
end;
result := FblockSize;
end;
function TCfbBlockCipher.EncryptBlock(const input: TCryptoLibByteArray;
inOff: Int32; const outBytes: TCryptoLibByteArray; outOff: Int32): Int32;
var
I, count: Int32;
begin
if ((inOff + FblockSize) > System.length(input)) then
begin
raise EDataLengthCryptoLibException.CreateRes(@SInputBufferTooShort);
end;
if ((outOff + FblockSize) > System.length(outBytes)) then
begin
raise EDataLengthCryptoLibException.CreateRes(@SOutputBufferTooShort);
end;
Fcipher.ProcessBlock(FcfbV, 0, FcfbOutV, 0);
// XOR the FcfbV with the plaintext producing the ciphertext
for I := 0 to System.Pred(FblockSize) do
begin
outBytes[outOff + I] := Byte(FcfbOutV[I] xor input[inOff + I]);
end;
//
// change over the input block.
//
count := (System.length(FcfbV) - FblockSize) * System.SizeOf(Byte);
if count > 0 then
begin
System.Move(FcfbV[FblockSize], FcfbV[0], count);
end;
System.Move(outBytes[outOff], FcfbV[(System.length(FcfbV) - FblockSize)],
FblockSize * System.SizeOf(Byte));
result := FblockSize;
end;
procedure TCfbBlockCipher.Reset;
begin
System.Move(FIV[0], FcfbV[0], System.length(FIV));
Fcipher.Reset();
end;
function TCfbBlockCipher.GetAlgorithmName: String;
begin
result := Fcipher.AlgorithmName + '/CFB' + IntToStr(FblockSize * 8);
end;
function TCfbBlockCipher.GetBlockSize: Int32;
begin
result := FblockSize;
end;
function TCfbBlockCipher.GetIsPartialBlockOkay: Boolean;
begin
result := true;
end;
function TCfbBlockCipher.GetUnderlyingCipher: IBlockCipher;
begin
result := Fcipher;
end;
procedure TCfbBlockCipher.Init(forEncryption: Boolean;
const parameters: ICipherParameters);
var
ivParam: IParametersWithIV;
iv: TCryptoLibByteArray;
Lparameters: ICipherParameters;
diff: Int32;
begin
Fencrypting := forEncryption;
Lparameters := parameters;
if Supports(Lparameters, IParametersWithIV, ivParam) then
begin
iv := ivParam.GetIV();
diff := System.length(FIV) - System.length(iv);
System.Move(iv[0], FIV[diff], System.length(iv) * System.SizeOf(Byte));
System.FillChar(FIV[0], diff, Byte(0));
Lparameters := ivParam.parameters;
end;
Reset();
// if it's Nil, key is to be reused.
if (Lparameters <> Nil) then
begin
Fcipher.Init(true, Lparameters);
end;
end;
function TCfbBlockCipher.ProcessBlock(const input: TCryptoLibByteArray;
inOff: Int32; const output: TCryptoLibByteArray; outOff: Int32): Int32;
begin
if Fencrypting then
begin
result := EncryptBlock(input, inOff, output, outOff);
end
else
begin
result := DecryptBlock(input, inOff, output, outOff);
end;
end;
end.
|
unit Splitter;
interface
uses
Messages, Windows, Classes, Sysutils, Controls, Graphics;
{$INCLUDE Splitter.inc}
const
cDefaultTrackWidth = 2;
type
TSplitterStyle = (ssNone, ssLowered, ssRaised);
type
TSplitter = class;
TOnNotify = procedure (Sender : TSplitter; x, y : integer) of object;
TSplitter =
class(TCustomControl)
private
fStyle : TSplitterStyle;
fAutoTrack : boolean;
fTrackWidth : integer;
fOnNotify : TOnNotify;
procedure SetStyle(which : TSplitterStyle);
published
property Align;
property Color;
property ParentShowHint;
property ShowHint;
property Visible;
property OnDblClick;
property TrackWidth : integer read fTrackWidth write fTrackWidth default cDefaultTrackWidth;
property Style : TSplitterStyle read fStyle write SetStyle default ssNone;
property AutoTrack : boolean read fAutoTrack write fAutoTrack;
property OnNotify : TOnNotify read fOnNotify write fOnNotify;
public
constructor Create(aOwner : TComponent); override;
protected
procedure Paint; override;
procedure SetBounds(aLeft, aTop, aWidth, aHeight : integer); override;
procedure MouseDown(Button : TMouseButton; Shift : TShiftState; x, y : integer); override;
procedure MouseMove(Shift : TShiftState; x, y : integer); override;
procedure MouseUp(Button : TMouseButton; Shift : TShiftState; x, y : integer); override;
procedure DblClick; override;
private
fDown : boolean;
fTracking : boolean;
fDblClick : boolean;
fClient : TRect;
fPos : TPoint;
dc : HDC;
pen : HPen;
rop : integer;
procedure InitializeTracking(x, y : integer);
procedure EndTracking;
procedure Show;
procedure Hide;
procedure Notify;
function ClipPoint(x, y : integer) : TPoint;
end;
procedure Register;
implementation
// -- TSplitter
procedure TSplitter.SetStyle(which : TSplitterStyle);
begin
inherited;
if which <> fStyle
then
begin
fStyle := which;
Invalidate;
end;
end;
constructor TSplitter.Create(aOwner : TComponent);
begin
inherited;
ControlStyle := ControlStyle + [csReplicatable];
fStyle := ssNone;
fTrackWidth := cDefaultTrackWidth;
Color := clBtnFace;
Width := 50;
Height := 50;
end;
procedure TSplitter.Paint;
var
Color2 : TColor;
begin
with Canvas do
begin
Pen.Width := 1;
case fStyle of
ssRaised :
begin
Pen.Color := clBtnHighlight;
Color2 := clBtnShadow;
end;
ssLowered :
begin
Pen.Color := clBtnShadow;
Color2 := clBtnHighlight;
end;
else
Pen.Color := Color;
Color2 := Color;
end;
PolyLine([Point(0, Height - 1), Point(0, 0), Point(Width - 1, 0)]);
Pen.Color := Color2;
PolyLine([Point(Width - 1, 0), Point(Width - 1, Height - 1), Point(0, Height - 1)]);
if (Width > 2) and (Height > 2)
then
begin
Pen.Color := Color;
Brush.Color := Color;
Rectangle(1, 1, Width - 2, Height - 2);
end;
end;
end;
procedure TSplitter.SetBounds(aLeft, aTop, aWidth, aHeight : integer);
begin
inherited;
if Width < Height
then Cursor := crHSplit
else Cursor := crVSplit;
end;
procedure TSplitter.MouseDown(Button : TMouseButton; Shift : TShiftState; x, y : integer);
begin
if not fDblClick
then fDown := Button = mbLeft
else fDblClick := false;
inherited;
end;
procedure TSplitter.MouseMove(Shift : TShiftState; x, y : integer);
begin
if fDown
then
begin
if not fTracking
then InitializeTracking(x, y);
Hide;
fPos := ClipPoint(x, y);
if fAutoTrack
then Notify;
Show;
end;
inherited;
end;
procedure TSplitter.MouseUp(Button : TMouseButton; Shift : TShiftState; x, y : integer);
begin
if Button = mbLeft
then
begin
if fTracking
then
begin
EndTracking;
Parent.Invalidate;
Notify;
end;
fDown := false;
end;
inherited;
end;
procedure TSplitter.DblClick;
begin
fDblClick := true;
inherited;
end;
procedure TSplitter.InitializeTracking(x, y : integer);
const
PenColor = $00DCDCDC;
begin
dc := GetDC(0);
pen := SelectObject(dc, CreatePen(PS_SOLID, fTrackWidth, PenColor));
rop := SetROP2(dc, R2_XORPEN);
fPos := ClientToScreen(Point(x, y));
with Parent, fClient do
begin
TopLeft := ClientOrigin;
BottomRight := ClientToScreen(Point(ClientWidth, ClientHeight));
end;
Show;
fTracking := true;
end;
procedure TSplitter.EndTracking;
begin
fTracking := false;
Hide;
SetROP2(dc, rop);
DeleteObject(SelectObject(dc, pen));
ReleaseDC(0, dc);
end;
procedure TSplitter.Show;
var
xi, yi : integer;
xf, yf : integer;
begin
if Width > Height
then
begin
xi := fClient.Left;
yi := fPos.y;
xf := fClient.Right;
yf := fPos.y;
end
else
begin
xi := fPos.x;
yi := fClient.Top;
xf := fPos.x;
yf := fClient.Bottom;
end;
MoveToEx(dc, xi, yi, nil);
LineTo(dc, xf, yf);
end;
procedure TSplitter.Hide;
begin
Show;
end;
procedure TSplitter.Notify;
begin
with Parent, ScreenToClient(fPos) do
if assigned(fOnNotify)
then fOnNotify(Self, x, y)
else
if Width < Height
then Left := x
else Top := y;
end;
function TSplitter.ClipPoint(x, y : integer) : TPoint;
begin
result := ClientToScreen(Point(x, y));
with result, fClient do
begin
if x < Left
then x := Left;
if x > Right
then x := Right;
if y < Top
then y := Top;
if y > Bottom
then y := Bottom;
end;
end;
procedure Register;
begin
RegisterComponents('Merchise', [TSplitter]);
end;
end.
|
unit G2Mobile.Controller.Clientes;
interface
uses
FMX.ListView,
System.Classes,
Datasnap.DBClient,
FireDAC.Comp.Client,
FMX.Objects,
FMX.Graphics,
FMX.Grid;
type
iModelClientes = interface
['{25F82A84-4E2F-43D5-ADE2-143CE97FFC1D}']
function BuscaClientesServidor(Super, cod_vend: Integer; ADataSet: TFDMemTable): iModelClientes;
function PopulaClientesSqLite(ADataSet: TFDMemTable): iModelClientes;
function LimpaTabelaClientes: iModelClientes;
function PopulaListView(value: TListView; positivo, negativo: TImage; Pesq: String): iModelClientes;
function PopulaCampos(value: Integer; AList: TStringList): iModelClientes;
function BuscarCliente(value: Integer): String;
function RetornaLimite(value: Integer): String;
function ValidaCliente(value: Integer): Integer;
end;
iModelPreCadClientes = interface
['{018B1039-EAD5-49F9-A925-68A98E48F93C}']
function TipoPes(value: Integer): iModelPreCadClientes;
function CpfCnpj(value: String): iModelPreCadClientes;
function NomeRazao(value: String): iModelPreCadClientes;
function NomeFant(value: String): iModelPreCadClientes;
function Endereco(value: String): iModelPreCadClientes;
function Bairro(value: String): iModelPreCadClientes;
function Numero(value: Integer): iModelPreCadClientes;
function Cep(value: String): iModelPreCadClientes;
function Telefone(value: String): iModelPreCadClientes;
function Email(value: String): iModelPreCadClientes;
function CodVendedor(value: Integer): iModelPreCadClientes;
function InsertPreCadCliente: iModelPreCadClientes;
function UpdatePreCadCliente: iModelPreCadClientes;
function DeletePreCadCliente: iModelPreCadClientes;
function PopulaCamposPreCadCliente(AList: TStringList): iModelPreCadClientes;
function PopulaListViewPreCadCliente(value: TListView; icon: TImage): iModelPreCadClientes;
end;
iModelTitulosCliente = interface
['{F849F3CA-ED71-4B3E-99C4-7ED92DFF56C4}']
function CodVend(value: Integer): iModelTitulosCliente;
function CodCliente(value: Integer): iModelTitulosCliente;
function CodPedcar(value: Integer): iModelTitulosCliente;
function DeleteTitulos: iModelTitulosCliente;
function DeleteItensTitulo: iModelTitulosCliente;
function BuscaTitulosServidor(DataSet: TFDMemTable): iModelTitulosCliente;
function BuscaItensTituloServidor(DataSet: TFDMemTable): iModelTitulosCliente;
function GravaTitulosSqlite(DataSet: TFDMemTable): iModelTitulosCliente;
function GravaItensTituloSqlite(DataSet: TFDMemTable): iModelTitulosCliente;
function PopulaListView(value: TListView; aberta, vencida: TImage): iModelTitulosCliente;
function PopulaItemTituloStringGrid(Grid: TStringGrid): iModelTitulosCliente;
end;
implementation
end.
|
unit Thread._ImportarBaixasTFO;
interface
uses
System.Classes, Common.ENum, Control.EntregadoresExpressas, Control.Entregas, Dialogs, Windows, Forms, SysUtils, Messages,
Controls, FireDAC.Comp.Client, Control.Sistema, System.DateUtils, Control.Bases, Control.VerbasExpressas;
type
Thread_ImportarBaixasTFO = class(TThread)
private
{ Private declarations }
entregas: TEntregasControl;
entregadores : TEntregadoresExpressasControl;
bases: TBasesControl;
verbas : TVerbasExpressasControl;
sMensagem: String;
FdPos: Double;
bCancel : Boolean;
dPos: Double;
iPos : Integer;
iLinha : Integer;
iTotal : Integer;
protected
procedure Execute; override;
procedure AtualizaLog;
procedure AtualizaProgress;
procedure TerminaProcesso;
procedure IniciaProcesso;
public
FFile: String;
end;
implementation
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure Thread_ImportarBaixasTFO.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
uses Data.SisGeF, View.ImportarBaixasTFO, Common.Utils, Global.Parametros;
{ Thread_ImportarBaixasTFO }
procedure Thread_ImportarBaixasTFO.AtualizaLog;
begin
view_ImportarBaixasTFO.memLOG.Lines.Add(sMensagem);
view_ImportarBaixasTFO.memLOG.Lines.Add('');
iLinha := view_ImportarBaixasTFO.memLOG.Lines.Count - 1;
view_ImportarBaixasTFO.memLOG.Refresh;
end;
procedure Thread_ImportarBaixasTFO.AtualizaProgress;
begin
view_ImportarBaixasTFO.pbImportacao.Position := FdPos;
view_ImportarBaixasTFO.pbImportacao.Properties.Text := FormatFloat('0.00%',FdPos);
view_ImportarBaixasTFO.pbImportacao.Refresh;
view_ImportarBaixasTFO.memLOG.Lines[iLinha] := ' >>> ' + IntToStr(iPos) + ' registros processados';
view_ImportarBaixasTFO.memLOG.Refresh;
if not(view_ImportarBaixasTFO.actCancelar.Visible) then
begin
view_ImportarBaixasTFO.actCancelar.Visible := True;
view_ImportarBaixasTFO.actFechar.Enabled := False;
view_ImportarBaixasTFO.actImportar.Enabled := False;
end;
end;
procedure Thread_ImportarBaixasTFO.Execute;
var
aParam: array of Variant;
FDQuery : TFDQuery;
FDQuery1 : TFDQuery;
FDVerba : TFDQUery;
iAgente : Integer;
iEntregador : Integer;
dVerba: Double;
dVerbaTabela: Double;
iGrupo: Integer;
sCEP : String;
sNome : String;
begin
{ Place thread code here }
try
try
entregas := TEntregasControl.Create;
entregadores := TEntregadoresExpressasControl.Create;
bases := TBasesControl.Create;
verbas := TVerbasExpressasControl.Create;
Data_Sisgef.FDBDataSetWriter.DataSet := Data_Sisgef.mtbBaixasTFO;
Data_Sisgef.FDBTextReader.FileName := FFile;
Data_Sisgef.FDBTextReader.DataDef.WithFieldNames := True;
Data_Sisgef.FDBatchMove.GuessFormat;
Data_SisGeF.FDBatchMove.Mappings.AddAll;
Data_Sisgef.FDBatchMove.Execute;
iAgente := 1;
iEntregador := 781;
if Data_Sisgef.mtbBaixasTFO.Active then
begin
if Data_Sisgef.mtbBaixasTFO.Fields.Count <> 19 then
begin
Application.MessageBox('Arquivo informado não é de Planilha de Baixas da TFO !', 'Atenção', MB_OK + MB_ICONASTERISK);
Abort;
end;
iTotal := Data_Sisgef.mtbBaixasTFO.RecordCount;
Synchronize(IniciaProcesso);
Data_Sisgef.mtbBaixasTFO.First;
iPos := 0;
dPos := 0;
dVerba := 0;
dVerbaTabela := 0;
sCEP := '';
sNome := '';
while not Data_Sisgef.mtbBaixasTFO.Eof do
begin
iGrupo := 1;
if Common.Utils.TUtils.ENumero(Data_Sisgef.mtbBaixasTFO.Fields[0].AsString) then
begin
FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery;
SetLength(aParam,2);
aParam[0] := 'NN';
aParam[1] := IntToStr(Data_Sisgef.mtbBaixasTFO.Fields[0].AsInteger);
FDQuery := entregas.Localizar(aParam);
Finalize(aParam);
if not FDQuery.IsEmpty then
begin
dVerba := 0;
FDQuery1 := TSistemaControl.GetInstance.Conexao.ReturnQuery;
SetLength(aParam,2);
aParam[0] := 'ENTREGADOR';
aParam[1] := Data_Sisgef.mtbBaixasTFO.Fields[6].AsString;
FDQuery1 := entregadores.Localizar(aParam);
Finalize(aParam);
if not FDQuery1.IsEmpty then
begin
iAgente := FDQuery1.FieldByName('COD_AGENTE').AsInteger;
iEntregador := FDQuery1.FieldByName('COD_ENTREGADOR').AsInteger;
dVerba := FDQuery1.FieldByName('VAL_VERBA').AsFloat;
sNome := FDQuery1.FieldByName('NOM_FANTASIA').AsString;
if Pos('PESADO',sNome) > 0 then iGrupo := 2;
end
else
begin
sMensagem := 'Entregador ' + Data_Sisgef.mtbBaixasTFO.Fields[7].AsString + '-' +
Data_Sisgef.mtbBaixasTFO.Fields[8].AsString + ', do pedido ' +
Data_Sisgef.mtbBaixasTFO.Fields[0].AsString + ', não cadastrado no banco de dados!';
Synchronize(AtualizaLog);
end;
FDQuery1.Free;
if dVerba = 0 then
begin
FDQuery1 := TSistemaControl.GetInstance.Conexao.ReturnQuery;
SetLength(aParam,2);
aParam[0] := 'CODIGO';
aParam[1] := iAgente;
FDQuery1 := bases.Localizar(aParam);
Finalize(aParam);
if not FDQuery1.IsEmpty then
begin
dVerba := FDQuery1.FieldByName('VAL_VERBA').AsFloat;
end;
FDQuery1.Free;
end;
if dVerba = 0 then
begin
if iGrupo = 1 then
begin
SetLength(aParam,7);
aParam[0] := 'CEPPESO';
aParam[1] := 5;
aParam[2] := FDQuery.FieldByName('COD_CLIENTE_EMPRESA').AsInteger;
aParam[3] := iGrupo;
aParam[4] := StrToDateTime(Data_Sisgef.mtbBaixasTFO.Fields[11].AsString);
aParam[5] := FDQuery.FieldByName('NUM_CEP').Value;
aParam[6] := Trunc(1000 * StrToFloatDef(Data_Sisgef.mtbBaixasTFO.Fields[17].AsString,0));
end
else
begin
SetLength(aParam,6);
aParam[0] := 'FIXACEP';
aParam[1] := 2;
aParam[2] := FDQuery.FieldByName('COD_CLIENTE_EMPRESA').AsInteger;
aParam[3] := iGrupo;
aParam[4] := StrToDateTime(Data_Sisgef.mtbBaixasTFO.Fields[11].AsString);
aParam[5] := FDQuery.FieldByName('NUM_CEP').Value;
end;
FDVerba := TSistemaControl.GetInstance.Conexao.ReturnQuery;
FDVerba := verbas.Localizar(aParam);
Finalize(aParam);
if not FDVerba.IsEmpty then
begin
FDVerba.First;
dVerbaTabela := FDVerba.FieldByName('VAL_VERBA').AsFloat;
end;
FDVerba.Free;
if dVerbaTabela > 0 then dVerba := dVerbaTabela;
end;
if dVerba = 0 then
begin
sMensagem := 'Verba não encontrada para o entregador ' + sNome + ', pedido ' +
Data_Sisgef.mtbBaixasTFO.Fields[0].AsString + ' !';
Synchronize(AtualizaLog);
end;
entregas.Entregas.NN := FDQuery.FieldByName('NUM_NOSSONUMERO').AsString;
entregas.Entregas.Distribuidor:= iAgente;
entregas.Entregas.Entregador:= iEntregador;
entregas.Entregas.Cliente:= FDQuery.FieldByName('COD_CLIENTE').AsInteger;
entregas.Entregas.NF:= FDQuery.FieldByName('NUM_NF').Value;
entregas.Entregas.Consumidor:= FDQuery.FieldByName('NOM_CONSUMIDOR').Value;
entregas.Entregas.Endereco:= FDQuery.FieldByName('DES_ENDERECO').Value;
entregas.Entregas.Complemento:= FDQuery.FieldByName('DES_COMPLEMENTO').Value;
entregas.Entregas.Bairro:= FDQuery.FieldByName('DES_BAIRRO').Value;
entregas.Entregas.Cidade:= FDQuery.FieldByName('NOM_CIDADE').Value;
entregas.Entregas.CEP:= FDQuery.FieldByName('NUM_CEP').Value;
entregas.Entregas.Telefone:= FDQuery.FieldByName('NUM_TELEFONE').Value;
entregas.Entregas.Expedicao:= FDQuery.FieldByName('DAT_EXPEDICAO').Value;
entregas.Entregas.Previsao:= FDQuery.FieldByName('DAT_PREV_DISTRIBUICAO').Value;
entregas.Entregas.Volumes:= FDQuery.FieldByName('QTD_VOLUMES').Value;
entregas.Entregas.Atribuicao:= FDQuery.FieldByName('DAT_ATRIBUICAO').Value;
entregas.Entregas.Baixa:= StrToDateTime(Data_Sisgef.mtbBaixasTFO.Fields[11].AsString);
entregas.Entregas.Baixado:= 'S';
entregas.Entregas.Pagamento:= FDQuery.FieldByName('DAT_PAGAMENTO').Value;
entregas.Entregas.Pago:= FDQuery.FieldByName('DOM_PAGO').Value;
entregas.Entregas.Fechado:= FDQuery.FieldByName('DOM_FECHADO').Value;
entregas.Entregas.Status:= FDQuery.FieldByName('COD_STATUS').Value;
entregas.Entregas.Entrega:= StrToDateTime(Data_Sisgef.mtbBaixasTFO.Fields[1].AsString);
entregas.Entregas.PesoReal:= FDQuery.FieldByName('QTD_PESO_REAL').Value;
entregas.Entregas.PesoFranquia:= FDQuery.FieldByName('QTD_PESO_FRANQUIA').Value;
entregas.Entregas.VerbaFranquia:= FDQuery.FieldByName('VAL_VERBA_FRANQUIA').Value;
entregas.Entregas.Advalorem:= FDQuery.FieldByName('VAL_ADVALOREM').Value;
entregas.Entregas.PagoFranquia:= FDQuery.FieldByName('VAL_PAGO_FRANQUIA').Value;
entregas.Entregas.VerbaEntregador := dVerba;
entregas.Entregas.Extrato:= FDQuery.FieldByName('NUM_EXTRATO').Value;
if entregas.Entregas.Previsao < entregas.Entregas.Entrega then
begin
entregas.Entregas.Atraso := DaysBetween(entregas.Entregas.Previsao,entregas.Entregas.Entrega)
end
else
begin
entregas.Entregas.Atraso := 0;
end;
entregas.Entregas.VolumesExtra:= FDQuery.FieldByName('QTD_VOLUMES_EXTRA').Value;
entregas.Entregas.ValorVolumes:= FDQuery.FieldByName('VAL_VOLUMES_EXTRA').Value;
entregas.Entregas.PesoCobrado:= StrToFloatDef(Data_Sisgef.mtbBaixasTFO.Fields[17].AsString,0);
entregas.Entregas.TipoPeso:= Data_Sisgef.mtbBaixasTFO.Fields[18].AsString;
entregas.Entregas.Recebimento:= FDQuery.FieldByName('DAT_RECEBIDO').Value;
entregas.Entregas.Recebido:= FDQuery.FieldByName('DOM_RECEBIDO').Value;
entregas.Entregas.CTRC:= FDQuery.FieldByName('NUM_CTRC').Value;
entregas.Entregas.Manifesto:= FDQuery.FieldByName('NUM_MANIFESTO').Value;
entregas.Entregas.Rastreio:= FDQuery.FieldByName('DES_RASTREIO').Value;
entregas.Entregas.Rastreio := entregas.Entregas.Rastreio + #13 +
'> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' baixado por importação por ' +
Global.Parametros.pUser_Name;
entregas.Entregas.Lote:= FDQuery.FieldByName('NUM_LOTE_REMESSA').Value;
entregas.Entregas.Retorno:= FDQuery.FieldByName('DES_RETORNO').Value;
entregas.Entregas.Credito:= FDQuery.FieldByName('DAT_CREDITO').Value;
entregas.Entregas.Creditado:= FDQuery.FieldByName('DOM_CREDITO').Value;
entregas.Entregas.Container:= FDQuery.FieldByName('NUM_CONTAINER').Value;
entregas.Entregas.ValorProduto:= FDQuery.FieldByName('VAL_PRODUTO').Value;
entregas.Entregas.Altura:= FDQuery.FieldByName('QTD_ALTURA').Value;
entregas.Entregas.Largura:= FDQuery.FieldByName('QTD_LARGURA').Value;
entregas.Entregas.Comprimento:= FDQuery.FieldByName('QTD_COMPRIMENTO').Value;
entregas.Entregas.CodigoFeedback:= FDQuery.FieldByName('COD_FEEDBACK').Value;
entregas.Entregas.DataFeedback:= FDQuery.FieldByName('DAT_FEEDBACK').Value;
entregas.Entregas.Conferido:= FDQuery.FieldByName('DOM_CONFERIDO').Value;
entregas.Entregas.Pedido:= Data_Sisgef.mtbBaixasTFO.Fields[13].AsString;
entregas.Entregas.CodCliente:= FDQuery.FieldByName('COD_CLIENTE_EMPRESA').AsInteger;
if Copy(Data_Sisgef.mtbBaixasTFO.Fields[10].AsString, 1, 7) = 'FRANQUE' then
begin
entregas.Entregas.CodigoFeedback := 101;
entregas.Entregas.DataFeedback := StrToDateTimeDef(Data_Sisgef.mtbBaixasTFO.Fields[11].AsString,0);
end;
if entregas.Entregas.PesoCobrado > 25 then
begin
entregas.Entregas.VerbaEntregador := 15;
end;
if entregas.Entregas.Fechado <> 'S' then
begin
entregas.Entregas.Acao := tacAlterar;
if not entregas.Gravar then
begin
sMensagem := 'Erro ao baixar o pedido ' + Data_Sisgef.mtbBaixasTFO.Fields[0].AsString + ' !';
Synchronize(AtualizaLog);
end;
end;
end
else
begin
sMensagem := 'Pedido ' + Data_Sisgef.mtbBaixasTFO.Fields[0].AsString + ', não encontrado no banco de dados!';
Synchronize(AtualizaLog);
end;
FDQuery.Free;
end;
Data_Sisgef.mtbBaixasTFO.Next;
iPos := iPos + 1;
FdPos := (iPos / iTotal) * 100;
if not(Self.Terminated) then
begin
Synchronize(AtualizaProgress);
end
else
begin
Abort;
end;
end;
end;
Except
on E: Exception do
begin
Application.MessageBox(PChar('Classe: ' + E.ClassName + chr(13) +'Mensagem: ' + E.Message),'Erro', MB_OK + MB_ICONERROR);
bCancel := True;
end;
end;
finally
if bCancel then
begin
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) +' importação cancelada ...';
Synchronize(AtualizaLog);
Application.MessageBox('Importação cancelada!','Importação de Baixas', MB_OK + MB_ICONWARNING);
end
else
begin
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) +' importação concluída com sucesso';
Synchronize(AtualizaLog);
Application.MessageBox('Importação concluída com sucesso!','Importação de baixas', MB_OK + MB_ICONINFORMATION);
end;
Synchronize(TerminaProcesso);
entregas.Free;
entregadores.Free;
Data_Sisgef.FDBatchMove.Mappings.Clear;
Data_Sisgef.FDBTextReader.DataDef.Fields.Clear;
Data_Sisgef.mtbBaixasTFO.Edit;
Data_Sisgef.mtbBaixasTFO.ClearFields;
Data_Sisgef.mtbBaixasTFO.Close;
end;
end;
procedure Thread_ImportarBaixasTFO.IniciaProcesso;
begin
bCancel := False;
view_ImportarBaixasTFO.actCancelar.Enabled := True;
view_ImportarBaixasTFO.actFechar.Enabled := False;
view_ImportarBaixasTFO.actImportar.Enabled := False;
view_ImportarBaixasTFO.actAbrir.Enabled := False;
view_ImportarBaixasTFO.dxLayoutItem7.Visible := True;
sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' iniciando importação de ' + IntToStr(iTotal) +
' registros do arquivo' + FFile;
AtualizaLog;
end;
procedure Thread_ImportarBaixasTFO.TerminaProcesso;
begin
view_ImportarBaixasTFO.actCancelar.Enabled := False;
view_ImportarBaixasTFO.actFechar.Enabled := True;
view_ImportarBaixasTFO.actImportar.Enabled := True;
view_ImportarBaixasTFO.actAbrir.Enabled := True;
view_ImportarBaixasTFO.edtArquivo.Clear;
view_ImportarBaixasTFO.pbImportacao.Position := 0;
view_ImportarBaixasTFO.pbImportacao.Clear;
view_ImportarBaixasTFO.dxLayoutItem7.Visible := False;
end;
end.
|
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower OfficePartner
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 2000-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
unit ExSMail2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, OpShared, OpOlkXP, OpOutlk, sMemo, sButton, sEdit,
sLabel, sPanel;
type
TForm2 = class(TForm)
Panel1: TsPanel;
edtTo: TsEdit;
btnTo: TsButton;
edtCC: TsEdit;
btnCC: TsButton;
edtBcc: TsEdit;
btnBCC: TsButton;
edtSubject: TsEdit;
Label1: TsLabel;
Panel2: TsPanel;
mmoBody: TsMemo;
btnSend: TsButton;
btnCancel: TsButton;
OpOutlook1: TOpOutlook;
attach: TsLabel;
Edit1: TsEdit;
procedure btnToClick(Sender: TObject);
procedure edtToChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
fOutlook: TOpOutlook;
public
property Outlook: TOpOutlook read fOutlook write fOutlook;
end;
var
Form2: TForm2;
implementation
{$R *.DFM}
uses
ExSMail3;
procedure TForm2.btnToClick(Sender: TObject);
var
Dlg : TForm3;
begin
Dlg := TForm3.Create( Self );
try
Dlg.Outlook := Outlook;
if Dlg.ShowModal = mrOK then
begin
if edtTo.Text = '' then
edtTo.Text := Dlg.RecipientTo
else
edtTo.Text := edtTo.Text + ';' + Dlg.RecipientTo;
if edtCC.Text = '' then
edtCC.Text := Dlg.RecipientCC
else
edtCC.Text := edtCC.Text + ';' + Dlg.RecipientCC;
if edtBCC.Text = '' then
edtBCC.Text := Dlg.RecipientBCC
else
edtBCC.Text := edtBCC.Text + ';' + Dlg.RecipientBCC;
end;
finally
Dlg.Free
end;
end;
procedure TForm2.edtToChange(Sender: TObject);
begin
btnSend.Enabled := edtTo.Text <> '';
end;
procedure TForm2.FormShow(Sender: TObject);
begin
if ( not Assigned(Outlook) ) or ( not(Outlook.Connected) ) then
Close;
end;
procedure TForm2.btnSendClick(Sender: TObject);
var
MailItem: TOpMailItem;
begin
MailItem := Outlook.CreateMailItem;
if assigned( MailItem ) then
with MailItem do
begin
MsgTo := edtTo.Text;
if edtCC.Text <> '' then
MsgCC := edtCC.Text;
if edtBCC.Text <> '' then
MsgBCC := edtBCC.Text;
if edtSubject.Text <> '' then
Subject := edtSubject.Text;
if mmoBody.Text <> '' then
Body := mmoBody.Text;
Attachments.Add(Edit1.Text);
try
Send;
except
MessageDlg( 'Mail send failure', mtWarning, [mbOK], 0 )
end;
end;
Close
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
// Try
if not OpOutlook1.Connected then
OpOutlook1.Connected := True;
Outlook := OpOutlook1;
{ except
close ;
Raise Exception.Create('Error happened');
end; }
end;
end.
|
unit Funcionarios;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, DBCtrls, Mask, Buttons;
type
TformFuncionarios = class(TForm)
lblMatricula: TLabel;
fldMatricula: TDBText;
lblNomeFuncionario: TLabel;
fldNomeFuncionario: TDBEdit;
fldEndereco: TDBEdit;
fldNumero: TDBEdit;
fldBairro: TDBEdit;
fldCidade: TDBEdit;
fldCEP: TDBEdit;
fldTelefone: TDBEdit;
lblEndereco: TLabel;
lblNumero: TLabel;
lblBairro: TLabel;
lblCidade: TLabel;
lblEstado: TLabel;
fldEstado: TDBComboBox;
lblCEP: TLabel;
lblTelefone: TLabel;
btnPrimeiro: TSpeedButton;
btnAnterior: TSpeedButton;
btnProximo: TSpeedButton;
btnUltimo: TSpeedButton;
btnGravar: TSpeedButton;
btnLocalizar: TSpeedButton;
btnExcluir: TSpeedButton;
btnAdicionar: TSpeedButton;
btnRetornar: TSpeedButton;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnPrimeiroClick(Sender: TObject);
procedure btnAnteriorClick(Sender: TObject);
procedure btnProximoClick(Sender: TObject);
procedure btnUltimoClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnLocalizarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnAdicionarClick(Sender: TObject);
procedure btnRetornarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
formFuncionarios: TformFuncionarios;
implementation
uses ModuloDados, RotinasGerais, SeekFuncionario;
{$R *.DFM}
procedure TformFuncionarios.FormShow(Sender: TObject);
var
FArquivo: TextFile;
strDados: string;
begin
dmBaseDados.tblFuncionarios.Open;
AssignFile(FArquivo,'C:\SGE\TABELAS\ESTADOS.TXT');
Reset(FArquivo);
ReadLn(FArquivo,strDados);
while (not Eof(FArquivo)) do
begin
fldEstado.Items.Add(strDados);
ReadLn(FArquivo,strDados);
end;
CloseFile(FArquivo);
if (dmBaseDados.tblFuncionarios.RecordCount = 0) then
begin
dmBaseDados.tblFuncionarios.Append;
dmBaseDados.tblFuncionariosCodigoFuncionario.AsString := '001';
dmBaseDados.tblFuncionarios.Post;
end;
fldNomeFuncionario.SetFocus;
end;
procedure TformFuncionarios.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
dmBaseDados.tblFuncionarios.Close;
end;
procedure TformFuncionarios.btnPrimeiroClick(Sender: TObject);
begin
dmBaseDados.tblFuncionarios.First;
fldNomeFuncionario.SetFocus;
end;
procedure TformFuncionarios.btnAnteriorClick(Sender: TObject);
begin
dmBaseDados.tblFuncionarios.Prior;
if (dmBaseDados.tblFuncionarios.Bof) then
begin
InicioTabela;
dmBasedados.tblFuncionarios.First;
end;
fldNomeFuncionario.SetFocus;
end;
procedure TformFuncionarios.btnProximoClick(Sender: TObject);
begin
dmBaseDados.tblFuncionarios.Next;
if (dmBaseDados.tblFuncionarios.Eof) then
begin
FimTabela;
dmBasedados.tblFuncionarios.Last;
end;
fldNomeFuncionario.SetFocus;
end;
procedure TformFuncionarios.btnUltimoClick(Sender: TObject);
begin
dmBaseDados.tblFuncionarios.Last;
fldNomeFuncionario.SetFocus;
end;
procedure TformFuncionarios.btnGravarClick(Sender: TObject);
begin
dmBaseDados.tblFuncionarios.Post;
fldNomeFuncionario.SetFocus;
end;
procedure TformFuncionarios.btnLocalizarClick(Sender: TObject);
begin
formSeekFuncionario.ShowModal;
fldNomeFuncionario.SetFocus;
end;
procedure TformFuncionarios.btnExcluirClick(Sender: TObject);
begin
dmBaseDados.tblFuncionarios.Delete;
fldNomeFuncionario.SetFocus;
end;
procedure TformFuncionarios.btnAdicionarClick(Sender: TObject);
var
intCodigo,intTamanho: integer;
strCodigo: string;
begin
dmBaseDados.tblFuncionarios.Last;
intCodigo := StrToInt(dmBaseDados.tblFuncionariosCodigoFuncionario.AsString);
Inc(intCodigo);
strCodigo := IntToStr(intCodigo);
intTamanho := Length(strCodigo);
strCodigo := Copy('000'+strCodigo,intTamanho+1,3);
dmBaseDados.tblFuncionarios.Append;
dmBaseDados.tblFuncionariosCodigoFuncionario.AsString := strCodigo;
dmBaseDados.tblFuncionarios.Post;
fldNomeFuncionario.SetFocus;
end;
procedure TformFuncionarios.btnRetornarClick(Sender: TObject);
begin
Close;
end;
end.
|
unit PE.DataDirectories;
interface
uses
System.Classes,
System.SysUtils,
PE.Common,
PE.Msg,
PE.Section,
PE.Sections,
PE.Types.Directories,
PE.Utils;
type
TDataDirectories = class
private
FPE: TObject; // TPEImage
FItems: array of TImageDataDirectory;
function GetCount: integer; inline;
procedure SetCount(const Value: integer);
public
constructor Create(APE: TObject);
procedure Clear;
procedure NullInvalid(const Msg: TMsgMgr);
// Load array of TImageDataDirectory (va,size) from stream.
procedure LoadDirectoriesFromStream(
Stream: TStream;
const Msg: TMsgMgr;
DeclaredCount: uint32; // # of rva and sizes
MaxBytes: uint16
);
// Save array of TImageDataDirectory (va,size) to stream.
// Return saved size.
function SaveDirectoriesToStream(Stream: TStream): integer;
// Check if index is in item range.
function IsGoodIndex(Index: integer): boolean; inline;
// Get TImageDataDirectory by Index.
// Result is True if Index exists.
// OutDir is optional and can be nil.
function Get(Index: integer; OutDir: PImageDataDirectory): boolean;
// Get directory name.
function GetName(Index: integer): string;
// Put directory safely. If Index > than current item count, empty items
// will be added.
procedure Put(Index: integer; const Dir: TImageDataDirectory); overload;
procedure Put(Index: integer; RVA, Size: uint32); overload;
// If Index exists set RVA and Size to 0.
procedure Null(Index: integer);
// Check if directory by Index occuppies whole section. If it's true,
// result is section. Otherwise result is nil.
function GetSectionDedicatedToDir(Index: integer;
AlignSize: boolean = False): TPESection;
// Get index of directory, which occupies whole Section. Result is -1 if
// not found.
function GetDirDedicatedToSection(Section: TPESection; AlignSize: boolean = False): integer;
// Save data pointed by directory RVA and Size to file.
// Index is directory index.
function SaveToStream(Index: integer; Stream: TStream): boolean;
function SaveToFile(Index: integer; const FileName: string): boolean;
// Load data into memory pointed by directory RVA and Size.
// Index is directory index.
// Offset is file offset where to start reading from.
// Result is True if complete size was read.
function LoadFromStream(Index: integer; Stream: TStream; Offset: uint64): boolean;
function LoadFromFile(Index: integer; const FileName: string; Offset: uint64): boolean;
property Count: integer read GetCount write SetCount;
end;
implementation
uses
// Expand
PE.Headers,
PE.Image;
{ TDataDirectories }
procedure TDataDirectories.Clear;
begin
FItems := nil;
self.Count := 0;
end;
constructor TDataDirectories.Create(APE: TObject);
begin
self.FPE := APE;
end;
function TDataDirectories.GetSectionDedicatedToDir(Index: integer;
AlignSize: boolean): TPESection;
var
Dir: TImageDataDirectory;
sec: TPESection;
ExpectedSize, VSize: uint32;
img: TPEImage;
begin
Result := nil;
if not Get(Index, @Dir) then
exit;
if Dir.IsEmpty then
exit;
img := TPEImage(FPE);
if not img.Sections.RVAToSec(Dir.VirtualAddress, @sec) then
exit;
if (sec.RVA <> Dir.VirtualAddress) then
exit;
if AlignSize then
begin
ExpectedSize := AlignUp(Dir.Size, img.SectionAlignment);
VSize := AlignUp(sec.VirtualSize, img.SectionAlignment);
end
else
begin
ExpectedSize := Dir.Size;
VSize := sec.VirtualSize;
end;
if (VSize = ExpectedSize) then
Result := sec;
end;
function TDataDirectories.IsGoodIndex(Index: integer): boolean;
begin
Result := (Index >= 0) and (Index < Length(FItems));
end;
function TDataDirectories.Get(Index: integer; OutDir: PImageDataDirectory): boolean;
begin
Result := IsGoodIndex(Index);
if Result and Assigned(OutDir) then
OutDir^ := FItems[Index];
end;
procedure TDataDirectories.Put(Index: integer; const Dir: TImageDataDirectory);
begin
if Index >= Length(FItems) then
SetLength(FItems, Index + 1)
else if Index < 0 then
Index := 0;
FItems[Index] := Dir;
end;
procedure TDataDirectories.Put(Index: integer; RVA, Size: uint32);
var
d: TImageDataDirectory;
begin
d.RVA := RVA;
d.Size := Size;
Put(Index, d);
end;
procedure TDataDirectories.Null(Index: integer);
begin
if (Index >= 0) and (Index < Length(FItems)) then
FItems[Index] := NULL_IMAGE_DATA_DIRECTORY;
end;
function TDataDirectories.GetCount: integer;
begin
Result := Length(FItems);
end;
function TDataDirectories.GetDirDedicatedToSection(Section: TPESection; AlignSize: boolean = False): integer;
var
i: integer;
begin
for i := 0 to Length(FItems) - 1 do
begin
if GetSectionDedicatedToDir(i, AlignSize) = Section then
exit(i);
end;
exit(-1);
end;
function TDataDirectories.GetName(Index: integer): string;
begin
if IsGoodIndex(Index) then
Result := GetDirectoryName(index)
else
Result := '';
end;
procedure TDataDirectories.NullInvalid(const Msg: TMsgMgr);
var
i: integer;
needToNullDir: boolean;
begin
// Check RVAs.
for i := 0 to self.Count - 1 do
begin
// Empty dir is ok.
if FItems[i].IsEmpty then
continue;
needToNullDir := False;
if (FItems[i].Size = 0) and (FItems[i].RVA <> 0) then
begin
Msg.Write(SCategoryDataDirecory, 'Directory # %d has size = 0.', [i]);
needToNullDir := true;
end
else if not TPEImage(FPE).RVAExists(FItems[i].RVA) then
begin
Msg.Write(SCategoryDataDirecory, 'Directory # %d RVA is not in image.', [i]);
needToNullDir := true;
end;
if needToNullDir and (PO_NULL_INVALID_DIRECTORY in TPEImage(FPE).Options) then
begin
FItems[i] := NULL_IMAGE_DATA_DIRECTORY;
Msg.Write(SCategoryDataDirecory, 'Directory # %d nulled.', [i]);
end;
end;
end;
procedure TDataDirectories.LoadDirectoriesFromStream;
var
MaxCountPossible: integer;
CountToRead: integer;
SizeToFileEnd: uint64;
Size: uint32;
MaxSizePossible: uint16;
begin
Clear;
if DeclaredCount = 0 then
begin
Msg.Write(SCategoryDataDirecory, 'No data directories.');
exit;
end;
SizeToFileEnd := (Stream.Size - Stream.Position);
// Max size available for dirs.
if SizeToFileEnd > MaxBytes then
MaxSizePossible := MaxBytes
else
MaxSizePossible := SizeToFileEnd;
MaxCountPossible := MaxSizePossible div SizeOf(TImageDataDirectory);
// File can have part of dword stored. It must be extended with zeros.
if (MaxSizePossible mod SizeOf(TImageDataDirectory)) <> 0 then
inc(MaxCountPossible);
if DeclaredCount <> TYPICAL_NUMBER_OF_DIRECTORIES then
Msg.Write(SCategoryDataDirecory, 'Non-usual count of directories declared (0x%x).', [DeclaredCount]);
if DeclaredCount > MaxCountPossible then
begin
CountToRead := MaxCountPossible;
Msg.Write(SCategoryDataDirecory,
'Declared count of directories is greater than file can contain (0x%x > 0x%x).',
[DeclaredCount, MaxCountPossible]);
Msg.Write(SCategoryDataDirecory, 'Fall back to 0x%x.', [MaxCountPossible]);
end
else
begin
CountToRead := DeclaredCount;
end;
// Read data directories.
Size := CountToRead * SizeOf(TImageDataDirectory);
SetLength(FItems, CountToRead);
// Must clear buffer, cause it can have partial values (filled with zeros).
FillChar(FItems[0], Size, 0);
// Not all readed size/rva can be valid. You must check rvas before use.
Stream.Read(FItems[0], Size);
// Set final count.
self.Count := CountToRead;
NullInvalid(Msg);
end;
function TDataDirectories.SaveToStream(Index: integer; Stream: TStream): boolean;
var
Dir: TImageDataDirectory;
begin
if Get(Index, @Dir) then
begin
TPEImage(FPE).SaveRegionToStream(Stream, Dir.VirtualAddress, Dir.Size);
exit(true);
end;
exit(False);
end;
function TDataDirectories.SaveToFile(Index: integer; const FileName: string): boolean;
var
fs: TFileStream;
begin
fs := TFileStream.Create(FileName, fmCreate);
try
Result := SaveToStream(Index, fs);
finally
fs.Free;
end;
end;
function TDataDirectories.LoadFromStream(Index: integer; Stream: TStream; Offset: uint64): boolean;
var
Dir: TImageDataDirectory;
ReadCount: uint32;
begin
if Get(Index, @Dir) then
begin
TPEImage(FPE).LoadRegionFromStream(Stream, Offset, Dir.VirtualAddress, Dir.Size, @ReadCount);
exit(ReadCount = Dir.Size);
end;
exit(False);
end;
function TDataDirectories.LoadFromFile(Index: integer; const FileName: string; Offset: uint64): boolean;
var
fs: TFileStream;
begin
fs := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Result := LoadFromStream(Index, fs, Offset);
finally
fs.Free;
end;
end;
function TDataDirectories.SaveDirectoriesToStream(Stream: TStream): integer;
begin
Result := Stream.Write(FItems[0], Length(FItems) * SizeOf(TImageDataDirectory))
end;
procedure TDataDirectories.SetCount(const Value: integer);
begin
SetLength(FItems, Value);
TPEImage(FPE).OptionalHeader.NumberOfRvaAndSizes := Value;
end;
end.
|
unit clCadastro;
interface
uses clpessoajuridica, Vcl.Dialogs,System.SysUtils, clConexao, System.StrUtils;
type
TCadastro = class(TPessoaJuridica)
private
FCodigo: Integer;
FTipoCadastro: Integer;
FDepartamento: Integer;
FSubTipo: Integer;
FFilial: Integer;
FFuncao: Integer;
FTipoDoc: String;
FDataCadastro: TDateTime;
FUsuario: Integer;
FRoteiro: Integer;
FStatusGR: Integer;
FStatusCadastro: Integer;
conexao: TConexao;
procedure SetCodigo(val: Integer);
procedure SetTipoCadastro(val: Integer);
procedure SetDepartamento(val: Integer);
procedure SetSubTipo(val: Integer);
procedure SetFilial(val: Integer);
procedure SetFuncao(val: Integer);
procedure SetTipoDoc(val: String);
procedure SetDataCadastro(val: TDateTime);
procedure SetUsuario(val: Integer);
procedure SetRoteiro(val: Integer);
procedure SetStatusGR(val: Integer);
procedure SetStatusCadastro(val: Integer);
public
property Codigo: Integer read FCodigo write SetCodigo;
property TipoCadastro: Integer read FTipoCadastro write SetTipoCadastro;
property Departamento: Integer read FDepartamento write SetDepartamento;
property SubTipo: Integer read FSubTipo write SetSubTipo;
property Filial: Integer read FFilial write SetFilial;
property Funcao: Integer read FFuncao write SetFuncao;
property TipoDoc: String read FTipoDoc write SetTipoDoc;
property DataCadastro: TDateTime read FDataCadastro write SetDataCadastro;
property Usuario: Integer read FUsuario write SetUsuario;
property Roteiro: Integer read FRoteiro write SetRoteiro;
property StatusGR: Integer read FStatusGR write SetStatusGR;
property StatusCadastro: Integer read FStatusCadastro
write SetStatusCadastro;
function ValidarDados: Boolean;
function getObject(sId: String; sFiltro: String): Boolean;
constructor Create;
function getObjects: Boolean;
function Delete(sFiltro: String): Boolean;
destructor Destroy; override;
function Insert: Boolean;
function Update: Boolean;
function getField(sCampo: String; sColuna: String): String;
end;
CONST
TABLENAME = 'CAD_CADASTRO';
implementation
uses udm;
procedure TCadastro.SetCodigo(val: Integer);
begin
FCodigo := val;
end;
procedure TCadastro.SetTipoCadastro(val: Integer);
begin
FTipoCadastro := val;
end;
procedure TCadastro.SetDepartamento(val: Integer);
begin
FDepartamento := val;
end;
procedure TCadastro.SetSubTipo(val: Integer);
begin
FSubTipo := val;
end;
procedure TCadastro.SetFilial(val: Integer);
begin
FFilial := val;
end;
procedure TCadastro.SetFuncao(val: Integer);
begin
FFuncao := val;
end;
procedure TCadastro.SetTipoDoc(val: String);
begin
FTipoDoc := val;
end;
procedure TCadastro.SetDataCadastro(val: TDateTime);
begin
FDataCadastro := val;
end;
procedure TCadastro.SetUsuario(val: Integer);
begin
FUsuario := val;
end;
procedure TCadastro.SetRoteiro(val: Integer);
begin
FRoteiro := val;
end;
procedure TCadastro.SetStatusGR(val: Integer);
begin
FStatusGR := val;
end;
procedure TCadastro.SetStatusCadastro(val: Integer);
begin
FStatusCadastro := val;
end;
function TCadastro.ValidarDados: Boolean;
begin
try
Result := False;
if Self.TipoCadastro = 0 then
begin
MessageDlg('Informe o Tipo de Cadastro!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Departamento = 0 then
begin
MessageDlg('Informe o Departamento!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.SubTipo = 0 then
begin
MessageDlg('Informe o Sub-Tipo!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Filial = 0 then
begin
MessageDlg('Informe a Filial!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Nome.IsEmpty then
begin
MessageDlg('Informe o Nomeou Razão Social!',mtWarning,[mbCancel],0);
Exit;
end;
//Empresa
if Self.TipoCadastro = 2 then
begin
if Self.Responsavel.IsEmpty then
begin
MessageDlg('Informe o nome do Responsável!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Fantasia.IsEmpty then
begin
MessageDlg('Informe o nome Fantasia!',mtWarning,[mbCancel],0);
Exit;
end;
Self.TipoDoc := 'CNPJ';
if Self.CNPJ.IsEmpty then
begin
MessageDlg('Informe o Número do CNPJ!',mtWarning,[mbCancel],0);
Exit;
end;
if (not Self.VerificaCNPJ(Self.CNPJ)) then
begin
MessageDlg('CNPJ Inválido!',mtWarning,[mbCancel],0);
Exit;
end;
if (not Self.RG.IsEmpty) then
begin
if Self.Expedidor.IsEmpty then
begin
MessageDlg('Informe o Orgão Expedidor do RG do Responsável!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.UFRG.IsEmpty then
begin
MessageDlg('Informe o Estdo do RG do Resposável!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Naturalidade.IsEmpty then
begin
MessageDlg('Informe a Naturalidade do Responsável!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.UFNaturalidade.IsEmpty then
begin
MessageDlg('Informe o Estado da Naturalidade do Responsável!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.DataRG = 0 then
begin
MessageDlg('Informe a Data de Emissão do RG do Responsável!',mtWarning,[mbCancel],0);
Exit;
end;
end;
if (not Self.RegistroCNH.IsEmpty) then
begin
if Self.ValidadeCNH = 0 then
begin
MessageDlg('Informe a Validade da CNH do Responsável!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.ValidadeCNH < Now then
begin
MessageDlg('CNH do Responsável esta expirada!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.CategoriaCNH.IsEmpty then
begin
MessageDlg('Informe o Número da CNH do Responsável!',mtWarning,[mbCancel],0);
Exit;
end;
if Pos(Self.CategoriaCNH, 'ABCDEABACADAE') = 0 then
begin
MessageDlg('Categoria do CNH do Responsável inválida!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.UFCNH.IsEmpty then
begin
MessageDlg('Informe o Estado da CNH do Responsável!',mtWarning,[mbCancel],0);
Exit;
end;
end;
end;
//Funcionarios
if Self.TipoCadastro = 1 then
begin
if Self.CNPJ.IsEmpty then
begin
MessageDlg('Informe o Número do CPF!',mtWarning,[mbCancel],0);
Exit;
end;
Self.TipoDoc := 'CPF';
if (not Self.VerificaCPF(Self.CNPJ)) then
begin
MessageDlg('CPF Inválido!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Funcao = 0 then
begin
MessageDlg('Informe a Função!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.SubTipo = 0 then
begin
MessageDlg('Informe o Sub-Tipo!',mtWarning,[mbCancel],0);
Exit;
end;
if (not Self.RG.IsEmpty) then
begin
if Self.Expedidor.IsEmpty then
begin
MessageDlg('Informe o Orgão Expedidor do RG!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.UFRG.IsEmpty then
begin
MessageDlg('Informe o Estdo do RG!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Naturalidade.IsEmpty then
begin
MessageDlg('Informe a Naturalidade!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.UFNaturalidade.IsEmpty then
begin
MessageDlg('Informe o Estado da Naturalidade!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.DataRG = 0 then
begin
MessageDlg('Informe a Data de Emissão do RG!',mtWarning,[mbCancel],0);
Exit;
end;
end;
if (not Self.RegistroCNH.IsEmpty) then
begin
if Self.ValidadeCNH = 0 then
begin
MessageDlg('Informe a Validade da CNH!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.ValidadeCNH < Now then
begin
MessageDlg('CNH esta expirada!',mtWarning,[mbCancel],0);
Exit;
end;
if Pos(Self.CategoriaCNH, 'ABCDEABACADAE') = 0 then
begin
MessageDlg('Categoria do CNH do Responsável inválida!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.UFCNH.IsEmpty then
begin
MessageDlg('Informe o Estado da CNH do Responsável!',mtWarning,[mbCancel],0);
Exit;
end;
end;
if (not Self.PIS.IsEmpty) then
begin
if (not Self.VerificarPIS(Self.PIS)) then
begin
MessageDlg('PIS inválido!',mtWarning,[mbCancel],0);
Exit;
end;
end;
if (not Self.CTPS.IsEmpty) then
begin
if Self.SerieCTPS.IsEmpty then
begin
MessageDlg('Informe a Série da Carteira Profissional!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.UFCTPS.IsEmpty then
begin
MessageDlg('Informe o Estado da Carteira Profissional!',mtWarning,[mbCancel],0);
Exit;
end;
end;
end;
//Entregadores / Autonomos
if (Self.TipoCadastro = 3) or (Self.TipoCadastro = 4) then
begin
if Self.CNPJ.IsEmpty then
begin
MessageDlg('Informe o Número do CPF!',mtWarning,[mbCancel],0);
Exit;
end;
Self.TipoDoc := 'CPF';
if (not Self.VerificaCPF(Self.CNPJ)) then
begin
MessageDlg('CPF Inválido!',mtWarning,[mbCancel],0);
Exit;
end;
if (not Self.RG.IsEmpty) then
begin
if Self.Expedidor.IsEmpty then
begin
MessageDlg('Informe o Orgão Expedidor do RG!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.UFRG.IsEmpty then
begin
MessageDlg('Informe o Estdo do RG!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Naturalidade.IsEmpty then
begin
MessageDlg('Informe a Naturalidade!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.UFNaturalidade.IsEmpty then
begin
MessageDlg('Informe o Estado da Naturalidade!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.DataRG = 0 then
begin
MessageDlg('Informe a Data de Emissão do RG!',mtWarning,[mbCancel],0);
Exit;
end;
end;
if (not Self.RegistroCNH.IsEmpty) then
begin
if Self.ValidadeCNH = 0 then
begin
MessageDlg('Informe a Validade da CNH!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.ValidadeCNH < Now then
begin
MessageDlg('CNH esta expirada!',mtWarning,[mbCancel],0);
Exit;
end;
if Pos(Self.CategoriaCNH, 'ABCDEABACADAE') = 0 then
begin
MessageDlg('Categoria do CNH do Responsável inválida!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.UFCNH.IsEmpty then
begin
MessageDlg('Informe o Estado da CNH do Responsável!',mtWarning,[mbCancel],0);
Exit;
end;
end;
end;
// Financeiro
if (not Self.FormaCredito.IsEmpty) then
begin
if Pos(Copy(Self.FormaCredito,1,2),'010204') > 0 then
begin
if Self.TipoConta.IsEmpty then
begin
MessageDlg('Informe o Tipo de Conta Bancária!',mtWarning,[mbCancel],0);
Exit;
end;
if StrToIntDef(Self.Banco,0) = 0 then
begin
MessageDlg('Informe o Banco da Conta!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Agencia.IsEmpty then
begin
MessageDlg('Informe a Agência Bancária da Conta!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Conta.IsEmpty then
begin
MessageDlg('Informe o Número da Conta Bancária!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Favorecido.IsEmpty then
begin
MessageDlg('Informe o Nome do Favorecido da Conta Bancária!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.CNPJFavorecido.IsEmpty then
begin
MessageDlg('Informe o CPF/CNPJ do Favorecido da Conta Bancária!',mtWarning,[mbCancel],0);
Exit;
end
else
begin
if (not Self.VerificaCNPJ(Self.CNPJFavorecido)) then
begin
if (not Self.VerificaCPF(Self.CNPJFavorecido)) then
begin
MessageDlg('CPF/CNPJ do Favorecido da Conta Bancária é inválido!',mtWarning,[mbCancel],0);
Exit;
end;
end;
end;
end;
end;
Result := True;
except on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message);
end;
end;
function TCadastro.getObject(sId: String; sFiltro: String): Boolean;
begin
try
Result := False;
if sId.IsEmpty then begin
Exit;
end;
if sFiltro.IsEmpty then begin
Exit;
end;
if (not conexao.VerifyConnZEOS(0)) then begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
if dm.qryGetObject.Active then begin
dm.qryGetObject.Close;
end;
dm.qryGetObject.SQL.Clear;
dm.qryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME);
if sFiltro = 'CADASTRO' then begin
dm.qryGetObject.SQL.Add(' WHERE COD_CADASTRO = :CODIGO');
dm.qryGetObject.ParamByName('CADASTRO').AsInteger := StrToInt(sId);
end
else if sFiltro = 'NOME' then begin
dm.qryGetObject.SQL.Add(' WHERE NOM_NOME_RAZAO LIKE (:NOME)');
dm.qryGetObject.ParamByName('CTPS').AsString := QuotedStr('%' + sId + '%');
end
else if sFiltro = 'CNPJ' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_CNPJ = :CNPJ');
dm.qryGetObject.ParamByName('CNPJ').AsString := sId;
end
else if sFiltro = 'CPF' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_CPF = :CPF');
dm.qryGetObject.ParamByName('CPF').AsString := sId;
end
else if sFiltro = 'RG' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_RG = :RG');
dm.qryGetObject.ParamByName('RG').AsString := sId;
end
else if sFiltro = 'IE' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_IE = :IE');
dm.qryGetObject.ParamByName('IE').AsString := sId;
end
else if sFiltro = 'PIS' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_PIS = :PIS');
dm.qryGetObject.ParamByName('PIS').AsString := sId;
end
else if sFiltro = 'CTPS' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_CTPS = :CTPS');
dm.qryGetObject.ParamByName('CTPS').AsString := sId;
end
else if sFiltro = 'CNH' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_REGISTRO_CNH = :CNH');
dm.qryGetObject.ParamByName('CNH').AsString := sId;
end
else if sFiltro = 'TIPOCADASTRO' then begin
dm.qryGetObject.SQL.Add(' WHERE COD_TIPO_CADASTRO = :TIPOCADASTRO');
dm.qryGetObject.ParamByName('TIPOCADASTRO').AsInteger := StrToIntDef(sId,0);
end
else if sFiltro = 'DEPARTAMENTO' then begin
dm.qryGetObject.SQL.Add(' WHERE COD_DEPARTAMENTO = :DEPARTAMENTO');
dm.qryGetObject.ParamByName('DEPARTAMENTO').AsInteger := StrToIntDef(sId,0);
end
else if sFiltro = 'FILIAL' then begin
dm.qryGetObject.SQL.Add(' WHERE COD_FILIAL = :FILIAL');
dm.qryGetObject.ParamByName('FILIAL').AsInteger := StrToIntDef(sId,0);
end
else if sFiltro = 'FILTRO' then begin
dm.qryGetObject.SQL.Add(' WHERE ' + sId);
end;
dm.ZConn.PingServer;
dm.qryGetObject.Open;
if (not dm.qryGetObject.IsEmpty) then
begin
dm.qryGetObject.First;
Self.Codigo := dm.qryGetObject.FieldByName('COD_CADASTRO').AsInteger;
Self.TipoCadastro := dm.qryGetObject.FieldByName('COD_TIPO_CADASTRO').AsInteger;
Self.Departamento := dm.qryGetObject.FieldByName('COD_DEPARTAMENTO').AsInteger;
Self.SubTipo := dm.qryGetObject.FieldByName('COD_SUB_TIPO').AsInteger;
Self.Filial := dm.qryGetObject.FieldByName('COD_FILIAL').AsInteger;
Self.Nome := dm.qryGetObject.FieldByName('NOM_NOME_RAZAO').AsString;
Self.Responsavel := dm.qryGetObject.FieldByName('NOM_RESPONSAVEL').AsString;
Self.Fantasia := dm.qryGetObject.FieldByName('NOM_FANTASIA').AsString;
Self.Funcao := dm.qryGetObject.FieldByName('COD_FUNCAO').AsInteger;
Self.TipoDoc := dm.qryGetObject.FieldByName('DES_TIPO_DOC').AsString;
Self.CPF := dm.qryGetObject.FieldByName('NUM_CPF').AsString;
Self.CNPJ := dm.qryGetObject.FieldByName('NUM_CNPJ').AsString;
Self.RG := dm.qryGetObject.FieldByName('NUM_RG').AsString;
Self.IE := dm.qryGetObject.FieldByName('NUM_IE').AsString;
Self.IEST := dm.qryGetObject.FieldByName('NUM_IEST').AsString;
Self.IM := dm.qryGetObject.FieldByName('NUM_IM').AsString;
Self.Expedidor := dm.qryGetObject.FieldByName('DES_EXPEDIDOR').AsString;
Self.UFRG := dm.qryGetObject.FieldByName('UF_EXPEDIDOR').AsString;
Self.DataRG := dm.qryGetObject.FieldByName('DAT_EMISSAO').AsDateTime;
Self.Nascimento := dm.qryGetObject.FieldByName('DAT_NASCIMENTO').AsDateTime;
Self.Pai := dm.qryGetObject.FieldByName('NOM_PAI').AsString;
Self.Mae := dm.qryGetObject.FieldByName('NOM_MAE').AsString;
Self.Naturalidade := dm.qryGetObject.FieldByName('DES_NATURALIDADE').AsString;
Self.UFNaturalidade := dm.qryGetObject.FieldByName('UF_NATURALIDADE').AsString;
Self.SUFRAMA := dm.qryGetObject.FieldByName('NUM_SUFRAMA').AsString;
Self.CNH := dm.qryGetObject.FieldByName('NUM_CNH').AsString;
Self.CNAE := dm.qryGetObject.FieldByName('NUM_CNAE').AsString;
Self.CRT := dm.qryGetObject.FieldByName('NUM_CRT').AsInteger;
Self.RegistroCNH := dm.qryGetObject.FieldByName('NUM_REGISTRO_CNH').AsString;
Self.UFCNH := dm.qryGetObject.FieldByName('UF_CNH').AsString;
Self.ValidadeCNH := dm.qryGetObject.FieldByName('DAT_VALIDADE_CNH').AsDateTime;
Self.CategoriaCNH := dm.qryGetObject.FieldByName('DES_CATEGORIA').AsString;
Self.PrimeiraCNH := dm.qryGetObject.FieldByName('DAT_PRIMEIRA_CNH').AsDateTime;
Self.PIS := dm.qryGetObject.FieldByName('NUM_PIS').AsString;
Self.CTPS := dm.qryGetObject.FieldByName('NUM_CTPS').AsString;
Self.SerieCTPS := dm.qryGetObject.FieldByName('NUM_SERIE_CTPS').AsString;
Self.UFCTPS := dm.qryGetObject.FieldByName('UF_CTPS').AsString;
Self.EstadoCivil := dm.qryGetObject.FieldByName('DES_ESTADO_CIVIL').AsString;
Self.TituloEleitor := dm.qryGetObject.FieldByName('NUM_TITULO_ELEITOR').AsString;
Self.Reservista := dm.qryGetObject.FieldByName('NUM_RESERVISTA').AsString;
Self.FormaCredito := dm.qryGetObject.FieldByName('DES_FORMA_CREDITO').AsString;
Self.TipoConta := dm.qryGetObject.FieldByName('DES_TIPO_CONTA').AsString;
Self.Banco := dm.qryGetObject.FieldByName('COD_BANCO').AsString;
Self.Agencia := dm.qryGetObject.FieldByName('NUM_AGENCIA').AsString;
Self.Conta := dm.qryGetObject.FieldByName('NUM_CONTA').AsString;
Self.Favorecido := dm.qryGetObject.FieldByName('NOM_FAVORECIDO').AsString;
Self.CPFFavorecido := dm.qryGetObject.FieldByName('NUM_CPF_CNPJ_FAVORECIDO').AsString;
Self.DataCadastro := dm.qryGetObject.FieldByName('DAT_CADASTRO').AsDateTime;
Self.Usuario := dm.qryGetObject.FieldByName('COD_USUARIO_PROPRIETARIO').AsInteger;
Self.Roteiro := dm.qryGetObject.FieldByName('NUM_ROTEIRO').AsInteger;
Self.StatusGR := dm.qryGetObject.FieldByName('DES_STATUS_GR').AsInteger;
Self.StatusCadastro := dm.qryGetObject.FieldByName('DES_STATUS_CADASTRO').AsInteger;
end
else
begin
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
end;
Result := True;
except on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message);
end;
end;
constructor TCadastro.Create;
begin
inherited Create;
conexao := TConexao.Create;
end;
function TCadastro.getObjects: Boolean;
begin
try
Result := False;
if (not conexao.VerifyConnZEOS(0)) then begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
if dm.qryGetObject.Active then begin
dm.qryGetObject.Close;
end;
dm.qryGetObject.SQL.Clear;
dm.qryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME);
dm.ZConn.PingServer;
dm.qryGetObject.Open;
if dm.qryGetObject.IsEmpty then
begin
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
Exit;
end;
dm.qryGetObject.First;
Result := True;
except on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message);
end;
end;
function TCadastro.Delete(sFiltro: String): Boolean;
begin
try
Result := False;
if (not conexao.VerifyConnZEOS(0)) then begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Add('DELETE FROM ' + TABLENAME);
if sFiltro = 'CADASTRO' then begin
dm.qryGetObject.SQL.Add(' WHERE COD_CADASTRO = :CODIGO');
dm.qryGetObject.ParamByName('CADASTRO').AsInteger := Self.Codigo;
end
else if sFiltro = 'CNPJ' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_CNPJ = :CNPJ');
dm.qryGetObject.ParamByName('CNPJ').AsString := Self.CNPJ;
end
else if sFiltro = 'CPF' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_CPF = :CPF');
dm.qryGetObject.ParamByName('CPF').AsString := Self.CPF;
end
else if sFiltro = 'RG' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_RG = :RG');
dm.qryGetObject.ParamByName('RG').AsString := Self.RG;
end
else if sFiltro = 'IE' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_IE = :IE');
dm.qryGetObject.ParamByName('IE').AsString := Self.RG;
end
else if sFiltro = 'PIS' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_PIS = :PIS');
dm.qryGetObject.ParamByName('PIS').AsString := Self.PIS;
end
else if sFiltro = 'CTPS' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_CTPS = :CTPS');
dm.qryGetObject.ParamByName('CTPS').AsString := Self.CTPS;
end
else if sFiltro = 'CNH' then begin
dm.qryGetObject.SQL.Add(' WHERE NUM_REGISTRO_CNH = :CNH');
dm.qryGetObject.ParamByName('CNH').AsString := Self.RegistroCNH;
end;
dm.ZConn.PingServer;
dm.qryCRUD.ExecSQL;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
Result := True;
except on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message);
end;
end;
destructor TCadastro.Destroy;
begin
inherited Destroy;
conexao.Free;
end;
function TCadastro.Insert: Boolean;
begin
try
Result := False;
if (not conexao.VerifyConnZEOS(0)) then begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
dm.qryCRUD.SQL.Text := 'INSERT INTO ' + TABLENAME + '(' +
'COD_TIPO_CADASTRO,' +
'COD_DEPARTAMENTO,' +
'COD_SUB_TIPO,' +
'COD_FILIAL,' +
'NOM_NOME_RAZAO,' +
'NOM_RESPONSAVEL,' +
'NOM_FANTASIA,' +
'COD_FUNCAO,' +
'DES_TIPO_DOC,' +
'NUM_CPF,' +
'NUM_CNPJ,' +
'NUM_RG,' +
'NUM_IE,' +
'NUM_IEST,' +
'NUM_IM,' +
'DES_EXPEDIDOR,' +
'UF_EXPEDIDOR,' +
'DAT_EMISSAO_RG,' +
'DAT_NASCIMENTO,' +
'NOM_PAI,' +
'NOM_MAE,' +
'DES_NATURALIDADE,' +
'UF_NATURALIDADE,' +
'NUM_SUFRAMA,' +
'NUM_CNH,' +
'NUM_CNAE,' +
'NUM_CRT,' +
'NUM_REGISTRO_CNH,' +
'UF_CNH,' +
'DAT_VALIDADE_CNH,' +
'DES_CATEGORIA_CNH,' +
'DAT_PRIMEIRA_CNH,' +
'NUM_PIS,' +
'NUM_CTPS,' +
'NUM_SERIE_CTPS,' +
'UF_CTPS,' +
'DES_ESTADO_CIVIL,' +
'NUM_TITULO_ELEITOR,' +
'NUM_RESERVISTA,' +
'DES_FORMA_CREDITO,' +
'DES_TIPO_CONTA,' +
'COD_BANCO,' +
'NUM_AGENCIA,' +
'NUM_CONTA,' +
'NOM_FAVORECIDO,' +
'NUM_CPF_CNPJ_FAVORECIDO,' +
'DAT_CADASTRO,' +
'COD_USUARIO_PROPRIETARIO,' +
'NUM_ROTEIRO,' +
'DES_STATUS_GR,' +
'DES_STATUS_CADASTRO) ' +
'VALUES (' +
':CODIGO, ' +
':TIPOCADASTRO, ' +
':DEPARTAMENTO, ' +
':SUBTIPO, ' +
':FILIAL, ' +
':NOME, ' +
':RESPONSAVEL, ' +
':FANTASIA, ' +
':FUNCAO, ' +
':TIPODOC, ' +
':CPF, ' +
':CNPJ, ' +
':RG, ' +
':IE, ' +
':IEST, ' +
':IM, ' +
':EXPEDIDOR, ' +
':UFEXPEDIDOR, ' +
':EMISSAO, ' +
':NASCIMENTO, ' +
':PAI, ' +
':MAE, ' +
':NATURALIDADE, ' +
'UF_NATURALIDADE, ' +
':SUFRAMA, ' +
':CNH, ' +
':CNAE, ' +
':CRT, ' +
':REGISTROCNH, ' +
':UFCNH, ' +
':VALIDADECNH, ' +
':CATEGORIA, ' +
':PRIMEIRACNH, ' +
':PIS, ' +
':CTPS, ' +
':SERIECTPS, ' +
':UFCTPS, ' +
':ESTADOCIVIL, ' +
':TITULO, ' +
':RESERVISTA, ' +
':FORMACREDITO, ' +
':TIPOCONTA, ' +
':BANCO, ' +
':AGENCIA, ' +
':CONTA, ' +
':FAVORECIDO, ' +
':CPFFAVORECIDO, ' +
':DATACADASTRO, ' +
':USUARIO, ' +
':ROTEIRO, ' +
':STATUSGR, ' +
':STATUSCADASTRO);';
dm.qryCRUD.ParamByName('TIPOCADASTRO').AsInteger := Self.TipoCadastro;
dm.qryCRUD.ParamByName('DEPARTAMENTO').AsInteger := Self.Departamento;
dm.qryCRUD.ParamByName('SUBTIPO').AsInteger := Self.SubTipo;
dm.qryCRUD.ParamByName('FILIAL').AsInteger := Self.Filial;
dm.qryCRUD.ParamByName('NOME').AsString := Self.Nome;
dm.qryCRUD.ParamByName('RESPONSAVEL').AsString := Self.Responsavel;
dm.qryCRUD.ParamByName('FANTASIA').AsString := Self.Fantasia;
dm.qryCRUD.ParamByName('FUNCAO').AsInteger := Self.Funcao;
dm.qryCRUD.ParamByName('TIPODOC').AsString := Self.TipoDoc;
dm.qryCRUD.ParamByName('CPF').AsString := Self.CPF;
dm.qryCRUD.ParamByName('CNPJ').AsString := Self.CNPJ;
dm.qryCRUD.ParamByName('RG').AsString := Self.RG;
dm.qryCRUD.ParamByName('IE').AsString := Self.IE;
dm.qryCRUD.ParamByName('IEST').AsString := Self.IEST;
dm.qryCRUD.ParamByName('IM').AsString := Self.IM;
dm.qryCRUD.ParamByName('EXPEDIDOR').AsString := Self.Expedidor;
dm.qryCRUD.ParamByName('UFEXPEDIDOR').AsString := Self.UFRG;
dm.qryCRUD.ParamByName('EMISSAO').AsDate := Self.DataRG;
dm.qryCRUD.ParamByName('NASCIMENTO').AsDateTime := Self.Nascimento;
dm.qryCRUD.ParamByName('PAI').AsString := Self.Pai;
dm.qryCRUD.ParamByName('MAE').AsString := Self.Mae;
dm.qryCRUD.ParamByName('NATURALIDADE').AsString := Self.Naturalidade;
dm.qryCRUD.ParamByName('UFNATURALIDADE').AsString := Self.UFNaturalidade;
dm.qryCRUD.ParamByName('SUFRAMA').AsString := Self.SUFRAMA;
dm.qryCRUD.ParamByName('CNH').AsString := Self.CNH;
dm.qryCRUD.ParamByName('CNAE').AsString := Self.CNAE;
dm.qryCRUD.ParamByName('CRT').AsInteger := Self.CRT;
dm.qryCRUD.ParamByName('REGISTROCNH').AsString := Self.RegistroCNH;
dm.qryCRUD.ParamByName('UFCNH').AsString := Self.UFCNH;
dm.qryCRUD.ParamByName('VALIDADE').AsDateTime := Self.ValidadeCNH;
dm.qryCRUD.ParamByName('CATEGORIA').AsString := Self.CategoriaCNH;
dm.qryCRUD.ParamByName('PRIMEIRACNH').AsDateTime := Self.PrimeiraCNH;
dm.qryCRUD.ParamByName('PIS').AsString := Self.PIS;
dm.qryCRUD.ParamByName('CTPS').AsString := Self.CTPS;
dm.qryCRUD.ParamByName('SERIECTPS').AsString := Self.SerieCTPS;
dm.qryCRUD.ParamByName('UFCTPS').AsString := Self.UFCTPS;
dm.qryCRUD.ParamByName('ESTADOCIVIL').AsString := Self.EstadoCivil;
dm.qryCRUD.ParamByName('TITULO').AsString := Self.TituloEleitor;
dm.qryCRUD.ParamByName('RESERVISTA').AsString := Self.Reservista;
dm.qryCRUD.ParamByName('FORMACREDITO').AsString := Self.FormaCredito;
dm.qryCRUD.ParamByName('TIPOCONTA').AsString := Self.TipoConta;
dm.qryCRUD.ParamByName('BANCO').AsString := Self.Banco;
dm.qryCRUD.ParamByName('AGENCIA').AsString := Self.Agencia;
dm.qryCRUD.ParamByName('CONTA').AsString := Self.Conta;
dm.qryCRUD.ParamByName('FAVORECIDO').AsString := Self.Favorecido;
dm.qryCRUD.ParamByName('CPFFAVORECIDO').AsString := Self.CPFFavorecido;
dm.qryCRUD.ParamByName('DATACADASTRO').AsDateTime := Self.DataCadastro;
dm.qryCRUD.ParamByName('USUARIO').AsInteger := Self.Usuario;
dm.qryCRUD.ParamByName('ROTEIRO').AsInteger := Self.Roteiro;
dm.qryCRUD.ParamByName('STATUSGR').AsInteger := Self.StatusGR;
dm.qryCRUD.ParamByName('STATUSCADASTRO').AsInteger := Self.StatusCadastro;
dm.ZConn.PingServer;
dm.qryCRUD.ExecSQL;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
Result := True;
except on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message);
end;
end;
function TCadastro.Update: Boolean;
begin
try
Result := False;
if (not conexao.VerifyConnZEOS(0)) then begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
dm.qryCRUD.SQL.Text := 'UPDATE ' + TABLENAME + 'SET ' +
'COD_CADASTRO = :CODIGO,' +
'COD_TIPO_CADASTRO = :TIPOCADASTRO,' +
'COD_DEPARTAMENTO = :DEPARTAMENTO,' +
'COD_SUB_TIPO = :SUBTIPO,' +
'COD_FILIAL = :FILIAL,' +
'NOM_NOME_RAZAO = :NOME,' +
'NOM_RESPONSAVEL = :RESPONSAVEL,' +
'NOM_FANTASIA = :FANTASIA,' +
'COD_FUNCAO = :FUNCAO,' +
'DES_TIPO_DOC = :TIPODOC,' +
'NUM_CPF = :CPF,' +
'NUM_CNPJ = :CNPJ,' +
'NUM_RG = :RG,' +
'NUM_IE = :IE,' +
'NUM_IEST = :IEST,' +
'NUM_IM = :IM,' +
'DES_EXPEDIDOR = :EXPEDIDOR,' +
'UF_EXPEDIDOR = :UFEXPEDIDOR,' +
'DAT_EMISSAO_RG = :EMISSAO,' +
'DAT_NASCIMENTO = :NASCIMENTO,' +
'NOM_PAI = :PAI,' +
'NOM_MAE = :MAE,' +
'DES_NATURALIDADE = :NATURALIDADE,' +
'UF_NATURALIDADE = :UFNATURALIDADE,' +
'NUM_SUFRAMA = :SUFRAMA,' +
'NUM_CNH = :CNH,' +
'NUM_CNAE = :CNAE,' +
'NUM_CRT = :CRT,' +
'NUM_REGISTRO_CNH = :REGISTROCNH,' +
'UF_CNH = :UFCNH,' +
'DAT_VALIDADE_CNH = :VALIDADE,' +
'DES_CATEGORIA_CNH = :CATEGORIA,' +
'DAT_PRIMEIRA_CNH = :PRIMEIRACNH,' +
'NUM_PIS = :PIS,' +
'NUM_CTPS = :CTPS,' +
'NUM_SERIE_CTPS = :SERIECTPS,' +
'UF_CTPS = :UFCTPS,' +
'DES_ESTADO_CIVIL = :ESTADOCIVIL,' +
'NUM_TITULO_ELEITOR = :TITULO,' +
'NUM_RESERVISTA = :RESERVISTA,' +
'DES_FORMA_CREDITO = :FORMACREDITO,' +
'DES_TIPO_CONTA = :TIPOCONTA,' +
'COD_BANCO = :BANCO,' +
'NUM_AGENCIA = :AGENCIA,' +
'NUM_CONTA = :CONTA,' +
'NOM_FAVORECIDO = :FAVORECIDO,' +
'NUM_CPF_CNPJ_FAVORECIDO = :CPFFAVORECIDO,' +
'DAT_CADASTRO = :DATACADASTRO,' +
'COD_USUARIO_PROPRIETARIO = :USUARIO,' +
'NUM_ROTEIRO = :ROTEIRO, ' +
'DES_STATUS_GR = :STATUSGR,' +
'DES_STATUS_CADASTRO = :STATUSCADASTRO, ' +
'WHERE COD_CADASTRO = :CODIGO;';
dm.qryCRUD.ParamByName('CODIGO').AsInteger := Self.Codigo;
dm.qryCRUD.ParamByName('TIPOCADASTRO').AsInteger := Self.TipoCadastro;
dm.qryCRUD.ParamByName('DEPARTAMENTO').AsInteger := Self.Departamento;
dm.qryCRUD.ParamByName('SUBTIPO').AsInteger := Self.SubTipo;
dm.qryCRUD.ParamByName('FILIAL').AsInteger := Self.Filial;
dm.qryCRUD.ParamByName('NOME').AsString := Self.Nome;
dm.qryCRUD.ParamByName('RESPONSAVEL').AsString := Self.Responsavel;
dm.qryCRUD.ParamByName('FANTASIA').AsString := Self.Fantasia;
dm.qryCRUD.ParamByName('FUNCAO').AsInteger := Self.Funcao;
dm.qryCRUD.ParamByName('TIPODOC').AsString := Self.TipoDoc;
dm.qryCRUD.ParamByName('CPF').AsString := Self.CPF;
dm.qryCRUD.ParamByName('CNPJ').AsString := Self.CNPJ;
dm.qryCRUD.ParamByName('RG').AsString := Self.RG;
dm.qryCRUD.ParamByName('IE').AsString := Self.IE;
dm.qryCRUD.ParamByName('IEST').AsString := Self.IEST;
dm.qryCRUD.ParamByName('IM').AsString := Self.IM;
dm.qryCRUD.ParamByName('EXPEDIDOR').AsString := Self.Expedidor;
dm.qryCRUD.ParamByName('UFEXPEDIDOR').AsString := Self.UFRG;
dm.qryCRUD.ParamByName('EMISSAO').AsDate := Self.DataRG;
dm.qryCRUD.ParamByName('NASCIMENTO').AsDateTime := Self.Nascimento;
dm.qryCRUD.ParamByName('PAI').AsString := Self.Pai;
dm.qryCRUD.ParamByName('MAE').AsString := Self.Mae;
dm.qryCRUD.ParamByName('NATURALIDADE').AsString := Self.Naturalidade;
dm.qryCRUD.ParamByName('UFNATURALIDADE').AsString := Self.UFNaturalidade;
dm.qryCRUD.ParamByName('SUFRAMA').AsString := Self.SUFRAMA;
dm.qryCRUD.ParamByName('CNH').AsString := Self.CNH;
dm.qryCRUD.ParamByName('CNAE').AsString := Self.CNAE;
dm.qryCRUD.ParamByName('CRT').AsInteger := Self.CRT;
dm.qryCRUD.ParamByName('REGISTROCNH').AsString := Self.RegistroCNH;
dm.qryCRUD.ParamByName('UFCNH').AsString := Self.UFCNH;
dm.qryCRUD.ParamByName('VALIDADE').AsDateTime := Self.ValidadeCNH;
dm.qryCRUD.ParamByName('CATEGORIA').AsString := Self.CategoriaCNH;
dm.qryCRUD.ParamByName('PRIMEIRACNH').AsDateTime := Self.PrimeiraCNH;
dm.qryCRUD.ParamByName('PIS').AsString := Self.PIS;
dm.qryCRUD.ParamByName('CTPS').AsString := Self.CTPS;
dm.qryCRUD.ParamByName('SERIECTPS').AsString := Self.SerieCTPS;
dm.qryCRUD.ParamByName('UFCTPS').AsString := Self.UFCTPS;
dm.qryCRUD.ParamByName('ESTADOCIVIL').AsString := Self.EstadoCivil;
dm.qryCRUD.ParamByName('TITULO').AsString := Self.TituloEleitor;
dm.qryCRUD.ParamByName('RESERVISTA').AsString := Self.Reservista;
dm.qryCRUD.ParamByName('FORMACREDITO').AsString := Self.FormaCredito;
dm.qryCRUD.ParamByName('TIPOCONTA').AsString := Self.TipoConta;
dm.qryCRUD.ParamByName('BANCO').AsString := Self.Banco;
dm.qryCRUD.ParamByName('AGENCIA').AsString := Self.Agencia;
dm.qryCRUD.ParamByName('CONTA').AsString := Self.Conta;
dm.qryCRUD.ParamByName('FAVORECIDO').AsString := Self.Favorecido;
dm.qryCRUD.ParamByName('CPFFAVORECIDO').AsString := Self.CPFFavorecido;
dm.qryCRUD.ParamByName('DATACADASTRO').AsDateTime := Self.DataCadastro;
dm.qryCRUD.ParamByName('USUARIO').AsInteger := Self.Usuario;
dm.qryCRUD.ParamByName('ROTEIRO').AsInteger := Self.Roteiro;
dm.qryCRUD.ParamByName('STATUSGR').AsInteger := Self.StatusGR;
dm.qryCRUD.ParamByName('STATUSCADASTRO').AsInteger := Self.StatusCadastro;
dm.ZConn.PingServer;
dm.qryCRUD.ExecSQL;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
Result := True;
except on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message);
end;
end;
function TCadastro.getField(sCampo: String; sColuna: String): String;
begin
try
Result := '';
if sCampo.IsEmpty then
begin
Exit;
end;
if sColuna.IsEmpty then
begin
Exit;
end;
if (not conexao.VerifyConnZEOS(0)) then begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
dm.qryFields.Close;
dm.qryFields.SQL.Clear;
dm.qryFields.SQL.Add('SELECT ' + sCampo + ' FROM ' + TABLENAME);
if sColuna = 'CADASTRO' then begin
dm.qryfields.SQL.Add(' WHERE COD_CADASTRO = :CODIGO');
dm.qryfields.ParamByName('CADASTRO').AsInteger := Self.Codigo;
end
else if sColuna = 'CNPJ' then begin
dm.qryfields.SQL.Add(' WHERE NUM_CNPJ = :CNPJ');
dm.qryfields.ParamByName('CNPJ').AsString := Self.CNPJ;
end
else if sColuna = 'CPF' then begin
dm.qryfields.SQL.Add(' WHERE NUM_CPF = :CPF');
dm.qryfields.ParamByName('CPF').AsString := Self.CPF;
end
else if sColuna = 'RG' then begin
dm.qryfields.SQL.Add(' WHERE NUM_RG = :RG');
dm.qryfields.ParamByName('RG').AsString := Self.RG;
end
else if sColuna = 'IE' then begin
dm.qryfields.SQL.Add(' WHERE NUM_IE = :IE');
dm.qryfields.ParamByName('IE').AsString := Self.RG;
end
else if sColuna = 'PIS' then begin
dm.qryfields.SQL.Add(' WHERE NUM_PIS = :PIS');
dm.qryfields.ParamByName('PIS').AsString := Self.PIS;
end
else if sColuna = 'CTPS' then begin
dm.qryfields.SQL.Add(' WHERE NUM_CTPS = :CTPS');
dm.qryfields.ParamByName('CTPS').AsString := Self.CTPS;
end
else if sColuna = 'CNH' then begin
dm.qryfields.SQL.Add(' WHERE NUM_REGISTRO_CNH = :CNH');
dm.qryfields.ParamByName('CNH').AsString := Self.RegistroCNH;
end;
dm.ZConn.PingServer;
dm.qryFields.Open;
if (not dm.qryFields.IsEmpty) then
begin
dm.qryFields.First;
Result := dm.qryFields.FieldByName(sCampo).AsString;
end;
dm.qryFields.Close;
dm.qryFields.SQL.Clear;
except on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message);
end;
end;
end.
|
unit MasterURLHandler;
interface
uses
Windows, Classes, Controls, GameTypes, Protocol, MapTypes, VoyagerInterfaces;
type
TSetWorldInfo =
record
MapImage : TMapImage;
BuildClasses : IBuildingClassBag;
end;
type
TTestMasterUrlHandler =
class(TInterfacedObject, IMetaURLHandler, IMasterURLHandler)
public
constructor Create;
destructor Destroy; override;
private // IMetaURLHandler
function getName : string;
function getOptions : TURLHandlerOptions;
function getCanHandleURL(URL : TURL) : THandlingAbility;
function Instantiate : IURLHandler;
private // IMasterURLHandler
function HandleURL(URL : TURL) : TURLHandlingResult;
function HandleEvent(EventId : TEventId; var info) : TEventHandlingResult;
function getControl : TControl;
procedure setMasterURLHandler(URLHandler : IMasterURLHandler);
function RegisterMetaHandler(aMetaURLHandler : IMetaURLHandler) : TMetaHandlerRegistrationResult;
procedure RegisterDefaultHandler(Handler : string);
procedure RegisterExclusion(Excluder, ToExclude : string; mutual : boolean);
procedure ReportNavigation( Handler : IURLHandler; URL : TURL; localBack, localForward : boolean );
function getURLIsLocal(URL : TURL) : boolean;
private // IClientView
procedure CreateCircuitSeg( CircuitId, OwnerId, x1, y1, x2, y2, cost : integer; out ErrorCode : TErrorCode );
procedure BreakCircuitAt( CircuitId, OwnerId, x, y : integer; out ErrorCode : TErrorCode );
procedure WipeCircuit( CircuitId, OwnerId, x1, y1, x2, y2 : integer; out ErrorCode : TErrorCode );
function SegmentsInArea( CircuitId, x, y, dx, dy : integer; out ErrorCode : TErrorCode ) : TSegmentReport;
procedure DisposeSegmentReport( var SegmentReport : TSegmentReport );
private
fRoadSegs : TSegmentReport;
fRailroadSegs : TSegmentReport;
end;
implementation
uses
SysUtils, Land, URLParser;
const
tidMetaHandlerName_TestServer = 'TestServer';
constructor TTestMasterUrlHandler.Create;
var
rawsegs : TStringList;
segment : string;
coord : string;
i : integer;
begin
inherited;
rawsegs := TStringList.Create;
try
//rawsegs.LoadFromFile(getWorldURL + '\roads.' + getWorldName + '.dat');
if rawsegs.count > 0
then
with fRoadSegs do
begin
getmem(Segments, rawsegs.Count*sizeof(Segments[0]));
SegmentCount := rawsegs.Count;
for i := 0 to pred(rawsegs.Count) do
begin
segment := rawsegs[i];
coord := copy(segment, 1, pred(Pos(' ', segment)));
delete(segment, 1, Pos(' ', segment));
Segments[i].x1 := StrToInt(coord);
coord := copy(segment, 1, pred(Pos(' ', segment)));
delete(segment, 1, Pos(' ', segment));
Segments[i].y1 := StrToInt(coord);
coord := copy(segment, 1, pred(Pos(' ', segment)));
delete(segment, 1, Pos(' ', segment));
Segments[i].x2 := StrToInt(coord);
coord := segment;
Segments[i].y2 := StrToInt(coord);
end;
end
else
begin
fRoadSegs.SegmentCount := 0;
fRoadSegs.Segments := nil
end;
fRailroadSegs.SegmentCount := 0;
fRailroadSegs.Segments := nil;
//segments.LoadFromFile(getWorldURL + '\railroads.' + getWorldName + '.dat');
finally
rawsegs.Free;
end;
end;
destructor TTestMasterUrlHandler.Destroy;
begin
assert(RefCount = 0);
DisposeSegmentReport(fRoadSegs);
DisposeSegmentReport(fRailroadSegs);
inherited;
end;
function TTestMasterUrlHandler.getName : string;
begin
Result := tidMetaHandlerName_TestServer;
end;
function TTestMasterUrlHandler.getOptions : TURLHandlerOptions;
begin
Result := [hopNonvisual];
end;
function TTestMasterUrlHandler.getCanHandleURL(URL : TURL) : THandlingAbility;
begin
Result := 0;
end;
function TTestMasterUrlHandler.Instantiate : IURLHandler;
begin
Result := IMasterUrlHandler(self);
end;
function TTestMasterUrlHandler.HandleURL(URL : TURL) : TURLHandlingResult;
begin
Result := urlNotHandled;
end;
function TTestMasterUrlHandler.HandleEvent(EventId : TEventId; var info) : TEventHandlingResult;
begin
Result := evnNotHandled;
end;
function TTestMasterUrlHandler.getControl : TControl;
begin
Result := nil;
end;
procedure TTestMasterUrlHandler.setMasterURLHandler(URLHandler : IMasterURLHandler);
begin
end;
function TTestMasterUrlHandler.RegisterMetaHandler(aMetaURLHandler : IMetaURLHandler) : TMetaHandlerRegistrationResult;
begin
Result := mhrRegistered;
end;
procedure TTestMasterUrlHandler.RegisterDefaultHandler(Handler : string);
begin
end;
procedure TTestMasterUrlHandler.RegisterExclusion(Excluder, ToExclude : string; mutual : boolean);
begin
end;
procedure TTestMasterUrlHandler.ReportNavigation( Handler : IURLHandler; URL : TURL; localBack, localForward : boolean );
begin
end;
function TTestMasterUrlHandler.getURLIsLocal(URL : TURL) : boolean;
begin
Result := URLParser.GetAnchorData( URL ).FrameId = '';
end;
procedure TTestMasterUrlHandler.CreateCircuitSeg(CircuitId, OwnerId, x1, y1, x2, y2, cost : integer; out ErrorCode : TErrorCode);
var
RawSegments : TSegmentReport;
FileName : string;
begin
ErrorCode := NOERROR;
case CircuitId of
cirRoads:
begin
RawSegments := fRoadSegs;
FileName := '\roads.dat';
end;
cirRailroads:
begin
RawSegments := fRailroadSegs;
FileName := '\railroads.dat';
end;
end;
if (CircuitId = cirRoads) or (CircuitId = cirRailroads)
then
with RawSegments do
begin
reallocmem(Segments, (SegmentCount + 1)*sizeof(Segments[0]));
Segments[SegmentCount].x1 := x1;
Segments[SegmentCount].y1 := y1;
Segments[SegmentCount].x2 := x2;
Segments[SegmentCount].y2 := y2;
inc(SegmentCount);
end;
case CircuitId of
cirRoads:
fRoadSegs := RawSegments;
cirRailroads:
fRailroadSegs := RawSegments;
end;
//RawSegments.SaveToFile(getWorldURL + FileName);
end;
procedure TTestMasterUrlHandler.BreakCircuitAt(CircuitId, OwnerId, x, y : integer; out ErrorCode : TErrorCode);
begin
ErrorCode := NOERROR;
end;
procedure TTestMasterUrlHandler.WipeCircuit(CircuitId, OwnerId, x1, y1, x2, y2 : integer; out ErrorCode : TErrorCode);
begin
ErrorCode := NOERROR;
end;
function TTestMasterUrlHandler.SegmentsInArea(CircuitId, x, y, dx, dy : integer; out ErrorCode : TErrorCode) : TSegmentReport;
var
SegmentReport : TSegmentReport;
i : integer;
x1, y1 : integer;
x2, y2 : integer;
tmp : integer;
DesiredSegs : TSegmentReport;
begin
ErrorCode := NOERROR;
case CircuitId of
cirRoads:
DesiredSegs := fRoadSegs;
cirRailroads:
DesiredSegs := fRailroadSegs
else DesiredSegs.Segments := nil;
end;
if (DesiredSegs.Segments <> nil) and (DesiredSegs.SegmentCount <> 0)
then
with SegmentReport do
begin
getmem(Segments, DesiredSegs.SegmentCount*sizeof(Segments[0]));
SegmentCount := 0;
for i := 0 to pred(DesiredSegs.SegmentCount) do
begin
x1 := DesiredSegs.Segments[i].x1;
y1 := DesiredSegs.Segments[i].y1;
x2 := DesiredSegs.Segments[i].x2;
y2 := DesiredSegs.Segments[i].y2;
if x1 > x2
then
begin
tmp := x1;
x1 := x2;
x2 := tmp
end;
if y1 > y2
then
begin
tmp := y1;
y1 := y2;
y2 := tmp
end;
if (x1 < x + dx) and (x2 >= x) and (y1 < y + dx) and (y2 >= y)
then
begin
Segments[SegmentCount].x1 := x1;
Segments[SegmentCount].y1 := y1;
Segments[SegmentCount].x2 := x2;
Segments[SegmentCount].y2 := y2;
inc(SegmentCount);
end;
end;
reallocmem(Segments, SegmentCount*sizeof(Segments[0]))
end
else
begin
SegmentReport.SegmentCount := 0;
SegmentReport.Segments := nil
end;
Result := SegmentReport
end;
procedure TTestMasterUrlHandler.DisposeSegmentReport( var SegmentReport : TSegmentReport );
begin
with SegmentReport do
begin
Freemem(Segments);
SegmentCount := 0;
Segments := nil;
end;
end;
end.
|
unit VCLForm1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Script.Interfaces
;
type
TForm1 = class(TForm, IscriptCompileLog, IscriptRunLog)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Edit1: TEdit;
CompileLog: TMemo;
RunLog: TMemo;
Run: TButton;
procedure Button1Click(Sender: TObject);
procedure RunClick(Sender: TObject);
private
{ Private declarations }
procedure IscriptCompileLog_Log(const aString: String);
procedure IscriptCompileLog.Log = IscriptCompileLog_Log;
procedure IscriptRunLog_Log(const aString: String);
procedure IscriptRunLog.Log = IscriptRunLog_Log;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
Testing.Engine,
Script.Engine
;
{$R *.dfm}
procedure TForm1.IscriptCompileLog_Log(const aString: String);
begin
CompileLog.Lines.Add(aString);
{$IfNDef NoTesting}
TtestEngine.CurrentTest.SocketMetric(TtestSocket.Create(Self, 'IscriptCompileLog_Log')).PutValue(aString);
{$EndIf NoTesting}
end;
procedure TForm1.IscriptRunLog_Log(const aString: String);
begin
RunLog.Lines.Add(aString);
{$IfNDef NoTesting}
TtestEngine.CurrentTest.SocketMetric(TtestSocket.Create(Self, 'IscriptRunLog_Log')).PutValue(aString);
{$EndIf NoTesting}
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Edit1.Text := (Sender As TButton).Caption + ' clicked';
end;
procedure TForm1.RunClick(Sender: TObject);
const
l_FileName = 'FirstScript.script';
begin
CompileLog.Lines.Clear;
RunLog.Lines.Clear;
{$IfNDef NoTesting}
TtestEngine.StartTest(l_FileName);
try
{$EndIf NoTesting}
TScriptEngine.RunScript(l_FileName, Self, Self);
{$IfNDef NoTesting}
finally
TtestEngine.StopTest;
end;//try..finally
{$EndIf NoTesting}
end;
end.
|
unit G2Mobile.Model.NovoPedidoItem;
interface
uses
FMX.Grid,
FMX.ListView,
System.Classes,
Datasnap.DBClient,
FireDAC.Comp.Client,
FMX.Objects,
FMX.Graphics,
System.UITypes, G2Mobile.Controller.Pedidos;
const
CONST_POPULAPRODSQLSTRINGGRID =
' SELECT vi.cod_prod, vi.valor, vi.desconto, case when vi.unidade = 0 then ''UND'' else ''PESO'' end as unidade, '+
' pd.desc_ind as nomeproduto, vi.quantidade as qtd_ped, ia.qtd_tot, ia.pes_tot, ia.vlr_tot, VI.TOTAL '+
' FROM VENDITEM vi left outer join venda v on (vi.chave = v.chave) left outer join produto pd on (pd.cod_prod = vi.cod_prod) '+
' left outer join ITENS_ATUALIZADO ia on (ia.cod_prod = vi.cod_prod and vi.chave = ia.chave) WHERE vi.chave = :chave ';
CONST_CALCPRODUTO = ' SELECT CASE WHEN VALOR_PROD < :EDTVALORITEM THEN 0 ELSE (VALOR_PROD - :EDTVALORITEM) * ' +
' CASE ' + ' WHEN TIPO_CALC = 0 THEN CASE WHEN PESO_PADRAO = 0 THEN 1 ELSE PESO_PADRAO END ' +
' WHEN TIPO_CALC = 1 THEN CASE WHEN QUANT_CX = 0 THEN 1 ELSE QUANT_CX END ' + ' END * :QUANTIDADE END AS DESCONTO, '
+ ' :QUANTIDADE * :EDTVALORITEM * ' + ' CASE ' +
' WHEN TIPO_CALC = 0 THEN CASE WHEN PESO_PADRAO = 0 THEN 1 ELSE PESO_PADRAO END ' +
' WHEN TIPO_CALC = 1 THEN CASE WHEN QUANT_CX = 0 THEN 1 ELSE QUANT_CX END ' + ' END AS VALORPROD ' +
' FROM PRODUTO WHERE COD_PROD = :CODPROD ';
CONST_VALIDAVALORMINIMO = ' SELECT ' +
' CASE WHEN VALOR_MIN > :EDTVALORITEM AND (SELECT BLOQ_VLR_MIN FROM PARAMETROS) = 1 THEN 0 /*BLOQUEIA DIRETO*/ ' +
' WHEN VALOR_MIN > :EDTVALORITEM AND (SELECT BLOQ_VLR_MIN FROM PARAMETROS) = 0 THEN 1 /*PERGUNTA REALMENTE QUER INCLUIR*/ '
+ ' ELSE 2 /*ok*/ END AS SITUACAO FROM PRODUTO WHERE COD_PROD = :CODPROD; ';
CONST_INSERTITENS = ' INSERT INTO venditem (chave,cod_prod,quantidade, valor,desconto,total,unidade,pcBruto) VALUES '
+ ' (:chave, :cod_prod, :quantidade, :valor, :desconto, :total, :unidade, :pcBruto) ';
CONST_EDITARPOPULARITEM =
' SELECT vi.cod_prod, vi.quantidade, vi.valor, vi.desconto, case when vi.unidade = 0 then ''UND'' else ''PESO'' end as unidade, '
+ ' Vi.TOTAL , pd.desc_ind , vi.pcBruto FROM VENDITEM vi left outer join venda v on (vi.chave = v.chave) ' +
' left outer join produto pd on (pd.cod_prod = vi.cod_prod) where vi.chave = :chave ';
CONST_DELETEITENS = ' DELETE FROM VENDITEM WHERE CHAVE = :CHAVE ';
type
TModelNovoPedidoItem = class(TInterfacedObject, iModelNovoPedidoItem)
private
FQry: TFDQuery;
FCodProd: Integer;
FNomeProd: String;
FQnt: Integer;
FVlrUnit: Double;
FTotBruto: Double;
FVlrDesconto: Double;
FVlrLiquido: Double;
FUnd: Integer;
FChave: String;
public
constructor create;
destructor destroy; override;
class function new: iModelNovoPedidoItem;
function chave(value: String): iModelNovoPedidoItem;
function cod_Prod(value: Integer): iModelNovoPedidoItem;
function NomeProd(value: String): iModelNovoPedidoItem;
function Und(value: Integer): iModelNovoPedidoItem;
function Qnt(value: Integer): iModelNovoPedidoItem;
function VlrUnit(value: Double): iModelNovoPedidoItem;
function TotBruto(value: Double): iModelNovoPedidoItem;
function VlrDesconto(value: Double): iModelNovoPedidoItem;
function VlrLiquido(value: Double): iModelNovoPedidoItem;
Function PopulaProdInfoStringGrid(chave: String; Grid: TStringGrid): iModelNovoPedidoItem;
Function InsertItens(Grid: TStringGrid): iModelNovoPedidoItem;
function CalcProduto(AList: TStringList): iModelNovoPedidoItem;
function ValidaPrecoMinino: Integer;
function AddProdlistPedido(Grid: TStringGrid): iModelNovoPedidoItem;
function VerificaItemIncluidos(Grid: TStringGrid): Integer;
function SomaStringGrid(AList: TStringList; Grid: TStringGrid): iModelNovoPedidoItem;
function EditaRecplicarItem(Grid: TStringGrid): iModelNovoPedidoItem;
function DeleteItems: iModelNovoPedidoItem;
end;
implementation
{ TModelNovoPedidoItem }
uses
uDmDados,
System.SysUtils,
uFrmUtilFormate,
Form_Mensagem;
class function TModelNovoPedidoItem.new: iModelNovoPedidoItem;
begin
Result := Self.create;
end;
constructor TModelNovoPedidoItem.create;
begin
FQry := TFDQuery.create(nil);
FQry.Connection := DmDados.ConexaoInterna;
FQry.FetchOptions.RowsetSize := 50000;
FQry.Active := false;
FQry.SQL.Clear;
end;
destructor TModelNovoPedidoItem.destroy;
begin
FreeandNil(FQry);
inherited;
end;
function TModelNovoPedidoItem.chave(value: String): iModelNovoPedidoItem;
begin
Result := Self;
FChave := value;
end;
function TModelNovoPedidoItem.cod_Prod(value: Integer): iModelNovoPedidoItem;
begin
Result := Self;
FCodProd := value;
end;
function TModelNovoPedidoItem.NomeProd(value: String): iModelNovoPedidoItem;
begin
Result := Self;
FNomeProd := value;
end;
function TModelNovoPedidoItem.Qnt(value: Integer): iModelNovoPedidoItem;
begin
Result := Self;
FQnt := value;
end;
function TModelNovoPedidoItem.TotBruto(value: Double): iModelNovoPedidoItem;
begin
Result := Self;
FTotBruto := value;
end;
function TModelNovoPedidoItem.Und(value: Integer): iModelNovoPedidoItem;
begin
Result := Self;
FUnd := value;
end;
function TModelNovoPedidoItem.VlrDesconto(value: Double): iModelNovoPedidoItem;
begin
Result := Self;
FVlrDesconto := value;
end;
function TModelNovoPedidoItem.VlrLiquido(value: Double): iModelNovoPedidoItem;
begin
Result := Self;
FVlrLiquido := value;
end;
function TModelNovoPedidoItem.VlrUnit(value: Double): iModelNovoPedidoItem;
begin
Result := Self;
FVlrUnit := value;
end;
function TModelNovoPedidoItem.PopulaProdInfoStringGrid(chave: String; Grid: TStringGrid): iModelNovoPedidoItem;
var
I: Integer;
begin
Result := Self;
FQry.SQL.Text := CONST_POPULAPRODSQLSTRINGGRID;
FQry.ParamByName('CHAVE').AsString := chave;
FQry.Open;
for I := 0 to FQry.RecordCount - 1 do
begin
with Grid do
begin
RowCount := RowCount + 1;
Row := RowCount - 1;
Cells[0, Row] := FQry.FieldByName('cod_prod').AsString;
Cells[1, Row] := FQry.FieldByName('nomeproduto').AsString;
Cells[2, Row] := FQry.FieldByName('unidade').AsString;
Cells[3, Row] := FormatFloat('0000',FQry.FieldByName('qtd_ped').AsFloat);
Cells[4, Row] := FormatFloat('0000',FQry.FieldByName('qtd_tot').AsFloat);
Cells[5, Row] := FormatFloat('#,##0.000',FQry.FieldByName('pes_tot').AsFloat);
Cells[6, Row] := FormatFloat('#,##0.00',FQry.FieldByName('valor').AsFloat);
Cells[7, Row] := FormatFloat('#,##0.00',FQry.FieldByName('desconto').AsFloat);
Cells[8, Row] := FormatFloat('#,##0.00',FQry.FieldByName('total').AsFloat);
Cells[9, Row] := FormatFloat('#,##0.00', FQry.FieldByName('vlr_tot').AsFloat);
end;
FQry.Next;
end;
end;
function TModelNovoPedidoItem.DeleteItems: iModelNovoPedidoItem;
begin
Result := Self;
FQry.SQL.Text := CONST_DELETEITENS;
FQry.ParamByName('CHAVE').AsString := FChave;
FQry.ExecSQL;
end;
function TModelNovoPedidoItem.EditaRecplicarItem(Grid: TStringGrid): iModelNovoPedidoItem;
var
I: Integer;
begin
Result := Self;
FQry.SQL.Text := CONST_EDITARPOPULARITEM;
FQry.ParamByName('CHAVE').AsString := FChave;
FQry.Open;
for I := 0 to FQry.RecordCount - 1 do
begin
with Grid do
begin
RowCount := RowCount + 1;
Row := RowCount - 1;
Cells[0, Row] := FQry.FieldByName('cod_prod').AsString;
Cells[1, Row] := FQry.FieldByName('desc_ind').AsString;
Cells[2, Row] := FQry.FieldByName('unidade').AsString;
Cells[3, Row] := formatfloat('0000', FQry.FieldByName('quantidade').AsFloat);
Cells[4, Row] := formatfloat('#,##0.00', FQry.FieldByName('valor').AsFloat);
Cells[5, Row] := formatfloat('#,##0.00', FQry.FieldByName('pcbruto').AsFloat);
Cells[6, Row] := formatfloat('#,##0.00', FQry.FieldByName('desconto').AsFloat);
Cells[7, Row] := formatfloat('#,##0.00', FQry.FieldByName('total').AsFloat);
end;
FQry.Next;
end;
end;
function TModelNovoPedidoItem.CalcProduto(AList: TStringList): iModelNovoPedidoItem;
var
I: Integer;
begin
Result := Self;
FQry.SQL.Text := CONST_CALCPRODUTO;
FQry.ParamByName('CODPROD').AsInteger := FCodProd;
FQry.ParamByName('QUANTIDADE').AsInteger := FQnt;
FQry.ParamByName('EDTVALORITEM').AsFloat := FVlrUnit;
FQry.Open;
for I := 0 to FQry.FieldCount - 1 do
begin
AList.Add(FQry.Fields[I].AsString);
FQry.Next;
end;
end;
function TModelNovoPedidoItem.ValidaPrecoMinino: Integer;
begin
FQry.SQL.Text := CONST_VALIDAVALORMINIMO;
FQry.ParamByName('CODPROD').AsInteger := FCodProd;
FQry.ParamByName('EDTVALORITEM').AsFloat := FVlrUnit;
FQry.Open;
Result := FQry.FieldByName('SITUACAO').AsInteger;
end;
function TModelNovoPedidoItem.VerificaItemIncluidos(Grid: TStringGrid): Integer;
var
I: Integer;
begin
with Grid do
begin
for I := 0 to Grid.RowCount - 1 do
begin
if Cells[0, Row] = FCodProd.ToString then
Result := 1;
end;
end;
end;
function TModelNovoPedidoItem.AddProdlistPedido(Grid: TStringGrid): iModelNovoPedidoItem;
var
I: Integer;
begin
Result := Self;
with Grid do
begin
RowCount := RowCount + 1;
Row := RowCount - 1;
Cells[0, Row] := FCodProd.ToString;
Cells[1, Row] := FNomeProd;
case FUnd of
0:
Cells[2, Row] := 'UND';
1:
Cells[2, Row] := 'PESO';
end;
Cells[3, Row] := formatfloat('0000', FQnt.ToDouble);
Cells[4, Row] := formatfloat('#,##0.00', FVlrUnit);
Cells[5, Row] := formatfloat('#,##0.00', FVlrLiquido + FVlrDesconto);
Cells[6, Row] := formatfloat('#,##0.00', FVlrDesconto);
Cells[7, Row] := formatfloat('#,##0.00', FVlrLiquido);
end;
end;
function TModelNovoPedidoItem.SomaStringGrid(AList: TStringList; Grid: TStringGrid): iModelNovoPedidoItem;
var
I: Integer;
VlrBruto, VlrDesc, VlrLiq: Double;
begin
VlrBruto := 0;
VlrDesc := 0;
VlrLiq := 0;
for I := 0 to Grid.RowCount - 1 do
begin
VlrBruto := VlrBruto + StrParaDouble(Grid.Cells[5, I]);
VlrDesc := VlrDesc + StrParaDouble(Grid.Cells[6, I]);
VlrLiq := VlrLiq + StrParaDouble(Grid.Cells[7, I]);
end;
AList.Add(formatfloat('#,##0.00', VlrBruto));
AList.Add(formatfloat('#,##0.00', VlrDesc));
AList.Add(formatfloat('#,##0.00', VlrLiq));
end;
function TModelNovoPedidoItem.InsertItens(Grid: TStringGrid): iModelNovoPedidoItem;
var
I: Integer;
begin
Result := Self;
for I := 0 to Grid.RowCount - 1 do
begin
FQry.SQL.Text := CONST_INSERTITENS;
FQry.ParamByName('chave').AsString := FChave;
FQry.ParamByName('cod_prod').AsString := Grid.Cells[0, I];
FQry.ParamByName('quantidade').AsString := Grid.Cells[3, I];
FQry.ParamByName('valor').AsFloat := StrParaDouble(Grid.Cells[4, I]);
FQry.ParamByName('desconto').AsFloat := StrParaDouble(Grid.Cells[6, I]);
FQry.ParamByName('total').AsFloat := StrParaDouble(Grid.Cells[7, I]);
if Grid.Cells[2, I].Equals('UND') then
begin
FQry.ParamByName('unidade').AsInteger := 0;
end
else
FQry.ParamByName('unidade').AsInteger := 1;
FQry.ParamByName('pcBruto').AsFloat := StrParaDouble(Grid.Cells[5, I]);
FQry.ExecSQL;
end;
end;
END.
|
unit caDataProviderParams;
// Модуль: "w:\common\components\rtl\Garant\ComboAccess\caDataProviderParams.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TcaDataProviderParams" MUID: (56A86B450218)
{$Include w:\common\components\rtl\Garant\ComboAccess\caDefine.inc}
interface
{$If Defined(UsePostgres) AND Defined(TestComboAccess)}
uses
l3IntfUses
, htDataProviderParams
, pgDataProviderParams
, k2Base
, daDataProviderParams
;
type
TcaDataProviderParams = class(ThtDataProviderParams)
private
f_HTParams: ThtDataProviderParams;
f_PGParams: TpgDataProviderParams;
protected
function pm_GetDataServerHostName: AnsiString;
procedure pm_SetDataServerHostName(const aValue: AnsiString);
function pm_GetDataServerPort: Integer;
procedure pm_SetDataServerPort(aValue: Integer);
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aHTParams: ThtDataProviderParams;
aPGParams: TpgDataProviderParams); reintroduce;
procedure LoadFromAlienParams;
procedure SaveToAlienParams;
procedure ChangeBasePath(const aPath: AnsiString); override;
procedure AssignParams(aParams: TdaDataProviderParams); override;
class function GetTaggedDataType: Tk2Type; override;
public
property HTParams: ThtDataProviderParams
read f_HTParams;
property PGParams: TpgDataProviderParams
read f_PGParams;
property DataServerHostName: AnsiString
read pm_GetDataServerHostName
write pm_SetDataServerHostName;
property DataServerPort: Integer
read pm_GetDataServerPort
write pm_SetDataServerPort;
end;//TcaDataProviderParams
{$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess)
implementation
{$If Defined(UsePostgres) AND Defined(TestComboAccess)}
uses
l3ImplUses
, SysUtils
, ComboAccessProviderParams_Const
//#UC START# *56A86B450218impl_uses*
//#UC END# *56A86B450218impl_uses*
;
function TcaDataProviderParams.pm_GetDataServerHostName: AnsiString;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.StrA[k2_attrDataServerHostName]);
end;//TcaDataProviderParams.pm_GetDataServerHostName
procedure TcaDataProviderParams.pm_SetDataServerHostName(const aValue: AnsiString);
begin
TaggedData.StrW[k2_attrDataServerHostName, nil] := (aValue);
end;//TcaDataProviderParams.pm_SetDataServerHostName
function TcaDataProviderParams.pm_GetDataServerPort: Integer;
begin
Assert(Self <> nil);
Assert(TaggedData <> nil);
Result := (TaggedData.IntA[k2_attrDataServerPort]);
end;//TcaDataProviderParams.pm_GetDataServerPort
procedure TcaDataProviderParams.pm_SetDataServerPort(aValue: Integer);
begin
TaggedData.IntW[k2_attrDataServerPort, nil] := (aValue);
end;//TcaDataProviderParams.pm_SetDataServerPort
constructor TcaDataProviderParams.Create(aHTParams: ThtDataProviderParams;
aPGParams: TpgDataProviderParams);
//#UC START# *56B9C44F02BE_56A86B450218_var*
//#UC END# *56B9C44F02BE_56A86B450218_var*
begin
//#UC START# *56B9C44F02BE_56A86B450218_impl*
inherited Create;
aHTParams.SetRefTo(f_HTParams);
aPGParams.SetRefTo(f_PGParams);
//#UC END# *56B9C44F02BE_56A86B450218_impl*
end;//TcaDataProviderParams.Create
procedure TcaDataProviderParams.LoadFromAlienParams;
//#UC START# *56B9D5D8017F_56A86B450218_var*
//#UC END# *56B9D5D8017F_56A86B450218_var*
begin
//#UC START# *56B9D5D8017F_56A86B450218_impl*
Login := f_HTParams.Login;
Password := f_HTParams.Password;
DocStoragePath := f_HTParams.DocStoragePath;
DocImagePath := f_HTParams.DocImagePath;
HomeDirPath := f_HTParams.HomeDirPath;
DocBaseVersion := f_HTParams.DocBaseVersion;
AdminBaseVersion := f_HTParams.AdminBaseVersion;
UserID := f_HTParams.UserID;
StationName := f_HTParams.StationName;
TablePath := f_HTParams.TablePath;
LockPath := f_HTParams.LockPath;
TmpDirPath := f_HTParams.TmpDirPath;
DataServerHostName := f_PGParams.DataServerHostName;
DataServerPort := f_PGParams.DataServerPort;
//#UC END# *56B9D5D8017F_56A86B450218_impl*
end;//TcaDataProviderParams.LoadFromAlienParams
procedure TcaDataProviderParams.SaveToAlienParams;
//#UC START# *56B9E3810358_56A86B450218_var*
procedure lp_SaveCommon(const aTarget: TdaDataProviderParams);
begin
aTarget.Login := Login;
aTarget.Password := Password;
aTarget.DocStoragePath := DocStoragePath;
aTarget.DocImagePath := DocImagePath;
aTarget.HomeDirPath := HomeDirPath;
aTarget.DocBaseVersion := DocBaseVersion;
aTarget.AdminBaseVersion := AdminBaseVersion;
aTarget.UserID := UserID;
end;
//#UC END# *56B9E3810358_56A86B450218_var*
begin
//#UC START# *56B9E3810358_56A86B450218_impl*
lp_SaveCommon(f_HTParams);
lp_SaveCommon(f_PGParams);
f_HTParams.StationName := StationName;
f_HTParams.TablePath := TablePath;
f_HTParams.LockPath := LockPath;
f_HTParams.TmpDirPath := TmpDirPath;
f_PGParams.DataServerHostName := DataServerHostName;
f_PGParams.DataServerPort := DataServerPort;
//#UC END# *56B9E3810358_56A86B450218_impl*
end;//TcaDataProviderParams.SaveToAlienParams
procedure TcaDataProviderParams.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_56A86B450218_var*
//#UC END# *479731C50290_56A86B450218_var*
begin
//#UC START# *479731C50290_56A86B450218_impl*
FreeAndNil(f_HTParams);
FreeAndNil(f_PGParams);
inherited;
//#UC END# *479731C50290_56A86B450218_impl*
end;//TcaDataProviderParams.Cleanup
procedure TcaDataProviderParams.ChangeBasePath(const aPath: AnsiString);
//#UC START# *55195AE803E0_56A86B450218_var*
//#UC END# *55195AE803E0_56A86B450218_var*
begin
//#UC START# *55195AE803E0_56A86B450218_impl*
SaveToAlienParams;
inherited;
HTParams.ChangeBasePath(aPath);
PGParams.ChangeBasePath(aPath);
LoadFromAlienParams;
//#UC END# *55195AE803E0_56A86B450218_impl*
end;//TcaDataProviderParams.ChangeBasePath
procedure TcaDataProviderParams.AssignParams(aParams: TdaDataProviderParams);
//#UC START# *553A37E902C9_56A86B450218_var*
//#UC END# *553A37E902C9_56A86B450218_var*
begin
//#UC START# *553A37E902C9_56A86B450218_impl*
inherited;
if aParams is TcaDataProviderParams then
begin
SaveToAlienParams;
HTParams.AssignParams(TcaDataProviderParams(aParams).HTParams);
PGParams.AssignParams(TcaDataProviderParams(aParams).PGParams);
LoadFromAlienParams;
end;
//#UC END# *553A37E902C9_56A86B450218_impl*
end;//TcaDataProviderParams.AssignParams
class function TcaDataProviderParams.GetTaggedDataType: Tk2Type;
begin
Result := k2_typComboAccessProviderParams;
end;//TcaDataProviderParams.GetTaggedDataType
{$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess)
end.
|
unit kwPopEditorSetShowDocumentParts;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "ScriptEngine"
// Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorSetShowDocumentParts.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_SetShowDocumentParts
//
// *Формат:* aValue anEditorControl pop:editor:SetShowDocumentParts
// *Описание:* Устанавливает свойство ShowDocumentParts (отображать структуру документа). Значение
// aValue булевского типа.
// *Пример:*
// {code}
// true focused:control:push pop:editor:SetShowDocumentParts
// {code}
// *Результат:* В редакторе будет отображаться структура документа.
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\ScriptEngine\seDefine.inc}
interface
{$If not defined(NoScripts)}
uses
evCustomEditorWindow,
tfwScriptingInterfaces,
Controls,
Classes
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type
{$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas}
TkwPopEditorSetShowDocumentParts = {final} class(_kwEditorFromStackWord_)
{* *Формат:* aValue anEditorControl pop:editor:SetShowDocumentParts
*Описание:* Устанавливает свойство ShowDocumentParts (отображать структуру документа). Значение aValue булевского типа.
*Пример:*
[code]
true focused:control:push pop:editor:SetShowDocumentParts
[code]
*Результат:* В редакторе будет отображаться структура документа. }
protected
// realized methods
procedure DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow); override;
public
// overridden public methods
class function GetWordNameForRegister: AnsiString; override;
end;//TkwPopEditorSetShowDocumentParts
{$IfEnd} //not NoScripts
implementation
{$If not defined(NoScripts)}
uses
tfwAutoregisteredDiction,
tfwScriptEngine,
Windows,
afwFacade,
Forms
;
{$IfEnd} //not NoScripts
{$If not defined(NoScripts)}
type _Instance_R_ = TkwPopEditorSetShowDocumentParts;
{$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas}
// start class TkwPopEditorSetShowDocumentParts
procedure TkwPopEditorSetShowDocumentParts.DoWithEditor(const aCtx: TtfwContext;
anEditor: TevCustomEditorWindow);
//#UC START# *4F4CB81200CA_4F4CB59F0116_var*
//#UC END# *4F4CB81200CA_4F4CB59F0116_var*
begin
//#UC START# *4F4CB81200CA_4F4CB59F0116_impl*
if aCtx.rEngine.IsTopBool then
anEditor.ShowDocumentParts := aCtx.rEngine.PopBool
else
Assert(False, 'Не задано значение для anEditor.ShowDocumentParts');
//#UC END# *4F4CB81200CA_4F4CB59F0116_impl*
end;//TkwPopEditorSetShowDocumentParts.DoWithEditor
class function TkwPopEditorSetShowDocumentParts.GetWordNameForRegister: AnsiString;
{-}
begin
Result := 'pop:editor:SetShowDocumentParts';
end;//TkwPopEditorSetShowDocumentParts.GetWordNameForRegister
{$IfEnd} //not NoScripts
initialization
{$If not defined(NoScripts)}
{$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas}
{$IfEnd} //not NoScripts
end. |
unit ActionHandler.Scripts;
interface
uses
ActionHandler, SysUtils, Classes, Import_COMMON, IMP_GsDocument, PaxCompiler, PaxRunner, PaxProgram;
const
PARAM_FILENAME = 'filename';
type
TScriptActionHandler = class(TAbstractActionHandler)
private
FPC: TPaxCompiler;
FPaxProgram: TPaxProgram;
FPaxPascalLanguage: TPaxPascalLanguage;
protected
procedure PrepareParams(ActionName: string; ActionKind: TActionHandlerKind); override;
public
constructor Create(AOwner: TActionHandlerManager); override;
procedure ExecuteAction(UserData: Pointer = nil); override;
destructor Destroy; override;
end;
implementation
{ TScriptActionHandler }
constructor TScriptActionHandler.Create(AOwner: TActionHandlerManager);
begin
inherited Create(AOwner);
FPC := TPaxCompiler.Create(nil);
FPaxProgram := TPaxProgram.Create(nil);
FPaxPascalLanguage := TPaxPascalLanguage.Create(nil);
end;
destructor TScriptActionHandler.Destroy;
begin
FPaxPascalLanguage.Free;
FPaxProgram.Free;
FPC.Free;
inherited;
end;
procedure TScriptActionHandler.ExecuteAction;
var
FScript: string;
FStream: TStringStream;
begin
FScript := EmptyStr;
if Param[PARAM_FILENAME] = EmptyStr then
Exit;
FStream := TStringStream.Create;
try
FStream.LoadFromFile(Param[PARAM_FILENAME]);
FScript := FStream.DataString;
finally
FStream.Free;
end;
if FScript <> EmptyStr then
begin
FPC.Reset;
FPC.ResetCompilation;
FPC.RegisterLanguage(FPaxPascalLanguage);
FPC.AddModule('main', FPaxPascalLanguage.LanguageName);
FPC.AddCode('main', FScript);
if FPC.Compile(FPaxProgram) then
FPaxProgram.Run;
end;
end;
procedure TScriptActionHandler.PrepareParams(ActionName: string; ActionKind: TActionHandlerKind);
begin
if ActionKind = hkScript then
Param[PARAM_FILENAME] := ActionName;
end;
end.
|
unit TestBed;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
FileCtrl, StrUtils,
KM_Game, KM_CommonTypes, ExtAIDelphi, ExtAILog, KM_Consts, ExtAIInfo,
// Detection of IP address
Winsock, Vcl.ComCtrls;
// @Krom: This is my test bed, please ignore this project (WebSocketTest). The main project is called Game.
type
TExtAIAndGUI = record
ID: Word;
AI: TExtAIDelphi;
Log: TExtAILog;
tsTab: TTabSheet;
mLog: TMemo;
end;
TExtAIAndGUIArr = record
Count: Word; // Count of elements in Arr
ID: Word; // ID of ExtAI (imagine if we start game with 3 AIs and we lose connection with AI 2)
Arr: array of TExtAIAndGUI;
end;
TExtAI_TestBed = class(TForm)
btnAddPath: TButton;
btnAutoFill: TButton;
btnClientConnect: TButton;
btnClientSendAction: TButton;
btnClientSendState: TButton;
btnCreateExtAI: TButton;
btnRemove: TButton;
btnSendEvent: TButton;
btnSendState: TButton;
btnServerStartMap: TButton;
btnStartServer: TButton;
btnTerminateAI: TButton;
btnTerminateExtAIs: TButton;
cbLoc00: TComboBox;
cbLoc01: TComboBox;
cbLoc02: TComboBox;
cbLoc03: TComboBox;
cbLoc04: TComboBox;
cbLoc05: TComboBox;
cbLoc06: TComboBox;
cbLoc07: TComboBox;
cbLoc08: TComboBox;
cbLoc09: TComboBox;
cbLoc10: TComboBox;
cbLoc11: TComboBox;
chbControlAll: TCheckBox;
edPingLoc00: TEdit;
edPingLoc01: TEdit;
edPingLoc02: TEdit;
edPingLoc03: TEdit;
edPingLoc04: TEdit;
edPingLoc05: TEdit;
edPingLoc06: TEdit;
edPingLoc07: TEdit;
edPingLoc08: TEdit;
edPingLoc09: TEdit;
edPingLoc10: TEdit;
edPingLoc11: TEdit;
edServerPort: TEdit;
gbAIControlInterface: TGroupBox;
gbDLLs: TGroupBox;
gbExtAIsDLL: TGroupBox;
gbExtAIsExe: TGroupBox;
gbKP: TGroupBox;
gbLobby: TGroupBox;
gbServer: TGroupBox;
gbSimulation: TGroupBox;
labLoc00: TLabel;
labLoc01: TLabel;
labLoc02: TLabel;
labLoc03: TLabel;
labLoc04: TLabel;
labLoc05: TLabel;
labLoc06: TLabel;
labLoc07: TLabel;
labLoc08: TLabel;
labLoc09: TLabel;
labLoc10: TLabel;
labLoc11: TLabel;
labPortNumber: TLabel;
lbDLLs: TListBox;
lbPaths: TListBox;
mTutorial: TMemo;
pcLogExtAIExe: TPageControl;
prgServer: TProgressBar;
reLog: TRichEdit;
reLogDLL: TRichEdit;
stDLLs: TStaticText;
stExtAIName: TStaticText;
stPathsDLL: TStaticText;
stPing: TStaticText;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnAddPathClick(Sender: TObject);
procedure btnStartServerClick(Sender: TObject);
procedure btnClientConnectClick(Sender: TObject);
procedure btnClientSendActionClick(Sender: TObject);
procedure btnServerSendEventClick(Sender: TObject);
procedure btnClientSendStateClick(Sender: TObject);
procedure btnServerStartMapClick(Sender: TObject);
procedure btnCreateExtAIClick(Sender: TObject);
procedure btnTerminateExtAIClick(Sender: TObject);
procedure btnTerminateExtAIsClick(Sender: TObject);
procedure pcOnChangeTab(Sender: TObject);
procedure chbControlAllClick(Sender: TObject);
procedure btnAutoFillClick(Sender: TObject);
procedure cbOnChange(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
private
fGame: TKMGame;
fExtAIAndGUIArr: TExtAIAndGUIArr;
fcbLoc: array[0..MAX_HANDS_COUNT-1] of TComboBox;
fedPingLoc: array[0..MAX_HANDS_COUNT-1] of TEdit;
procedure RefreshDLLs();
procedure RefreshComboBoxes(aServerClient: TExtAIInfo = nil);
procedure ConnectClient(aIdx: Word);
procedure DisconnectClient(aIdx: Integer);
procedure UpdateAIGUI();
procedure RefreshAIGUI(Sender: TObject);
function GetIdxByID(var aIdx: Integer; aID: Byte): boolean;
function GetSelectedClient(var aIdx: Integer): boolean;
procedure UpdateSimStatus(const aLogDLL: String = '');
public
procedure Log(const aText: String);
procedure LogID(const aText: String; const aID: Byte);
procedure LogDLL(const aText: String);
property AI: TExtAIAndGUIArr read fExtAIAndGUIArr write fExtAIAndGUIArr;
end;
const
TAB_NAME = 'tsExtAI';
CLOSED_LOC = 'Closed';
USE_LOCALHOST_IP = True;
var
ExtAI_TestBed: TExtAI_TestBed;
implementation
uses
ExtAINetworkTypes;
{$R *.dfm}
procedure TExtAI_TestBed.FormCreate(Sender: TObject);
begin
// Game log (log every input from Socket)
gLog := TExtAILog.Create(Log);
gLog.Log('TExtAI_TestBed-Create');
// Game class
fGame := TKMGame.Create(UpdateSimStatus);
// Game events for GUI
fGame.ExtAIMaster.OnAIConfigured := RefreshComboBoxes;
fGame.ExtAIMaster.OnAIDisconnect := RefreshComboBoxes;
// Define ComboBoxes
fedPingLoc[0] := edPingLoc00; fcbLoc[0] := cbLoc00;
fedPingLoc[1] := edPingLoc01; fcbLoc[1] := cbLoc01;
fedPingLoc[2] := edPingLoc02; fcbLoc[2] := cbLoc02;
fedPingLoc[3] := edPingLoc03; fcbLoc[3] := cbLoc03;
fedPingLoc[4] := edPingLoc04; fcbLoc[4] := cbLoc04;
fedPingLoc[5] := edPingLoc05; fcbLoc[5] := cbLoc05;
fedPingLoc[6] := edPingLoc06; fcbLoc[6] := cbLoc06;
fedPingLoc[7] := edPingLoc07; fcbLoc[7] := cbLoc07;
fedPingLoc[8] := edPingLoc08; fcbLoc[8] := cbLoc08;
fedPingLoc[9] := edPingLoc09; fcbLoc[9] := cbLoc09;
fedPingLoc[10] := edPingLoc10; fcbLoc[10] := cbLoc10;
fedPingLoc[11] := edPingLoc11; fcbLoc[11] := cbLoc11;
// Init ExtAI ID
fExtAIAndGUIArr.ID := 1; // ID starts from 1
// Init GUI
RefreshDLLs(); // Includes refresh combo boxes
end;
procedure TExtAI_TestBed.FormDestroy(Sender: TObject);
begin
gLog.Log('TExtAI_TestBed-Destroy');
btnTerminateExtAIsClick(nil);
fGame.TerminateSimulation(); // Tell thread to properly finish the simulation
fGame.WaitFor; // Wait for server to close (this method is called by main thread)
fGame.Free;
gLog.Free;
end;
//------------------------------------------------------------------------------
// DLLs
//------------------------------------------------------------------------------
procedure TExtAI_TestBed.btnAddPathClick(Sender: TObject);
var
K: Integer;
Path: String;
begin
Path := ParamStr(0);
if not FileCtrl.SelectDirectory(Path, [sdAllowCreate, sdPerformCreate, sdPrompt],1000) then
Exit
else
for K := 0 to lbPaths.Items.Count - 1 do
if (AnsiCompareText(lbPaths.Items[K],Path) = 0) then
Exit;
lbPaths.Items.Add(Path);
RefreshDLLs();
end;
procedure TExtAI_TestBed.btnRemoveClick(Sender: TObject);
begin
if (lbPaths.ItemIndex >= 0) then
lbPaths.Items.Delete(lbPaths.ItemIndex);
RefreshDLLs();
end;
procedure TExtAI_TestBed.RefreshDLLs();
var
K: Integer;
Paths: TStringList;
begin
if (fGame = nil) then
Exit;
// Get paths
Paths := TStringList.Create();
try
for K := 0 to lbPaths.Items.Count - 1 do
Paths.Add(lbPaths.Items[K]);
// Refresh DLLs
fGame.ExtAIMaster.DLLs.RefreshList(Paths);
finally
Paths.Free;
end;
// Update GUI
RefreshComboBoxes();
//lbPaths.Clear;
//for K := 0 to fGame.ExtAIMaster.DLLs.Paths.Count - 1 do
// lbPaths.Items.Add(fGame.ExtAIMaster.DLLs.Paths[K]);
lbDLLs.Clear;
for K := 0 to fGame.ExtAIMaster.DLLs.Count - 1 do
lbDLLs.Items.Add(fGame.ExtAIMaster.DLLs[K].Name);
end;
//------------------------------------------------------------------------------
// Server
//------------------------------------------------------------------------------
procedure TExtAI_TestBed.btnStartServerClick(Sender: TObject);
begin
if fGame.ExtAIMaster.Net.Listening then
begin
if fGame.GameState <> gsLobby then
btnServerStartMapClick(Sender);
fGame.ExtAIMaster.Net.StopListening();
prgServer.Style := pbstNormal;
btnStartServer.Caption := 'Start Server';
btnServerStartMap.Enabled := False;
btnSendEvent.Enabled := False;
btnSendState.Enabled := False;
end
else
begin
try
fGame.ExtAIMaster.Net.StartListening(StrToInt(edServerPort.Text), 'Testing server');
except
Log('Invalid port');
Exit;
end;
if fGame.ExtAIMaster.Net.Listening then
begin
prgServer.Style := pbstMarquee;
btnStartServer.Caption := 'Stop Server';
btnServerStartMap.Enabled := True;
btnSendEvent.Enabled := True;
//btnSendState.Enabled := True;
end;
end;
end;
// Generic callback for combo boxes
procedure TExtAI_TestBed.cbOnChange(Sender: TObject);
begin
RefreshComboBoxes();
end;
// Refresh list of available ExtAIs in the combo boxes so player can select just 1 instance of the AI for 1 slot
procedure TExtAI_TestBed.RefreshComboBoxes(aServerClient: TExtAIInfo);
var
ItemFound: Boolean;
K,L,Cnt: Integer;
AvailableAIs, AvailableDLLs: TStringArray;
SelectedAIs: array[0..MAX_HANDS_COUNT-1] of String;
begin
// Get available ExtAIs and DLLs
AvailableAIs := fGame.ExtAIMaster.GetExtAIClientNames();
AvailableDLLs := fGame.ExtAIMaster.GetExtAIDLLNames();
// Filter already selected AI players
Cnt := Length(AvailableAIs);
for K := Low(fcbLoc) to High(fcbLoc) do
begin
// Get actual selection (String, name of the ExtAI)
SelectedAIs[K] := fcbLoc[K].Items[ fcbLoc[K].ItemIndex ];
// Try to find selection in list of new names
ItemFound := False;
for L := 0 to Cnt - 1 do
if (AnsiCompareText(AvailableAIs[L],SelectedAIs[K]) = 0) then
begin
// Confirm selection and remove AI from list of possible names
ItemFound := True;
Cnt := Cnt - 1;
AvailableAIs[L] := AvailableAIs[Cnt];
Break;
end;
for L := Low(AvailableDLLs) to High(AvailableDLLs) do
if (AnsiCompareText(AvailableDLLs[L],SelectedAIs[K]) = 0) then
ItemFound := True;
// Remove selection
if not ItemFound then
SelectedAIs[K] := '';
end;
// Refresh combo boxes [Closed, ActualSelection, PossibleSelection1, PossibleSelection2, ...]
for K := Low(fcbLoc) to High(fcbLoc) do
begin
fcbLoc[K].Items.Clear;
fcbLoc[K].Items.Add(CLOSED_LOC);
// Closed by default, first index if there is existing already selected AI
if (Length(SelectedAIs[K]) > 0) then
fcbLoc[K].Items.Add(SelectedAIs[K]);
fcbLoc[K].ItemIndex := fcbLoc[K].Items.Count - 1;
for L := 0 to Cnt - 1 do
fcbLoc[K].Items.Add(AvailableAIs[L]);
for L := Low(AvailableDLLs) to High(AvailableDLLs) do
if (AnsiCompareText(AvailableDLLs[L],SelectedAIs[K]) <> 0) then
fcbLoc[K].Items.Add(AvailableDLLs[L]);
end;
end;
procedure TExtAI_TestBed.pcOnChangeTab(Sender: TObject);
begin
RefreshAIGUI(nil);
end;
procedure TExtAI_TestBed.btnAutoFillClick(Sender: TObject);
var
K: Integer;
begin
for K := Low(fcbLoc) to High(fcbLoc) do
if (fcbLoc[K].ItemIndex = 0) AND (fcbLoc[K].Items.Count > 1) then // Loc is closed and we have available ExtAI
begin
fcbLoc[K].ItemIndex := 1;
RefreshComboBoxes(); // Refresh GUI
end;
end;
//------------------------------------------------------------------------------
// Simulation
//------------------------------------------------------------------------------
procedure TExtAI_TestBed.btnServerStartMapClick(Sender: TObject);
var
K, Cnt: Integer;
AIs: TStringArray;
begin
btnServerStartMap.Enabled := True;
if (fGame.GameState = gsLobby) then
begin
// Get AI players in the lobby
SetLength(AIs,MAX_HANDS_COUNT);
Cnt := 0;
for K := Low(fcbLoc) to High(fcbLoc) do
begin
// Get actual selection
AIs[Cnt] := fcbLoc[K].Items[ fcbLoc[K].ItemIndex ];
Cnt := Cnt + Byte((Length(AIs[Cnt]) > 0) AND (AnsiCompareText(AIs[Cnt],CLOSED_LOC) <> 0));
end;
SetLength(AIs,Cnt);
// Start / stop the simulation with specific AI players
fGame.StartGame(AIs);
btnServerStartMap.Caption := 'Stop Map';
btnServerStartMap.Enabled := True;
end
else if (fGame.GameState = gsPlay) then
begin
btnServerStartMap.Caption := 'Stop Map';
fGame.EndGame();
end
else
begin
btnServerStartMap.Caption := 'Start Map';
end
end;
procedure TExtAI_TestBed.btnServerSendEventClick(Sender: TObject);
begin
fGame.SendEvent;
end;
procedure TExtAI_TestBed.UpdateSimStatus(const aLogDLL: String = '');
var
K,L: Integer;
AvailableAIs: TStringArray;
begin
// Add log if exists
if (Length(aLogDLL) > 0) then
LogDLL(aLogDLL);
// Get available AI players
AvailableAIs := fGame.ExtAIMaster.GetExtAIClientNames();
// Update ping
for K := Low(fcbLoc) to High(fcbLoc) do
begin
fedPingLoc[K].Text := '0';
for L := Low(AvailableAIs) to High(AvailableAIs) do
if (AnsiCompareText(AvailableAIs[L], fcbLoc[K].Items[ fcbLoc[K].ItemIndex ]) = 0) then
fedPingLoc[K].Text := IntToStr(fGame.ExtAIMaster.AIs[L].ServerClient.NetPing);
end;
// Update Start simulation button
case fGame.GameState of
gsLobby, gsEnd: btnServerStartMap.Caption := 'Start Map';
gsLoad, gsPlay: btnServerStartMap.Caption := 'Stop Map';
else begin end;
end;
end;
//------------------------------------------------------------------------------
// ExtAI
//------------------------------------------------------------------------------
procedure TExtAI_TestBed.btnCreateExtAIClick(Sender: TObject);
var
Cnt: Integer;
begin
// Set Length
Cnt := fExtAIAndGUIArr.Count;
if (Length(fExtAIAndGUIArr.Arr) <= Cnt) then
SetLength(fExtAIAndGUIArr.Arr, Cnt + 12);
// Increase cnt
Inc(fExtAIAndGUIArr.Count);
with fExtAIAndGUIArr.Arr[Cnt] do
begin
ID := fExtAIAndGUIArr.ID;
// Increase number
Inc(fExtAIAndGUIArr.ID);
// Create GUI
tsTab := TTabSheet.Create(pcLogExtAIExe);
tsTab.Caption := Format('Log AI %d',[ID]);
//tsTab.Caption := Format('%s %d',[AI.Client.ClientName, ID]);
tsTab.Name := Format('%s%d',[TAB_NAME,ID]);
tsTab.PageControl := pcLogExtAIExe;
mLog := TMemo.Create(tsTab);
mLog.Parent := tsTab;
mLog.Align := alClient;
mLog.ScrollBars := ssBoth;
// Create new ExtAI
Log := TExtAILog.Create(LogID, ID);
AI := TExtAIDelphi.Create(Log, ID);
AI.Client.OnConnectSucceed := RefreshAIGUI;
AI.Client.OnForcedDisconnect := RefreshAIGUI;
end;
// Try to connect to server
ConnectClient(Cnt);
end;
procedure TExtAI_TestBed.btnTerminateExtAIClick(Sender: TObject);
var
Idx: Integer;
begin
if GetSelectedClient(Idx) then
with fExtAIAndGUIArr do
begin
Arr[Idx].AI.TerminateSimulation();
Arr[Idx].AI.WaitFor; // Wait for ExtAI thread to close (this method is called by main thread)
Arr[Idx].AI.Free;
Arr[Idx].Log.Free;
Arr[Idx].tsTab.Free; // Free tab and all GUI stuff in it
Arr[Idx] := Arr[Count-1];
Count := Count - 1;
end;
end;
procedure TExtAI_TestBed.btnTerminateExtAIsClick(Sender: TObject);
var
K: Integer;
begin
with fExtAIAndGUIArr do
begin
for K := Count - 1 downto 0 do
Arr[K].AI.TerminateSimulation();
for K := Count - 1 downto 0 do
begin
Arr[K].AI.WaitFor; // Wait for ExtAI thread to close (this method is called by main thread)
Arr[K].AI.Free;
Arr[K].Log.Free;
Arr[K].tsTab.Free; // Free tab and all GUI stuff in it
end;
Count := 0;
//ID := 0;
end;
end;
procedure TExtAI_TestBed.btnClientConnectClick(Sender: TObject);
var
Conn: Boolean;
K, Idx: Integer;
begin
// Send command to all ExtAIs
if chbControlAll.Checked then
begin
Conn := True;
for K := 0 to fExtAIAndGUIArr.Count - 1 do
with fExtAIAndGUIArr.Arr[K].AI do
Conn := Conn AND Client.Connected;
for Idx := 0 to pcLogExtAIExe.PageCount - 1 do
if Conn then
DisconnectClient(Idx)
else
ConnectClient(Idx);
end
// Send command only to selected AI
else if GetSelectedClient(Idx) then
begin
if fExtAIAndGUIArr.Arr[Idx].AI.Client.Connected then
DisconnectClient(Idx)
else
ConnectClient(Idx);
end;
end;
procedure TExtAI_TestBed.chbControlAllClick(Sender: TObject);
begin
RefreshAIGUI(Sender);
end;
procedure TExtAI_TestBed.btnClientSendActionClick(Sender: TObject);
var
K,Idx: Integer;
begin
if chbControlAll.Checked then
begin
for K := 0 to fExtAIAndGUIArr.Count - 1 do
with fExtAIAndGUIArr.Arr[K].AI do
Actions.Log(Format('This is debug message (Action.Log) from ExtAI ID = %d',[ID]));
end
else if GetSelectedClient(Idx) then
with fExtAIAndGUIArr.Arr[Idx].AI do
begin
Actions.Log(Format('This is debug message (Action.Log) from ExtAI ID = %d',[ID]));
//Actions.GroupOrderWalk(1,2,3,4);
end;
end;
procedure TExtAI_TestBed.btnClientSendStateClick(Sender: TObject);
begin
//fExtAIDelphi.State.Log('This is debug message (States) from ExtAI in Delphi');
Log('States are not implemented');
end;
function TExtAI_TestBed.GetIdxByID(var aIdx: Integer; aID: Byte): boolean;
var
K: Integer;
begin
Result := False;
for K := 0 to fExtAIAndGUIArr.Count - 1 do
if (fExtAIAndGUIArr.Arr[K].ID = aID) then
begin
aIdx := K;
Exit(True);
end;
end;
function TExtAI_TestBed.GetSelectedClient(var aIdx: Integer): boolean;
var
tsTab: TTabSheet;
TabID: String;
ID: Byte;
begin
Result := False;
if (pcLogExtAIExe.PageCount > 0) then
begin
tsTab := pcLogExtAIExe.ActivePage;
TabID := tsTab.Name;
TabID := Copy(TabID, 1 + Length(TAB_NAME), Length(TabID) - Length(TAB_NAME));
try
ID := StrToInt(TabID);
if GetIdxByID(aIdx, ID) then
Exit(True);
except
Log('Cannot extract ID from name of the tab');
end;
end;
end;
procedure TExtAI_TestBed.ConnectClient(aIdx: Word);
// Simple function for detection of actual IP address
function GetIP(var aIPAddress: String): Boolean;
type
pu_long = ^u_long;
var
TWSA: TWSAData;
phe: PHostEnt;
Addr: TInAddr;
Buffer: array[0..255] of AnsiChar;
begin
Result := False;
aIPAddress := '';
if (WSAStartup($101,TWSA) = 0) AND (GetHostName(Buffer, SizeOf(Buffer)) = 0) then
begin
phe := GetHostByName(Buffer);
if (phe = nil) then
Exit;
Addr.S_addr := u_long(pu_long(phe^.h_addr_list^)^);
aIPAddress := String(inet_ntoa(Addr));
Result := True;
end;
WSACleanUp;
end;
var
Port: Integer;
IP: String;
begin
try
Port := StrToInt(edServerPort.Text);
except
Log('Invalid port');
Exit;
end;
if USE_LOCALHOST_IP then
fExtAIAndGUIArr.Arr[aIdx].AI.Client.ConnectTo('127.0.0.1', Port)
else if GetIP(IP) then
fExtAIAndGUIArr.Arr[aIdx].AI.Client.ConnectTo(IP, Port);
end;
procedure TExtAI_TestBed.DisconnectClient(aIdx: Integer);
begin
with fExtAIAndGUIArr.Arr[aIdx].AI.Client do
if Connected then
Disconnect;
btnClientConnect.Caption := 'Connect client';
btnClientSendAction.Enabled := False;
btnClientSendState.Enabled := False;
end;
procedure TExtAI_TestBed.UpdateAIGUI();
var
Conn: Boolean;
K, ID: Integer;
begin
if GetSelectedClient(ID) then
begin
// Check selected client
Conn := fExtAIAndGUIArr.Arr[ID].AI.Client.Connected;
// Check if all clients are connected
if Conn AND chbControlAll.Checked then
for K := 0 to fExtAIAndGUIArr.Count - 1 do
with fExtAIAndGUIArr.Arr[K].AI do
Conn := Conn AND Client.Connected;
// Update buttons
if Conn then
begin
btnClientConnect.Caption := 'Disconnect client';
btnClientSendAction.Enabled := True;
//btnClientSendState.Enabled := True;
end
else
begin
btnClientConnect.Caption := 'Connect client';
btnClientSendAction.Enabled := False;
btnClientSendState.Enabled := False;
end;
end;
end;
procedure TExtAI_TestBed.RefreshAIGUI(Sender: TObject);
begin
TThread.Synchronize(nil, UpdateAIGUI);
end;
//------------------------------------------------------------------------------
// Logs
//------------------------------------------------------------------------------
procedure TExtAI_TestBed.Log(const aText: String);
begin
with reLog.SelAttributes do
begin
if ContainsText(aText, 'Create' ) then Color := clGreen
else if ContainsText(aText, 'Destroy' ) then Color := clRed
else if ContainsText(aText, 'Server Status' ) then Color := clPurple
else if ContainsText(aText, 'ExtAIInfo' ) then Color := clMedGray
else if ContainsText(aText, 'TKMGame-Execute') then Color := clNavy;
end;
reLog.Lines.Add(aText);
SendMessage(reLog.handle, WM_VSCROLL, SB_BOTTOM, 0);
end;
procedure TExtAI_TestBed.LogID(const aText: String; const aID: Byte);
var
Idx: Integer;
begin
if GetIdxByID(Idx, aID) then
fExtAIAndGUIArr.Arr[Idx].mLog.Lines.Append(aText);
end;
procedure TExtAI_TestBed.LogDLL(const aText: String);
begin
if (Length(aText) > 0) then
begin
with reLogDLL.SelAttributes do
begin
if ContainsText(aText, 'Create' ) then Color := clGreen
else if ContainsText(aText, 'Destroy' ) then Color := clRed
else if ContainsText(aText, 'Client' ) then Color := clPurple;
//else if ContainsText(aText, 'ExtAIInfo' ) then Color := clMedGray
//else if ContainsText(aText, 'TKMGame-Execute') then Color := clNavy;
end;
reLogDLL.Lines.Add(aText);
SendMessage(reLogDLL.handle, WM_VSCROLL, SB_BOTTOM, 0);
end;
end;
end.
|
{!DOCTOPIC}{
Type » T2DIntArray
}
{!DOCREF} {
@method: function T2DIntArray.Len(): Int32;
@desc: Returns the length of the arr. Same as c'Length(Arr)'
}
function T2DIntArray.Len(): Int32;
begin
Result := Length(Self);
end;
{!DOCREF} {
@method: function T2DIntArray.IsEmpty(): Boolean;
@desc: Returns True if the ATIA is empty. Same as c'Length(ATIA) = 0'
}
function T2DIntArray.IsEmpty(): Boolean;
begin
Result := Length(Self) = 0;
end;
{!DOCREF} {
@method: procedure T2DIntArray.Append(const Arr:TIntArray);
@desc: Add another element to the array
}
procedure T2DIntArray.Append(const Arr:TIntArray);
var
l:Int32;
begin
l := Length(Self);
SetLength(Self, l+1);
Self[l] := Arr;
end;
{!DOCREF} {
@method: procedure T2DIntArray.Insert(idx:Int32; Value:TIntArray);
@desc:
Inserts a new item `value` in the array at the given position. If position `idx` is greater then the length,
it will append the item `value` to the end. If it's less then 0 it will substract the index from the length of the array.[br]
`Arr.Insert(0, x)` inserts at the front of the list, and `Arr.Insert(length(a), x)` is equivalent to `Arr.Append(x)`.
}
procedure T2DIntArray.Insert(idx:Int32; Value:TIntArray);
var i,l:Int32;
begin
l := Length(Self);
if (idx < 0) then
idx := math.modulo(idx,l);
if (l <= idx) then begin
self.append(value);
Exit();
end;
SetLength(Self, l+1);
for i:=l downto idx+1 do
Self[i] := Self[i-1];
Self[i] := Value;
end;
{!DOCREF} {
@method: function T2DIntArray.Pop(): TIntArray;
@desc: Removes and returns the last item in the array
}
function T2DIntArray.Pop(): TIntArray;
var
H:Int32;
begin
H := high(Self);
Result := Self[H];
SetLength(Self, H);
end;
{!DOCREF} {
@method: function T2DIntArray.PopLeft(): TIntArray;
@desc: Removes and returns the first item in the array
}
function T2DIntArray.PopLeft(): TIntArray;
begin
Result := Self[0];
Self := Self.Slice(1,-1);
end;
{!DOCREF} {
@method: function T2DIntArray.Slice(Start,Stop: Int32; Step:Int32=1): T2DIntArray;
@desc:
Slicing similar to slice in Python, tho goes from 'start to and including stop'
Can be used to eg reverse an array, and at the same time allows you to c'step' past items.
You can give it negative start, and stop, then it will wrap around based on length(..)
If c'Start >= Stop', and c'Step <= -1' it will result in reversed output.
[note]Don't pass positive c'Step', combined with c'Start > Stop', that is undefined[/note]
}
function T2DIntArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): T2DIntArray;
begin
if (Start = DefVar64) then
if Step < 0 then Start := -1
else Start := 0;
if (Stop = DefVar64) then
if Step > 0 then Stop := -1
else Stop := 0;
if Step = 0 then Exit;
try Result := exp_slice(Self, Start,Stop,Step);
except SetLength(Result,0) end;
end;
{!DOCREF} {
@method: procedure T2DIntArray.Extend(Arr:T2DIntArray);
@desc: Extends the 2D-array with a 2D-array
}
procedure T2DIntArray.Extend(Arr:T2DIntArray);
var L,i:Int32;
begin
L := Length(Self);
SetLength(Self, Length(Arr) + L);
for i:=L to High(Self) do
begin
SetLength(Self[i],Length(Arr[i-L]));
MemMove(Arr[i-L][0], Self[i][0], Length(Arr[i-L])*SizeOf(Int32));
end;
end;
{!DOCREF} {
@method: function T2DIntArray.Merge(): TIntArray;
@desc: Merges all the groups in the array, and return a TIA
}
function T2DIntArray.Merge(): TIntArray;
var i,s,l: Integer;
begin
s := 0;
for i:=0 to High(Self) do
begin
L := Length(Self[i]);
SetLength(Result, S+L);
MemMove(Self[i][0], Result[S], L*SizeOf(Int32));
S := S + L;
end;
end;
{!DOCREF} {
@method: function T2DIntArray.Sorted(Key:TSortKey=sort_Default): T2DIntArray;
@desc:
Returns a new sorted array from the input array.
Supported keys: c'sort_Default, sort_Length, sort_Mean, sort_First'
}
function T2DIntArray.Sorted(Key:TSortKey=sort_Default): T2DIntArray;
begin
Result := Self.Slice();
case Key of
sort_Default, sort_Length: se.SortATIAByLength(Result);
sort_Mean: se.SortATIAByMean(Result);
sort_First: se.SortATIAByFirst(Result);
else
WriteLn('TSortKey not supported');
end;
end;
{!DOCREF} {
@method: function T2DIntArray.Sorted(Index:Integer): T2DIntArray; overload;
@desc: Sorts a copy of the ATIA by the given index in each group
}
function T2DIntArray.Sorted(Index:Integer): T2DIntArray; overload;
begin
Result := Self.Slice();
se.SortATIAByIndex(Result, Index);
end;
{!DOCREF} {
@method: procedure T2DIntArray.Sort(Key:TSortKey=sort_Default);
@desc:
Sorts the ATIA with the given key, returns a copy
Supported keys: c'sort_Default, sort_Length, sort_Mean, sort_First'
}
procedure T2DIntArray.Sort(Key:TSortKey=sort_Default);
begin
case Key of
sort_Default, sort_Length: se.SortATIAByLength(Self);
sort_Mean: se.SortATIAByMean(Self);
sort_First: se.SortATIAByFirst(Self);
else
WriteLn('TSortKey not supported');
end;
end;
{!DOCREF} {
@method: procedure T2DIntArray.Sort(Index:Integer); overload;
@desc:
Sorts the ATIA by the given index in each group. If the group is not that large it will be set to the last item in that group.
Negative 'index' will result in counting from right to left: High(Arr[i]) - index
}
procedure T2DIntArray.Sort(Index:Integer); overload;
begin
se.SortATIAByIndex(Self, Index);
end;
{!DOCREF} {
@method: function T2DIntArray.Reversed(): T2DIntArray;
@desc: Creates a reversed copy of the array
}
function T2DIntArray.Reversed(): T2DIntArray;
begin
Self := Self.Slice(,,-1);
end;
{!DOCREF} {
@method: procedure T2DIntArray.Reverse();
@desc: Reverses the array
}
procedure T2DIntArray.Reverse();
begin
Self := Self.Slice(,,-1);
end;
{=============================================================================}
// The functions below this line is not in the standard array functionality
//
// By "standard array functionality" I mean, functions that all standard
// array types should have.
{=============================================================================}
{!DOCREF} {
@method: function T2DIntArray.Sum(): Int64;
@desc: Returns the sum of the 2d array
}
function T2DIntArray.Sum(): Int64;
var i,L: Integer;
begin
for i:=0 to High(Self) do
Result := Result + Self[i].Sum();
end;
{!DOCREF} {
@method: function T2DIntArray.Mean(): Extended;
@desc: Returns the mean of the 2d array
}
function T2DIntArray.Mean(): Extended;
var i,L: Integer;
begin
for i:=0 to High(Self) do
Result := Result + Self[i].Mean();
Result := Result / High(Self);
end;
{!DOCREF} {
@method: function T2DIntArray.Stdev(): Extended;
@desc: Returns the standard deviation of the array
}
function T2DIntArray.Stdev(): Extended;
begin
Result := Self.Merge().Stdev();
end;
{!DOCREF} {
@method: function T2DIntArray.Variance(): Extended;
@desc:
Return the sample variance.
Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of the array.
A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.
}
function T2DIntArray.Variance(): Extended;
var
Arr:TIntArray;
avg:Extended;
i:Int32;
begin
Arr := Self.Merge();
avg := Arr.Mean();
for i:=0 to High(Arr) do
Result := Result + Sqr(Arr[i] - avg);
Result := Result / length(Arr);
end;
{!DOCREF} {
@method: function T2DIntArray.Mode(): Int32;
@desc:
Returns the sample mode of the array, which is the most frequently occurring value in the array.
When there are multiple values occurring equally frequently, mode returns the smallest of those values.
}
function T2DIntArray.Mode(): Int32;
begin
Result := Self.Merge().Mode();
end;
|
program squareRoot(input, output);
var
x: real;
begin
repeat
write('Enter a number: ' );
read(x);
if x >= 0
then writeln(sqrt(x))
else writeln(x, ' Does not have a real square root.')
until x = 0;
end. |
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpX9FieldID;
interface
uses
ClpCryptoLibTypes,
ClpIX9FieldID,
ClpIDerInteger,
ClpAsn1Sequence,
ClpIAsn1Sequence,
ClpAsn1EncodableVector,
ClpIAsn1EncodableVector,
ClpX9ObjectIdentifiers,
ClpDerInteger,
ClpBigInteger,
ClpDerSequence,
ClpDerObjectIdentifier,
ClpIDerObjectIdentifier,
ClpIProxiedInterface,
ClpAsn1Encodable;
resourcestring
SInconsistentKValues = 'Inconsistent K Values';
type
/// <summary>
/// ASN.1 def for Elliptic-Curve Field ID structure. See X9.62, for further
/// details.
/// </summary>
TX9FieldID = class(TAsn1Encodable, IX9FieldID)
strict private
var
Fid: IDerObjectIdentifier;
Fparameters: IAsn1Object;
function GetIdentifier: IDerObjectIdentifier; inline;
function GetParameters: IAsn1Object; inline;
constructor Create(const seq: IAsn1Sequence); overload;
public
// /**
// * Constructor for elliptic curves over prime fields
// * <code>F<sub>2</sub></code>.
// * @param primeP The prime <code>p</code> defining the prime field.
// */
constructor Create(const primeP: TBigInteger); overload;
// /**
// * Constructor for elliptic curves over binary fields
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param m The exponent <code>m</code> of
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
// * x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.
// */
constructor Create(m, k1: Int32); overload;
// /**
// * Constructor for elliptic curves over binary fields
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param m The exponent <code>m</code> of
// * <code>F<sub>2<sup>m</sup></sub></code>.
// * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.
// * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>.
// * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
// * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
// * represents the reduction polynomial <code>f(z)</code>..
// */
constructor Create(m, k1, k2, k3: Int32); overload;
property Identifier: IDerObjectIdentifier read GetIdentifier;
property Parameters: IAsn1Object read GetParameters;
/// <summary>
/// <para>
/// Produce a Der encoding of the following structure. <br />
/// <pre>
/// </para>
/// <para>
/// FieldID ::= Sequence { fieldType FIELD-ID.&amp;id({IOSet}),
/// parameters FIELD-ID.&amp;Type({IOSet}{&#64;fieldType})} <br />
/// </para>
/// <para>
/// </pre> <br />
/// </para>
/// </summary>
function ToAsn1Object(): IAsn1Object; override;
class function GetInstance(obj: TObject): IX9FieldID; static;
end;
implementation
{ TX9FieldID }
constructor TX9FieldID.Create(m, k1: Int32);
begin
Create(m, k1, 0, 0);
end;
constructor TX9FieldID.Create(const primeP: TBigInteger);
begin
Inherited Create();
Fid := TX9ObjectIdentifiers.PrimeField;
Fparameters := TDerInteger.Create(primeP);
end;
constructor TX9FieldID.Create(const seq: IAsn1Sequence);
begin
Inherited Create();
Fid := TDerObjectIdentifier.GetInstance(seq[0] as TAsn1Encodable);
Fparameters := seq[1].ToAsn1Object();
end;
constructor TX9FieldID.Create(m, k1, k2, k3: Int32);
var
fieldIdParams: IAsn1EncodableVector;
begin
inherited Create();
Fid := TX9ObjectIdentifiers.CharacteristicTwoField;
fieldIdParams := TAsn1EncodableVector.Create
([TDerInteger.Create(m) as IDerInteger]);
if (k2 = 0) then
begin
if (k3 <> 0) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInconsistentKValues);
end;
fieldIdParams.Add([TX9ObjectIdentifiers.TPBasis, TDerInteger.Create(k1)
as IDerInteger]);
end
else
begin
if ((k2 <= k1) or (k3 <= k2)) then
begin
raise EArgumentCryptoLibException.CreateRes(@SInconsistentKValues);
end;
fieldIdParams.Add([TX9ObjectIdentifiers.PPBasis,
TDerSequence.Create([TDerInteger.Create(k1) as IDerInteger,
TDerInteger.Create(k2) as IDerInteger, TDerInteger.Create(k3)
as IDerInteger])]);
end;
Fparameters := TDerSequence.Create(fieldIdParams);
end;
function TX9FieldID.GetIdentifier: IDerObjectIdentifier;
begin
result := Fid;
end;
class function TX9FieldID.GetInstance(obj: TObject): IX9FieldID;
var
x9FieldId: IX9FieldID;
begin
x9FieldId := obj as TX9FieldID;
if (x9FieldId <> Nil) then
begin
result := x9FieldId;
Exit;
end;
if (obj = Nil) then
begin
result := Nil;
Exit;
end;
result := TX9FieldID.Create(TAsn1Sequence.GetInstance(obj));
end;
function TX9FieldID.GetParameters: IAsn1Object;
begin
result := Fparameters;
end;
function TX9FieldID.ToAsn1Object: IAsn1Object;
begin
result := TDerSequence.Create([Fid, Fparameters]);
end;
end.
|
unit np.HttpUt;
interface
function ResponseText(const AValue: Integer) : UTF8String;
implementation
const
// HTTP Status
RSHTTPChunkStarted = 'Chunk Started';
RSHTTPContinue = 'Continue';
RSHTTPSwitchingProtocols = 'Switching protocols';
RSHTTPOK = 'OK';
RSHTTPCreated = 'Created';
RSHTTPAccepted = 'Accepted';
RSHTTPNonAuthoritativeInformation = 'Non-authoritative Information';
RSHTTPNoContent = 'No Content';
RSHTTPResetContent = 'Reset Content';
RSHTTPPartialContent = 'Partial Content';
RSHTTPMovedPermanently = 'Moved Permanently';
RSHTTPMovedTemporarily = 'Moved Temporarily';
RSHTTPSeeOther = 'See Other';
RSHTTPNotModified = 'Not Modified';
RSHTTPUseProxy = 'Use Proxy';
RSHTTPBadRequest = 'Bad Request';
RSHTTPUnauthorized = 'Unauthorized';
RSHTTPForbidden = 'Forbidden';
RSHTTPNotFound = 'Not Found';
RSHTTPMethodNotAllowed = 'Method not allowed';
RSHTTPNotAcceptable = 'Not Acceptable';
RSHTTPProxyAuthenticationRequired = 'Proxy Authentication Required';
RSHTTPRequestTimeout = 'Request Timeout';
RSHTTPConflict = 'Conflict';
RSHTTPGone = 'Gone';
RSHTTPLengthRequired = 'Length Required';
RSHTTPPreconditionFailed = 'Precondition Failed';
RSHTTPPreconditionRequired = 'Precondition Required';
RSHTTPTooManyRequests = 'Too Many Requests';
RSHTTPRequestHeaderFieldsTooLarge = 'Request Header Fields Too Large';
RSHTTPNetworkAuthenticationRequired = 'Network Authentication Required';
RSHTTPRequestEntityTooLong = 'Request Entity Too Long';
RSHTTPRequestURITooLong = 'Request-URI Too Long. 256 Chars max';
RSHTTPUnsupportedMediaType = 'Unsupported Media Type';
RSHTTPExpectationFailed = 'Expectation Failed';
RSHTTPInternalServerError = 'Internal Server Error';
RSHTTPNotImplemented = 'Not Implemented';
RSHTTPBadGateway = 'Bad Gateway';
RSHTTPServiceUnavailable = 'Service Unavailable';
RSHTTPGatewayTimeout = 'Gateway timeout';
RSHTTPHTTPVersionNotSupported = 'HTTP version not supported';
RSHTTPUnknownResponseCode = 'Unknown Response Code';
function ResponseText(const AValue: Integer) : UTF8String;
begin
case AValue of
100: ResponseText := RSHTTPContinue;
// 2XX: Success
200: ResponseText := RSHTTPOK;
201: ResponseText := RSHTTPCreated;
202: ResponseText := RSHTTPAccepted;
203: ResponseText := RSHTTPNonAuthoritativeInformation;
204: ResponseText := RSHTTPNoContent;
205: ResponseText := RSHTTPResetContent;
206: ResponseText := RSHTTPPartialContent;
// 3XX: Redirections
301: ResponseText := RSHTTPMovedPermanently;
302: ResponseText := RSHTTPMovedTemporarily;
303: ResponseText := RSHTTPSeeOther;
304: ResponseText := RSHTTPNotModified;
305: ResponseText := RSHTTPUseProxy;
// 4XX Client Errors
400: ResponseText := RSHTTPBadRequest;
401: ResponseText := RSHTTPUnauthorized;
403: ResponseText := RSHTTPForbidden;
404: begin
ResponseText := RSHTTPNotFound;
// Close connection
end;
405: ResponseText := RSHTTPMethodNotAllowed;
406: ResponseText := RSHTTPNotAcceptable;
407: ResponseText := RSHTTPProxyAuthenticationRequired;
408: ResponseText := RSHTTPRequestTimeout;
409: ResponseText := RSHTTPConflict;
410: ResponseText := RSHTTPGone;
411: ResponseText := RSHTTPLengthRequired;
412: ResponseText := RSHTTPPreconditionFailed;
413: ResponseText := RSHTTPRequestEntityTooLong;
414: ResponseText := RSHTTPRequestURITooLong;
415: ResponseText := RSHTTPUnsupportedMediaType;
417: ResponseText := RSHTTPExpectationFailed;
428: ResponseText := RSHTTPPreconditionRequired;
429: ResponseText := RSHTTPTooManyRequests;
431: ResponseText := RSHTTPRequestHeaderFieldsTooLarge;
// 5XX Server errors
500: ResponseText := RSHTTPInternalServerError;
501: ResponseText := RSHTTPNotImplemented;
502: ResponseText := RSHTTPBadGateway;
503: ResponseText := RSHTTPServiceUnavailable;
504: ResponseText := RSHTTPGatewayTimeout;
505: ResponseText := RSHTTPHTTPVersionNotSupported;
511: ResponseText := RSHTTPNetworkAuthenticationRequired;
else
ResponseText := RSHTTPUnknownResponseCode;
end;
{if ResponseNo >= 400 then
// Force COnnection closing when there is error during the request processing
CloseConnection := true;
end;}
end;
end.
|
unit uProxyWalmart;
interface
uses
SysUtils, Classes, AppEvnts, Forms, Controls, Dialogs, DateUtils,
uMatVars, udmDadosCTe, ACBrSocket, udmPrincipal,
DBXJSON, DBXJSONReflect, RTTI;
type
TcodeRetorno = (SUCESSO, CRITICA, ERRO, OUTROS);
TmodalDocumento = (rodo, aereo, maritmo, fluvial, ferroviario);
TcondicaoFrete = (cif, fob);
TOcorrenciaCollection = class;
TOcorrenciaCollectionItem = class;
TPlanLocomocaoCollection = class;
TPlanLocomocaoCollectionItem = class;
TNFSeCollection = class;
TNFSeCollectionItem = class;
TCompCollection = class;
TCompCollectionItem = class;
TNotaFiscalClienteCollection = class;
TNotaFiscalClienteCollectionItem = class;
TWalmartApi = class(TACBrHTTP)
private
FMensagem: string;
FCodRetorno: integer;
FstatusLeitura: TcodeRetorno;
FOcorrencias: TOcorrenciaCollection;
public
function EnviarCTe(AXmlAutorizacao: WideString): Boolean;
function CancelarCTE(AXmlCancelamento: WideString): Boolean;
function EnviarNFSe: Boolean;
function CancelarNFSe(ASerie: String; ANumero: Integer): Boolean;
function ListarNFSeEnviadas: Boolean;
function EnviarOcorrencia: Boolean;
function ListarOcorrencias: Boolean;
published
property CodRetorno: integer read FCodRetorno write FCodRetorno;
property statusLeitura: TcodeRetorno read FstatusLeitura write FstatusLeitura;
property Mensagem: string read FMensagem write FMensagem;
property Ocorrencias: TOcorrenciaCollection read FOcorrencias write FOcorrencias;
end;
TOcorrenciaCollection = class(TCollection)
private
function GetItem(Index: Integer): TOcorrenciaCollectionItem;
procedure SetItem(Index: Integer; Value: TOcorrenciaCollectionItem);
public
constructor Create(AOwner: TWalmartApi);
function Add: TOcorrenciaCollectionItem;
property Items[Index: Integer]: TOcorrenciaCollectionItem read GetItem write SetItem; default;
end;
TOcorrenciaCollectionItem = class(TCollectionItem)
private
FcodigoOcorrencia: string;
Flatitude: string;
FcnpjCpfRemetenteNotaFiscal: integer;
FdescricaoOcorrencia: string;
FtipoEnvio: string;
Flongitude: string;
FserieNotaFiscal: string;
FnumeroNotaFiscal: integer;
FplanejamentoLocomocoes: TPlanLocomocaoCollection;
FdataOcorrencia: TDateTime;
public
constructor Create; reintroduce;
destructor Destroy; override;
published
property tipoEnvio: string read FtipoEnvio write FtipoEnvio;
property cnpjCpfRemetenteNotaFiscal: integer read FcnpjCpfRemetenteNotaFiscal write FcnpjCpfRemetenteNotaFiscal;
property numeroNotaFiscal: integer read FnumeroNotaFiscal write FnumeroNotaFiscal;
property serieNotaFiscal: string read FserieNotaFiscal write FserieNotaFiscal;
property codigoOcorrencia: string read FcodigoOcorrencia write FcodigoOcorrencia;
property dataOcorrencia: TDateTime read FdataOcorrencia write FdataOcorrencia;
property descricaoOcorrencia: string read FdescricaoOcorrencia write FdescricaoOcorrencia;
property longitude: string read Flongitude write Flongitude; //opcional
property latitude: string read Flatitude write Flatitude; //opcional
property planejamentoLocomocoes: TPlanLocomocaoCollection read FplanejamentoLocomocoes write FplanejamentoLocomocoes;
end;
TPlanLocomocaoCollection = class(TCollection)
private
function GetItem(Index: Integer): TPlanLocomocaoCollectionItem;
procedure SetItem(Index: Integer; Value: TPlanLocomocaoCollectionItem);
public
constructor Create(AOwner: TOcorrenciaCollectionItem);
function Add: TPlanLocomocaoCollectionItem;
property Items[Index: Integer]: TPlanLocomocaoCollectionItem read GetItem write SetItem; default;
end;
TPlanLocomocaoCollectionItem = class(TCollectionItem)
private
FtipoEvento: string;
FdataEvento: TDateTime;
FdescricaoLocalidade: string;
FcodigoLocalidade: string;
public
constructor Create; reintroduce;
destructor Destroy; override;
published
property codigoLocalidade: string read FcodigoLocalidade write FcodigoLocalidade;
property descricaoLocalidade: string read FdescricaoLocalidade write FdescricaoLocalidade;
property tipoEvento: string read FtipoEvento write FtipoEvento;
property dataEvento: TDateTime read FdataEvento write FdataEvento; //opcional
end;
TNFSeCollection = class(TCollection)
private
function GetItem(Index: Integer): TNFSeCollectionItem;
procedure SetItem(Index: Integer; Value: TNFSeCollectionItem);
public
constructor Create(AOwner: TWalmartApi);
function Add: TNFSeCollectionItem;
property Items[Index: Integer]: TNFSeCollectionItem read GetItem write SetItem; default;
end;
TNFSeCollectionItem = class(TCollectionItem)
private
Fpeso: real;
Fmodal: TmodalDocumento;
FsubstituicaoTributaria: boolean;
Fserie: string;
Fcfop: integer;
Fnumero: integer;
FvalorTotal: currency;
FdataEmissao: TDateTime;
Fcondicao: TcondicaoFrete;
FcnpjRemetente: string;
Fcubagem: real;
Fcomposicao: TCompCollection;
FnotaFiscalCliente: TNotaFiscalClienteCollection;
public
constructor Create; reintroduce;
destructor Destroy; override;
published
property cnpjRemetente: string read FcnpjRemetente write FcnpjRemetente;
property numero: integer read Fnumero write Fnumero;
property serie: string read Fserie write Fserie;
property dataEmissao: TDateTime read FdataEmissao write FdataEmissao;
property cfop: integer read Fcfop write Fcfop;
property substituicaoTributaria: boolean read FsubstituicaoTributaria write FsubstituicaoTributaria;
property valorTotal: currency read FvalorTotal write FvalorTotal;
property composicao: TCompCollection read Fcomposicao write Fcomposicao;
property peso: real read Fpeso write Fpeso;
property cubagem: real read Fcubagem write Fcubagem;
property modal: TmodalDocumento read Fmodal write Fmodal;
property condicao: TcondicaoFrete read Fcondicao write Fcondicao;
property notaFiscalCliente: TNotaFiscalClienteCollection read FnotaFiscalCliente write FnotaFiscalCliente;
end;
TCompCollection = class(TCollection)
private
function GetItem(Index: Integer): TCompCollectionItem;
procedure SetItem(Index: Integer; Value: TCompCollectionItem);
public
constructor Create(AOwner: TNFSeCollectionItem);
function Add: TNFSeCollectionItem;
property Items[Index: Integer]: TCompCollectionItem read GetItem write SetItem; default;
end;
TCompCollectionItem = class(TCollectionItem)
private
Ftaxa: currency;
Fvalor: currency;
FbaseDeCalculo: currency;
Fnome: string;
public
constructor Create; reintroduce;
destructor Destroy; override;
published
property nome: string read Fnome write Fnome;
property valor: currency read Fvalor write Fvalor;
property baseDeCalculo: currency read FbaseDeCalculo write FbaseDeCalculo;
property taxa: currency read Ftaxa write Ftaxa;
end;
TNotaFiscalClienteCollection = class(TCollection)
private
function GetItem(Index: Integer): TNotaFiscalClienteCollectionItem;
procedure SetItem(Index: Integer; Value: TNotaFiscalClienteCollectionItem);
public
constructor Create(AOwner: TNFSeCollectionItem);
function Add: TNotaFiscalClienteCollectionItem;
property Items[Index: Integer]: TNotaFiscalClienteCollectionItem read GetItem write SetItem; default;
end;
TNotaFiscalClienteCollectionItem = class(TCollectionItem)
private
Ftaxa: currency;
Fvalor: currency;
FbaseDeCalculo: currency;
Fnome: string;
public
constructor Create; reintroduce;
destructor Destroy; override;
published
property nome: string read Fnome write Fnome;
property valor: currency read Fvalor write Fvalor;
property baseDeCalculo: currency read FbaseDeCalculo write FbaseDeCalculo;
property taxa: currency read Ftaxa write Ftaxa;
end;
implementation
{ TWalmartApi }
function TWalmartApi.CancelarCTE(AXmlCancelamento: WideString): Boolean;
begin
end;
function TWalmartApi.CancelarNFSe(ASerie: String; ANumero: Integer): Boolean;
var
jo: TJSONObject;
jp: TJSONPair;
begin
try
jo := TJSONObject.Create;
jp := TJSONPair.Create('numero', TJSONNumber.Create(ANumero));
jo.AddPair(jp);
jo.AddPair(TJSONPair.Create('serie', TJSONString.Create(ASerie)));
ShowMessage(jo.ToString);
finally
jo.Free;
end;
end;
function TWalmartApi.EnviarCTe(AXmlAutorizacao: WideString): Boolean;
begin
end;
function TWalmartApi.EnviarNFSe: Boolean;
begin
end;
function TWalmartApi.EnviarOcorrencia: Boolean;
begin
end;
function TWalmartApi.ListarNFSeEnviadas: Boolean;
begin
end;
function TWalmartApi.ListarOcorrencias: Boolean;
begin
end;
{ TPlanLocomocaoCollectionItem }
constructor TPlanLocomocaoCollectionItem.Create;
begin
end;
destructor TPlanLocomocaoCollectionItem.Destroy;
begin
inherited;
end;
{ TOcorrenciaCollectionItem }
constructor TOcorrenciaCollectionItem.Create;
begin
FplanejamentoLocomocoes := TPlanLocomocaoCollection.Create(Self);
end;
destructor TOcorrenciaCollectionItem.Destroy;
begin
FplanejamentoLocomocoes.Free;
inherited;
end;
{ TOcorrenciaCollection }
function TOcorrenciaCollection.Add: TOcorrenciaCollectionItem;
begin
Result := TOcorrenciaCollectionItem(inherited Add);
Result.create;
end;
constructor TOcorrenciaCollection.Create(AOwner: TWalmartApi);
begin
inherited Create(TOcorrenciaCollectionItem);
end;
function TOcorrenciaCollection.GetItem(Index: Integer): TOcorrenciaCollectionItem;
begin
Result := TOcorrenciaCollectionItem(inherited GetItem(Index));
end;
procedure TOcorrenciaCollection.SetItem(Index: Integer; Value: TOcorrenciaCollectionItem);
begin
inherited SetItem(Index, Value);
end;
{ TPlanLocomocaoCollection }
function TPlanLocomocaoCollection.Add: TPlanLocomocaoCollectionItem;
begin
Result := TPlanLocomocaoCollectionItem(inherited Add);
Result.create;
end;
constructor TPlanLocomocaoCollection.Create(AOwner: TOcorrenciaCollectionItem);
begin
inherited Create(TPlanLocomocaoCollectionItem);
end;
function TPlanLocomocaoCollection.GetItem(Index: Integer): TPlanLocomocaoCollectionItem;
begin
Result := TPlanLocomocaoCollectionItem(inherited GetItem(Index));
end;
procedure TPlanLocomocaoCollection.SetItem(Index: Integer; Value: TPlanLocomocaoCollectionItem);
begin
inherited SetItem(Index, Value);
end;
{ TCompCollectionItem }
constructor TCompCollectionItem.Create;
begin
end;
destructor TCompCollectionItem.Destroy;
begin
inherited;
end;
{ TNFSeCollectionItem }
constructor TNFSeCollectionItem.Create;
begin
FnotaFiscalCliente := TNotaFiscalClienteCollection.Create(Self);
Fcomposicao := TCompCollection.Create(Self);
end;
destructor TNFSeCollectionItem.Destroy;
begin
Fcomposicao.Free;
FnotaFiscalCliente.Free;
inherited;
end;
{ TNotaFiscalClienteCollection }
function TNotaFiscalClienteCollection.Add: TNotaFiscalClienteCollectionItem;
begin
Result := TNotaFiscalClienteCollectionItem(inherited Add);
Result.create;
end;
constructor TNotaFiscalClienteCollection.Create(AOwner: TNFSeCollectionItem);
begin
inherited Create(TNotaFiscalClienteCollectionItem);
end;
function TNotaFiscalClienteCollection.GetItem(Index: Integer): TNotaFiscalClienteCollectionItem;
begin
Result := TNotaFiscalClienteCollectionItem(inherited GetItem(Index));
end;
procedure TNotaFiscalClienteCollection.SetItem(Index: Integer; Value: TNotaFiscalClienteCollectionItem);
begin
inherited SetItem(Index, Value);
end;
{ TNFSeCollection }
function TNFSeCollection.Add: TNFSeCollectionItem;
begin
Result := TNFSeCollectionItem(inherited Add);
Result.create;
end;
constructor TNFSeCollection.Create(AOwner: TWalmartApi);
begin
inherited Create(TNFSeCollectionItem);
end;
function TNFSeCollection.GetItem(Index: Integer): TNFSeCollectionItem;
begin
Result := TNFSeCollectionItem(inherited GetItem(Index));
end;
procedure TNFSeCollection.SetItem(Index: Integer; Value: TNFSeCollectionItem);
begin
inherited SetItem(Index, Value);
end;
{ TCompCollection }
function TCompCollection.Add: TNFSeCollectionItem;
begin
Result := TNFSeCollectionItem(inherited Add);
Result.create;
end;
constructor TCompCollection.Create(AOwner: TNFSeCollectionItem);
begin
inherited Create(TCompCollectionItem);
end;
function TCompCollection.GetItem(Index: Integer): TCompCollectionItem;
begin
Result := TCompCollectionItem(inherited GetItem(Index));
end;
procedure TCompCollection.SetItem(Index: Integer; Value: TCompCollectionItem);
begin
inherited SetItem(Index, Value);
end;
{ TNotaFiscalClienteCollectionItem }
constructor TNotaFiscalClienteCollectionItem.Create;
begin
end;
destructor TNotaFiscalClienteCollectionItem.Destroy;
begin
inherited;
end;
end.
|
unit ChangeAllTablesTest;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "TestFormsTest"
// Модуль: "w:/common/components/gui/Garant/Daily/ChangeAllTablesTest.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TChangeAllTablesTest
//
// Работа со всеми таблицами документа.
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
interface
{$If defined(nsTest) AND not defined(NoVCM)}
uses
evCustomEditor,
TextViaEditorProcessor,
PrimTextLoad_Form
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
type
TChangeAllTablesTest = {abstract} class(TTextViaEditorProcessor)
{* Работа со всеми таблицами документа. }
protected
// realized methods
procedure Process(aForm: TPrimTextLoadForm); override;
{* Собственно процесс обработки текста }
protected
// overridden protected methods
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
protected
// protected methods
procedure ApplyEditorTool(aEditor: TevCustomEditor); virtual; abstract;
{* Вызов инструмента из редактора }
end;//TChangeAllTablesTest
{$IfEnd} //nsTest AND not NoVCM
implementation
{$If defined(nsTest) AND not defined(NoVCM)}
uses
evTypes,
TestFrameWork
;
{$IfEnd} //nsTest AND not NoVCM
{$If defined(nsTest) AND not defined(NoVCM)}
// start class TChangeAllTablesTest
procedure TChangeAllTablesTest.Process(aForm: TPrimTextLoadForm);
//#UC START# *4BE13147032C_4C3FEB280134_var*
//#UC END# *4BE13147032C_4C3FEB280134_var*
begin
//#UC START# *4BE13147032C_4C3FEB280134_impl*
aForm.Text.Select(ev_stDocument);
ApplyEditorTool(aForm.Text);
//#UC END# *4BE13147032C_4C3FEB280134_impl*
end;//TChangeAllTablesTest.Process
function TChangeAllTablesTest.GetFolder: AnsiString;
{-}
begin
Result := 'Everest';
end;//TChangeAllTablesTest.GetFolder
function TChangeAllTablesTest.GetModelElementGUID: AnsiString;
{-}
begin
Result := '4C3FEB280134';
end;//TChangeAllTablesTest.GetModelElementGUID
{$IfEnd} //nsTest AND not NoVCM
end. |
unit uBloqueio;
interface
uses
udmBloqueio,
uIntegracaoUnilever,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Soap.InvokeRegistry, System.Net.URLClient, Soap.Rio, Soap.SOAPHTTPClient;
type
TfrmBloqueio = class(TForm)
ScrollBox1: TScrollBox;
GroupBox1: TGroupBox;
Label2: TLabel;
edtCodBloqueioWeb: TEdit;
Label3: TLabel;
Label4: TLabel;
Label7: TLabel;
edtQtdeCaixa: TEdit;
edtCodLPN: TEdit;
pnlResult: TPanel;
lblRetorno: TLabel;
pnlConfirmacao: TPanel;
Button1: TButton;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure Bloqueio;
procedure InsereMovimento(const pLPN: string);
public
{ Public declarations }
ic_confirmacao : Boolean;
cd_lpn,
cd_bloqueio_web,
qt_bloqueio : String
end;
var
frmBloqueio: TfrmBloqueio;
implementation
{$R *.dfm}
procedure TfrmBloqueio.InsereMovimento(const pLPN: string);
begin
with dmBloqueio do
begin
try
qryInsereMovimento.Close;
qryInsereMovimento.ParamByName('cd_motivo_bloqueio').Value := StrToIntDef(stpConsultaBloqueioLotenm_codigo_motivo.AsString,0);
qryInsereMovimento.ParamByName('cd_local_bloqueio').Value := dmBloqueio.qryParametroLogisticacd_local_bloqueio_unilever.AsInteger;
qryInsereMovimento.ParamByName('cd_lote_produto').Value := stpConsultaBloqueioLotecd_lote_produto.AsInteger;
qryInsereMovimento.ParamByName('cd_produto').Value := stpConsultaBloqueioLotecd_produto.AsInteger;
qryInsereMovimento.ParamByName('nm_ref_lote_produto').Value := stpConsultaBloqueioLotenm_ref_lote_produto.AsString;
qryInsereMovimento.ParamByName('qt_movimento').Value := stpConsultaBloqueioLoteqt_produto.AsFloat;
qryInsereMovimento.ParamByName('cd_fase_produto').Value := 0;
qryInsereMovimento.ParamByName('dt_bloqueio_movimento').Value := stpConsultaBloqueioLotedt_bloqueio.AsDateTime;
qryInsereMovimento.ParamByName('cd_lpn_produto').Value := stpConsultaBloqueioLotenm_cod_lpn.AsString;
qryInsereMovimento.ExecSQL;
except
on E:exception do
begin
ShowMessage('Atenção! Não foi possível gerar o movimento de bloqueio de lote');
Abort;
end;
end;
end;
end;
procedure TfrmBloqueio.Button1Click(Sender: TObject);
begin
Bloqueio;
end;
procedure TfrmBloqueio.Bloqueio;
var
lValido : Boolean;
msgRetorno : String;
begin
//--------------------------------------------------
//-->> Bloqueio com Pallet Recebido e Não Utilizado
//--------------------------------------------------
lValido := BloqueioLote(
'3', //CodAcao
cd_bloqueio_web, //CodBloqueioWeb
dmBloqueio.qryParametroLogisticacd_local_bloqueio_unilever.asstring, //CodLocalBloqueio
'', //EmailUsuario
qt_bloqueio, //Qtde. Caixas
cd_lpn, //Numero da LPN
msgRetorno //Mensagem de Retorno
);
if lValido then
begin
InsereMovimento(cd_lpn);
lblRetorno.Caption := 'LPN '+cd_lpn+' - Bloqueado com Sucesso!'
end
else
lblRetorno.Caption := msgRetorno;
Application.ProcessMessages;
Sleep(2000);
end;
procedure TfrmBloqueio.FormCreate(Sender: TObject);
begin
with dmBloqueio.qryParametroLogistica do
begin
Close;
Open;
end;
end;
procedure TfrmBloqueio.FormShow(Sender: TObject);
begin
pnlConfirmacao.Visible := ic_confirmacao;
if not ic_confirmacao then
Bloqueio;
end;
end.
|
{
UDebug: Delphi units debugging module.
Copyright by Andrej Pakhutin
}
{$IFDEF SERVER}
{$I ok_server.inc}
{$ELSE}
{$I ok_sklad.inc}
{$ENDIF}
unit UDebug;
interface
uses
Classes;
const
fStackPtrMax = 1000;
debugLevelHigh = 10;
debugLevelHi = 10;
debugLevelMed = 5;
debugLevelMedium = 5;
debugLevelLow = 1;
debugLevelLo = 1;
debugLevelNone = 0;
type
TLoopedList = class
private
FData, FID: array of Variant;
FPosition: Integer; // current position (internal)
FUserPos: Integer; // used to store position for First, next, etc.. to work
Filled: Boolean; // if capacity is all used
function getData(const idx: Integer): Variant;
procedure setData(const idx: Integer; const Value: Variant);
function getID(const idx: Integer): Variant;
procedure setID(const idx: Integer; const Value: Variant);
public
constructor Create(const ALength: Integer);
destructor Destroy; override;
procedure Clear;
function Count: Integer;
function Capacity: Integer;
//procedure SetLength(NewLength: Integer);
procedure Push(Adata: Variant); overload;
procedure Push(Adata: Variant; AID: Variant); overload;
//function Pop: Variant;
function bof: Boolean;
function eof: Boolean;
procedure Next;
procedure Prev;
procedure First;
procedure Last;
function CurrentData: Variant; // current element
function CurrentID: Variant; // current element
property Position: Integer read FPosition;
property Data[const idx: Integer]: Variant read getData write setData; default;
property ID[const idx: Integer]: Variant read getID write setID;
end;
//--------------------------------------
Tprofiler = class
private
FID: Cardinal;
Fstart, Fend: TDateTime;
Fcalls: Cardinal;
FtotalTime: Integer;
Frunning: Boolean;
public
constructor Create; reintroduce;
destructor Destroy; override;
procedure Start(id: Cardinal);
function Stop: Integer;
function Spent: Integer;
function SpentStr: String;
property Calls: Cardinal read Fcalls;
property Started: TDateTime read FStart;
property Stopped: TDateTime read Fend;
end;
//--------------------------------------
Tdebug = class
private
FID: Cardinal;
Fplace: String;
Fprofiler: Tprofiler;
FunitID: Integer;
FCheckPoints: TStringList;
procedure addTrace(start: Boolean; sp: Integer = 0);
procedure Clear; // internal pre-create settings
public
constructor Create(const place: String; LogIt: Boolean = True); overload;
constructor Create(const level, unitID: Integer; const fname: String); overload;
destructor Destroy; overload; override;
destructor Destroy(const msg: String); reintroduce; overload;
procedure add(const s: String);
procedure CheckPoint(const s: String = '');
function getCheckPoints: String;
end; // Tdebug
function profTopByTime: String;
function profTopByCalls: String;
function GetSpent(spent: Integer; showMs: Boolean = True): String; // time in milliseconds
procedure udebug3(const fnam, pnam, pinf: String);
procedure udebug1(const s: String);
function udebugDump(html: Boolean = False; max: Cardinal = fStackPtrMax): String;
function debugRegisterUnit(uname: String; DebugAllowed: pointer; groupID: String): Integer;
procedure debugUnRegisterUnit(uID: Integer);
procedure setUnitDebugLevel(uID: Integer; level: Integer);
procedure debugStoreErrorPlace; // need that?
procedure debugInstantLog(const s: String; SaveInStack:Boolean = True);
procedure debugProfilingLevel(const APL: Integer);
function debugMemDump(const APtr: Pointer; Alen: Integer; const ADigitGroups: Integer = 0): String;
function debugStrDump(const APtr: Pointer; const Alen: Integer = 0): String; // dumps string with non-printables in hex
procedure udebugSetLogFile(Aname: String);
function translateAccViolAddr(mapfile, errstr: String): String; // gets address from standard 'Access Violation at addr...' message and finds function name in memmap
var
FProfilingLevel: Integer;
cmdLineDebugLevel: Integer = 0;
//#########################################################################################
//#########################################################################################
//#########################################################################################
implementation
uses
{$IFNDEF PKG}
ssRegUtils,
{$IFDEF SERVER}
ssSrvConst,
{$ELSE}
ClientData, ssBaseConst,
{$ENDIF}
{$ENDIF}
xClasses, strUtils, SysUtils, Windows, DateUtils, Math, Types, Variants;
type
PByte = ^Byte;
CharPtr = ^Char;
{const
udebugMutexName: String = 'udebugMutex1';
}
var
udebugMutexTimeOut: Integer = 1000; // msec
udebugMutex: TxMutex = nil;
udebugLogFileName: String;
udebugLogFile: TextFile;
type
TitemType = (itDefault, itFuncStart, itFuncStop, itFuncSingleCall, itFuncMultiple);
//--------------------------------------
TprofTop = class // Top NN profiler's list data container
public
Val: Integer;
added: TDateTime; // time added to the list
end;
//--------------------------------------
TfStackItem = record
parent: Tdebug;
ownerid: Cardinal; // for Tdebug's addtrace to know what items are their own
itemType: TitemType;
fname: String;
parname: String;
parinfo: String;
count: Cardinal;
spent: Integer;
time: TDateTime;
end;
//--------------------------------------
TdebugStack = array [1..fStackPtrMax] of TfStackItem;
//--------------------------------------
TdebugID = record
id: Integer;
place: String;
end;
//--------------------------------------
Tunits = record
name: String;
group: String;
Debugging: ^boolean;
level: Integer;
end;
var
fTraceStack: TdebugStack;
fTraceStackPtr: Cardinal = 0;
fCallStack: TdebugStack; // just a function nesting information
fCallStackPtr: Cardinal = 0;
debugID: Cardinal = 1; // uniq trace counter
fTraceStackFilled: Boolean = False;
//IDList: TList;
units: array of Tunits;
profTopByTime_list: TStringList;
profTopByCalls_list: TStringList;
clearLog: Boolean = True;
//===============================================================
function translateAccViolAddr(mapfile, errstr: String): String;
const
key = '63257671816471645';
var
addr, curraddr: LongInt;
map: TStringList;
i,min,max: Integer;
s: String;
begin
//Access violation at address 0054EA80 in module 'OK-Ser~1.EXE'. Read of address 00000008
Result := '';
s := AnsiLowerCase(errstr);
i := AnsiPos('at address', s) + 11;
s := AnsiMidStr(s, i, 999);
i := AnsiPos(' ', s);
s := AnsiMidStr(s, 1, i - 1);
if not TryStrToInt(s, addr) then Exit;
addr := addr - $401000;
map := TStringList.Create;
try // finally
try // except
map.LoadFromFile(mapfile);
min := 0;
max := map.Count - 1;
// addresses are sorted ascended, so performing fast search
while True do begin
i := (max - min) div 2 + min;
if max <= i + 1 then break; // found it
if not TryStrToInt(AnsiLowerCase(map.Names[i]), curraddr) then Exit;
if curraddr < addr
then min := i
else if curraddr = addr
then break
else max := i;
end; // while
s := map.ValueFromIndex[i];
for i := 1 to length(s) // decoding function name
do Result := Result + chr( ord(s[i]) - StrToInt(key[i mod length(key) + 1]) );
except
end;
finally
map.Free;
end;
end;
//===============================================================
//===============================================================
// TLoopedList
//===============================================================
//===============================================================
procedure TLoopedList.Clear;
begin
FPosition := -1;
FUserPos := -1;
Filled := False;
end;
//===============================================================
constructor TLoopedList.Create(const ALength: Integer);
begin
Clear;
System.setLength(FData, ALength);
System.setLength(FID, ALength);
end;
//===============================================================
destructor TLoopedList.Destroy;
begin
inherited;
end;
//===============================================================
function TLoopedList.Count: Integer;
begin
if Filled
then Result := High(FData) + 1
else Result := FPosition + 1;
end;
//===============================================================
function TLoopedList.Capacity: Integer;
begin
Result := High(FData) + 1;
end;
//===============================================================
{procedure TLoopedList.SetLength(NewLength: Integer);
begin
end;
}
//===============================================================
procedure TLoopedList.Push(Adata: Variant);
begin
Push(AData, Null);
end;
//===============================================================
procedure TLoopedList.Push(Adata: Variant; AID: Variant);
begin
inc(FPosition);
if FPosition > High(FData) then begin
FPosition := 0;
Filled := True;
end;
FData[FPosition] := AData;
FID[FPosition] := AID;
FUserPos := FPosition;
end;
//===============================================================
{function TLoopedList.Pop: Variant;
var
i: Integer;
begin
if FPosition = -1 then begin
Result := Null;
Exit;
end;
Result := FData[FPosition];
if Filled then begin
i := ifThen(FPosition = High(FData), 0, FPosition + 1);
end;
dec(FPosition);
end;
}
//===============================================================
function TLoopedList.bof: Boolean;
begin
if not Filled or (Filled and (FPosition = High(FData)))
then Result := (FUserPos <= 0)
else Result := (FUserPos = FPosition + 1);
end;
//===============================================================
function TLoopedList.eof: Boolean;
begin
Result := (FPosition = -1) or (FUserPos = FPosition);
end;
//===============================================================
procedure TLoopedList.First;
begin
if not Filled or (Filled and (FPosition = High(FData)))
then FUserPos := 0
else FUserPos := FPosition + 1;
end;
//===============================================================
procedure TLoopedList.Last;
begin
FUserPos := FPosition;
end;
//===============================================================
procedure TLoopedList.Next;
begin
if Self.Eof then Exit;
if Filled and (FUserPos = High(FData))
then FUserPos := 0
else inc(FUserPos);
end;
//===============================================================
procedure TLoopedList.Prev;
begin
if Self.Bof then Exit;
if Filled and (FUserPos = 0)
then FUserPos := High(FData)
else dec(FUserPos);
end;
//===============================================================
function TLoopedList.CurrentData: Variant; // current element
begin
Result := FData[FUserPos];
end;
//===============================================================
function TLoopedList.CurrentID: Variant; // current element
begin
Result := FID[FUserPos];
end;
//===============================================================
function TLoopedList.getData(const idx: Integer): Variant;
begin
if (idx < 0) or (idx > High(FData))
then Result := Null
else Result := FData[idx];
end;
//===============================================================
procedure TLoopedList.setData(const idx: Integer; const Value: Variant);
begin
FData[idx] := Value;
end;
//===============================================================
function TLoopedList.getID(const idx: Integer): Variant;
begin
if (idx < 0) or (idx > High(FData))
then Result := Null
else Result := FID[idx];
end;
//===============================================================
procedure TLoopedList.setID(const idx: Integer; const Value: Variant);
begin
FID[idx] := Value;
end;
//===============================================================
//===============================================================
//===============================================================
//===============================================================
procedure preparePush(AParent: Tdebug);
begin
if fTraceStackPtr = fStackPtrMax
then begin
fTraceStackPtr := 1;
fTraceStackFilled := True;
end
else inc(fTraceStackPtr);
with fTraceStack[fTraceStackPtr] do begin
parent := AParent;
itemType := itDefault;
ownerid := 0; //Tdebug class id is always <> 0
end;
end;
//===============================================================
procedure prepareCSPush(AParent: Tdebug);
var n: Cardinal;
begin
if fCallStackPtr = fStackPtrMax
then for n := 2 to fStackPtrMax do fCallStack[n - 1] := fCallStack[n] // shifting down
else inc(fCallStackPtr);
if fCallStackPtr < 1 then fCallStackPtr := 1;
with fCallStack[fCallStackPtr] do begin
parent := Aparent;
if AParent <> nil then begin
fname := AParent.Fplace;
ownerid := AParent.FID;
end
else begin
fname := '';
ownerid := 0;
end;
parname := '';
parinfo := '';
itemType := itDefault;
end;
end;
//===============================================================
procedure pushStackInternal(const fnam, pnam, pinf: String);
begin
try
if (fTraceStackPtr > 0) and (fTraceStack[fTraceStackPtr].fname = fnam)
then inc(fTraceStack[fTraceStackPtr].count)
else begin
preparePush(nil);
with fTraceStack[fTraceStackPtr] do begin
parname := pnam;
parinfo := pinf;
fname := fnam;
count := 1;
time := GetTime;
spent := 0;
end;
end;
except
end;
end;
//===============================================================
function debugRegisterUnit(uname: String; DebugAllowed: Pointer; groupID: String): Integer;
var
n,l: Integer;
begin
Result := -1;
if udebugMutex = nil then udebugMutex := txMutex.Create(udebugMutexTimeOut);
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
try
SetLength(units, High(units) + 2);
n := High(units);
units[n].name := uname;
units[n].group := groupID;
units[n].Debugging := DebugAllowed;
{$IFNDEF PKG}
if ReadFromRegInt(MainRegKey+'\debug\units', uname, l)
then units[n].level := l
else units[n].level := debugLevelNone;
{$ENDIF}
Result := n;
try
Boolean(DebugAllowed^) := True; // turning debug for this unit on while there is no automatic catchup code
pushStackInternal('Unit registered: ' + uname, '', '');
except
pushStackInternal('Unit reg: ' + uname + ' failed at the end point', '', '');
end;
finally
udebugMutex.Release;
end;
end;
//===============================================================
procedure debugUnRegisterUnit(uID: Integer);
begin
{
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
try
try
pushStackInternal('Unit UNregistered: '+units[uID].name, '', '');
except
end;
finally
udebugMutex.Release;
end;
}
end;
//===============================================================
function GetSpent(spent: Integer; showMs: Boolean = True): String; // time in milliseconds
var
h,m,s: integer;
ms: String;
begin
Result := '';
if spent = 0 then begin Result := 'Zero time'; Exit; end;
h := 0; m := 0; s := 0;
if spent >= 3600000 then begin
h := spent div 3600000;
spent := spent - h * 3600000;
end;
if spent >= 60000 then begin
m := spent div 60000;
spent := spent - m * 60000;
end;
if spent >= 1000 then begin
s := spent div 1000;
spent := spent - s * 1000;
end;
if showMS
then ms := Format('.%-03d', [spent])
else ms := '';
if (h > 0) and (m + s = 0) then Result := IntToStr(h) + ' hour' + ifThen(h > 1, 's', '')
else if (m > 0) and (h + s = 0) then Result := IntToStr(m) + ' minute' + ifThen(m > 1, 's', '')
else if (s > 0) and (h + m = 0) then Result := IntToStr(s) + ' second' + ifThen(s > 1, 's', '')
else begin
if h > 0 then Result := ifThen(h > 9, '', '0') + IntToStr(h) + ':';
Result := Result + ifThen(m > 9, '', '0') + IntToStr(m) + ':';
Result := Result + ifThen(s > 9, '', '0') + IntToStr(s) + ms;
end;
end;
//===============================================================
function profTopCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
if (List.Objects[Index2] as TProfTop).Val < (List.Objects[Index1] as TProfTop).Val
then Result := -1
else if (List.Objects[Index2] as TProfTop).Val > (List.Objects[Index1] as TProfTop).Val
then Result := 1
else Result := 0;
end;
//===============================================================
function profTopByTime: String;
var i: integer;
begin
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
try
Result := '';
profTopByTime_list.CustomSort(profTopCompare);
for i := 0 to profTopByTime_list.Count - 1 do
Result := Result + Format('%3d: ', [i]) + GetSpent((profTopByTime_list.Objects[i] as TProfTop).Val)
+ ' on ' + profTopByTime_list[i] + #13#10;
finally
udebugMutex.Release;
end;
end;
//===============================================================
function profTopByCalls: String;
var i: integer;
begin
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
try
Result := '';
ProfTopByCalls_list.CustomSort(profTopCompare);
for i := 0 to profTopByCalls_list.Count - 1 do
Result := Result + Format('%3d: %d calls of ', [i, (profTopByCalls_list.Objects[i] as TProfTop).Val])
+ profTopByCalls_list[i] + #13#10;
finally
udebugMutex.Release;
end;
end;
//===============================================================
procedure profAddTop(var list: TStringList; s: String; newval: Integer);
var
i, fi: Integer;
min: Integer;
mindate: TDateTime;
pto: TprofTop;
begin
try
fi := list.IndexOf(s);
if fi = -1 then begin
if list.Count = 100 then begin
min := MaxInt;
mindate := now;
for i := 0 to list.Count - 1 do // getting minimum
with (list.objects[i] as TProfTop) do
if (Val <= min) and (LessThanValue = compareDateTime(added, mindate)) then begin
min := Val;
fi := i;
end;
if (list.objects[fi] as TProfTop).Val > newval then Exit; // this val is too low for Top
(list.objects[fi] as TProfTop).Free;
list.Delete(fi);
end;
pto := TprofTop.Create;
pto.val := newval;
pto.added := now;
list.AddObject(s, pto);
end
else (list.Objects[fi] as TProfTop).Val := (list.objects[fi] as TProfTop).Val + newval;
except
{$IFDEF DEBUG}pushStackInternal('profAddTop croaked at ' + s, '', '');{$ENDIF}
end;
end;
//===============================================================
//===============================================================
//= Tprofiler ===================================================
//===============================================================
//===============================================================
constructor TProfiler.Create;
begin
FID := 0;
Fcalls := 0;
Frunning := False;
//Fstart, Fend: TDateTime;
//FtotalTime: TDateTime;
end;
//===============================================================
destructor TProfiler.Destroy;
begin
if FRunning then Stop;
inherited;
end;
//===============================================================
procedure TProfiler.Start(id: Cardinal);
begin
Fstart := GetTime;
Frunning := True;
inc(Fcalls);
end;
//===============================================================
function TProfiler.Stop: Integer;
begin
if not Frunning then begin
Result := MilliSecondsBetween(Fend, Fstart);
Exit;
end;
Fend := GetTime;
Result := MilliSecondsBetween(Fend,Fstart);
FtotalTime := FtotalTime + Result;
Frunning := False;
end;
//===============================================================
function TProfiler.Spent: Integer;
begin
if Frunning
then Result := MilliSecondsBetween(GetTime, Fstart)
else Result := MilliSecondsBetween(Fend, Fstart);
end;
//===============================================================
function TProfiler.SpentStr: String;
begin
Result := getSpent(spent);
end;
//===============================================================
//===============================================================
//= TDebug ======================================================
//===============================================================
//===============================================================
procedure Tdebug.Clear; //internal only
begin
FID := 0;
Fplace := '';
Fprofiler := nil;
FunitID := -1;
FCheckPoints := nil;
end;
//===============================================================
constructor Tdebug.Create(const place: String; LogIt: Boolean = True);
begin
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
Clear;
try
try
Fplace := place;
FID := debugID;
inc(debugID);
if debugID = 0 then inc(debugID);
addTrace(True);
except
Fplace := '';
Fprofiler := nil;
end;
finally
udebugMutex.Release;
end;
if logIt and ( cmdLineDebugLevel > 14) then debugInstantLog('TDebug.Create(' + place + ')', False);
end;
//===============================================================
constructor Tdebug.Create(const level, unitID: Integer; const fname: String);
begin
try
Create(fname, False);
FunitID := unitID;
if FProfilingLevel > 0 then begin
Fprofiler := Tprofiler.Create;
Fprofiler.Start(0);
end;
if cmdLineDebugLevel > 14 then debugInstantLog('TDebug.Create(' + fname + ')', False);
except
Fplace := '';
Fprofiler := nil;
end
end;
//===============================================================
destructor Tdebug.Destroy;
var
sp: Integer;
begin
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
sp := 0;
try
try
if Fprofiler <> nil then begin
sp := Fprofiler.Stop;
if sp > 0 then profAddTop(profTopByTime_list, Fplace, sp);
profAddTop(profTopByCalls_list, Fplace, Fprofiler.calls);
Fprofiler.Destroy;
end;
except
end;
try
addTrace(False, sp);
except
end;
finally
udebugMutex.Release;
end;
if cmdLineDebugLevel > 14 then debugInstantLog('TDebug.Destroy(' + fplace + '), spent: ' + GetSpent(sp, True), False);
FCheckPoints.Free;
inherited;
end;
//===============================================================
destructor TDebug.Destroy(const msg: String);
begin
Destroy;
udebug1(Fplace + ' *** Exit with message: ' + msg);
end;
//===============================================================
procedure Tdebug.add(const s: String);
begin
udebug1(s);
end;
//===============================================================
procedure Tdebug.CheckPoint(const s: String = '');
begin
if FcheckPoints = nil then FcheckPoints := TStringlist.Create;
if s = ''
then FCheckPoints.Add(IntToStr(FCheckPoints.Count + 1))
else FCheckPoints.Add(IntToStr(FCheckPoints.Count + 1) + ': ' + s);
end;
//===============================================================
function Tdebug.getCheckPoints: String;
begin
if (FCheckPoints = nil) or (FCheckPoints.Count = 0)
then Result := ''
else Result := FCheckPoints.Text;
end;
//===============================================================
{procedure getStack(const Value: Cardinal);
begin
if (Value < 1) or (Value > fTraceStackPtr) then Result := nil;
else Result := fTraceStack[Value];
end;
}
//===============================================================
function lookCSID(AID: Cardinal; startFrom: Cardinal = 0): Cardinal; // looks up matching id down the fCallStack
var lp: Cardinal;
begin
Result := 0;
if startFrom = 0 then startFrom := fCallStackPtr;
for lp := startFrom downto 1 do
if fCallStack[lp].ownerid = AID then begin Result := lp; Exit; end;
end;
//===============================================================
function lookID(AID: Cardinal): Cardinal; // looks up matching id down the fTraceStack
var lp: Cardinal;
begin
Result := 0;
for lp := fTraceStackPtr - 1 downto 1 do
if fTraceStack[lp].ownerid = AID then begin Result := lp; Exit; end;
if not fTraceStackFilled or (fTraceStackPtr = fStackPtrMax) then Exit; // no loop possible
for lp := fStackPtrMax downto fTraceStackPtr + 1 do
if fTraceStack[lp].ownerid = AID then begin Result := lp; Exit; end;
end;
//===============================================================
procedure Tdebug.addTrace(start: Boolean; sp: Integer = 0);
var
lp: Integer;
begin
// for start of func we're always adding a new entry. when it ends we'll look what was behind it
if start then begin
preparePush(Self);
with fTraceStack[fTraceStackPtr] do begin
ownerid := FID;
itemType := itFuncStart;
fname := Fplace;
parname := units[FunitID].name;
count := 1;
time := GetTime;
spent := sp;
end;
prepareCSPush(Self);
with fCallStack[fCallStackPtr] do begin
itemType := itFuncStart;
parname := units[FunitID].name;
end;
Exit;
end; // if start
// trying to clear stack till our function start. even if some intermediate was not unregistered itself from the top of call stack
lp := LookCSID(FID);
if lp > 0 then begin
fCallStackPtr := lp - 1;
if fCallStackPtr < 1 then fCallStackPtr := 1;
end
else begin
prepareCSPush(Self);
with fCallStack[fCallStackPtr] do begin
parname := units[FunitID].name;
parinfo := '--- Stalled stack item';
end;
end;
// if this is not our start on the stack top - marking exit as separate item
if FID <> fTraceStack[fTraceStackPtr].ownerid then begin
preparePush(Self);
with fTraceStack[fTraceStackPtr] do begin
ownerID := FID;
itemType := itFuncStop;
fname := FPlace;
parname := units[FunitID].name;
count := 1;
time := GetTime;
spent := sp;
end;
Exit;
end;
// so, here is our beginning on top of the stack
// for the end of func we should check if it is repeated or recursive call, etc...
lp := fTraceStackPtr - 1; // getting back one step (if there was something of course)
if lp <= 0 then
if fTraceStackFilled
then lp := fStackPtrMax // stack was full, so looping to the top
else lp := 1; // we're 1st element!
// cannot merge if previous element is NOT the same func as we are OR it is not marked as repeated call
if (FPlace <> fTraceStack[lp].fname) or (not (fTraceStack[lp].itemType in [itFuncSingleCall, itFuncMultiple]))
then
with fTraceStack[fTraceStackPtr] do begin // just marking our ending separately
itemType := itFuncSingleCall;
count := 1;
time := GetTime;
spent := sp;
Exit;
end;
// we can merge with previous call
with fTraceStack[lp] do begin
itemType := itFuncMultiple;
inc(count);
spent := spent + sp;
end;
fTraceStackPtr := lp; // making our beginning element vanish
end;
//===============================================================
procedure udebug3(const fnam, pnam, pinf: String);
begin
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
try
pushStackInternal(fnam, pnam, pinf);
finally
udebugMutex.Release;
end;
end;
//===============================================================
procedure udebug1(const s: String);
begin
udebug3(s, '', '');
end;
//===============================================================
function hTag(html: Boolean; tag: string; crp: Integer = 0): String;
begin
Result := ifThen( (crp and 2) = 2, #13#10, '');
if html then Result := Result + tag;
if (crp and 1) = 1 then Result := Result + #13#10;
end;
//===============================================================
function udebugDumpCallStack(html: Boolean = False): String;
var
i: Cardinal;
begin
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
try
Result := hTag(html, '<P>', 2) + 'CallStack:';
if fCallStackPtr = 0 then begin
Result := Result + ' Empty...';
Exit;
end;
for i := 1 to fCallStackPtr do
with fCallStack[i] do begin
Result := Result + hTag(html, '<BR>', 2) + format('%3d/%5d - ', [i, ownerid]) + fname + '/' + parname + ' ' + parinfo;
if (parent <> nil) and (parent.getCheckPoints <> '')
then Result := Result + hTag(html, '<BR>', 2) + 'CheckPoints: '#13#10 + parent.getCheckPoints;
end;
finally
udebugMutex.Release;
end;
end;
//===============================================================
function udebugDump(html: Boolean = False; max: Cardinal = fStackPtrMax): String;
var
i, lastpos, level: Cardinal;
timeprefix, prefix, sprefix, spaces, suffix: String;
procedure MakePrefix;
begin
spaces := StringOfChar(' ', level * 2);
sprefix := #13#10 + spaces + StringOfChar(' ', 13);
timeprefix := TimeToStr(fTraceStack[i].time);
if level > 0 then begin
prefix := hTag(html, '<LI> ', 2) + timeprefix + ': ' + spaces;
suffix := hTag(html, '</LI>', 1);
end
else begin
prefix := hTag(html, '<BR> ', 2) + timeprefix + ': ';
suffix := '';
end;
end;
function AddSpent(spent: Integer): String;
begin
if spent = 0 then begin
Result := '';
Exit;
end;
Result := ', ' + getSpent(spent);
if spent > 500 then Result := Result + ' <<<<<============ SLOW';
end;
begin
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
try
if fTraceStackPtr = 0 then begin Result := #13#10'Stack is Empty'; exit; end;
Result := hTag(html, '<P>', 2) + 'Debug dump starts here. Shivvver in Great Fear ye puny earthlings! '#13#10 + StringOFChar('-', 20);
if fTraceStackFilled then begin // cycle it
if max > fStackPtrMax then max := fStackPtrMax;
i := fTraceStackPtr + 1;
if i > fStackPtrMax then i := 0;
lastpos := i + max;
if lastpos > fStackPtrMax then lastpos := lastpos - fStackPtrMax - 1; //set it before begin
end
else begin // from begin to stackptr
if max > fTraceStackPtr then max := fTraceStackPtr;
i := 0;
lastpos := fTraceStackPtr;
end;
Result := udebugDumpCallStack + hTag(html, '<H2>', 2) + 'Trace log for ' + intToStr(max) + ' positions' + hTag(html, '</H2><DIV>');
level := 0;
while i <> lastpos do begin
inc(i);
if i = fStackPtrMax then i := 1;
MakePrefix;
with fTraceStack[i] do
case itemType of
itDefault:
if fname <> '' then begin
MakePrefix;
if (parname = '') and (parinfo = '') // it is a single message, not a Tdebug matter
then Result := Result + hTag(html, '<BR>', 2) + timeprefix + fname + #13#10
else Result := Result + prefix + fname;
if count > 1 then Result := Result + ' (' + IntToStr(count) + ' times)';
if parname <> '' then Result := Result + ' of ' + parname;
if parinfo <> '' then Result := Result + ' / ' + parinfo;
end;
itFuncStart:
begin
MakePrefix;
inc(level);
Result := Result + prefix + ' +++++ Begin lvl: ' + IntTostr(level) + ' ' + fname + '/' + parname + sprefix + hTag(html, '<UL>');
end;
itFuncStop: begin
if level > 0 then begin // in case of stack cycled and begin of func was erased.
dec(level);
MakePrefix;
Result := Result + sprefix + hTag(html, '</UL>') + prefix + ' ----- End lvl: ' + IntTostr(level + 1) + ' '
+ fname + '/' + parname + AddSpent(spent) + suffix;
end
else Result := Result + prefix + ' ----- End ' + fname + '/' + parname + AddSpent(spent) + suffix;
end; // itFuncStop
itFuncSingleCall: begin
MakePrefix;
Result := Result + prefix + fname + '/' + parname + AddSpent(spent) + suffix;
end; //itFuncSingleCall
itFuncMultiple: begin
MakePrefix;
Result := Result + prefix + fname + '/' + parname + ' (' + IntToStr(count) + ' times)' + AddSpent(spent) + suffix;
end; //itFuncSingleCall
end; // case
end; // while
Result := Result + sprefix + hTag(html, '<BR>' ,2) + 'Debug dump ends here ---------------------------------------------' + hTag(html, '</div>', 2);
finally
udebugMutex.Release;
end;
end;
//===============================================================
procedure setUnitDebugLevel(uID: Integer; level: Integer);
begin
{$IFNDEF PKG}
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
try
WriteToRegInt(MainRegKey+'\debug\units', units[uID].name, level);
units[uID].level := level;
finally
udebugMutex.Release;
end;
{$ENDIF}
end;
//===============================================================
procedure debugStoreErrorPlace; // just visually splits log for now
begin
udebug3('-*-*-*-*-*-*-*- Error here -*-*-*-*-*-*-*-',
'-*-*-*-*-*-*-*- Error here -*-*-*-*-*-*-*-',
'-*-*-*-*-*-*-*- Error here -*-*-*-*-*-*-*-');
udebug1(udebugDumpCallStack);
end;
//===============================================================
procedure udebugSetLogFile(Aname: String);
begin
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
try
try
AssignFile(udebugLogFile, AName);
except
Exit;
end;
try
Append(udebugLogFile);
except
try
Rewrite(udebugLogFile);
except
Exit;
end;
end;
CloseFile(udebugLogFile);
finally
udebugMutex.Release;
end;
udebugLogFileName := Aname;
end;
//===============================================================
procedure debugInstantLog(const s: String; SaveInStack: Boolean = True);
begin
if udebugMutex = nil then udebugMutex := txMutex.Create(udebugMutexTimeOut);
case udebugMutex.Obtain of
twTimedOut: Exit;
//twAbandoned,
//twSuccess:
end; // case udebugMutex.Obtain of
try
if SaveInStack then pushStackInternal(s, '', '');
{try
AssignFile(F, ExtractFilePath(ParamStr(0)) + udebugLogFileName);
except
raise Exception.Create('assignfile(' + udebugLogFileName + ')');
Exit;
end;
}
if clearLog // clear log on first call
then
try
clearLog := False;
Rewrite(udebugLogFile)
except
//raise Exception.Create('rewrite1(' + udebugLogFileName + ')');
Exit;
end
else
try
Append(udebugLogFile);
except
try
Rewrite(udebugLogFile);
except
//raise Exception.Create('rewrite2(' + udebugLogFileName + ')');
Exit;
end;
end;
try
Writeln(udebugLogFile, DateToStr(now) + ' ' + TimeToStr(now) + ': ' + s);
CloseFile(udebugLogFile);
except
//raise Exception.Create(udebugLogFileName + ' write error ;)');
end;
finally
udebugMutex.Release;
end;
end;
//===============================================================
procedure debugProfilingLevel(const APL: Integer);
begin
FProfilingLevel := APL;
end;
//===============================================================
function debugMemDump(const APtr: Pointer; Alen: Integer; const ADigitGroups: Integer = 0): String;
var
pc: ^Char;
g: Integer;
begin
Result := '';
pc := APtr;
g := 0;
while ALen > 0 do begin
Result := Result + IntToHex(Byte(pc^), 2);
inc(pc);
dec(Alen);
if ADigitGroups > 0 then begin
inc(g);
if g = ADigitGroups then begin
Result := Result + ' ';
g := 0;
end;
end;
end;
end;
//===============================================================
function debugStrDump(const APtr: Pointer; const Alen: Integer = 0): String;
var
pc: ^Char;
str: Boolean;
len: Integer;
begin
Result := '';
pc := APtr;
str := False;
len := ALen;
while ((ALen <> 0) and (Len > 0)) or ((ALen = 0) and (pc^ <> #0)) do begin
if (Byte(pc^) > 32) and (Byte(pc^) < $ff) then begin
if not str then begin
str := True;
Result := Result + '''';
end;
Result := Result + pc^;
end
else begin
if str then begin
str := False;
Result := Result + ''' ';
end;
Result := Result + '0x' + IntToHex(Byte(pc^), 2) + ' ';
end;
inc(pc);
dec(len);
end;
if str then Result := Result + '''';
end;
//===============================================================
initialization
if udebugMutex = nil then udebugMutex := txMutex.Create(udebugMutexTimeOut);
//IDList := Tlist.Create;
profTopByTime_list := TStringlist.Create;
profTopByCalls_list := TStringlist.Create;
FProfilingLevel := debugLevelNone;
udebugSetLogFile(ExtractFilePath(ParamStr(0)) + 'messages.log');
//===============================================================
finalization
udebugMutex.Free;
end.
|
unit LUX.Map.D3;
interface //#################################################################### ■
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TArray3D<T_Item>
TArray3D<T_Item> = class
private
_AllX :Integer;
_AllY :Integer;
_AllZ :Integer;
///// メソッド
procedure MakeArray;
function XYZtoI( const X_,Y_,Z_:Integer ) :Integer; inline;
protected
_CountX :Integer;
_CountY :Integer;
_CountZ :Integer;
_MarginX :Integer;
_MarginY :Integer;
_MarginZ :Integer;
_Item :array of T_Item;
///// アクセス
procedure SetCountX( const CountX_:Integer );
procedure SetCountY( const CountY_:Integer );
procedure SetCountZ( const CountZ_:Integer );
procedure SetMarginX( const MarginX_:Integer );
procedure SetMarginY( const MarginY_:Integer );
procedure SetMarginZ( const MarginZ_:Integer );
function GetItem( const X_,Y_,Z_:Integer ) :T_Item;
procedure SetItem( const X_,Y_,Z_:Integer; const Item_:T_Item );
public
constructor Create; overload;
constructor Create( const CountX_,CountY_,CountZ_:Integer ); overload;
constructor Create( const CountX_,CountY_,CountZ_,Margin_:Integer ); overload;
constructor Create( const CountX_,CountY_,CountZ_,MarginX_,MarginY_,MarginZ_:Integer ); overload;
procedure AfterConstruction; override;
destructor Destroy; override;
///// プロパティ
property CountX :Integer read _CountX write SetCountX;
property CountY :Integer read _CountY write SetCountY;
property CountZ :Integer read _CountZ write SetCountZ;
property MarginX :Integer read _MarginX write SetMarginX;
property MarginY :Integer read _MarginY write SetMarginY;
property MarginZ :Integer read _MarginZ write SetMarginZ;
property Item[ const X_,Y_,Z_:Integer ] :T_Item read GetItem write SetItem; default;
///// メソッド
class procedure Swap( var Array0_,Array1_:TArray3D<T_Item> ); static;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGridMap3D<T_Item>
TGridMap3D<T_Item> = class( TArray3D<T_Item> )
private
protected
///// アクセス
function GetDivX :Integer;
procedure SetDivX( const DivX_:Integer );
function GetDivY :Integer;
procedure SetDivY( const DivY_:Integer );
function GetDivZ :Integer;
procedure SetDivZ( const DivZ_:Integer );
public
constructor Create; overload;
constructor Create( const DivX_,DivY_,DivZ_:Integer ); overload;
constructor Create( const DivX_,DivY_,DivZ_,Margin_:Integer ); overload;
constructor Create( const DivX_,DivY_,DivZ_,MarginX_,MarginY_,MarginZ_:Integer ); overload;
destructor Destroy; override;
///// プロパティ
property DivX :Integer read GetDivX write SetDivX;
property DivY :Integer read GetDivY write SetDivY;
property DivZ :Integer read GetDivZ write SetDivZ;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TArray3D<T_Item>
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
/////////////////////////////////////////////////////////////////////// メソッド
procedure TArray3D<T_Item>.MakeArray;
begin
_AllX := _MarginX + _CountX + _MarginX;
_AllY := _MarginY + _CountY + _MarginY;
_AllZ := _MarginZ + _CountZ + _MarginZ;
SetLength( _Item, _AllX * _AllY * _AllZ );
end;
function TArray3D<T_Item>.XYZtoI( const X_,Y_,Z_:Integer ) :Integer;
begin
Result := ( _MarginX + X_ ) + _AllX * ( ( _MarginY + Y_ ) + _AllY * ( _MarginZ + Z_ ) );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
procedure TArray3D<T_Item>.SetCountX( const CountX_:Integer );
begin
_CountX := CountX_; MakeArray;
end;
procedure TArray3D<T_Item>.SetCountY( const CountY_:Integer );
begin
_CountY := CountY_; MakeArray;
end;
procedure TArray3D<T_Item>.SetCountZ( const CountZ_:Integer );
begin
_CountZ := CountZ_; MakeArray;
end;
procedure TArray3D<T_Item>.SetMarginX( const MarginX_:Integer );
begin
_MarginX := MarginX_; MakeArray;
end;
procedure TArray3D<T_Item>.SetMarginY( const MarginY_:Integer );
begin
_MarginY := MarginY_; MakeArray;
end;
procedure TArray3D<T_Item>.SetMarginZ( const MarginZ_:Integer );
begin
_MarginZ := MarginZ_; MakeArray;
end;
function TArray3D<T_Item>.GetItem( const X_,Y_,Z_:Integer ) :T_Item;
begin
Result := _Item[ XYZtoI( X_, Y_, Z_ ) ];
end;
procedure TArray3D<T_Item>.SetItem( const X_,Y_,Z_:Integer; const Item_:T_Item );
begin
_Item[ XYZtoI( X_, Y_, Z_ ) ] := Item_;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TArray3D<T_Item>.Create;
begin
Create( 0, 0, 0 );
end;
constructor TArray3D<T_Item>.Create( const CountX_,CountY_,CountZ_:Integer );
begin
Create( CountX_, CountY_, CountZ_, 0 );
end;
constructor TArray3D<T_Item>.Create( const CountX_,CountY_,CountZ_,Margin_:Integer );
begin
Create( CountX_, CountY_, CountZ_, Margin_, Margin_, Margin_ );
end;
constructor TArray3D<T_Item>.Create( const CountX_,CountY_,CountZ_,MarginX_,MarginY_,MarginZ_:Integer );
begin
inherited Create;
_CountX := CountX_;
_CountY := CountY_;
_CountZ := CountZ_;
_MarginX := MarginX_;
_MarginY := MarginY_;
_MarginZ := MarginZ_;
end;
procedure TArray3D<T_Item>.AfterConstruction;
begin
MakeArray;
end;
destructor TArray3D<T_Item>.Destroy;
begin
inherited;
end;
/////////////////////////////////////////////////////////////////////// メソッド
class procedure TArray3D<T_Item>.Swap( var Array0_,Array1_:TArray3D<T_Item> );
var
A :TArray3D<T_Item>;
begin
A := Array0_; Array0_ := Array1_; Array1_ := A;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGridMap3D<T_Item>
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TGridMap3D<T_Item>.GetDivX :Integer;
begin
Result := _CountX - 1;
end;
procedure TGridMap3D<T_Item>.SetDivX( const DivX_:Integer );
begin
_CountX := DivX_ + 1; MakeArray;
end;
function TGridMap3D<T_Item>.GetDivY :Integer;
begin
Result := _CountY - 1;
end;
procedure TGridMap3D<T_Item>.SetDivY( const DivY_:Integer );
begin
_CountY := DivY_ + 1; MakeArray;
end;
function TGridMap3D<T_Item>.GetDivZ :Integer;
begin
Result := _CountZ - 1;
end;
procedure TGridMap3D<T_Item>.SetDivZ( const DivZ_:Integer );
begin
_CountZ := DivZ_ + 1; MakeArray;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TGridMap3D<T_Item>.Create;
begin
Create( 0, 0, 0 );
end;
constructor TGridMap3D<T_Item>.Create( const DivX_,DivY_,DivZ_:Integer );
begin
Create( DivX_, DivY_, DivZ_, 0 );
end;
constructor TGridMap3D<T_Item>.Create( const DivX_,DivY_,DivZ_,Margin_:Integer );
begin
Create( DivX_, DivY_, DivZ_, Margin_, Margin_, Margin_ );
end;
constructor TGridMap3D<T_Item>.Create( const DivX_,DivY_,DivZ_,MarginX_,MarginY_,MarginZ_:Integer );
begin
inherited;
_CountX := DivX_ + 1;
_CountY := DivY_ + 1;
_CountZ := DivZ_ + 1;
end;
destructor TGridMap3D<T_Item>.Destroy;
begin
inherited;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■
|
unit evConstStringStorable;
// Модуль: "w:\common\components\gui\Garant\Everest\evConstStringStorable.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevConstStringStorable" MUID: (48F49EEA0008)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, evStringStorable
, evdInterfaces
, nevTools
, l3Interfaces
, afwNavigation
;
type
TevConstStringStorable = class(TevStringStorable)
private
f_Data: IevdHyperlinkInfo;
protected
function Text: Tl3WString; override;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure GetAddress(var Addr: TevAddress); override;
procedure ClearFields; override;
public
constructor Create(const aData: IevdHyperlinkInfo;
const aReader: InevTagReader); reintroduce;
class function Make(const aData: IevdHyperlinkInfo;
const aReader: InevTagReader): IevdDataObject; reintroduce;
public
property Data: IevdHyperlinkInfo
read f_Data;
end;//TevConstStringStorable
implementation
uses
l3ImplUses
, l3Base
, l3String
//#UC START# *48F49EEA0008impl_uses*
//#UC END# *48F49EEA0008impl_uses*
;
constructor TevConstStringStorable.Create(const aData: IevdHyperlinkInfo;
const aReader: InevTagReader);
//#UC START# *4CDD2A59034A_48F49EEA0008_var*
//#UC END# *4CDD2A59034A_48F49EEA0008_var*
begin
//#UC START# *4CDD2A59034A_48F49EEA0008_impl*
inherited Create(aReader);
f_Data := aData;
//#UC END# *4CDD2A59034A_48F49EEA0008_impl*
end;//TevConstStringStorable.Create
class function TevConstStringStorable.Make(const aData: IevdHyperlinkInfo;
const aReader: InevTagReader): IevdDataObject;
var
l_Inst : TevConstStringStorable;
begin
l_Inst := Create(aData, aReader);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TevConstStringStorable.Make
function TevConstStringStorable.Text: Tl3WString;
//#UC START# *48F494FD001D_48F49EEA0008_var*
//#UC END# *48F494FD001D_48F49EEA0008_var*
begin
//#UC START# *48F494FD001D_48F49EEA0008_impl*
Result := l3PCharLen(Data.Text);
//#UC END# *48F494FD001D_48F49EEA0008_impl*
end;//TevConstStringStorable.Text
procedure TevConstStringStorable.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_48F49EEA0008_var*
//#UC END# *479731C50290_48F49EEA0008_var*
begin
//#UC START# *479731C50290_48F49EEA0008_impl*
inherited;
f_Data := nil;
//#UC END# *479731C50290_48F49EEA0008_impl*
end;//TevConstStringStorable.Cleanup
procedure TevConstStringStorable.GetAddress(var Addr: TevAddress);
//#UC START# *48F494F102DD_48F49EEA0008_var*
//#UC END# *48F494F102DD_48F49EEA0008_var*
begin
//#UC START# *48F494F102DD_48F49EEA0008_impl*
TevdAddress(Addr) := Data.Address;
//#UC END# *48F494F102DD_48F49EEA0008_impl*
end;//TevConstStringStorable.GetAddress
procedure TevConstStringStorable.ClearFields;
begin
f_Data := nil;
inherited;
end;//TevConstStringStorable.ClearFields
end.
|
{$I ViewerOptions.inc}
unit UFormPluginsOptions;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, ExtCtrls;
type
TFormPluginsOptions = class(TForm)
btnCancel: TButton;
btnOK: TButton;
boxPlugins: TGroupBox;
List: TListView;
btnAdd: TButton;
btnRemove: TButton;
btnConfig: TButton;
btnUp: TButton;
btnDown: TButton;
boxOptions: TGroupBox;
chkPriority: TCheckBox;
chkTCVar: TCheckBox;
chkHideKeys: TCheckBox;
btnHelp: TButton;
procedure btnAddClick(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
procedure btnConfigClick(Sender: TObject);
procedure btnUpClick(Sender: TObject);
procedure btnDownClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ListSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure btnHelpClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
function PluginPresent(const fn: string): boolean;
procedure AddPluginsFromTCIni(const fExeFilename, fIniFilename: string);
procedure AddPluginsFromFolder(const fn: string);
procedure AddPluginFile(const fn: string);
procedure AddPluginZip(Files: TStrings);
public
{ Public declarations }
FConfigFolder: string;
end;
function FArchiveProp(
const fn: string;
var SDesc, SType, SDefDir: string): boolean;
function FAddPluginZip(
const fn, sFolderPlugins: string;
const Handle: THandle;
var sPlugin: string): boolean;
implementation
uses
ATxSProc, ATxFProc, WLXProc,
ATxMsg, ATxMsgProc, ATViewerMsg,
ATxUtils, ATxTotalCmd, ATxVersionInfo,
ATxUnpack_Dll,
UFormPluginsAdd, UFormPluginsEdit,
IniFiles;
{$R *.DFM}
//-------------------------------------
function FArchiveProp(
const fn: string;
var SDesc, SType, SDefDir: string): boolean;
const
cInf = 'pluginst.inf';
cSec = 'plugininstall';
var
Ini: TIniFile;
fn_inf, fn_wlx: string;
begin
SDesc:= '';
SType:= '';
SDefDir:= '';
fn_inf:= FTempPath + '\' + cInf;
FDelete(fn_inf);
FUnpackSingle(fn, FTempPath, cInf);
Result:= IsFileExist(fn_inf);
if not Result then
begin
while FSearchDir('*.wlx', FTempPath, fn_wlx) do FDelete(fn_wlx);
if not FUnpackSingle(fn, FTempPath, '*.wlx') then Exit;
if not FSearchDir('*.wlx', FTempPath, fn_wlx) then Exit;
FDelete(fn_wlx);
Result:= true;
SDesc:= ChangeFileExt(ExtractFileName(fn_wlx), '');
SType:= 'wlx';
SDefDir:= SDesc;
Exit;
end;
Ini:= TIniFile.Create(fn_inf);
try
SDesc:= Ini.ReadString(cSec, 'description', '');
SType:= Ini.ReadString(cSec, 'type', '');
SDefDir:= Ini.ReadString(cSec, 'defaultdir', '');
SDefDir:= ExtractFileName(SDefDir);
finally
Ini.Free;
FDelete(fn_inf);
end;
end;
procedure ListSwapItems(List: TListView; n1, n2: integer);
var
s: string;
en: boolean;
begin
with List do
begin
Items.BeginUpdate;
s:= Items[n1].Caption;
Items[n1].Caption:= Items[n2].Caption;
Items[n2].Caption:= s;
s:= Items[n1].SubItems[0];
Items[n1].SubItems[0]:= Items[n2].SubItems[0];
Items[n2].SubItems[0]:= s;
s:= Items[n1].SubItems[1];
Items[n1].SubItems[1]:= Items[n2].SubItems[1];
Items[n2].SubItems[1]:= s;
en:= Items[n1].Checked;
Items[n1].Checked:= Items[n2].Checked;
Items[n2].Checked:= en;
Items.EndUpdate;
end;
end;
procedure ListSelect(List: TListView; n: integer);
begin
with List do
begin
if n>Items.Count-1 then Dec(n);
if n>=0 then
begin
ItemFocused:= Items[n];
Selected:= ItemFocused;
Selected.MakeVisible(false);
end;
end;
end;
procedure TFormPluginsOptions.btnAddClick(Sender: TObject);
var
fn1, fn2: AnsiString;
begin
with TFormPluginsAdd.Create(Self) do
try
if ShowModal=mrOk then
begin
fn1:= edPath1.Text;
fn2:= edPath2.Text;
if chkSrcFolder.Checked then AddPluginsFromFolder(fn1) else
if chkSrcTC.Checked then AddPluginsFromTCIni(fn2, fn1) else
if chkSrcFile.Checked then AddPluginFile(fn1) else
if chkSrcZip.Checked then AddPluginZip(OpenDialog1.Files);
end;
finally
Release;
end;
end;
procedure TFormPluginsOptions.btnRemoveClick(Sender: TObject);
var
n: integer;
begin
with List do
if Assigned(Selected) then
begin
{
if MsgBox('Do you want also to remove plugin folder:'#13 +
SExtractFileDir(Selected.SubItems[1]), MsgViewerCaption,
mb_okcancel or mb_iconwarning, Handle) = idok then
begin
end;
}
n:= Selected.Index;
List.Items.Delete(n);
ListSelect(List, n);
end;
end;
procedure TFormPluginsOptions.btnConfigClick(Sender: TObject);
begin
with List do
if Assigned(Selected) then
with Items[Selected.Index] do
with TFormPluginsEdit.Create(Self) do
try
edFilename.Text:= SubItems[1];
edDetect.Text:= SubItems[0];
if ShowModal=mrOk then
SubItems[0]:= edDetect.Text;
finally
Release;
end;
end;
procedure TFormPluginsOptions.btnUpClick(Sender: TObject);
var
n: integer;
begin
with List do
if Assigned(Selected) then
begin
n:= Selected.Index;
if n>0 then
begin
ListSwapItems(List, n, n-1);
ListSelect(List, n-1);
end;
end;
end;
procedure TFormPluginsOptions.btnDownClick(Sender: TObject);
var
n: integer;
begin
with List do
if Assigned(Selected) then
begin
n:= Selected.Index;
if n<Items.Count-1 then
begin
ListSwapItems(List, n, n+1);
ListSelect(List, n+1);
end;
end;
end;
procedure TFormPluginsOptions.FormShow(Sender: TObject);
begin
{$I Lang.FormPluginsOptions.inc}
ListSelect(List, 0);
ListSelectItem(Self, nil, false);
end;
function TFormPluginsOptions.PluginPresent(const fn: TWlxFilename): boolean;
var
i: integer;
begin
Result:= false;
with List do
for i:= 0 to Items.Count-1 do
if UpperCase(fn) = UpperCase(Items[i].SubItems[1]) then
begin Result:= true; Break end;
end;
//-----------------------------------------------
procedure TFormPluginsOptions.AddPluginsFromTCIni(const fExeFilename, fIniFilename: string);
const
Section = 'ListerPlugins';
var
i: integer;
fn: TWlxFilename;
detect, desc: string;
sAdded, sDups: string;
begin
if (fIniFilename='') or (not IsFileExist(fIniFilename)) then
begin MsgError(MsgViewerPluginsInvalidFile, Handle); Exit end;
if (fExeFilename='') or (Pos('Total Commander', FGetVersionInfo(fExeFilename, vsFileDescription))=0) then
begin MsgError(MsgViewerPluginsInvalidTCExe, Handle); Exit end;
SetEnvironmentVariable('COMMANDER_PATH', PChar(ExtractFileDir(fExeFilename)));
sAdded:= '';
sDups:= '';
with List do
begin
//Items.BeginUpdate;
for i:= 0 to WlxPluginsMaxCount-1 do
begin
SetTcIniFilename(fIniFilename);
fn:= GetTcIniKey(Section, IntToStr(i));
fn:= SExpandVars(fn);
if fn='' then Break;
detect:= GetTcIniKey(Section, IntToStr(i)+'_detect');
if detect='' then
detect:= WlxGetDetectString(fn);
desc:= SPluginName(fn);
if PluginPresent(fn) then
begin
sDups:= sDups + desc + #13;
end
else
begin
sAdded:= sAdded + desc + #13;
with Items.Add do
begin
Checked:= true;
Caption:= desc;
SubItems.Add(detect);
SubItems.Add(fn);
end;
end;
end;
//Items.EndUpdate;
MsgInstall(sAdded, sDups, False, Handle);
end;
end;
//-----------------------------------------------
procedure TFormPluginsOptions.AddPluginFile(const fn: TWlxFilename);
var
detect, desc: string;
sAdded, sDups: string;
begin
if (fn='') or (not IsFileExist(fn)) then
begin MsgError(MsgViewerPluginsInvalidFile, Handle); Exit end;
sAdded:= '';
sDups:= '';
detect:= WlxGetDetectString(fn);
desc:= SPluginName(fn);
if PluginPresent(fn) then
begin
sDups:= sDups+desc+#13;
end
else
begin
sAdded:= sAdded+desc+#13;
with List.Items.Add do
begin
Checked:= true;
Caption:= desc;
SubItems.Add(detect);
SubItems.Add(fn);
end;
end;
MsgInstall(sAdded, sDups, False, Handle);
end;
//-----------------------------------------------
function SFolderNameFromZipFile(const fn: string): string;
begin
//Strip extension
Result:= ChangeFileExt(ExtractFileName(fn), '');
//Strip trailing numbers
while (Result <> '') and
(Result[Length(Result)] in ['0'..'9', '.', '_', '-']) do
SetLength(Result, Length(Result) - 1);
end;
//-----------------------------------------------
function FAddPluginZip(
const fn, sFolderPlugins: string;
const Handle: THandle;
var sPlugin: string): boolean;
const
cInf = 'pluginst.inf';
var
SDesc, SType, SDefDir,
sFolder: string;
begin
Result:= false;
sPlugin:= '';
FArchiveProp(fn, SDesc, SType, SDefDir);
if sDefDir <> '' then
sFolder:= sFolderPlugins + '\' + sDefDir
else
sFolder:= sFolderPlugins + '\' + SFolderNameFromZipFile(fn);
if not IsFileExist(fn) then
begin MsgError(MsgViewerPluginsInvalidFile, Handle); Exit end;
if not FUnpackAll(fn, sFolder) then
begin MsgError(Format(MsgString(215), [ExtractFileName(fn), sFolder]), Handle); Exit end;
if not FSearchDir('*.wlx', sFolder, sPlugin) then
begin MsgError(Format(MsgString(216), [ExtractFileName(fn)]), Handle); Exit end;
DeleteFile(PChar(sFolder + '\' + cInf));
Result:= true;
end;
//-----------------------------------------------
procedure TFormPluginsOptions.AddPluginZip(Files: TStrings);
var
detect, desc: string;
sAdded, sDups: string;
sFolderPlugins, sPlugin: string;
i: integer;
begin
sAdded:= '';
sDups:= '';
sFolderPlugins:= FConfigFolder + '\Plugins';
FCreateDir(sFolderPlugins);
for i:= 0 to Files.Count - 1 do
begin
if not FAddPluginZip(Files[i],
sFolderPlugins, Handle, sPlugin) then Continue;
detect:= WlxGetDetectString(sPlugin);
desc:= SPluginName(sPlugin);
if PluginPresent(sPlugin) then
begin
sDups:= sDups + desc + #13;
end
else
begin
sAdded:= sAdded + desc + #13;
with List.Items.Add do
begin
Checked:= true;
Caption:= desc;
SubItems.Add(detect);
SubItems.Add(sPlugin);
end;
end;
Application.ProcessMessages;
end;
MsgInstall(sAdded, sDups, True, Handle);
end;
//-----------------------------------------------
procedure TFormPluginsOptions.AddPluginsFromFolder(const fn: TWlxFilename);
begin
//
end;
//-----------------------------------------------
procedure TFormPluginsOptions.ListSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
var
Sel: boolean;
begin
Sel:= Assigned(List.Selected);
btnRemove.Enabled:= Sel;
btnConfig.Enabled:= Sel;
btnUp.Enabled:= Sel and (List.Selected.Index > 0);
btnDown.Enabled:= Sel and (List.Selected.Index < List.Items.Count - 1);
end;
procedure TFormPluginsOptions.btnHelpClick(Sender: TObject);
begin
ShowHelp(Handle, 'Plugins.html');
end;
procedure TFormPluginsOptions.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_INSERT then
btnAddClick(Self)
else
if Key = VK_DELETE then
btnRemoveClick(Self);
end;
end.
|
unit Processor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Utils, StdCtrls, ComCtrls, ExtCtrls, DialMessages;
type
TCreateThumbnail = procedure(const PictureFile, ThumbnailFile: string;
const Size: Integer);
TProcessorForm = class(TForm)
ProgressLabel: TLabel;
ProgressBar: TProgressBar;
CancelButton: TButton;
RunJob: TTimer;
ImageCounterLabel: TLabel;
procedure CancelButtonClick(Sender: TObject);
procedure RunJobTimer(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
ImagingDLLInstance: THandle;
CreateThumbnail: TCreateThumbnail;
Language: TLanguage;
Preset: TPreset;
function IndexName(const Num: Integer): string;
function ImageName(const Num: Integer): string;
function IndexLinkList(const Current, Total: Integer): string;
procedure GenerateIndex(ImageList: TStringList);
procedure GenerateImagePage(ImageList: TStringList;
const ImageIndex: Integer);
public
{ Public declarations }
Canceled: Boolean;
constructor Create(AOwner: TComponent; const Language: TLanguage;
const Preset: TPreset); reintroduce;
end;
var
ProcessorForm: TProcessorForm;
implementation
uses Math;
{$R *.dfm}
const
ImagingDLL: string = 'VampImg.dll';
CreateThumbnailProc: string = 'ProportionalResize';
ImageExtensions: array[0..6] of string = ('.jpg', 'jpeg', '.gif', '.png',
'.tif', '.tiff', '.bmp');
ImageNameFiller: Char = '0';
HTMLFileExtension: string = '.htm';
HTMLIndexName: string = 'index';
ThumbnailSuffix: string = '_small';
resourcestring
rsImagingDLLLoadingError = 'Error loading %s!';
{ TProgressForm }
constructor TProcessorForm.Create(AOwner: TComponent;
const Language: TLanguage; const Preset: TPreset);
begin
inherited Create(AOwner);
Self.Language := Language;
Self.Preset := Preset;
Canceled := False;
end;
procedure TProcessorForm.CancelButtonClick(Sender: TObject);
begin
Canceled := True;
end;
procedure TProcessorForm.RunJobTimer(Sender: TObject);
var
ImageList: TStringList;
ImageExtensionCounter: Integer;
ImageCounter: Integer;
begin
RunJob.Enabled := False;
ImagingDLLInstance := LoadLibrary(PAnsiChar(ExtractFilePath(ApplicationFileName) + ImagingDLL));
if ImagingDLLInstance <> 0 then
begin
@CreateThumbnail := GetProcAddress(ImagingDLLInstance, PChar(CreateThumbnailProc));
ImageList := TStringList.Create;
try
for ImageExtensionCounter := 0 to Length(ImageExtensions) - 1 do
begin
ListFileDir(ImageList, Preset.Directories.Images, ChangeFileExt(AllFileNamesMask, ImageExtensions[ImageExtensionCounter]), True);
end;
ImageList.Sort;
GenerateIndex(ImageList);
ProgressBar.Max := Min(Preset.Album.MaxImageCount, ImageList.Count);
for ImageCounter := 0 to ImageList.Count - 1 do
begin
if Canceled then
begin
Break;
end;
GenerateImagePage(ImageList, ImageCounter);
CopyFile(PChar(IncludeTrailingPathDelimiter(Preset.Directories.Images) + ImageList[ImageCounter]), PChar(IncludeTrailingPathDelimiter(Preset.Directories.Output) + ImageName(ImageCounter + 1) + ExtractFileExt(ImageList[ImageCounter])), False);
CreateThumbnail(IncludeTrailingPathDelimiter(Preset.Directories.Images) + ImageList[ImageCounter], IncludeTrailingPathDelimiter(Preset.Directories.Output) + ImageName(ImageCounter + 1) + ThumbnailSuffix + ExtractFileExt(ImageList[ImageCounter]), Preset.Thumbnails.Size);
ImageCounterLabel.Caption := IntToStr(ImageCounter + 1);
ProgressBar.StepIt;
Application.ProcessMessages;
if (ImageCounter = Preset.Album.MaxImageCount - 1) then
begin
Break;
end;
end;
finally
FreeAndNil(ImageList);
end;
end
else
begin
ErrorMsg(Format(rsImagingDLLLoadingError, [ImagingDLL]));
end;
Close;
end;
procedure TProcessorForm.FormActivate(Sender: TObject);
begin
RunJob.Enabled := True;
end;
procedure TProcessorForm.GenerateIndex(ImageList: TStringList);
var
HTMLFile: TextFile;
IndexCount, IndexCounter: Integer;
StartIndex, EndIndex: Integer;
ImageCount: Integer;
ImageCounter: Integer;
begin
IndexCount := Min(Preset.Album.MaxImageCount, ImageList.Count) div (Preset.Index.ColCount * Preset.Index.RowCount) + Sign(Min(Preset.Album.MaxImageCount, ImageList.Count) mod (Preset.Index.ColCount * Preset.Index.RowCount));
for IndexCounter := 0 to IndexCount - 1 do
begin
StartIndex := IndexCounter * Preset.Index.ColCount * Preset.Index.RowCount;
if IndexCounter < IndexCount - 1 then
begin
EndIndex := (IndexCounter + 1) * Preset.Index.ColCount * Preset.Index.RowCount - 1;
end
else
begin
EndIndex := Min(Preset.Album.MaxImageCount, ImageList.Count) - 1;
end;
AssignFile(HTMLFile, IncludeTrailingPathDelimiter(Preset.Directories.Output) + IndexName(IndexCounter + 1) + HTMLFileExtension);
try
Rewrite(HTMLFile);
Writeln(HTMLFile, '<html>');
Writeln(HTMLFile, ' <head>');
Writeln(HTMLFile, ' <meta http-equiv="Content-Type" content="text/html; charset=' + Language.System.Charset + '">');
Writeln(HTMLFile, ' <link rel="stylesheet" type="text/css" href="' + Preset.Misc.CSSFileURL + '">');
Writeln(HTMLFile, ' <title>' + Preset.Album.Title + '</title>');
Writeln(HTMLFile, ' </head>');
Writeln(HTMLFile, ' <body>');
Writeln(HTMLFile, ' <table width=100% height=100%>');
Writeln(HTMLFile, ' <tbody>');
Writeln(HTMLFile, ' <tr valign="center">');
Writeln(HTMLFile, ' <td align="center">');
Writeln(HTMLFile, ' <table align="center" width="' + IntToStr(Preset.Index.ColCount * (Preset.Thumbnails.Indent + Preset.Thumbnails.Size + Preset.Thumbnails.Indent)) + '" style="font-family: Tahoma, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: normal">');
Writeln(HTMLFile, ' <tbody>');
if Preset.Album.Title <> EmptyStr then
begin
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '"><br></td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '" align="center"><h1>' + Preset.Album.Title + '</h1></td>');
Writeln(HTMLFile, ' </tr>');
end;
if Preset.Album.Description <> EmptyStr then
begin
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '" align="center">' + Preset.Album.Description + '</td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '"><br></td>');
Writeln(HTMLFile, ' </tr>');
end;
if (Preset.Album.MainPageURL <> EmptyStr) and (Preset.Album.MainPageLink <> EmptyStr) then
begin
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '" align="center"><a href="' + Preset.Album.MainPageURL + '" title="' + Language.Titles.MainPage + '">' + Preset.Album.MainPageLink + '</a></td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '"><br></td>');
Writeln(HTMLFile, ' </tr>');
end;
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '" align="center">' + Language.Links.ThumbnailsHint + '</td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '"><br></td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '"><hr></td>');
Writeln(HTMLFile, ' </tr>');
ImageCount := 0;
Writeln(HTMLFile, ' <tr>');
for ImageCounter := StartIndex to EndIndex do
begin
Inc(ImageCount);
if (ImageCount mod Preset.Index.ColCount = 1) and (ImageCount > 1) then
begin
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
end;
Writeln(HTMLFile, ' <td align="center" valign="center" width="' + IntToStr(Preset.Thumbnails.Indent + Preset.Thumbnails.Size + Preset.Thumbnails.Indent) + '" height="' + IntToStr(Preset.Thumbnails.Indent + Preset.Thumbnails.Size + Preset.Thumbnails.Indent) + '"><a href="' + ImageName(ImageCounter + 1) + HTMLFileExtension + '" title="' + ImageName(ImageCounter + 1) + ExtractFileExt(ImageList[ImageCounter]) + '"><img src="' + ImageName(ImageCounter + 1) + ThumbnailSuffix + ExtractFileExt(ImageList[ImageCounter]) + '" alt="' + ImageName(ImageCounter + 1) + ExtractFileExt(ImageList[ImageCounter]) + '" border="0"></a></td>');
end;
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '"><hr></td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '"><br></td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '" align="center" style="font-family: Tahoma, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: normal">' + IndexLinkList(IndexCounter + 1, IndexCount) + '</td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="' + IntToStr(Preset.Index.ColCount) + '"><br></td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' </tbody>');
Writeln(HTMLFile, ' </table>');
Writeln(HTMLFile, ' </td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' </tbody>');
Writeln(HTMLFile, ' </table>');
Writeln(HTMLFile, ' </body>');
Writeln(HTMLFile, '</html>');
finally
CloseFile(HTMLFile);
end;
end;
end;
function TProcessorForm.IndexName(const Num: Integer): string;
begin
if Num = 1 then
begin
Result := HTMLIndexName;
end
else
begin
Result := HTMLIndexName + IntToStr(Num);
end;
end;
function TProcessorForm.IndexLinkList(const Current,
Total: Integer): string;
const
ItemBegin: string = '[';
ItemEnd: string = ']';
var
Counter: Integer;
begin
Result := EmptyStr;
for Counter := 1 to Total do
begin
if Result <> EmptyStr then
begin
Result := Result + Space;
end;
if Counter = Current then
begin
Result := Result + ItemBegin + IntToStr(Counter) + ItemEnd;
end
else
begin
Result := Result + '<a href="' + IndexName(Counter) + HTMLFileExtension + '" title="' + Format(Language.Titles.IndexNum, [Counter]) + '">' + ItemBegin + IntToStr(Counter) + ItemEnd + '</a>';
end;
end;
end;
procedure TProcessorForm.GenerateImagePage(ImageList: TStringList;
const ImageIndex: Integer);
var
HTMLFile: TextFile;
begin
AssignFile(HTMLFile, IncludeTrailingPathDelimiter(Preset.Directories.Output) + ImageName(ImageIndex + 1) + HTMLFileExtension);
try
Rewrite(HTMLFile);
Writeln(HTMLFile, '<html>');
Writeln(HTMLFile, ' <head>');
Writeln(HTMLFile, ' <meta http-equiv="Content-Type" content="text/html; charset=' + Language.System.Charset + '">');
Writeln(HTMLFile, ' <link rel="stylesheet" type="text/css" href="' + Preset.Misc.CSSFileURL + '">');
Writeln(HTMLFile, ' <title>' + ChangeFileExt(ImageList[ImageIndex], EmptyStr) + '</title>');
Writeln(HTMLFile, ' </head>');
Writeln(HTMLFile, ' <body>');
Writeln(HTMLFile, ' <table width=100% height=100%>');
Writeln(HTMLFile, ' <tbody>');
Writeln(HTMLFile, ' <tr valign="center">');
Writeln(HTMLFile, ' <td align="center">');
Writeln(HTMLFile, ' <table align="center" style="font-family: Tahoma, Arial, Helvetica, sans-serif; font-size: 10pt; font-weight: normal">');
Writeln(HTMLFile, ' <tbody>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="3"><br></td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="3"><img src="' + ImageName(ImageIndex + 1) + ExtractFileExt(ImageList[ImageIndex]) + '" alt="' + ImageName(ImageIndex + 1) + ExtractFileExt(ImageList[ImageIndex]) + '"></td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="3"><br></td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
if ImageIndex > 0 then
begin
Writeln(HTMLFile, ' <td align="left" width="200"><a href="' + ImageName((ImageIndex - 1) + 1) + HTMLFileExtension + '" title="' + Language.Titles.Previous + '"><< ' + Language.Links.Previous + '</a></td>');
end
else
begin
Writeln(HTMLFile, ' <td align="left" width="200"><< ' + Language.Links.Previous + '</td>');
end;
if Preset.Misc.ShowIndexLink then
begin
Writeln(HTMLFile, ' <td align="center"><a href="' + IndexName(Trunc((ImageIndex + 1) / (Preset.Index.ColCount * Preset.Index.RowCount)) + 1) + HTMLFileExtension + '" title="' + Language.Titles.Index + '">' + Language.Links.Index + '</a></td>')
end
else
begin
Writeln(HTMLFile, ' <td align="center"></td>');
end;
if ImageIndex < ImageList.Count - 1 then
begin
Writeln(HTMLFile, ' <td align="right" width="200"><a href="' + ImageName((ImageIndex + 1) + 1) + HTMLFileExtension + '" title="' + Language.Titles.Next + '">' + Language.Links.Next + ' >></a></td>');
end
else
begin
Writeln(HTMLFile, ' <td align="right" width="200">' + Language.Links.Next + ' >></td>');
end;
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' <tr>');
Writeln(HTMLFile, ' <td colspan="3"><br></td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' </tbody>');
Writeln(HTMLFile, ' </table>');
Writeln(HTMLFile, ' </td>');
Writeln(HTMLFile, ' </tr>');
Writeln(HTMLFile, ' </tbody>');
Writeln(HTMLFile, ' </table>');
Writeln(HTMLFile, ' </body>');
Writeln(HTMLFile, '</html>');
finally
CloseFile(HTMLFile);
end;
end;
function TProcessorForm.ImageName(const Num: Integer): string;
begin
Result := IntToStr(Num);
while Length(Result) < Length(IntToStr(Preset.Album.MaxImageCount)) do
begin
Result := ImageNameFiller + Result;
end;
end;
end.
|
unit GPSParametersUnit;
interface
uses
HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit,
NullableBasicTypesUnit, GenericParametersUnit;
type
TGPSParameters = class(TGenericParameters)
private
[HttpQueryMember('format')]
[Nullable]
FFormat: NullableString;
[HttpQueryMember('member_id')]
[Nullable]
FMemberId: NullableInteger;
[HttpQueryMember('route_id')]
[Nullable]
FRouteId: NullableString;
[HttpQueryMember('tx_id')]
[Nullable]
FTxId: NullableString;
[HttpQueryMember('vehicle_id')]
[Nullable]
FVehicleId: NullableInteger;
[HttpQueryMember('course')]
[Nullable]
FCourse: NullableInteger;
[HttpQueryMember('speed')]
[Nullable]
FSpeed: NullableDouble;
[HttpQueryMember('lat')]
[Nullable]
FLatitude: NullableDouble;
[HttpQueryMember('lng')]
[Nullable]
FLongitude: NullableDouble;
[HttpQueryMember('altitude')]
[Nullable]
FAltitude: NullableDouble;
[HttpQueryMember('device_type')]
[Nullable]
FDeviceType: NullableString;
[HttpQueryMember('device_guid')]
[Nullable]
FDeviceGuid: NullableString;
[HttpQueryMember('device_timestamp')]
[Nullable]
FDeviceTimestamp: NullableString;
[HttpQueryMember('app_version')]
[Nullable]
FAppVersion: NullableString;
public
constructor Create; override;
property Format: NullableString read FFormat write FFormat;
property MemberId: NullableInteger read FMemberId write FMemberId;
property RouteId: NullableString read FRouteId write FRouteId;
property TxId: NullableString read FTxId write FTxId;
property VehicleId: NullableInteger read FVehicleId write FVehicleId;
property Course: NullableInteger read FCourse write FCourse;
property Speed: NullableDouble read FSpeed write FSpeed;
property Latitude: NullableDouble read FLatitude write FLatitude;
property Longitude: NullableDouble read FLongitude write FLongitude;
property Altitude: NullableDouble read FAltitude write FAltitude;
property DeviceType: NullableString read FDeviceType write FDeviceType;
property DeviceGuid: NullableString read FDeviceGuid write FDeviceGuid;
property DeviceTimestamp: NullableString read FDeviceTimestamp write FDeviceTimestamp;
property AppVersion: NullableString read FAppVersion write FAppVersion;
end;
implementation
{ TActivityParameters }
constructor TGPSParameters.Create;
begin
Inherited Create;
FFormat := NullableString.Null;
FMemberId := NullableInteger.Null;
FRouteId := NullableString.Null;
FTxId := NullableString.Null;
FVehicleId := NullableInteger.Null;
FCourse := NullableInteger.Null;
FSpeed := NullableDouble.Null;
FLatitude := NullableDouble.Null;
FLongitude := NullableDouble.Null;
FAltitude := NullableDouble.Null;
FDeviceType := NullableString.Null;
FDeviceGuid := NullableString.Null;
FDeviceTimestamp := NullableString.Null;
FAppVersion := NullableString.Null;
end;
end.
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Actions.Wait;
interface
uses
System.JSON,
Behavior3, Behavior3.Core.Action, Behavior3.Core.BaseNode, Behavior3.Core.Tick;
type
(**
* Wait a few seconds.
*
* @module b3
* @class Wait
* @extends Action
**)
TB3Wait = class(TB3Action)
private
protected
public
//* - **milliseconds** (*Integer*) Maximum time, in milliseconds, a child
//* can execute.
Milliseconds: Integer;
constructor Create; override;
(**
* Open method.
* @method open
* @param {Tick} tick A tick instance.
**)
procedure Open(Tick: TB3Tick); override;
(**
* Tick method.
* @method tick
* @param {Tick} tick A tick instance.
* @return {Constant} Always return `b3.SUCCESS`.
**)
function Tick(Tick: TB3Tick): TB3Status; override;
procedure Load(JsonNode: TJSONValue); override;
end;
implementation
{ TB3Wait }
uses
System.SysUtils, System.Diagnostics, System.TimeSpan,
Behavior3.Helper, Behavior3.Core.BehaviorTree;
constructor TB3Wait.Create;
begin
inherited;
(**
* Node name. Default to `Wait`.
* @property {String} name
* @readonly
**)
Name := 'Wait';
(**
* Node title. Default to `Wait XXms`. Used in Editor.
* @property {String} title
* @readonly
**)
Title := 'Wait <milliseconds>ms';
Milliseconds := 0;
end;
procedure TB3Wait.Open(Tick: TB3Tick);
begin
Tick.Blackboard.&Set('startTime', TStopWatch.GetTimeStamp, Tick.Tree.Id, Id);
end;
function TB3Wait.Tick(Tick: TB3Tick): TB3Status;
var
ElapsedTime, CurrTime, StartTime: Int64;
begin
CurrTime := TStopWatch.GetTimeStamp;
StartTime := Tick.Blackboard.Get('startTime', Tick.Tree.Id, Id).AsInt64;
ElapsedTime := (CurrTime - StartTime) div TTimeSpan.TicksPerMillisecond;
if ElapsedTime > Milliseconds then
Result := Behavior3.Success
else
Result := Behavior3.Running;
end;
procedure TB3Wait.Load(JsonNode: TJSONValue);
begin
inherited;
Milliseconds := LoadProperty(JsonNode, 'milliseconds', Milliseconds);
end;
end.
|
unit clRoteiroEntregador;
interface
uses
Vcl.Forms, System.SysUtils, System.Classes, Vcl.dialogs, clConexao, udm;
type
TRoteiroEntregador = class(TObject)
private
FRoteiroAntigo: String;
FRoteiroNovo: String;
FLog: String;
conexao: TConexao;
FID: Integer;
FDescricao: String;
FMostrar: String;
procedure SetRoteiroAntigo(val: String);
procedure SetRoteiroNovo(val: String);
procedure SetLog(val: String);
procedure SetID(val: Integer);
procedure SetDescricao(val: String);
procedure SetMostrar(val: String);
public
property RoteiroAntigo: String read FRoteiroAntigo write SetRoteiroAntigo;
property RoteiroNovo: String read FRoteiroNovo write SetRoteiroNovo;
property Log: String read FLog write SetLog;
property ID: Integer read FID write SetID;
property Descricao: String read FDescricao write SetDescricao;
property Mostrar: String read FMostrar write SetMostrar;
function Validar: Boolean; reintroduce;
function Insert: Boolean;
function Update: Boolean;
function Delete(sFiltro: String): Boolean;
function getObject(sId: String; sFiltro: String): Boolean;
function getField(sCampo: String; sFiltro: String): String;
function Exist: Boolean;
constructor Create;
destructor Destroy; override;
end;
const
TABLENAME = 'JOR_ROTEIRO_ENTREGADOR';
implementation
procedure TRoteiroEntregador.SetRoteiroAntigo(val: String);
begin
FRoteiroAntigo := val;
end;
procedure TRoteiroEntregador.SetRoteiroNovo(val: String);
begin
FRoteiroNovo := val;
end;
procedure TRoteiroEntregador.SetLog(val: String);
begin
FLog := val;
end;
procedure TRoteiroEntregador.SetID(val: Integer);
begin
FID := val;
end;
procedure TRoteiroEntregador.SetDescricao(val: String);
begin
FDescricao := val;
end;
procedure TRoteiroEntregador.SetMostrar(val: String);
begin
FMostrar := val;
end;
function TRoteiroEntregador.Validar: Boolean;
begin
Result := False;
if Self.Descricao.IsEmpty then
begin
MessageDlg('Informe a descrição do Roteiro!', mtWarning, [mbOK], 0);
Exit;
end;
if Self.RoteiroAntigo.IsEmpty then
begin
MessageDlg('Informe o código do roteiro antigo!', mtWarning, [mbOK], 0);
Exit;
end;
if Self.RoteiroNovo.IsEmpty then
begin
MessageDlg('Informe o código do roteiro novo!', mtWarning, [mbOK], 0);
Exit;
end;
Result := True;
end;
function TRoteiroEntregador.Insert: Boolean;
begin
Result := False;
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0);
Exit;
end;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
dm.qryCRUD.SQL.Text := 'INSERT INTO ' + TABLENAME + '(' +
'DES_ROTEIRO, ' +
'COD_ROTEIRO_ANTIGO, ' +
'COD_ROTEIRO_NOVO, ' +
'DOM_MOSTRAR, ' +
'DES_LOG) ' +
'VALUES (' +
':DESCRICAO, ' +
':ROTEIROANTIGO, ' +
':ROTEIRONOVO, ' +
':MOSTRAR, ' +
':LOG);';
dm.qryCRUD.ParamByName('DESCRICAO').AsString := Self.Descricao;
dm.qryCRUD.ParamByName('ROTEIROANTIGO').AsString := Self.RoteiroAntigo;
dm.qryCRUD.ParamByName('ROTEIRONOVO').AsString := Self.RoteiroNovo;
dm.qryCRUD.ParamByName('MOSTRAR').AsString := Self.Mostrar;
dm.qryCRUD.ParamByName('LOG').AsString := Self.Log;
dm.ZConn.PingServer;
dm.qryCRUD.ExecSQL;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
Result := True;
end;
function TRoteiroEntregador.Update: Boolean;
begin
Result := False;
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0);
Exit;
end;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
dm.qryCRUD.SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' +
'DES_ROTEIRO = :DESCRICAO, ' +
'COD_ROTEIRO_ANTIGO = :ROTEIROANTIGO, ' +
'COD_ROTEIRO_NOVO = :ROTEIRONOVO, ' +
'DOM_MOSTRAR = :MOSTRAR, ' +
'DES_LOG = :LOG ' +
'WHERE ' +
'ID_ROTEIRO = :ID;';
dm.qryCRUD.ParamByName('ID').AsInteger := Self.ID;
dm.qryCRUD.ParamByName('DESCRICAO').AsString := Self.Descricao;
dm.qryCRUD.ParamByName('ROTEIROANTIGO').AsString := Self.RoteiroAntigo;
dm.qryCRUD.ParamByName('ROTEIRONOVO').AsString := Self.RoteiroNovo;
dm.qryCRUD.ParamByName('MOSTRAR').AsString := Self.Mostrar;
dm.qryCRUD.ParamByName('LOG').AsString := Self.Log;
dm.ZConn.PingServer;
dm.qryCRUD.ExecSQL;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
Result := True;
end;
function TRoteiroEntregador.Delete(sFiltro: String): Boolean;
begin
Result := False;
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0);
Exit;
end;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
dm.qryCRUD.SQL.Add('DELETE FROM ' + TABLENAME);
if sFiltro = 'ID' then
begin
dm.qryCRUD.SQL.Add('WHERE ID_ROTEIRO = :ID');
dm.qryCRUD.ParamByName('ID').AsInteger := Self.ID;
end
else if sFiltro = 'ANTIGO' then
begin
dm.qryCRUD.SQL.Add('WHERE COD_ROTEIRO_ANTIGO = :ROTEIROANTIGO');
dm.qryCRUD.ParamByName('ROTEIROANTIGO').AsString := Self.RoteiroAntigo;
end
else if sFiltro = 'NOVO' then
begin
dm.qryCRUD.SQL.Add('WHERE COD_ROTEIRO_NOVO = :ROTEIRONOVO');
dm.qryCRUD.ParamByName('ROTEIRONOVO').AsString := Self.RoteiroNovo;
end;
dm.ZConn.PingServer;
dm.qryCRUD.ExecSQL;
dm.qryCRUD.Close;
dm.qryCRUD.SQL.Clear;
Result := True;
end;
function TRoteiroEntregador.getObject(sId: String; sFiltro: String): Boolean;
begin
Result := False;
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0);
Exit;
end;
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
dm.qryGetObject.SQL.Add('SELECT * FROM ' + TABLENAME);
if sFiltro = 'ID' then
begin
dm.qryGetObject.SQL.Add('WHERE ID_ROTEIRO = :ID');
dm.qryGetObject.ParamByName('ID').AsInteger := StrToIntDef(sId, 0);
end
else if sFiltro = 'DESCRICAO' then
begin
dm.qryGetObject.SQL.Add('WHERE DES_ROTEIRO LIKE :DESCRICAO');
dm.qryGetObject.ParamByName('DESCRICAO').AsString := '%' + sId + '%';
end
else if sFiltro = 'ANTIGO' then
begin
dm.qryGetObject.SQL.Add('WHERE COD_ROTEIRO_ANTIGO = :ROTEIROANTIGO');
dm.qryGetObject.ParamByName('ROTEIROANTIGO').AsString := sId;
end
else if sFiltro = 'NOVO' then
begin
dm.qryGetObject.SQL.Add('WHERE COD_ROTEIRO_NOVO = :ROTEIRONOVO');
dm.qryCRUD.ParamByName('ROTEIRONOVO').AsString := sId;
end;
dm.ZConn.PingServer;
dm.qryGetObject.Open;
if dm.qryGetObject.IsEmpty then
begin
dm.qryGetObject.Close;
dm.qryGetObject.SQL.Clear;
Exit;
end
else
begin
dm.qryGetObject.First;
Self.ID := dm.qryGetObject.FieldByName('ID_ROTEIRO').AsInteger;
Self.Descricao := dm.qryGetObject.FieldByName('DES_ROTEIRO').AsString;
Self.RoteiroAntigo := dm.qryGetObject.FieldByName('COD_ROTEIRO_ANTIGO').AsString;
Self.RoteiroNovo := dm.qryGetObject.FieldByName('COD_ROTEIRO_NOVO').AsString;
Self.Mostrar := dm.qryGetObject.FieldByName('DOM_MOSTRAR').AsString;
Self.Log := dm.qryGetObject.FieldByName('DES_LOG').AsString;
end;
Result := True;
end;
function TRoteiroEntregador.getField(sCampo: String; sFiltro: String): String;
begin
Result := '';
//if (not conexao.VerifyConnZEOS(0)) then
//begin
// MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0);
// Exit;
//end;
dm.qryFields.Close;
dm.qryFields.SQL.Clear;
dm.qryFields.SQL.Add('SELECT ' + sCampo + ' FROM ' + TABLENAME);
if sFiltro = 'ID' then
begin
dm.qryFields.SQL.Add('WHERE ID_ROTEIRO = :ID');
dm.qryFields.ParamByName('ID').AsInteger := Self.ID;
end
else if sFiltro = 'ANTIGO' then
begin
dm.qryFields.SQL.Add('WHERE COD_ROTEIRO_ANTIGO = :ROTEIROANTIGO');
dm.qryFields.ParamByName('ROTEIROANTIGO').AsString := Self.RoteiroAntigo;
end
else if sFiltro = 'NOVO' then
begin
dm.qryFields.SQL.Add('WHERE COD_ROTEIRO_NOVO = :ROTEIRONOVO');
dm.qryFields.ParamByName('ROTEIRONOVO').AsString := Self.RoteiroNovo;
end
else if sFiltro = 'CHAVE' then
begin
dm.qryFields.SQL.Add('WHERE COD_ROTEIRO_ANTIGO = :ROTEIROANTIGO AND COD_ROTEIRO_NOVO = :ROTEIRONOVO');
dm.qryFields.ParamByName('ROTEIROANTIGO').AsString := Self.RoteiroAntigo;
dm.qryFields.ParamByName('ROTEIRONOVO').AsString := Self.RoteiroNovo;
end;
dm.ZConn.PingServer;
dm.qryFields.Open;
if not dm.qryFields.IsEmpty then
begin
Result := dm.qryFields.FieldByName(sCampo).AsString;
end;
dm.qryFields.Close;
dm.qryFields.SQL.Clear;
end;
function TRoteiroEntregador.Exist: Boolean;
begin
Result := False;
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0);
Exit;
end;
dm.qryPesquisa.Close;
dm.qryPesquisa.SQL.Clear;
dm.qryPesquisa.SQL.Add('SELECT * FROM ' + TABLENAME);
dm.qryPesquisa.SQL.Add('WHERE COD_ROTEIRO_ANTIGO = :ROTEIROANTIGO AND COD_ROTEIRO_NOVO = :ROTEIRONOVO');
dm.qryPesquisa.ParamByName('ROTEIROANTIGO').AsString := Self.RoteiroAntigo;
dm.qryPesquisa.ParamByName('ROTEIRONOVO').AsString := Self.RoteiroNovo;
dm.ZConn.PingServer;
dm.qryPesquisa.Open;
if dm.qryPesquisa.IsEmpty then
begin
dm.qryPesquisa.Close;
dm.qryPesquisa.SQL.Clear;
Exit;
end
else
begin
dm.qryPesquisa.Close;
dm.qryPesquisa.SQL.Clear;
end;
Result := True;
end;
constructor TRoteiroEntregador.Create;
begin
inherited Create;
conexao := TConexao.Create;
end;
destructor TRoteiroEntregador.Destroy;
begin
conexao.Free;
inherited Destroy;
end;
end.
|
{
Clever Internet Suite
Copyright (C) 2014 Clever Components
All Rights Reserved
www.CleverComponents.com
}
unit clSFtp;
interface
{$I ..\common\clVer.inc}
uses
{$IFNDEF DELPHIXE2}
Classes, SysUtils,{$IFDEF DEMO}Forms, Windows,{$ENDIF}
{$ELSE}
System.Classes, System.SysUtils,{$IFDEF DEMO}Vcl.Forms, Winapi.Windows,{$ENDIF}
{$ENDIF}
clSocket, clTcpClient, clUtils, clSshSocket, clSshPacket, clConfig,
clSshConfig, clTranslator, clSFtpUtils, clSshUserKey, clSshUserIdentity, clSshAuth;
type
TclSFtpCommandEvent = procedure(Sender: TObject; AFxpCommand: Integer; ABuffer: TStream) of object;
TclSFtpDirectoryListingEvent = procedure(Sender: TObject; const AFileName: string; AFileAttrs: TclSFtpFileAttrs) of object;
TclSFtp = class(TclTcpClient)
private
FConfig: TclConfig;
FRootDir: string;
FCurrentDir: string;
FServerVersion: Integer;
FSshAgent: string;
FPassword: string;
FUserName: string;
FUserKey: TclSshUserKey;
FIdentity: TclSshUserIdentity;
FRequestId: Integer;
FResponseType: Integer;
FStatusCode: Integer;
FFileAttributes: TclSFtpFileAttrs;
FPacket: TclPacket;
FOnSendCommand: TclSFtpCommandEvent;
FOnReceiveResponse: TclSFtpCommandEvent;
FOnProgress: TclProgressEvent;
FOnVerifyServer: TclVerifySshPeerEvent;
FOnDirectoryListing: TclSFtpDirectoryListingEvent;
FOnShowBanner: TclSshShowBannerEvent;
procedure PutHEAD(AType: Byte; ALength: Integer);
procedure SendINIT;
procedure SendPathCommand(AFxp: Byte; const APath: TclByteArray; ASilent: Boolean); overload;
procedure SendPathCommand(AFxp: Byte; const APath1, APath2: TclByteArray); overload;
procedure SendREALPATH(const APath: TclByteArray);
procedure SendOPEN(const APath: TclByteArray; AMode: Integer);
procedure SendREAD(const AHandle: TclByteArray; AOffset: Int64; ALength: Integer);
procedure SendWRITE(const AHandle: TclByteArray; AOffset: Int64; const AData: TclByteArray; AStart, ALength: Integer);
procedure SendCLOSE(const APath: TclByteArray);
procedure SendMKDIR(const APath: TclByteArray);
procedure SendRMDIR(const APath: TclByteArray);
procedure SendREMOVE(const APath: TclByteArray);
procedure SendSTAT(const APath: TclByteArray; ASilent: Boolean);
procedure SendSETSTAT(const APath: TclByteArray; Attr: TclSFtpFileAttrs);
procedure SendREADLINK(const ALinkPath: TclByteArray);
procedure SendOPENDIR(const APath: TclByteArray);
procedure SendREADDIR(const APath: TclByteArray);
procedure SendRENAME(const AOldPath, ANewPath: TclByteArray);
procedure SendSYMLINK(const ALinkPath, ATargetPath: TclByteArray);
function ReadPacket(ASource: TStream; APacket: TclPacket): Integer;
procedure SetPassword(const Value: string);
procedure SetUserName(const Value: string);
procedure VerifyServer(Sender: TObject; const AHost, AKeyType, AFingerPrint, AHostKey: string; var AVerified: Boolean);
procedure SetSshAgent(const Value: string);
function GetFullPath(const APath: string): string;
function GetResponse: Integer;
procedure CheckError;
function GetFileSizeIfNeed(const AFileName: string): Int64;
function GetFileSizeSilent(const AFileName: string): Int64;
procedure InternalPutData(ASource: TStream; const ADestinationFile: string; AOffset, ASize: Int64; AMode: Integer);
procedure SetUserKey(const Value: TclSshUserKey);
procedure DoChanged(Sender: TObject);
protected
function WritePacket(APack: TclPacket; AFxp: Integer; ASilent: Boolean): Integer;
function CreateConfig: TclConfig; virtual;
procedure OpenChannel; virtual;
procedure CloseChannel; virtual;
procedure DoSendCommand(AFxpCommand: Integer; ABuffer: TStream); dynamic;
procedure DoReceiveResponse(AFxpCommand: Integer; ABuffer: TStream); dynamic;
procedure DoProgress(ABytesProceed, ATotalBytes: Int64); dynamic;
procedure DoVerifyServer(const AHost, AKeyType, AFingerPrint, AHostKey: string; var AVerified: Boolean); dynamic;
procedure DoDirectoryListing(const AFileName: string; AFileAttrs: TclSFtpFileAttrs); dynamic;
procedure DoShowBanner(const AMessage, ALanguage: string); dynamic;
function GetNetworkStream: TclNetworkStream; override;
procedure InternalOpen; override;
procedure InternalClose(ANotifyPeer: Boolean); override;
function GetDefaultPort: Integer; override;
procedure DoDestroy; override;
public
constructor Create(AOwner: TComponent); override;
procedure ChangeCurrentDir(const ANewDir: string);
procedure ChangeToParentDir;
procedure GetFile(const ASourceFile, ADestinationFile: string); overload;
procedure GetFile(const ASourceFile: string; ADestination: TStream); overload;
procedure GetFile(const ASourceFile: string; ADestination: TStream; APosition, ASize: Int64); overload;
procedure PutFile(const ASourceFile, ADestinationFile: string); overload;
procedure PutFile(ASource: TStream; const ADestinationFile: string); overload;
procedure PutFile(ASource: TStream; const ADestinationFile: string; APosition, ASize: Int64); overload;
procedure AppendFile(ASource: TStream; const ADestinationFile: string);
procedure MakeDir(const ANewDir: string);
procedure RemoveDir(const ADir: string);
procedure Delete(const AFileName: string);
function FileExists(const AFileName: string): Boolean;
procedure Rename(const ACurrentName, ANewName: string);
function GetFileAttributes(const AFileName: string): TclSFtpFileAttrs;
function GetFilePermissions(const AFileName: string): TclSFtpFilePermissions;
function GetFileSize(const AFileName: string): Int64;
procedure SetFileAttributes(const AFileName: string; Attr: TclSFtpFileAttrs);
procedure SetFilePermissions(const AFileName: string; APermissions: TclSFtpFilePermissions);
procedure MakeLink(const ALinkName, ATargetName: string);
function ReadLink(const ALinkName: string): string;
procedure GetList(AList: TStrings; const AFilePath: string = ''; ADetails: Boolean = True);
procedure DirectoryListing(const AFilePath: string = '');
property CurrentDir: string read FCurrentDir;
property RootDir: string read FRootDir;
property ServerVersion: Integer read FServerVersion;
property FileAttributes: TclSFtpFileAttrs read FFileAttributes;
property Config: TclConfig read FConfig;
published
property Port default DefaultSFtpPort;
property UserName: string read FUserName write SetUserName;
property Password: string read FPassword write SetPassword;
property UserKey: TclSshUserKey read FUserKey write SetUserKey;
property SshAgent: string read FSshAgent write SetSshAgent;
property OnSendCommand: TclSFtpCommandEvent read FOnSendCommand write FOnSendCommand;
property OnReceiveResponse: TclSFtpCommandEvent read FOnReceiveResponse write FOnReceiveResponse;
property OnProgress: TclProgressEvent read FOnProgress write FOnProgress;
property OnVerifyServer: TclVerifySshPeerEvent read FOnVerifyServer write FOnVerifyServer;
property OnDirectoryListing: TclSFtpDirectoryListingEvent read FOnDirectoryListing write FOnDirectoryListing;
property OnShowBanner: TclSshShowBannerEvent read FOnShowBanner write FOnShowBanner;
end;
implementation
uses
clSshUtils;
{$IFDEF DEMO}
{$IFNDEF IDEDEMO}
var
IsDemoDisplayed: Boolean = False;
{$ENDIF}
{$ENDIF}
type
TclSFtpUserIdentity = class(TclSshUserIdentity)
private
FOwner: TclSFtp;
public
constructor Create(AOwner: TclSFtp);
function GetUserName: string; override;
function GetPassword: string; override;
function GetUserKey: TclSshUserKey; override;
procedure ShowBanner(const AMessage, ALanguage: string); override;
end;
{ TclSFtp }
procedure TclSFtp.GetFile(const ASourceFile, ADestinationFile: string);
var
stream: TStream;
begin
stream := TFileStream.Create(ADestinationFile, fmCreate);
try
GetFile(ASourceFile, stream);
finally
stream.Free();
end;
end;
function TclSFtp.GetFileSizeSilent(const AFileName: string): Int64;
var
path: string;
attrs: TclSFtpFileAttrs;
begin
Result := -1;
path := GetFullPath(AFileName);
SendSTAT(TclTranslator.GetBytes(path), True);
if (FResponseType = SSH_FXP_ATTRS) then
begin
FPacket.GetInt();
attrs := TclSFtpFileAttrs.Create(FPacket);
try
Result := attrs.Size;
finally
attrs.Free();
end;
end;
end;
function TclSFtp.GetFileSize(const AFileName: string): Int64;
begin
Result := GetFileAttributes(AFileName).Size;
end;
function TclSFtp.GetFileSizeIfNeed(const AFileName: string): Int64;
begin
Result := -1;
if Assigned(OnProgress) then
begin
Result := GetFileSizeSilent(AFileName);
end;
end;
procedure TclSFtp.GetFile(const ASourceFile: string; ADestination: TStream);
begin
GetFile(ASourceFile, ADestination, -1, GetFileSizeIfNeed(ASourceFile));
end;
function TclSFtp.GetFullPath(const APath: string): string;
begin
Result := APath;
if (System.Pos('/', Result) <> 1) then
begin
if (CurrentDir <> '/') then
begin
Result := '/' + Result;
end;
Result := CurrentDir + Result;
end;
end;
procedure TclSFtp.DirectoryListing(const AFilePath: string);
var
list: TStrings;
begin
list := TStringList.Create();
try
GetList(list, AFilePath, True);
finally
list.Free();
end;
end;
procedure TclSFtp.GetList(AList: TStrings; const AFilePath: string; ADetails: Boolean);
var
path, nameStr: string;
handle, fileName, longName: TclByteArray;
count: Integer;
attrs: TclSFtpFileAttrs;
begin
{$IFNDEF DELPHI2005}handle := nil; fileName := nil; longName := nil;{$ENDIF}
path := GetFullPath(AFilePath);
SendOPENDIR(TclTranslator.GetBytes(path));
if (FResponseType <> SSH_FXP_STATUS) and (FResponseType <> SSH_FXP_HANDLE) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
FPacket.GetInt();
handle := FPacket.GetString();
AList.Clear();
repeat
SendREADDIR(handle);
if (FResponseType <> SSH_FXP_STATUS) and (FResponseType <> SSH_FXP_NAME) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
if (FResponseType = SSH_FXP_STATUS) and (FStatusCode = SSH_FX_EOF) then
begin
Break;
end;
FPacket.GetInt();
count := FPacket.GetInt();
while (count > 0) do
begin
fileName := FPacket.GetString();
nameStr := TclTranslator.GetString(fileName);
longName := FPacket.GetString();
if (ADetails) then
begin
AList.Add(TclTranslator.GetString(longName));
end else
begin
AList.Add(nameStr);
end;
attrs := TclSFtpFileAttrs.Create(FPacket);
try
DoDirectoryListing(nameStr, attrs);
Dec(count);
finally
attrs.Free();
end;
end;
until False;
SendCLOSE(handle);
end;
procedure TclSFtp.AppendFile(ASource: TStream; const ADestinationFile: string);
begin
InternalPutData(ASource, ADestinationFile, GetFileSizeSilent(ADestinationFile), -1, SSH_FXF_WRITE or SSH_FXF_CREAT);
end;
procedure TclSFtp.ChangeCurrentDir(const ANewDir: string);
var
path: string;
str: TclByteArray;
begin
{$IFNDEF DELPHI2005}str := nil;{$ENDIF}
path := GetFullPath(ANewDir);
SendREALPATH(TclTranslator.GetBytes(path));
if (FResponseType <> SSH_FXP_NAME) then
begin
raise EclSFtpClientError.Create(SFtpPathError, SFtpPathErrorCode);
end;
FPacket.GetInt();
FPacket.GetInt();
str := FPacket.GetString();
FCurrentDir := TclTranslator.GetString(str);
if (FCurrentDir <> '/') then
begin
FCurrentDir := RemoveTrailingBackSlash(FCurrentDir, '/');
end;
end;
procedure TclSFtp.ChangeToParentDir;
begin
ChangeCurrentDir('..');
end;
procedure TclSFtp.CheckError;
var
msg: TclByteArray;
begin
{$IFNDEF DELPHI2005}msg := nil;{$ENDIF}
if (FResponseType = SSH_FXP_STATUS) then
begin
if ((FStatusCode <> SSH_FX_OK) and (FStatusCode <> SSH_FX_EOF)) then
begin
if (ServerVersion >= 3) then
begin
msg := FPacket.GetString();
raise EclSFtpClientError.Create(TclTranslator.GetString(msg), FStatusCode);
end;
raise EclSFtpClientError.Create(SFtpError, FStatusCode);
end;
end;
end;
function TclSFtp.GetResponse: Integer;
begin
Result := FPacket.GetInt();
FResponseType := FPacket.GetByte();
FStatusCode := 0;
if (FResponseType = SSH_FXP_STATUS) then
begin
FPacket.GetInt();//request-id
FStatusCode := FPacket.GetInt();
end;
end;
procedure TclSFtp.CloseChannel;
begin
end;
constructor TclSFtp.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FConfig := CreateConfig();
FIdentity := TclSFtpUserIdentity.Create(Self);
FUserKey := TclSshUserKey.Create();
FUserKey.OnChanged := DoChanged;
FPacket := TclPacket.Create();
FRequestId := 0;
FRootDir := '';
FCurrentDir := '';
FServerVersion := 0;
FSshAgent := DefaultSshAgent;
FFileAttributes := nil;
end;
function TclSFtp.CreateConfig: TclConfig;
begin
Result := TclSshConfig.Create();
end;
procedure TclSFtp.VerifyServer(Sender: TObject; const AHost, AKeyType,
AFingerPrint, AHostKey: string; var AVerified: Boolean);
begin
DoVerifyServer(AHost, AKeyType, AFingerPrint, AHostKey, AVerified);
end;
function TclSFtp.WritePacket(APack: TclPacket; AFxp: Integer; ASilent: Boolean): Integer;
var
ms: TStream;
begin
ms := TMemoryStream.Create();
try
ms.Write(APack.Buffer[0], APack.GetIndex());
ms.Seek(0, soBeginning);
Connection.WriteData(ms);
Assert(ms.Position >= ms.Size - 1);
DoSendCommand(AFxp, ms);
ms.Size := 0;
while ((ms.Size <= 0) or Connection.NetworkStream.HasReadData) do
begin
Connection.ReadData(ms);
end;
DoReceiveResponse(AFxp, ms);
ReadPacket(ms, FPacket);
Result := GetResponse();
if (not ASilent) then
begin
CheckError();
end;
finally
ms.Free();
end;
end;
procedure TclSFtp.Delete(const AFileName: string);
var
path: string;
begin
path := GetFullPath(AFileName);
SendREMOVE(TclTranslator.GetBytes(path));
if (FResponseType <> SSH_FXP_STATUS) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
end;
procedure TclSFtp.DoChanged(Sender: TObject);
begin
Changed();
end;
procedure TclSFtp.DoDestroy;
begin
FFileAttributes.Free();
FPacket.Free();
FUserKey.Free();
FIdentity.Free();
FConfig.Free();
inherited DoDestroy();
end;
procedure TclSFtp.DoDirectoryListing(const AFileName: string; AFileAttrs: TclSFtpFileAttrs);
begin
if Assigned(OnDirectoryListing) then
begin
OnDirectoryListing(Self, AFileName, AFileAttrs);
end;
end;
procedure TclSFtp.DoProgress(ABytesProceed, ATotalBytes: Int64);
begin
if Assigned(OnProgress) then
begin
OnProgress(Self, ABytesProceed, ATotalBytes);
end;
end;
procedure TclSFtp.DoReceiveResponse(AFxpCommand: Integer; ABuffer: TStream);
begin
if Assigned(OnReceiveResponse) then
begin
OnReceiveResponse(Self, AFxpCommand, ABuffer);
end;
end;
procedure TclSFtp.DoSendCommand(AFxpCommand: Integer; ABuffer: TStream);
begin
if Assigned(OnSendCommand) then
begin
OnSendCommand(Self, AFxpCommand, ABuffer);
end;
end;
procedure TclSFtp.DoShowBanner(const AMessage, ALanguage: string);
begin
if Assigned(OnShowBanner) then
begin
OnShowBanner(Self, AMessage, ALanguage);
end;
end;
procedure TclSFtp.DoVerifyServer(const AHost, AKeyType, AFingerPrint, AHostKey: string; var AVerified: Boolean);
begin
if Assigned(OnVerifyServer) then
begin
OnVerifyServer(Self, AHost, AKeyType, AFingerPrint, AHostKey, AVerified);
end;
end;
function TclSFtp.FileExists(const AFileName: string): Boolean;
var
path: string;
begin
path := GetFullPath(AFileName);
SendSTAT(TclTranslator.GetBytes(path), True);
if (FResponseType = SSH_FXP_ATTRS) then
begin
Result := True;
end else
if (FResponseType = SSH_FXP_STATUS) and (FStatusCode = SSH_FX_NO_SUCH_FILE) then
begin
Result := False;
end else
begin
CheckError();
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
end;
function TclSFtp.GetDefaultPort: Integer;
begin
Result := DefaultSFtpPort;
end;
function TclSFtp.GetNetworkStream: TclNetworkStream;
var
ns: TclSshNetworkStream;
begin
ns := TclSshNetworkStream.Create(FConfig);
ns.SshAgent := SshAgent;
ns.Identity := FIdentity;
ns.TargetName := Server;
ns.ChannelType := 'session';
ns.SubSystem := 'sftp';
ns.OnVerifyPeer := VerifyServer;
Result := ns;
end;
procedure TclSFtp.InternalClose(ANotifyPeer: Boolean);
begin
try
if Active and not InProgress then
begin
CloseChannel();
end;
finally
inherited InternalClose(ANotifyPeer);
end;
end;
procedure TclSFtp.InternalOpen;
begin
inherited InternalOpen();
OpenChannel();
end;
procedure TclSFtp.InternalPutData(ASource: TStream;
const ADestinationFile: string; AOffset, ASize: Int64; AMode: Integer);
var
destFile: string;
handle, data: TclByteArray;
bufSize, toPut, i: Integer;
count, offset, sourceSize: Int64;
begin
{$IFNDEF DELPHI2005}handle := nil; data := nil;{$ENDIF}
destFile := GetFullPath(ADestinationFile);
SendOPEN(TclTranslator.GetBytes(destFile), AMode);
if (FResponseType <> SSH_FXP_STATUS) and (FResponseType <> SSH_FXP_HANDLE) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
FPacket.GetInt();
handle := FPacket.GetString();
bufSize := BatchSize;
SetLength(data, bufSize);
count := 0;
sourceSize := ASource.Size;
offset := AOffset;
DoProgress(offset, sourceSize);
repeat
toPut := bufSize;
if ((ASize > 0) and ((ASize - count) < toPut)) then
begin
toPut := ASize - count;
end;
if (toPut <= 0) then
begin
Break;
end;
i := ASource.Read(data[0], toPut);
if (i <= 0) then
begin
Break;
end;
if ((ASize > 0) and (count >= ASize)) then
begin
Break;
end;
SendWRITE(handle, offset, data, 0, i);
if (FResponseType <> SSH_FXP_STATUS) then
begin
Break;
end;
if (FResponseType = SSH_FXP_STATUS) and (FStatusCode <> SSH_FX_OK) then
begin
Break;
end;
offset := offset + i;
count := count + i;
DoProgress(offset, sourceSize);
until False;
SendCLOSE(handle);
if (FResponseType <> SSH_FXP_STATUS) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
end;
procedure TclSFtp.MakeDir(const ANewDir: string);
var
path: string;
begin
path := GetFullPath(ANewDir);
SendMKDIR(TclTranslator.GetBytes(path));
if (FResponseType <> SSH_FXP_STATUS) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
end;
procedure TclSFtp.MakeLink(const ALinkName, ATargetName: string);
var
linkPath, targetPath: string;
begin
if (FServerVersion < 2) then
begin
raise EclSFtpClientError.Create(SFtpOldVersionError, SFtpOldVersionErrorCode);
end;
linkPath := GetFullPath(ALinkName);
targetPath := GetFullPath(ATargetName);
SendSYMLINK(TclTranslator.GetBytes(linkPath), TclTranslator.GetBytes(targetPath));
if (FResponseType <> SSH_FXP_STATUS) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
end;
procedure TclSFtp.OpenChannel;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if (not IsDemoDisplayed) then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
SendINIT();
if (FResponseType <> SSH_FXP_VERSION) then
begin
raise EclSFtpClientError.Create(SFtpVersionError, SFtpVersionErrorCode);
end;
FServerVersion := FPacket.GetInt();
FResponseType := 0;
FStatusCode := 0;
ChangeCurrentDir('.');
FRootDir := FCurrentDir;
end;
procedure TclSFtp.PutFile(const ASourceFile, ADestinationFile: string);
var
stream: TStream;
begin
stream := TFileStream.Create(ASourceFile, fmOpenRead or fmShareDenyWrite);
try
PutFile(stream, ADestinationFile);
finally
stream.Free();
end;
end;
procedure TclSFtp.PutFile(ASource: TStream; const ADestinationFile: string);
begin
PutFile(ASource, ADestinationFile, -1, -1);
end;
procedure TclSFtp.PutFile(ASource: TStream; const ADestinationFile: string; APosition, ASize: Int64);
var
mode: Integer;
offset: Int64;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if (not IsDemoDisplayed) then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
mode := SSH_FXF_WRITE or SSH_FXF_CREAT;
if (APosition < 0) then
begin
mode := mode or SSH_FXF_TRUNC;
end;
offset := 0;
if (APosition > 0) then
begin
offset := APosition;
end;
ASource.Position := offset;
InternalPutData(ASource, ADestinationFile, offset, ASize, mode);
end;
procedure TclSFtp.PutHEAD(AType: Byte; ALength: Integer);
begin
FPacket.PutByte(SSH_MSG_CHANNEL_DATA);
FPacket.PutInt((TclSshNetworkStream(Connection.NetworkStream)).RecipientId);
FPacket.PutInt(ALength + 4);
FPacket.PutInt(ALength);
FPacket.PutByte(AType);
end;
function TclSFtp.ReadPacket(ASource: TStream; APacket: TclPacket): Integer;
begin
APacket.Init();
ASource.Position := 0;
Result := ASource.Read(APacket.Buffer[0], ASource.Size);
end;
function TclSFtp.ReadLink(const ALinkName: string): string;
var
linkPath: string;
fileName: TclByteArray;
begin
{$IFNDEF DELPHI2005}fileName := nil;{$ENDIF}
if (FServerVersion < 2) then
begin
raise EclSFtpClientError.Create(SFtpOldVersionError, SFtpOldVersionErrorCode);
end;
linkPath := GetFullPath(ALinkName);
SendREADLINK(TclTranslator.GetBytes(linkPath));
if ((FResponseType <> SSH_FXP_STATUS) and (FResponseType <> SSH_FXP_NAME)) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
FPacket.GetInt();
FPacket.GetInt();
fileName := FPacket.GetString();
Result := TclTranslator.GetString(fileName);
end;
procedure TclSFtp.RemoveDir(const ADir: string);
var
path: string;
begin
path := GetFullPath(ADir);
SendRMDIR(TclTranslator.GetBytes(path));
if (FResponseType <> SSH_FXP_STATUS) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
end;
procedure TclSFtp.Rename(const ACurrentName, ANewName: string);
var
oldPath, newPath: string;
begin
if (FServerVersion < 2) then
begin
raise EclSFtpClientError.Create(SFtpOldVersionError, SFtpOldVersionErrorCode);
end;
oldPath := GetFullPath(ACurrentName);
newPath := GetFullPath(ANewName);
SendRENAME(TclTranslator.GetBytes(oldPath), TclTranslator.GetBytes(newPath));
if (FResponseType <> SSH_FXP_STATUS) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
end;
procedure TclSFtp.SendCLOSE(const APath: TclByteArray);
begin
SendPathCommand(SSH_FXP_CLOSE, APath, False);
end;
procedure TclSFtp.SendINIT;
begin
CheckConnected();
FPacket.Reset();
PutHEAD(SSH_FXP_INIT, 5);
FPacket.PutInt(SFtpClientVersion);
WritePacket(FPacket, SSH_FXP_INIT, True);
end;
procedure TclSFtp.SendMKDIR(const APath: TclByteArray);
begin
CheckConnected();
FPacket.Reset();
PutHEAD(SSH_FXP_MKDIR, 9 + Length(APath) + 4);
FPacket.PutInt(FRequestId);
Inc(FRequestId);
FPacket.PutString(APath);
FPacket.PutInt(0);
WritePacket(FPacket, SSH_FXP_MKDIR, False);
end;
procedure TclSFtp.SendOPEN(const APath: TclByteArray; AMode: Integer);
begin
CheckConnected();
FPacket.Reset();
PutHEAD(SSH_FXP_OPEN, 17 + Length(APath));
FPacket.PutInt(FRequestId);
Inc(FRequestId);
FPacket.PutString(APath);
FPacket.PutInt(AMode);
FPacket.PutInt(0);
WritePacket(FPacket, SSH_FXP_OPEN, False);
end;
procedure TclSFtp.SendOPENDIR(const APath: TclByteArray);
begin
SendPathCommand(SSH_FXP_OPENDIR, APath, False);
end;
procedure TclSFtp.SendPathCommand(AFxp: Byte; const APath: TclByteArray; ASilent: Boolean);
begin
CheckConnected();
FPacket.Reset();
PutHEAD(AFxp, 9 + Length(APath));
FPacket.PutInt(FRequestId);
Inc(FRequestId);
FPacket.PutString(APath);
WritePacket(FPacket, AFxp, ASilent);
end;
procedure TclSFtp.SendPathCommand(AFxp: Byte; const APath1, APath2: TclByteArray);
begin
CheckConnected();
FPacket.Reset();
PutHEAD(AFxp, 13 + Length(APath1) + Length(APath2));
FPacket.PutInt(FRequestId);
Inc(FRequestId);
FPacket.PutString(APath1);
FPacket.PutString(APath2);
WritePacket(FPacket, AFxp, False);
end;
procedure TclSFtp.SendREAD(const AHandle: TclByteArray; AOffset: Int64; ALength: Integer);
begin
FPacket.Reset();
PutHEAD(SSH_FXP_READ, 21 + Length(AHandle));
FPacket.PutInt(FRequestId);
Inc(FRequestId);
FPacket.PutString(AHandle);
FPacket.PutLong(AOffset);
FPacket.PutInt(ALength);
WritePacket(FPacket, SSH_FXP_READ, False);
end;
procedure TclSFtp.SendREADDIR(const APath: TclByteArray);
begin
FPacket.Reset();
PutHEAD(SSH_FXP_READDIR, 9 + Length(APath));
FPacket.PutInt(FRequestId);
Inc(FRequestId);
FPacket.PutString(APath);
WritePacket(FPacket, SSH_FXP_READDIR, False);
end;
procedure TclSFtp.SendREADLINK(const ALinkPath: TclByteArray);
begin
SendPathCommand(SSH_FXP_READLINK, ALinkPath, False);
end;
procedure TclSFtp.SendREALPATH(const APath: TclByteArray);
begin
SendPathCommand(SSH_FXP_REALPATH, APath, False);
end;
procedure TclSFtp.SendREMOVE(const APath: TclByteArray);
begin
SendPathCommand(SSH_FXP_REMOVE, APath, False);
end;
procedure TclSFtp.SendRENAME(const AOldPath, ANewPath: TclByteArray);
begin
SendPathCommand(SSH_FXP_RENAME, AOldPath, ANewPath);
end;
procedure TclSFtp.SendRMDIR(const APath: TclByteArray);
begin
SendPathCommand(SSH_FXP_RMDIR, APath, False);
end;
procedure TclSFtp.SendSETSTAT(const APath: TclByteArray; Attr: TclSFtpFileAttrs);
begin
CheckConnected();
FPacket.Reset();
PutHEAD(SSH_FXP_SETSTAT, 9 + Length(APath) + attr.SavedLength());
FPacket.PutInt(FRequestId);
Inc(FRequestId);
FPacket.PutString(APath);
Attr.Save(FPacket);
WritePacket(FPacket, SSH_FXP_SETSTAT, False);
end;
procedure TclSFtp.SendSTAT(const APath: TclByteArray; ASilent: Boolean);
begin
SendPathCommand(SSH_FXP_STAT, APath, ASilent);
end;
procedure TclSFtp.SendSYMLINK(const ALinkPath, ATargetPath: TclByteArray);
begin
SendPathCommand(SSH_FXP_SYMLINK, ALinkPath, ATargetPath);
end;
procedure TclSFtp.SendWRITE(const AHandle: TclByteArray; AOffset: Int64;
const AData: TclByteArray; AStart, ALength: Integer);
begin
FPacket.Reset();
PutHEAD(SSH_FXP_WRITE, 21 + Length(AHandle) + ALength);
FPacket.PutInt(FRequestId);
Inc(FRequestId);
FPacket.PutString(AHandle);
FPacket.PutLong(AOffset);
FPacket.PutString(AData, AStart, ALength);
WritePacket(FPacket, SSH_FXP_WRITE, False);
end;
procedure TclSFtp.SetFileAttributes(const AFileName: string; Attr: TclSFtpFileAttrs);
var
path: string;
begin
path := GetFullPath(AFileName);
SendSETSTAT(TclTranslator.GetBytes(path), Attr);
if (FResponseType <> SSH_FXP_STATUS) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
end;
procedure TclSFtp.SetFilePermissions(const AFileName: string; APermissions: TclSFtpFilePermissions);
var
attrs: TclSFtpFileAttrs;
begin
attrs := TclSFtpFileAttrs.Create();
try
attrs.SetPermissions(APermissions);
SetFileAttributes(AFileName, attrs);
finally
attrs.Free();
end;
end;
procedure TclSFtp.SetPassword(const Value: string);
begin
if (FPassword <> Value) then
begin
FPassword := Value;
Changed();
end;
end;
procedure TclSFtp.SetSshAgent(const Value: string);
begin
if (FSshAgent <> Value) then
begin
FSshAgent := Value;
Changed();
end;
end;
procedure TclSFtp.SetUserKey(const Value: TclSshUserKey);
begin
FUserKey.Assign(Value);
Changed();
end;
procedure TclSFtp.SetUserName(const Value: string);
begin
if (FUserName <> Value) then
begin
FUserName := Value;
Changed();
end;
end;
procedure TclSFtp.GetFile(const ASourceFile: string; ADestination: TStream; APosition, ASize: Int64);
var
len, offset, count: Int64;
bufSize, toGet: Integer;
sourceFile: string;
handle, data: TclByteArray;
data_start, data_len: TclIntArray;
begin
{$IFNDEF DELPHI2005}handle := nil; data := nil; data_start := nil; data_len := nil;{$ENDIF}
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if (not IsDemoDisplayed) then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
len := APosition + ASize;
if (len < 0) then
begin
len := 0;
end;
if (len < APosition) then
begin
len := APosition;
end;
if (ADestination.Size < len) then
begin
ADestination.Size := len;
end;
if (APosition > -1) then
begin
ADestination.Position := APosition;
end;
sourceFile := GetFullPath(ASourceFile);
SendOPEN(TclTranslator.GetBytes(sourceFile), SSH_FXF_READ);
if (FResponseType <> SSH_FXP_STATUS) and (FResponseType <> SSH_FXP_HANDLE) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
FPacket.GetInt();
handle := FPacket.GetString();
data := nil;
SetLength(data_start, 1);
SetLength(data_len, 1);
offset := 0;
count := 0;
if (APosition > -1) then
begin
offset := offset + APosition;
end;
bufSize := BatchSize;
DoProgress(offset, ASize);
while ((ASize < 0) or (count < ASize)) do
begin
toGet := bufSize;
if ((ASize > 0) and ((ASize - count) < toGet)) then
begin
toGet := ASize - count;
end;
SendREAD(handle, offset, toGet);
if (FResponseType <> SSH_FXP_STATUS) and (FResponseType <> SSH_FXP_DATA) then
begin
Break;
end;
if (FResponseType = SSH_FXP_STATUS) and (FStatusCode = SSH_FX_EOF) then
begin
Break;
end;
FPacket.GetInt();
data := FPacket.GetString(data_start, data_len);
ADestination.Write(data[data_start[0]], data_len[0]);
offset := offset + data_len[0];
count := count + data_len[0];
DoProgress(offset, ASize);
end;
SendCLOSE(handle);
if (FResponseType <> SSH_FXP_STATUS) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
end;
function TclSFtp.GetFileAttributes(const AFileName: string): TclSFtpFileAttrs;
var
path: string;
begin
if (FFileAttributes = nil) then
begin
FFileAttributes := TclSFtpFileAttrs.Create();
end;
path := GetFullPath(AFileName);
SendSTAT(TclTranslator.GetBytes(path), False);
if (FResponseType <> SSH_FXP_ATTRS) then
begin
raise EclSFtpClientError.Create(EclSFtpClientError.GetSFtpStatusText(SSH_FX_FAILURE), SSH_FX_FAILURE);
end;
FPacket.GetInt();
FFileAttributes.Load(FPacket);
Result := FFileAttributes;
end;
function TclSFtp.GetFilePermissions(const AFileName: string): TclSFtpFilePermissions;
begin
Result := GetFileAttributes(AFileName).Permissions;
end;
{ TclSFtpUserIdentity }
constructor TclSFtpUserIdentity.Create(AOwner: TclSFtp);
begin
inherited Create();
FOwner := AOwner;
end;
function TclSFtpUserIdentity.GetPassword: string;
begin
Result := FOwner.Password;
end;
function TclSFtpUserIdentity.GetUserKey: TclSshUserKey;
begin
Result := FOwner.UserKey;
end;
function TclSFtpUserIdentity.GetUserName: string;
begin
Result := FOwner.UserName;
end;
procedure TclSFtpUserIdentity.ShowBanner(const AMessage, ALanguage: string);
begin
FOwner.DoShowBanner(AMessage, ALanguage);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.