text stringlengths 14 6.51M |
|---|
unit Alcinoe.AndroidApi.WebRTC;
interface
uses
Androidapi.JNIBridge,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.App,
Androidapi.JNI.OpenGL;
type
{****************************************}
JPeerConnection_TlsCertPolicy = interface;
JPeerConnection_IceServer = interface;
JPeerConnection_IceServer_Builder = interface;
JPeerConnection_IceConnectionState = interface;
JIceCandidate = interface;
JSessionDescription_Type = interface;
JSessionDescription = interface;
JALWebRTC_Listener = interface;
JALWebRTC_PeerConnectionParameters = interface;
JALWebRTC = interface;
{********************************************************}
JPeerConnection_TlsCertPolicyClass = interface(JEnumClass)
['{A9BDA269-B178-459A-8892-FC9D31652D8A}']
{class} function _GetTLS_CERT_POLICY_INSECURE_NO_CHECK: JPeerConnection_TlsCertPolicy; cdecl;
{class} function _GetTLS_CERT_POLICY_SECURE: JPeerConnection_TlsCertPolicy; cdecl;
{class} //function valueOf(name: JString): JPeerConnection_TlsCertPolicy; cdecl;
{class} //function values: TJavaObjectArray<JPeerConnection_TlsCertPolicy>; cdecl;
{class} property TLS_CERT_POLICY_INSECURE_NO_CHECK: JPeerConnection_TlsCertPolicy read _GetTLS_CERT_POLICY_INSECURE_NO_CHECK;
{class} property TLS_CERT_POLICY_SECURE: JPeerConnection_TlsCertPolicy read _GetTLS_CERT_POLICY_SECURE;
end;
{********************************************************}
[JavaSignature('org/webrtc/PeerConnection$TlsCertPolicy')]
JPeerConnection_TlsCertPolicy = interface(JEnum)
['{96BA5191-41C9-4968-98CA-38F71EF07FC0}']
end;
TJPeerConnection_TlsCertPolicy = class(TJavaGenericImport<JPeerConnection_TlsCertPolicyClass, JPeerConnection_TlsCertPolicy>) end;
{******************************************************}
JPeerConnection_IceServerClass = interface(JObjectClass)
['{3D0BB0FF-EFD1-429F-9C66-C9EB712F0B12}']
{class} function builder(uri: JString): JPeerConnection_IceServer_Builder; cdecl; overload;
{class} function builder(urls: JList): JPeerConnection_IceServer_Builder; cdecl; overload;
{class} function init(uri: JString): JPeerConnection_IceServer; cdecl; overload; deprecated;
{class} function init(uri: JString; username: JString; password: JString): JPeerConnection_IceServer; cdecl; overload; deprecated;
{class} function init(uri: JString; username: JString; password: JString; tlsCertPolicy: JPeerConnection_TlsCertPolicy): JPeerConnection_IceServer; cdecl; overload; deprecated;
{class} function init(uri: JString; username: JString; password: JString; tlsCertPolicy: JPeerConnection_TlsCertPolicy; hostname: JString): JPeerConnection_IceServer; cdecl; overload; deprecated;
end;
{****************************************************}
[JavaSignature('org/webrtc/PeerConnection$IceServer')]
JPeerConnection_IceServer = interface(JObject)
['{D31A3643-8680-4230-B255-D8E1E1220D2D}']
function _Gethostname: JString; cdecl;
function _Getpassword: JString; cdecl;
function _GettlsAlpnProtocols: JList; cdecl;
function _GettlsCertPolicy: JPeerConnection_TlsCertPolicy; cdecl;
function _GettlsEllipticCurves: JList; cdecl;
function _Geturi: JString; cdecl;
function _Geturls: JList; cdecl;
function _Getusername: JString; cdecl;
function toString: JString; cdecl;
property hostname: JString read _Gethostname;
property password: JString read _Getpassword;
property tlsAlpnProtocols: JList read _GettlsAlpnProtocols;
property tlsCertPolicy: JPeerConnection_TlsCertPolicy read _GettlsCertPolicy;
property tlsEllipticCurves: JList read _GettlsEllipticCurves;
property uri: JString read _Geturi; // deprecated
property urls: JList read _Geturls;
property username: JString read _Getusername;
end;
TJPeerConnection_IceServer = class(TJavaGenericImport<JPeerConnection_IceServerClass, JPeerConnection_IceServer>) end;
{**************************************************************}
JPeerConnection_IceServer_BuilderClass = interface(JObjectClass)
['{70F73023-A27C-4503-8EF6-794EB98332B4}']
end;
{************************************************************}
[JavaSignature('org/webrtc/PeerConnection$IceServer$Builder')]
JPeerConnection_IceServer_Builder = interface(JObject)
['{F7153AF4-045D-42E7-BCB2-CA8B29A01160}']
function createIceServer: JPeerConnection_IceServer; cdecl;
function setHostname(hostname: JString): JPeerConnection_IceServer_Builder; cdecl;
function setPassword(password: JString): JPeerConnection_IceServer_Builder; cdecl;
function setTlsAlpnProtocols(tlsAlpnProtocols: JList): JPeerConnection_IceServer_Builder; cdecl;
function setTlsCertPolicy(tlsCertPolicy: JPeerConnection_TlsCertPolicy): JPeerConnection_IceServer_Builder; cdecl;
function setTlsEllipticCurves(tlsEllipticCurves: JList): JPeerConnection_IceServer_Builder; cdecl;
function setUsername(username: JString): JPeerConnection_IceServer_Builder; cdecl;
end;
TJPeerConnection_IceServer_Builder = class(TJavaGenericImport<JPeerConnection_IceServer_BuilderClass, JPeerConnection_IceServer_Builder>) end;
{*************************************************************}
JPeerConnection_IceConnectionStateClass = interface(JEnumClass)
['{8DE67926-D8D5-4034-808D-8CFDF8CC3CE8}']
{class} function _GetCHECKING: JPeerConnection_IceConnectionState; cdecl;
{class} function _GetCLOSED: JPeerConnection_IceConnectionState; cdecl;
{class} function _GetCOMPLETED: JPeerConnection_IceConnectionState; cdecl;
{class} function _GetCONNECTED: JPeerConnection_IceConnectionState; cdecl;
{class} function _GetDISCONNECTED: JPeerConnection_IceConnectionState; cdecl;
{class} function _GetFAILED: JPeerConnection_IceConnectionState; cdecl;
{class} function _GetNEW: JPeerConnection_IceConnectionState; cdecl;
{class} //function valueOf(name: JString): JPeerConnection_IceConnectionState; cdecl;
{class} //function values: TJavaObjectArray<JPeerConnection_IceConnectionState>; cdecl;
{class} property CHECKING: JPeerConnection_IceConnectionState read _GetCHECKING;
{class} property CLOSED: JPeerConnection_IceConnectionState read _GetCLOSED;
{class} property COMPLETED: JPeerConnection_IceConnectionState read _GetCOMPLETED;
{class} property CONNECTED: JPeerConnection_IceConnectionState read _GetCONNECTED;
{class} property DISCONNECTED: JPeerConnection_IceConnectionState read _GetDISCONNECTED;
{class} property FAILED: JPeerConnection_IceConnectionState read _GetFAILED;
{class} property NEW: JPeerConnection_IceConnectionState read _GetNEW;
end;
{*************************************************************}
[JavaSignature('org/webrtc/PeerConnection$IceConnectionState')]
JPeerConnection_IceConnectionState = interface(JEnum)
['{8C929E60-7AE3-4881-867B-9D6041DF2467}']
end;
TJPeerConnection_IceConnectionState = class(TJavaGenericImport<JPeerConnection_IceConnectionStateClass, JPeerConnection_IceConnectionState>) end;
{******************************************}
JIceCandidateClass = interface(JObjectClass)
['{A403A5B2-A9E4-4FC8-A0C9-F9EB2193F02B}']
{class} function init(sdpMid: JString; sdpMLineIndex: Integer; sdp: JString): JIceCandidate; cdecl; overload;
end;
{****************************************}
[JavaSignature('org/webrtc/IceCandidate')]
JIceCandidate = interface(JObject)
['{F35CB50D-E2AB-4C86-9877-B3B311C944C6}']
function _GetsdpMid: JString; cdecl;
function _GetsdpMLineIndex: Integer; cdecl;
function _Getsdp: JString; cdecl;
function _GetserverUrl: JString; cdecl;
function toString: JString; cdecl;
property sdpMid: JString read _GetsdpMid;
property sdpMLineIndex: Integer read _GetsdpMLineIndex;
property sdp: JString read _Getsdp;
property serverUrl: JString read _GetserverUrl;
end;
TJIceCandidate = class(TJavaGenericImport<JIceCandidateClass, JIceCandidate>) end;
{***************************************************}
JSessionDescription_TypeClass = interface(JEnumClass)
['{DBA47293-EFE0-4ABE-9402-6BBB906689EF}']
{class} function _GetANSWER: JSessionDescription_Type; cdecl;
{class} function _GetOFFER: JSessionDescription_Type; cdecl;
{class} function _GetPRANSWER: JSessionDescription_Type; cdecl;
{class} //function valueOf(name: JString): JSessionDescription_Type; cdecl;
{class} //function values: TJavaObjectArray<JSessionDescription_Type>; cdecl;
{class} function fromCanonicalForm(canonical: JString): JSessionDescription_Type; cdecl;
{class} property ANSWER: JSessionDescription_Type read _GetANSWER;
{class} property OFFER: JSessionDescription_Type read _GetOFFER;
{class} property PRANSWER: JSessionDescription_Type read _GetPRANSWER;
end;
{***************************************************}
[JavaSignature('org/webrtc/SessionDescription$Type')]
JSessionDescription_Type = interface(JEnum)
['{D19319E6-779F-4468-AF80-48D0586F584E}']
function canonicalForm: JString; cdecl;
end;
TJSessionDescription_Type = class(TJavaGenericImport<JSessionDescription_TypeClass, JSessionDescription_Type>) end;
{************************************************}
JSessionDescriptionClass = interface(JObjectClass)
['{0C213174-3BB0-44AE-AD47-325249363921}']
{class} function init(&type: JSessionDescription_Type; description: JString): JSessionDescription; cdecl;
end;
{**********************************************}
[JavaSignature('org/webrtc/SessionDescription')]
JSessionDescription = interface(JObject)
['{0AD8B7AA-9D94-42FC-98EA-5754BBB3CB32}']
function _Getdescription: JString; cdecl;
function _Gettype: JSessionDescription_Type; cdecl;
property description: JString read _Getdescription;
property &type: JSessionDescription_Type read _Gettype;
end;
TJSessionDescription = class(TJavaGenericImport<JSessionDescriptionClass, JSessionDescription>) end;
{*********************************************}
JALWebRTC_ListenerClass = interface(IJavaClass)
['{90F484CB-D786-42A5-BF8F-E2F1A4339D19}']
end;
{*****************************************************}
[JavaSignature('com/alcinoe/webrtc/ALWebRTC$Listener')]
JALWebRTC_Listener = interface(IJavaInstance)
['{C758A92B-AE93-4291-BFD5-1EBB83041CC9}']
procedure onLocalFrameAvailable(textureId: integer; width: integer; height: integer; rotation: integer); cdecl;
procedure onRemoteFrameAvailable(textureId: integer; width: integer; height: integer; rotation: integer); cdecl;
procedure onLocalDescription(sdp: JSessionDescription); cdecl;
procedure onIceCandidate(candidate: JIceCandidate); cdecl;
procedure onIceCandidatesRemoved(candidates: TJavaObjectArray<JIceCandidate>); cdecl;
procedure onIceConnectionChange(newState: JPeerConnection_IceConnectionState); cdecl;
procedure onError(code: Integer; description: JString); cdecl;
end;
TJALWebRTC_Listener = class(TJavaGenericImport<JALWebRTC_ListenerClass, JALWebRTC_Listener>) end;
{***************************************************************}
JALWebRTC_PeerConnectionParametersClass = interface(JObjectClass)
['{0775B3FE-432A-41F5-BAC0-C9C2609AB4E1}']
{class} function init: JALWebRTC_PeerConnectionParameters; cdecl;
end;
{*********************************************************************}
[JavaSignature('com/alcinoe/webrtc/ALWebRTC$PeerConnectionParameters')]
JALWebRTC_PeerConnectionParameters = interface(JObject)
['{AF3349B3-C8B9-4CA4-8D64-7E8711E7A2F4}']
function _GetaecDump: Boolean; cdecl;
procedure _SetaecDump(Value: Boolean); cdecl;
function _GetaudioCodec: JString; cdecl;
procedure _SetaudioCodec(Value: JString); cdecl;
function _GetaudioStartBitrate: Integer; cdecl;
procedure _SetaudioStartBitrate(Value: Integer); cdecl;
function _GetdataChannelEnabled: Boolean; cdecl;
procedure _SetdataChannelEnabled(Value: Boolean); cdecl;
function _GetdataChannelId: Integer; cdecl;
procedure _SetdataChannelId(Value: Integer); cdecl;
function _GetdataChannelMaxRetransmitTimeMs: Integer; cdecl;
procedure _SetdataChannelMaxRetransmitTimeMs(Value: Integer); cdecl;
function _GetdataChannelMaxRetransmits: Integer; cdecl;
procedure _SetdataChannelMaxRetransmits(Value: Integer); cdecl;
function _GetdataChannelNegotiated: Boolean; cdecl;
procedure _SetdataChannelNegotiated(Value: Boolean); cdecl;
function _GetdataChannelOrdered: Boolean; cdecl;
procedure _SetdataChannelOrdered(Value: Boolean); cdecl;
function _GetdataChannelProtocol: JString; cdecl;
procedure _SetdataChannelProtocol(Value: JString); cdecl;
function _GetdisableBuiltInAEC: Boolean; cdecl;
procedure _SetdisableBuiltInAEC(Value: Boolean); cdecl;
function _GetdisableBuiltInNS: Boolean; cdecl;
procedure _SetdisableBuiltInNS(Value: Boolean); cdecl;
function _GetnoAudioProcessing: Boolean; cdecl;
procedure _SetnoAudioProcessing(Value: Boolean); cdecl;
function _GetvideoCallEnabled: Boolean; cdecl;
procedure _SetvideoCallEnabled(Value: Boolean); cdecl;
function _GetvideoCodec: JString; cdecl;
procedure _SetvideoCodec(Value: JString); cdecl;
function _GetvideoCodecHwAcceleration: Boolean; cdecl;
procedure _SetvideoCodecHwAcceleration(Value: Boolean); cdecl;
function _GetvideoFps: Integer; cdecl;
procedure _SetvideoFps(Value: Integer); cdecl;
function _GetvideoHeight: Integer; cdecl;
procedure _SetvideoHeight(Value: Integer); cdecl;
function _GetvideoMaxBitrate: Integer; cdecl;
procedure _SetvideoMaxBitrate(Value: Integer); cdecl;
function _GetvideoWidth: Integer; cdecl;
procedure _SetvideoWidth(Value: Integer); cdecl;
property videoCallEnabled: Boolean read _GetvideoCallEnabled write _SetvideoCallEnabled;
property videoWidth: Integer read _GetvideoWidth write _SetvideoWidth;
property videoHeight: Integer read _GetvideoHeight write _SetvideoHeight;
property videoFps: Integer read _GetvideoFps write _SetvideoFps;
property videoMaxBitrate: Integer read _GetvideoMaxBitrate write _SetvideoMaxBitrate;
property videoCodec: JString read _GetvideoCodec write _SetvideoCodec;
property videoCodecHwAcceleration: Boolean read _GetvideoCodecHwAcceleration write _SetvideoCodecHwAcceleration;
property audioStartBitrate: Integer read _GetaudioStartBitrate write _SetaudioStartBitrate;
property audioCodec: JString read _GetaudioCodec write _SetaudioCodec;
property noAudioProcessing: Boolean read _GetnoAudioProcessing write _SetnoAudioProcessing;
property aecDump: Boolean read _GetaecDump write _SetaecDump;
property disableBuiltInAEC: Boolean read _GetdisableBuiltInAEC write _SetdisableBuiltInAEC;
property disableBuiltInNS: Boolean read _GetdisableBuiltInNS write _SetdisableBuiltInNS;
property dataChannelEnabled: Boolean read _GetdataChannelEnabled write _SetdataChannelEnabled;
property dataChannelOrdered: Boolean read _GetdataChannelOrdered write _SetdataChannelOrdered;
property dataChannelMaxRetransmitTimeMs: Integer read _GetdataChannelMaxRetransmitTimeMs write _SetdataChannelMaxRetransmitTimeMs;
property dataChannelMaxRetransmits: Integer read _GetdataChannelMaxRetransmits write _SetdataChannelMaxRetransmits;
property dataChannelProtocol: JString read _GetdataChannelProtocol write _SetdataChannelProtocol;
property dataChannelNegotiated: Boolean read _GetdataChannelNegotiated write _SetdataChannelNegotiated;
property dataChannelId: Integer read _GetdataChannelId write _SetdataChannelId;
end;
TJALWebRTC_PeerConnectionParameters = class(TJavaGenericImport<JALWebRTC_PeerConnectionParametersClass, JALWebRTC_PeerConnectionParameters>) end;
{**************************************}
JALWebRTCClass = interface(JObjectClass)
['{3F5C8CF8-CEB7-4C92-B6E4-FD43F27BF995}']
{class} procedure initializeLibrary(appContext: JContext); cdecl;
{class} procedure finalizeLibrary; cdecl;
{class} function init(appContext: JContext; eglContext: Jopengl_EGLContext; iceServers: JList; peerConnectionParameters: JALWebRTC_PeerConnectionParameters): JALWebRTC; cdecl;
end;
{********************************************}
[JavaSignature('com/alcinoe/webrtc/ALWebRTC')]
JALWebRTC = interface(JObject)
['{45B6132D-E7E4-4D39-A150-E489495FC19D}']
procedure setListener(listener: JALWebRTC_Listener); cdecl;
function start: boolean; cdecl;
procedure stop; cdecl;
procedure resumeVideoCapturer; cdecl;
procedure pauseVideoCapturer; cdecl;
procedure setAudioEnabled(enable: boolean); cdecl;
procedure setVideoEnabled(enable: boolean); cdecl;
function setVideoMaxBitrate(maxBitrateKbps: integer): boolean; cdecl;
procedure createOffer; cdecl;
procedure createAnswer; cdecl;
procedure setRemoteDescription(sdpType: JSessionDescription_Type; sdpDescription: Jstring); cdecl;
procedure addRemoteIceCandidate(sdpMid: JString; sdpMLineIndex: integer; sdp: JString); cdecl;
procedure removeRemoteIceCandidates(candidates: TJavaObjectArray<JIceCandidate>); cdecl;
procedure switchCamera; cdecl;
procedure changeCaptureFormat(width: integer; height: integer; framerate: integer); cdecl;
end;
TJALWebRTC = class(TJavaGenericImport<JALWebRTCClass, JALWebRTC>) end;
implementation
{**********************}
procedure RegisterTypes;
begin
TRegTypes.RegisterType('Alcinoe.AndroidApi.WebRTC.JPeerConnection_TlsCertPolicy', TypeInfo(Alcinoe.AndroidApi.WebRTC.JPeerConnection_TlsCertPolicy));
TRegTypes.RegisterType('Alcinoe.AndroidApi.WebRTC.JPeerConnection_IceServer', TypeInfo(Alcinoe.AndroidApi.WebRTC.JPeerConnection_IceServer));
TRegTypes.RegisterType('Alcinoe.AndroidApi.WebRTC.JPeerConnection_IceServer_Builder', TypeInfo(Alcinoe.AndroidApi.WebRTC.JPeerConnection_IceServer_Builder));
TRegTypes.RegisterType('Alcinoe.AndroidApi.WebRTC.JPeerConnection_IceConnectionState', TypeInfo(Alcinoe.AndroidApi.WebRTC.JPeerConnection_IceConnectionState));
TRegTypes.RegisterType('Alcinoe.AndroidApi.WebRTC.JIceCandidate', TypeInfo(Alcinoe.AndroidApi.WebRTC.JIceCandidate));
TRegTypes.RegisterType('Alcinoe.AndroidApi.WebRTC.JSessionDescription_Type', TypeInfo(Alcinoe.AndroidApi.WebRTC.JSessionDescription_Type));
TRegTypes.RegisterType('Alcinoe.AndroidApi.WebRTC.JSessionDescription', TypeInfo(Alcinoe.AndroidApi.WebRTC.JSessionDescription));
TRegTypes.RegisterType('Alcinoe.AndroidApi.WebRTC.JALWebRTC_Listener', TypeInfo(Alcinoe.AndroidApi.WebRTC.JALWebRTC_Listener));
TRegTypes.RegisterType('Alcinoe.AndroidApi.WebRTC.JALWebRTC_PeerConnectionParameters', TypeInfo(Alcinoe.AndroidApi.WebRTC.JALWebRTC_PeerConnectionParameters));
TRegTypes.RegisterType('Alcinoe.AndroidApi.WebRTC.JALWebRTC', TypeInfo(Alcinoe.AndroidApi.WebRTC.JALWebRTC));
end;
initialization
RegisterTypes;
end.
|
unit ChartNT;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Menus,
ExtCtrls, StdCtrls, Spin, Buttons, Dialogs, Messages,
SysUtils, KzaCom;
type
TAxis = (aX,aY);
TAxisKind = (akCenter, akLeftCenter, akLeftBottom);
TChartNT = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
Panel5: TPanel;
BottomPanel: TPanel;
LeftPanel: TPanel;
Platform: TPaintBox;
TopPanel: TPanel;
RightPanel: TPanel;
Label1: TLabel;
HorizStepGridEdit: TSpinEdit;
RightBottomLabel: TLabel;
LeftBottomLabel: TLabel;
CenterBottomLabel: TLabel;
LeftTopLabel: TLabel;
Panel10: TPanel;
CloseBtn: TBitBtn;
RightTopLabel: TLabel;
CenterTopLabel: TLabel;
PopupMenu: TPopupMenu;
PanelsItem: TMenuItem;
AxisKindMenu: TMenuItem;
AxisCenterItem: TMenuItem;
AxisLeftCenterItem: TMenuItem;
AxisLeftBottomItem: TMenuItem;
GridVisibleItem: TMenuItem;
ScalesPanel: TPanel;
ScaleXEdit: TEdit;
ScaleYEdit: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
OkButton: TSpeedButton;
CancelButton: TSpeedButton;
ScaleItem: TMenuItem;
SaveBMPItem: TMenuItem;
SaveBMPDialog: TSaveDialog;
CursorItem: TMenuItem;
CursorPanel: TPanel;
XEdit: TEdit;
YEdit: TEdit;
Label5: TLabel;
Label6: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure PlatformPaint(Sender: TObject);
procedure HorizStepGridEditChange(Sender: TObject);
procedure PanelsItemClick(Sender: TObject);
procedure AxisCenterItemClick(Sender: TObject);
procedure AxisLeftCenterItemClick(Sender: TObject);
procedure AxisLeftBottomItemClick(Sender: TObject);
procedure GridVisibleItemClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure ScaleItemClick(Sender: TObject);
procedure SaveBMPItemClick(Sender: TObject);
procedure PlatformMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure CursorItemClick(Sender: TObject);
private
{ Private declarations }
canContinue: Boolean;
PrevPoint: TPoint;
FCenter: TPoint;
FAxisKind: TAxisKind;
FGridVisible: Boolean;
FHorizGridStep: Byte;
FVertGridStep: Byte;
FMaxLength: Word;
FCurentIndex: Integer;
FMaxX: Extended;
FMaxY: Extended;
FNameX: String;
FNameY: String;
FTakt: Double;
FScale: Byte;
FRateX: Extended;
FRateY: Extended;
FData: array [TAxis,0..1023] of Extended;
procedure SetCenter(Kind: TAxisKind);
procedure SetPanels(Kind: TAxisKind);
procedure SetRates(Kind: TAxisKind);
procedure SetAxisKind(Value: TAxisKind);
procedure SetHorizGridStep(Value: Byte);
procedure SetVertGridStep(Value: Byte);
function GetData(Axis: TAxis; Count: Cardinal): Extended;
procedure SetData(Axis: TAxis; Count: Cardinal; const Value: Extended);
function GetXX(Count: Cardinal): Extended;
function GetYY(Count: Cardinal): Extended;
procedure SetMaxLength(Value: Word);
procedure SetCurentIndex(Value: Integer);
procedure SetScale(Value: Byte);
procedure SetMaxX(Value: Extended);
procedure SetMaxY(Value: Extended);
procedure UpdateCursor;
procedure WMGetMinMaxInfo(var Message: TWMGetMinMaxInfo); message WM_GETMINMAXINFO;
public
{ Public declarations }
CurTakt: Extended;
canPaint: Boolean;
property Data[Axis: TAxis ;Count: Cardinal]: Extended read GetData write SetData;Default;
property XX[Count: Cardinal]: Extended read GetXX ;
property YY[Count: Cardinal]: Extended read GetYY ;
procedure AxisPaint;
procedure GridPaint;
procedure ChartPaint;
procedure AddPaint(ValueX,ValueY: Extended);
procedure Clear;
procedure UpdateMenu;
published
Property HorizGridStep: Byte read FHorizGridStep write SetHorizGridStep default 20;
Property VertGridStep: Byte read FVertGridStep write SetVertGridStep default 20;
property MaxLength: Word read FMaxLength write SetMaxLength default 1024;
property CurentIndex: Integer read FCurentIndex write SetCurentIndex default 0;
property GridVisible: boolean read FGridVisible write FGridVisible default True;
property AxisKind: TAxisKind read FAxisKind write SetAxisKind default akLeftBottom;
property MaxX: Extended read FMaxX write SetMaxX ;
property MaxY: Extended read FMaxY write SetMaxY ;
property Scale: Byte read FScale write SetScale default 100;
property NameX: String read FNameX Write FNameX;
property NameY: String read FNameY Write FNameY;
property Takt: Double read FTakt write FTakt;
end;
implementation
{$R *.DFM}
procedure TChartNT.FormCreate(Sender: TObject);
begin
canContinue:=True;
PrevPoint.X:=-1;
PrevPoint.Y:=-1;
FScale:=100;
FMaxX:=2;
MaxY:=3;
HorizGridStep:=20;
VertGridStep:=20;
MaxLength:=1024;
FCurentIndex:=0;
canPaint:=False;
GridVisible:=True;
AxisKind:=akLeftBottom;
{ For Component}
GridVisibleItem.Checked:=GridVisible;
case AxisKind of
akCenter : begin
AxisCenterItem.Checked:=True;
AxisLeftCenterItem.Checked:=False;
AxisLeftBottomItem.Checked:=False;
end;
akLeftCenter : begin
AxisCenterItem.Checked:=False;
AxisLeftCenterItem.Checked:=True;
AxisLeftBottomItem.Checked:=False;
end;
akLeftBottom : begin
AxisCenterItem.Checked:=False;
AxisLeftCenterItem.Checked:=False;
AxisLeftBottomItem.Checked:=True;
end;
end;
end;
procedure TChartNT.UpdateCursor;
var i,j: Integer;
t: Extended;
begin
j:=0;
t:=(PrevPoint.X-FCenter.X)/FRateX;
if (t<0)or(CurentIndex=0)or(t>xx[CurentIndex-1]) then begin
XEdit.Text:='Пусто';
YEdit.Text:='Пусто';
end else begin
for i:=0 to CurentIndex-1 do
if xx[i]>t then begin
j:=i-1;
break;
end;
XEdit.Text:=FloatToStr(xx[j]);
YEdit.Text:=FloatToStr(yy[j]);
end;
end;
procedure TChartNT.Clear;
begin
CurentIndex:=0;
PlatFormPaint(Self);
canContinue:=True;
end;
procedure TChartNT.UpdateMenu;
begin
if NameX='Текущее время' then CursorItem.Enabled:=True;
end;
procedure TChartNT.SetAxisKind(Value: TAxisKind);
begin
FAxisKind:=Value;
SetPanels(FAxisKind);
end;
procedure TChartNT.SetPanels(Kind: TAxisKind);
begin
Case Kind of
akCenter : begin
LeftPanel.Caption:=FloatToStr(-MaxX*Scale/100);
RightPanel.Caption:=FloatToStr(MaxX*Scale/100);
LeftTopLabel.Caption:='';
LeftBottomLabel.Caption:='';
RightTopLabel.Caption:='';
RightBottomLabel.Caption:='';
CenterTopLabel.Caption:=FloatToStr(MaxY*Scale/100);
CenterBottomLabel.Caption:=FloatToStr(-MaxY*Scale/100);
end;
akLeftCenter : begin
LeftPanel.Caption:='0';
RightPanel.Caption:=FloatToStr(MaxX*Scale/100);
LeftTopLabel.Caption:=FloatToStr(MaxY*Scale/100);
LeftBottomLabel.Caption:=FloatToStr(-MaxY*Scale/100);
RightTopLabel.Caption:='';
RightBottomLabel.Caption:='';
CenterTopLabel.Caption:='';
CenterBottomLabel.Caption:='';
end;
akLeftBottom : begin
LeftPanel.Caption:='';
RightPanel.Caption:='';
LeftTopLabel.Caption:=FloatToStr(MaxY*Scale/100);
LeftBottomLabel.Caption:='0 ';
RightTopLabel.Caption:='';
RightBottomLabel.Caption:=FloatToStr(MaxX*Scale/100);
CenterTopLabel.Caption:='';
CenterBottomLabel.Caption:='';
end;
end;
end;
procedure TChartNT.SetRates(Kind: TAxisKind);
begin
Case Kind of
akCenter : begin
FRateX := 100*(PlatForm.Width/(FMaxX*2*FScale));
FRateY := 100*(PlatForm.Height/(FMaxY*2*FScale));
end;
akLeftCenter : begin
FRateX := 100*(PlatForm.Width/(FMaxX*FScale));
FRateY := 100*(PlatForm.Height/(FMaxY*2*FScale));
end;
akLeftBottom : begin
FRateX := 100*(PlatForm.Width/(FMaxX*FScale));
FRateY := 100*(PlatForm.Height/(FMaxY*FScale));
end;
end;
if CursorItem.Checked then UpdateCursor;
end;
procedure TChartNT.SetMaxX(Value: Extended);
begin
FMaxX := Value;
SetRates(AxisKind);
SetPanels(AxisKind);
end;
procedure TChartNT.SetMaxY(Value: Extended);
begin
FMaxY := Value;
SetRates(AxisKind);
SetPanels(AxisKind);
end;
procedure TChartNT.SetCenter(Kind: TAxisKind);
begin
Case Kind of
akCenter : begin
FCenter.X:=PlatForm.Width div 2;
FCenter.Y:=Platform.Height div 2;
end;
akLeftCenter : begin
FCenter.X:=0;
FCenter.Y:=Platform.Height div 2;
end;
akLeftBottom : begin
FCenter.X:=0;
FCenter.Y:=Platform.Height-1;
end;
end;
end;
procedure TChartNT.AxisPaint;
begin
with PlatForm.Canvas do begin
Pen.Color:=clGray;
Pen.Style:=psSolid;
Pen.Mode:=pmCopy;
Pen.Width:=1;
MoveTo(FCenter.X,0);
LineTo(FCenter.X,Platform.Height-1);
MoveTo(0,FCenter.Y);
LineTo(Platform.Width-1,FCenter.Y);
end;
end;
procedure TChartNT.GridPaint;
begin
if GridVisible then begin
with PlatForm.Canvas do begin
Pen.Color:=clGray;
Pen.Style:=psDot;
Pen.Mode:=pmCopy;
Pen.Width:=1;
MoveTo(FCenter.X,0);
While (PlatForm.Width-1-PenPos.X)>HorizGridStep do begin
MoveTo(PenPos.X+HorizGridStep,0);
LineTo(PenPos.X,PlatForm.Height-1);
end;
MoveTo(FCenter.X,0);
While PenPos.X>HorizGridStep do begin
MoveTo(PenPos.X-HorizGridStep,0);
LineTo(PenPos.X,PlatForm.Height-1);
end;
MoveTo(0,FCenter.Y);
While (PenPos.Y)>VertGridStep do begin
MoveTo(0,PenPos.Y-VertGridStep);
LineTo(PlatForm.Width-1,PenPos.Y);
end;
MoveTo(0,FCenter.Y);
While (PlatForm.Height-1-PenPos.Y)>VertGridStep do begin
MoveTo(0,PenPos.Y+VertGridStep);
LineTo(PlatForm.Width-1,PenPos.Y);
end;
end;
end;
end;
procedure TChartNT.ChartPaint;
var i: Integer;
a,b,c,d,
x1,x2,y1,y2 : Extended;
begin
with PlatForm.Canvas do begin
Pen.Color:=clRed;
Pen.Style:=psSolid;
Pen.Mode:=pmCopy;
end;
for i:=1 to CurentIndex-1 do begin
a:=-1;
b:=-1;
c:=-1;
d:=-1;
x1:=FCenter.X+XX[i-1]*FRateX;
y1:=FCenter.Y-YY[i-1]*FRateY;
x2:=FCenter.X+XX[i]*FRateX;
y2:=FCenter.Y-yy[i]*FRateY;
with platform do begin
if abs(x1-x2)<1 then begin
if (x1>=0)and(x1<=Platform.Width) then begin
if y1>Platform.Height then begin
a:=trunc(x1); b:=Platform.Height;
end else begin
if y1<0 then begin
a:=trunc(x1); b:=0;
end else begin
a:=trunc(x1); b:=trunc(y1);
end;
end;{y1}
if y2>Platform.Height then begin
c:=trunc(x2); d:=Platform.Height;
end else begin
if y2<0 then begin
c:=trunc(x1); d:=0;
end else begin
c:=trunc(x2); d:=trunc(y2);
end;
end;{y2}
end;
end else begin{x1<>x2}
if abs(y1-y2)<1 then begin
if (y1>=0)and(y1<=Platform.Height) then begin
if x1>Platform.Width then begin
a:=Platform.Width; b:=trunc(y1);
end else begin
if x1<0 then begin
a:=0; b:=trunc(y1);
end else begin
a:=trunc(x1); b:=trunc(y1);
end;
end;{x1}
if x2>Platform.Width then begin
c:=Platform.Width; d:=y2;
end else begin
if x2<0 then begin
c:=0; d:=y2;
end else begin
c:=x2; d:=y2;
end;
end;{x2}
end;
end else begin{y1<>y2}
{begin x1,y1}
if x1<0 then begin
y1:=(-x2*(y1-y2)/(x1-x2)+y2);
x1:=0;
if y1<0 then begin
x1:=(-y2*(x1-x2)/(y1-y2)+x2);
y1:=0;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=0;
end;
end else begin
if y1>Platform.Height then begin
x1:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y1:=PlatForm.Height;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=Platform.Height;
end;
end else begin
a:=0; b:=y1;
end;
end;
end else begin
if x1>Platform.Width then begin
y1:=((Platform.Width-x2)*(y1-y2)/(x1-x2)+y2);
x1:=Platform.Width;
if y1<0 then begin
x1:=(-y2*(x1-x2)/(y1-y2)+x2);
y1:=0;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=0;
end;
end else begin
if y1>Platform.Height then begin
x1:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y1:=Platform.Height;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=Platform.Height;
end;
end else begin
a:=Platform.Width; b:=y1;
end;
end;
end else begin
if y1<0 then begin
x1:=(-y2*(x1-x2)/(y1-y2)+x2);
y1:=0;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=0;
end;
end else begin
if y1>Platform.Height then begin
x1:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y1:=PlatForm.Height;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=Platform.Height;
end;
end else begin
a:=x1; b:=y1;
end;
end;
end;
end;
{begin x2,y2}
if x2<0 then begin
y2:=(-x2*(y1-y2)/(x1-x2)+y2);
x2:=0;
if y2<0 then begin
x2:=(-y2*(x1-x2)/(y1-y2)+x2);
y2:=0;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=0;
end;
end else begin
if y2>Platform.Height then begin
x2:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y2:=PlatForm.Height;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=Platform.Height;
end;
end else begin
c:=0; d:=y2;
end;
end;
end else begin
if x2>Platform.Width then begin
y2:=((Platform.Width-x2)*(y1-y2)/(x1-x2)+y2);
x2:=Platform.Width;
if y2<0 then begin
x2:=(-y2*(x1-x2)/(y1-y2)+x2);
y2:=0;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=0;
end;
end else begin
if y2>Platform.Height then begin
x2:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y2:=PlatForm.Height;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=Platform.Height;
end;
end else begin
c:=Platform.Width; d:=y2;
end;
end;
end else begin
if y2<0 then begin
x2:=(-y2*(x1-x2)/(y1-y2)+x2);
y2:=0;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=0;
end;
end else begin
if y2>Platform.Height then begin
x2:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y2:=Platform.Height;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=Platform.Height;
end;
end else begin
c:=x2; d:=y2;
end;
end;
end;
end;
end;
end;
Canvas.MoveTo( trunc(a),trunc(b));
Canvas.LineTo( trunc(c),trunc(d))
end;
end;
end;
procedure TChartNT.AddPaint(ValueX,ValueY: Extended);
var a,b,c,d,
x1,x2,y1,y2: Extended;
begin
a:=-1;
b:=-1;
c:=-1;
d:=-1;
if (CurentIndex<MaxLength)then begin
if CurTakt>=Takt then begin
CurTakt:=0;
with PlatForm.Canvas do begin
Pen.Color:=clRed;
Pen.Style:=psSolid;
Pen.Mode:=pmCopy;
end;
Data[aX,CurentIndex]:=ValueX;
Data[aY,CurentIndex]:=ValueY;
if PlatForm.Visible then
if CurentIndex>0 then begin
x1:=FCenter.X+XX[curentIndex-1]*FRateX;
y1:=FCenter.Y-YY[CurentIndex-1]*FRateY;
x2:=FCenter.X+ValueX*FRateX;
y2:=FCenter.Y-ValueY*FRateY;
with platform do begin
if abs(x1-x2)<1 then begin
if (x1>=0)and(x1<=Platform.Width) then begin
if y1>Platform.Height then begin
a:=trunc(x1); b:=Platform.Height;
end else begin
if y1<0 then begin
a:=trunc(x1); b:=0;
end else begin
a:=trunc(x1); b:=trunc(y1);
end;
end;{y1}
if y2>Platform.Height then begin
c:=trunc(x2); d:=Platform.Height;
end else begin
if y2<0 then begin
c:=trunc(x1); d:=0;
end else begin
c:=trunc(x2); d:=trunc(y2);
end;
end;{y2}
end;
end else begin{x1<>x2}
if abs(y1-y2)<1 then begin
if (y1>=0)and(y1<=Platform.Height) then begin
if x1>Platform.Width then begin
a:=Platform.Width; b:=trunc(y1);
end else begin
if x1<0 then begin
a:=0; b:=trunc(y1);
end else begin
a:=trunc(x1); b:=trunc(y1);
end;
end;{x1}
if x2>Platform.Width then begin
c:=Platform.Width; d:=y2;
end else begin
if x2<0 then begin
c:=0; d:=y2;
end else begin
c:=x2; d:=y2;
end;
end;{x2}
end;
end else begin{y1<>y2}
{begin x1,y1}
if x1<0 then begin
y1:=(-x2*(y1-y2)/(x1-x2)+y2);
x1:=0;
if y1<0 then begin
x1:=(-y2*(x1-x2)/(y1-y2)+x2);
y1:=0;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=0;
end;
end else begin
if y1>Platform.Height then begin
x1:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y1:=PlatForm.Height;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=Platform.Height;
end;
end else begin
a:=0; b:=y1;
end;
end;
end else begin
if x1>Platform.Width then begin
y1:=((Platform.Width-x2)*(y1-y2)/(x1-x2)+y2);
x1:=Platform.Width;
if y1<0 then begin
x1:=(-y2*(x1-x2)/(y1-y2)+x2);
y1:=0;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=0;
end;
end else begin
if y1>Platform.Height then begin
x1:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y1:=Platform.Height;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=Platform.Height;
end;
end else begin
a:=Platform.Width; b:=y1;
end;
end;
end else begin
if y1<0 then begin
x1:=(-y2*(x1-x2)/(y1-y2)+x2);
y1:=0;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=0;
end;
end else begin
if y1>Platform.Height then begin
x1:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y1:=PlatForm.Height;
if (x1>=0)and(x1<=Platform.Width) then begin
a:=x1; b:=Platform.Height;
end;
end else begin
a:=x1; b:=y1;
end;
end;
end;
end;
{begin x2,y2}
if x2<0 then begin
y2:=(-x2*(y1-y2)/(x1-x2)+y2);
x2:=0;
if y2<0 then begin
x2:=(-y2*(x1-x2)/(y1-y2)+x2);
y2:=0;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=0;
end;
end else begin
if y2>Platform.Height then begin
x2:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y2:=PlatForm.Height;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=Platform.Height;
end;
end else begin
c:=0; d:=y2;
end;
end;
end else begin
if x2>Platform.Width then begin
y2:=((Platform.Width-x2)*(y1-y2)/(x1-x2)+y2);
x2:=Platform.Width;
if y2<0 then begin
x2:=(-y2*(x1-x2)/(y1-y2)+x2);
y2:=0;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=0;
end;
end else begin
if y2>Platform.Height then begin
x2:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y2:=PlatForm.Height;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=Platform.Height;
end;
end else begin
c:=Platform.Width; d:=y2;
end;
end;
end else begin
if y2<0 then begin
x2:=(-y2*(x1-x2)/(y1-y2)+x2);
y2:=0;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=0;
end;
end else begin
if y2>Platform.Height then begin
x2:=((Platform.Height-y2)*(x1-x2)/(y1-y2)+x2);
y2:=Platform.Height;
if (x2>=0)and(x2<=Platform.Width) then begin
c:=x2; d:=Platform.Height;
end;
end else begin
c:=x2; d:=y2;
end;
end;
end;
end;
end;
end;
Canvas.MoveTo( trunc(a),trunc(b));
Canvas.LineTo( trunc(c),trunc(d))
end;
end;
CurentIndex:=CurentIndex+1;
end; end else if canContinue then begin
MessageDlg('График "'+Caption+'" прекратил прорисовку. Исчерпан лимит памяти.',mtInformation,[mbOk],0);
CanContinue:=False;
end;
end;
procedure TChartNT.WMGetMinMaxInfo(var Message: TWMGetMinMaxInfo);
begin
inherited;
With (Message.MinMaxInfo^).ptMinTrackSize do begin
if CursorItem.Checked then x:=400
else x:=330;
y:=205;
end;
end;
procedure TChartNT.SetScale(Value: Byte);
begin
if (Value>200)or(Value<50) then
raise ERangeError.Create('Invalid scale Value!')
else begin
FScale:=Value;
HorizStepGridEdit.Value:=Value;
SetRates(AxisKind);
end;
end;
procedure TChartNT.SetCurentIndex(Value: Integer);
begin
if (Value>MaxLength) or (Value<0) then raise ERangeError.Create('CurentIndex Out of MaxLength')
else FCurentIndex:=Value;
end;
procedure TChartNT.SetData(Axis: TAxis; Count: Cardinal; const Value: Extended);
begin
if Count>MaxLength-1 then begin
raise ERangeError.Create('CurentIndex Out of MaxLength')
end else begin
FData[Axis, Count]:=Value;
end;
end;
function TChartNT.GetData(Axis: TAxis; Count: Cardinal): Extended;
begin
if Count>MaxLength-1 then begin
raise ERangeError.Create('CurentIndex Out of MaxLength')
end else begin
Result:=FData[Axis, Count];
end;
end;
function TChartNT.GetXX(Count: Cardinal): Extended;
begin
if Count>MaxLength-1 then begin
raise ERangeError.Create('CurentIndex Out of MaxLength')
end else begin
Result:=FData[aX, Count];
end;
end;
function TChartNT.GetYY(Count: Cardinal): Extended;
begin
if Count>MaxLength-1 then begin
raise ERangeError.Create('CurentIndex Out of MaxLength')
end else begin
Result:=FData[aY, Count];
end;
end;
procedure TChartNT.SetMaxLength(Value: Word);
begin
case Value of
0..1 : FMaxLength:=1;
2..1024 : FMaxLength:=Value;
else FMaxLength:=1024;
end;
end;
procedure TChartNT.SetHorizGridStep(Value: Byte);
begin
if Value<10 then FHorizGridStep:=10
else FHorizGridStep:=Value;
end;
procedure TChartNT.SetVertGridStep(Value: Byte);
begin
if Value<10 then FVertGridStep:=10
else FVertGridStep:=Value;
end;
procedure TChartNT.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TChartNT.PlatformPaint(Sender: TObject);
var p: TPoint;
begin
With Platform.Canvas do begin
Brush.Color:=clWhite;
Brush.Style:=bsSolid;
FillRect(ClipRect);
SetCenter(AxisKind);
GridPaint;
AxisPaint;
SetRates(AxisKind);
if canPaint then begin
ChartPaint;
end;
if CursorItem.Checked then begin
p:=PenPos;
Pen.Mode:=pmXor;
Pen.Color:=clRed;
moveTo(Self.PrevPoint.X,0);
lineTo(Self.PrevPoint.X,Platform.Height-1);
MoveTo(p.X,p.Y);
end;
end;
end;
procedure TChartNT.HorizStepGridEditChange(Sender: TObject);
var NewStep: Integer;
begin
Scale:=HorizStepGridEdit.Value;
NewStep:=Trunc(2000/Scale);
HorizGridStep:=NewStep;
VertGridStep:=NewStep;
SetPanels(AxisKind);
PlatForm.Refresh;
end;
procedure TChartNT.PanelsItemClick(Sender: TObject);
begin
If PanelsItem.Checked then begin
PanelsItem.Checked:=False;
LeftPanel.Visible:=False;
RightPanel.Visible:=False;
TopPanel.Visible:=False;
BottomPanel.Visible:=False;
end else begin
PanelsItem.Checked:=True;
LeftPanel.Visible:=True;
RightPanel.Visible:=True;
TopPanel.Visible:=True;
BottomPanel.Visible:=True;
end;
end;
procedure TChartNT.AxisCenterItemClick(Sender: TObject);
begin
AxisCenterItem.Checked:=True;
AxisLeftBottomItem.Checked:=False;
AxisLeftCenterItem.Checked:=False;
AxisKind:=akCenter;
canPaint:=True;
SetPanels(akCenter);
SetRates(akCenter);
Self.PlatformPaint(Self);
end;
procedure TChartNT.AxisLeftCenterItemClick(Sender: TObject);
begin
AxisCenterItem.Checked:=False;
AxisLeftBottomItem.Checked:=False;
AxisLeftCenterItem.Checked:=True;
AxisKind:=akLeftCenter;
canPaint:=True;
SetPanels(akLeftCenter);
SetRates(akLeftCenter);
Self.PlatformPaint(Self);
end;
procedure TChartNT.AxisLeftBottomItemClick(Sender: TObject);
begin
AxisCenterItem.Checked:=False;
AxisLeftBottomItem.Checked:=True;
AxisLeftCenterItem.Checked:=False;
AxisKind:=akLeftBottom;
canPaint:=True;
SetPanels(akLeftBottom);
SetRates(akLeftBottom);
Self.PlatformPaint(Self);
end;
procedure TChartNT.GridVisibleItemClick(Sender: TObject);
begin
GridVisible:=not GridVisible;
GridVisibleItem.Checked:=GridVisible;
Self.PlatformPaint(Self);
end;
procedure TChartNT.OkButtonClick(Sender: TObject);
begin
try
MaxX:=StrToFloat(ScaleXEdit.Text);
MaxY:=StrToFloat(ScaleYEdit.Text);
ScalesPanel.Hide;
SetPanels(AxisKind);
SetRates(AxisKind);
PlatForm.Refresh;
except
on EConvertError do MessageDlg('Try ones more! Dummy.',mtError,[mbOk],0);
end;
end;
procedure TChartNT.CancelButtonClick(Sender: TObject);
begin
ScalesPanel.Hide;
end;
procedure TChartNT.ScaleItemClick(Sender: TObject);
begin
ScalesPanel.Top:=Trunc((Panel5.Height-ScalesPanel.Height)/2);
ScalesPanel.Left:=Trunc((Panel5.Width-ScalesPanel.Width)/2);
ScaleXEdit.Text:=FloatToStr(MaxX);
ScaleYEdit.Text:=FloatToStr(MaxY);
ScalesPanel.Show;
end;
procedure TChartNT.SaveBMPItemClick(Sender: TObject);
var Bmp : TBitMap;
Rect2 : TRect;
Rect1: TRect;
begin
If SaveBmpDialog.Execute then begin
Bmp:=TBitMap.Create;
PlatFormPaint(Self);
Application.ProcessMessages;
Rect2.Left:=Self.ClientRect.Left+11;
Rect2.Top:=Self.ClientRect.Top+11;
Rect2.Right:=Self.ClientRect.Right-11;
Rect2.Bottom:=Self.ClientRect.Bottom-42;
Bmp.Width:=Rect2.Right-Rect2.Left+10;
Bmp.Height:=Rect2.Bottom-Rect2.Top+40;
Bmp.Monochrome:=False;
Rect1.left:=5;
Rect1.Top:=5;
Rect1.Right:=Bmp.Width-5;
Rect1.Bottom:=Bmp.Height-35;
With BMP.Canvas do begin
Pen.Color:=clRed;
Pen.Style:=psSolid;
Pen.Mode:=pmCopy;
Pen.Width:=1;
Brush.Color:=clWhite;
Brush.Style:=bsSolid;
FillRect(ClipRect);
Rectangle(Rect1.left-1,Rect1.Top-1,Rect1.Right+1,Rect1.Bottom+1);
Pen.Color:=clBlack;
TextOut(40,ClipRect.Bottom-25,'Рис. . '+Self.Caption+'.');
end;
Bmp.Canvas.CopyRect(Rect1,Self.Canvas,Rect2);
Bmp.SaveToFile(SaveBMPDialog.FileName);
Bmp.Free;
end;
end;
procedure TChartNT.PlatformMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
var p: TPoint;
begin
if Sender = PlatForm then
if CursorItem.Checked then begin
With PlatForm.Canvas do begin
p:=PenPos;
Pen.Mode:=pmXor;
Pen.Color:=clRed;
moveTo(Self.PrevPoint.X,0);
lineTo(Self.PrevPoint.X,Height-1);
moveTo(X,0);
lineTo(X,Height-1);
Self.PrevPoint.X:=X;
Self.PrevPoint.Y:=Y;
MoveTo(p.X,p.Y);
UpdateCursor;
end;
end;
end;
procedure TChartNT.CursorItemClick(Sender: TObject);
begin
platFormMouseMove(PlatForm,[],-1,-1);
CursorItem.Checked:= not CursorItem.Checked;
if CursorItem.Checked then PlatForm.Cursor:=crHSplit
else PlatForm.Cursor:=crDefault;
if Width<400 then Width:=400;
CursorPanel.Visible:=CursorItem.Checked;
end;
end.
|
unit DBDemosEntities;
interface
uses
Aurelius.Mapping.Attributes,
Aurelius.Types.Blob;
type
[Entity, Automapping]
[Id('FCustNo', TIdGenerator.None)]
TCustomer = class
private
FCustno: double;
FCompany: string;
[Column('Addr1', [])]
FAddr1: string;
[Column('Addr2', [])]
FAddr2: string;
FCity: string;
FState: string;
FZip: string;
FCountry: string;
FPhone: string;
FFax: string;
FTaxrate: double;
FContact: string;
FLastinvoicedate: TDateTime;
public
property Custno: double read FCustno write FCustno;
property Company: string read FCompany write FCompany;
property Addr1: string read FAddr1 write FAddr1;
property Addr2: string read FAddr2 write FAddr2;
property City: string read FCity write FCity;
property State: string read FState write FState;
property Zip: string read FZip write FZip;
property Country: string read FCountry write FCountry;
property Phone: string read FPhone write FPhone;
property Fax: string read FFax write FFax;
property Taxrate: double read FTaxrate write FTaxrate;
property Contact: string read FContact write FContact;
property Lastinvoicedate: TDateTime read FLastinvoicedate write FLastinvoicedate;
end;
[Entity, Automapping]
[Id('FSpeciesNo', TIdGenerator.None)]
TBiolife = class
private
FSpeciesNo: double;
FCategory: string;
FCommonName: string;
FSpeciesName: string;
[Column('LENGTH__CM_', [])]
FLengthCm: double;
FLengthIn: double;
FNotes: TBlob;
FGraphic: TBlob;
public
property SpeciesNo: double read FSpeciesNo write FSpeciesNo;
property Category: string read FCategory write FCategory;
property CommonName: string read FCommonName write FCommonName;
property SpeciesName: string read FSpeciesName write FSpeciesName;
property LengthCm: double read FLengthCm write FLengthCm;
property LengthIn: double read FLengthIn write FLengthIn;
property Notes: TBlob read FNotes write FNotes;
property Graphic: TBlob read FGraphic write FGraphic;
end;
implementation
initialization
RegisterEntity(TCustomer);
RegisterEntity(TBiolife);
end.
|
unit uFrmLembreteEditar;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls, Vcl.ExtCtrls,
uDM, uLembreteDAO, uLembrete, generics.defaults, generics.collections, Vcl.ComCtrls;
type
TfrmLembreteEditar = class(TForm)
Panel3: TPanel;
bInserir: TSpeedButton;
bExcluir: TSpeedButton;
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
edtTitulo: TEdit;
mmDescricao: TMemo;
dtpDataHora: TDateTimePicker;
procedure bInserirClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure bExcluirClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
_LembreteDAO: TLembreteDAO;
_Lembrete: TLembrete;
procedure PreencherLembrete;
procedure PreencherTela;
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent; pLembrete: TLembrete);
end;
var
frmLembreteEditar: TfrmLembreteEditar;
implementation
{$R *.dfm}
procedure TfrmLembreteEditar.PreencherLembrete;
begin
_Lembrete.Titulo := EdtTitulo.Text;
_Lembrete.Descricao := MmDescricao.Text;
_Lembrete.DataHora := DtpDataHora.DateTime;
end;
procedure TfrmLembreteEditar.PreencherTela;
begin
EdtTitulo.Text := _Lembrete.Titulo;
MmDescricao.Text := _Lembrete.Descricao;
DtpDataHora.DateTime := _Lembrete.DataHora;
end;
constructor TFrmLembreteEditar.Create(AOwner: TComponent; pLembrete: TLembrete);
begin
inherited Create(AOwner);
_LembreteDAO := TLembreteDAO.Create;
try
if Assigned(pLembrete) then
begin
_Lembrete := pLembrete;
PreencherTela;
end;
except on e: exception do
raise Exception.Create(E.Message);
end;
end;
procedure TfrmLembreteEditar.bExcluirClick(Sender: TObject);
begin
close;
end;
procedure TfrmLembreteEditar.bInserirClick(Sender: TObject);
begin
PreencherLembrete;
if _LembreteDAO.Alterar(_Lembrete) then
begin
ShowMessage('Registro editado com sucesso');
Close;
end;
end;
procedure TfrmLembreteEditar.FormDestroy(Sender: TObject);
begin
try
if Assigned(_LembreteDAO) then
FreeAndNil(_LembreteDAO);
except
on e: exception do
raise Exception.Create(E.Message);
end;
end;
procedure TfrmLembreteEditar.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = VK_ESCAPE then
close;
end;
end.
|
unit BaseNTests;
interface
uses
System.Generics.Collections, System.Math, System.NetEncoding, System.SysUtils,
DUnitX.TestFramework,
BaseTests, uBase64,
uBaseN, uBaseBigN, uStringGenerator;
type
IBaseNTests = interface
['{97E58C5C-BED5-49EC-9476-4AEC6DE7FE9C}']
end;
[TestFixture]
TBaseNTests = class(TInterfacedObject, IBaseNTests)
strict private
class function Helper(const InString: String): String; static;
public
[Test]
procedure BaseNCompareToBase64();
[Test]
procedure ReverseOrder();
[Test]
procedure GetOptimalBitsCount();
[Test]
procedure EncodeDecodeBaseN();
[Test]
procedure EncodeDecodeBaseBigN();
[Test]
procedure EncodeDecodeBaseBigNMaxCompression();
end;
implementation
procedure TBaseNTests.BaseNCompareToBase64();
var
s, encoded, base64standard: String;
_converter: IBaseN;
begin
s := 'aaa';
_converter := TBaseN.Create(TBase64.DefaultAlphabet);
encoded := _converter.EncodeString(s);
base64standard := Helper(s);
base64standard := StringReplace(base64standard, sLineBreak, '',
[rfReplaceAll]);
Assert.AreEqual(base64standard, encoded);
end;
class function TBaseNTests.Helper(const InString: String): String;
var
temp: TArray<Byte>;
begin
temp := TEncoding.UTF8.GetBytes(InString);
result := TNetEncoding.Base64.EncodeBytesToString(temp);
end;
procedure TBaseNTests.ReverseOrder();
var
_converter: IBaseN;
original, encoded, decoded: String;
begin
_converter := TBaseN.Create(TStringGenerator.GetAlphabet(54), 32, Nil, True);
original := 'sdfrewwekjthkjh';
encoded := _converter.EncodeString(original);
decoded := _converter.DecodeToString(encoded);
Assert.AreEqual(original, decoded);
end;
procedure TBaseNTests.GetOptimalBitsCount();
var
charsCountInBits: UInt32;
builder: TStringBuilder;
i, bits: Integer;
ratio, tempDouble: Double;
str: String;
begin
Assert.AreEqual(5, TBaseN.GetOptimalBitsCount2(32, charsCountInBits));
Assert.AreEqual(6, TBaseN.GetOptimalBitsCount2(64, charsCountInBits));
Assert.AreEqual(32, TBaseN.GetOptimalBitsCount2(85, charsCountInBits));
Assert.AreEqual(13, TBaseN.GetOptimalBitsCount2(91, charsCountInBits));
builder := TStringBuilder.Create;
for i := 2 to 256 do
begin
bits := TBaseBigN.GetOptimalBitsCount2(UInt32(i), charsCountInBits, 512);
tempDouble := (bits * 1.0);
ratio := tempDouble / charsCountInBits;
builder.AppendLine(IntToStr(bits) + ' ' + UIntToStr(charsCountInBits) + ' '
+ FormatFloat('0.0000000', ratio));
end;
str := builder.ToString();
end;
procedure TBaseNTests.EncodeDecodeBaseN();
var
bytes: TList<Byte>;
testByte: Byte;
radix: UInt32;
baseN: IBaseN;
testBytesCount, i: Integer;
_array, decoded: TArray<Byte>;
encoded: String;
begin
testByte := 157;
bytes := TList<Byte>.Create;
try
for radix := 2 to Pred(1000) do
begin
baseN := TBaseN.Create(TStringGenerator.GetAlphabet(Integer(radix)), 64);
testBytesCount := Max((baseN.BlockBitsCount + 7) div 8,
(baseN.BlockCharsCount));
bytes.Clear;
i := 0;
while i <= (testBytesCount + 1) do
begin
_array := bytes.ToArray();
encoded := baseN.Encode(_array);
decoded := baseN.Decode(encoded);
Assert.AreEqualMemory(Pointer(_array), Pointer(decoded),
Length(_array));
bytes.Add(testByte);
Inc(i);
end;
end;
finally
bytes.Free;
end;
end;
procedure TBaseNTests.EncodeDecodeBaseBigN();
var
bytes: TList<Byte>;
testByte: Byte;
radix: UInt32;
baseN: IBaseBigN;
testBytesCount, i: Integer;
_array, decoded: TArray<Byte>;
encoded: String;
begin
testByte := 157;
bytes := TList<Byte>.Create;
try
for radix := 2 to Pred(1000) do
begin
baseN := TBaseBigN.Create
(TStringGenerator.GetAlphabet(Integer(radix)), 256);
testBytesCount := Max((baseN.BlockBitsCount + 7) div 8,
(baseN.BlockCharsCount));
bytes.Clear;
i := 0;
while i <= (testBytesCount + 1) do
begin
_array := bytes.ToArray();
encoded := baseN.Encode(_array);
decoded := baseN.Decode(encoded);
Assert.AreEqualMemory(Pointer(_array), Pointer(decoded),
Length(_array));
bytes.Add(testByte);
Inc(i);
end;
end;
finally
bytes.Free;
end;
end;
procedure TBaseNTests.EncodeDecodeBaseBigNMaxCompression();
var
bytes: TList<Byte>;
testByte: Byte;
radix: UInt32;
baseN: IBaseBigN;
testBytesCount, i: Integer;
_array, decoded: TArray<Byte>;
encoded: String;
begin
testByte := 157;
bytes := TList<Byte>.Create;
try
for radix := 2 to Pred(1000) do
begin
baseN := TBaseBigN.Create(TStringGenerator.GetAlphabet(Integer(radix)),
256, Nil, False, True);
testBytesCount := Max((baseN.BlockBitsCount + 7) div 8,
(baseN.BlockCharsCount));
bytes.Clear;
i := 0;
while i <= (testBytesCount + 1) do
begin
_array := bytes.ToArray();
encoded := baseN.Encode(_array);
decoded := baseN.Decode(encoded);
Assert.AreEqualMemory(Pointer(_array), Pointer(decoded),
Length(_array));
bytes.Add(testByte);
Inc(i);
end;
end;
finally
bytes.Free;
end;
end;
initialization
TDUnitX.RegisterTestFixture(TBaseNTests);
end.
|
{Copyright (C) 2012-2015 Benito van der Zander
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
}
unit xidelbase;
{$mode objfpc}{$H+}
{$modeswitch advancedrecords}
interface
uses
Classes, {$ifdef win32} windows, {$endif}
extendedhtmlparser, xquery, sysutils, bbutils, simplehtmltreeparser, multipagetemplate,
internetaccess, contnrs, simplexmltreeparserfpdom, xquery_module_file, xquery_module_math,
rcmdline,math
;
var cgimode: boolean = false;
allowInternetAccess: boolean = true;
allowFileAccess: boolean = true;
xqueryDefaultCollation: string = '';
mycmdline: TCommandLineReader;
defaultUserAgent: string = 'Mozilla/3.0 (compatible; Xidel)';
majorVersion: integer = 0;
minorVersion: integer = 9;
buildVersion: integer = 7;
type EXidelException = class(Exception);
var
onPostParseCmdLine: procedure ();
onPrepareInternet: function (const useragent, proxy: string; onReact: TTransferReactEvent): tinternetaccess;
onRetrieve: function (const method, url, postdata, headers: string): string;
onPreOutput: procedure (extractionKind: TExtractionKind);
procedure perform;
implementation
uses process, strutils, bigdecimalmath, xquery_json, xquery__regex, xquery_utf8 {$ifdef unix},termio{$endif};
//{$R xidelbase.res}
///////////////LCL IMPORT
//uses lazutf8;
{$ifdef windows}
function WinCPToUTF8(const s: string): string; {$ifdef WinCe}inline;{$endif}
// result has codepage CP_ACP
var
UTF16WordCnt: SizeInt;
UTF16Str: UnicodeString;
begin
{$ifdef WinCE}
Result := SysToUtf8(s);
{$else}
Result:=s;(*
if IsASCII(Result) then begin
{$ifdef FPC_HAS_CPSTRING}
// prevent codepage conversion magic
SetCodePage(RawByteString(Result), CP_ACP, False);
{$endif}
exit;
end; *)
UTF16WordCnt:=MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Pointer(s), length(s), nil, 0);
// this will null-terminate
if UTF16WordCnt>0 then
begin
setlength(UTF16Str, UTF16WordCnt);
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Pointer(s), length(s), @UTF16Str[1], UTF16WordCnt);
Result:=UTF8Encode(UTF16Str);
{$ifdef FPC_HAS_CPSTRING}
// prevent codepage conversion magic
SetCodePage(system.RawByteString(Result), CP_ACP, False);
{$endif}
end;
{$endif}
end;
function ConsoleToUTF8(const s: string): string;// converts UTF8 string to console encoding (used by Write, WriteLn)
{$ifNdef WinCE}
var
Dst: PChar;
{$endif}
begin
{$ifdef WinCE}
Result := SysToUTF8(s);
{$else}
Dst := AllocMem((Length(s) + 1) * SizeOf(Char));
if OemToChar(PChar(s), Dst) then
Result := StrPas(Dst)
else
Result := s;
FreeMem(Dst);
Result := WinCPToUTF8(Result);
{$endif}
end;
(*
function UTF8ToConsole(const s: string): string;
{$ifNdef WinCE}
var
Dst: PChar;
{$endif}
begin
{$ifdef WinCE}
Result := UTF8ToSys(s);
{$else WinCE}
{$ifndef NO_CP_RTL}
Result := UTF8ToWinCP(s);
{$else NO_CP_RTL}
Result := UTF8ToSys(s); // Kept for compatibility
{$endif NO_CP_RTL}
Dst := AllocMem((Length(Result) + 1) * SizeOf(Char));
if CharToOEM(PChar(Result), Dst) then
Result := StrPas(Dst);
FreeMem(Dst);
{$ifndef NO_CP_RTL}
SetCodePage(RawByteString(Result), CP_OEMCP, False);
{$endif NO_CP_RTL}
{$endif WinCE}
end;*)
{$endif}
function GetEnvironmentVariableUTF8(const EnvVar: string): String;
begin
{$IFDEF FPC_RTL_UNICODE}
Result:=UTF16ToUTF8(SysUtils.GetEnvironmentVariable(UTF8ToUTF16(EnvVar)));
{$ELSE}
// on Windows SysUtils.GetEnvironmentString returns OEM encoded string
// so ConsoleToUTF8 function should be used!
// RTL issue: http://bugs.freepascal.org/view.php?id=15233
Result:={$ifdef windows}ConsoleToUTF8{$endif}(SysUtils.GetEnvironmentVariable({UTF8ToSys}(EnvVar)));
{$ENDIF}
end;
/////////////////////////////////////////////////////
type TOutputFormat = (ofAdhoc, ofJsonWrapped, ofXMLWrapped, ofRawXML, ofRawHTML, ofBash, ofWindowsCmd);
TColorOptions = (cAuto, cNever, cAlways, cJSON, cXML);
TMyConsoleColors = (ccNormal, ccRedBold, ccGreenBold, ccBlueBold, ccPurpleBold, ccYellowBold, ccCyanBold,
ccRed, ccGreen, ccBlue, ccPurple, ccYellow
);
var //output options
outputFormat: TOutputFormat;
windowsCmdPercentageEscape: string;
hasOutputEncoding: (oeAbsent,oeConvert,oePassRaw) = oeAbsent;
outputHeader, outputFooter, outputSeparator: string;
//outputArraySeparator: array[toutputformat] of string = ('', ', ', '</e><e>', '', '', '', '');
{$ifdef win32}systemEncodingIsUTF8: boolean = true;{$endif}
colorizing: TColorOptions;
lastConsoleColor: TMyConsoleColors = ccNormal;
isStdinTTY: boolean = false;
isStderrTTY: boolean = false;
isStdoutTTY: boolean = false;
internet: TInternetAccess;
type TInputFormat = (ifAuto, ifXML, ifHTML, ifXMLStrict, ifJSON, ifJSONStrict);
var
globalDefaultInputFormat: TInputFormat;
type
IData = interface //data interface, so we do not have to care about memory managment
function rawData: string;
function baseUri: string;
function displayBaseUri: string;
function contenttype: string;
function headers: TStringList;
function recursionLevel: integer;
function inputFormat: TInputFormat;
end;
{ THtmlTemplateParserBreaker }
THtmlTemplateParserBreaker = class(THtmlTemplateParser)
ignorenamespaces: boolean;
procedure initParsingModel(const data: IData);
procedure parseHTML(const data: IData);
procedure parseHTMLSimple(const data: IData);
procedure closeVariableLog;
procedure parseDoc(sender: TXQueryEngine; html,uri,contenttype: string; var node: TTreeNode);
end;
{ TTemplateReaderBreaker }
TTemplateReaderBreaker = class(TMultipageTemplateReader)
constructor create();
procedure setTemplate(atemplate: TMultiPageTemplate);
procedure perform(actions: TStringArray);
procedure selfLog(sender: TMultipageTemplateReader; logged: string; debugLevel: integer);
end;
//data processing classes
var htmlparser:THtmlTemplateParserBreaker;
xpathparser: TXQueryEngine;
multipage: TTemplateReaderBreaker;
multipagetemp: TMultiPageTemplate;
currentRoot: TTreeNode;
procedure setTerminalColor(err: boolean; color: TMyConsoleColors);
{$ifdef unix}
const colorCodes: array[TMyConsoleColors] of string = (
#27'[0m', #27'[1;31m', #27'[1;32m', #27'[1;34m', #27'[1;35m', #27'[1;33m', #27'[1;36m',
#27'[0;31m', #27'[0;32m', #27'[0;34m', #27'[0;35m', #27'[0;33m'
);
var
f: TextFile;
{$endif}
{$ifdef windows}
const colorCodes: array[TMyConsoleColors] of integer = (
FOREGROUND_RED or FOREGROUND_GREEN or FOREGROUND_BLUE,
FOREGROUND_RED or FOREGROUND_INTENSITY, FOREGROUND_GREEN or FOREGROUND_INTENSITY, FOREGROUND_BLUE or FOREGROUND_INTENSITY, FOREGROUND_RED or FOREGROUND_BLUE or FOREGROUND_INTENSITY, FOREGROUND_RED or FOREGROUND_GREEN or FOREGROUND_INTENSITY, FOREGROUND_BLUE or FOREGROUND_GREEN or FOREGROUND_INTENSITY,
FOREGROUND_RED, FOREGROUND_GREEN, FOREGROUND_BLUE, FOREGROUND_RED or FOREGROUND_BLUE, FOREGROUND_RED or FOREGROUND_GREEN
);
var handle: Integer;
{$endif}
begin
if err and not isStderrTTY then exit;
if not err and not isStdoutTTY then exit;
if color <> lastConsoleColor then begin
if err then Flush(stderr) else flush(StdOut);
{$ifdef unix}
if err then f := stderr else f := stdout;
write(f, colorCodes[color]);
{$endif}
{$ifdef windows}
if err then handle := StdErrorHandle else handle := StdOutputHandle;
SetConsoleTextAttribute(handle, colorCodes[color]);
{$endif}
lastConsoleColor := color;
end;
end;
procedure w(const s: string);
{$ifdef win32}
var
temp, temp2: String;
{$endif}
begin
if s = '' then exit;
{$IFDEF FPC_HAS_CPSTRING}
write(s);
{$ELSE}
fpc 3 is required now
if (outputEncoding = eUTF8) or (outputEncoding = eUnknown) then write(s)
{$ifdef win32}
else if outputEncoding = eUnknownUser1 then begin
if systemEncodingIsUTF8 then temp := s
else temp := Utf8ToAnsi(s);
SetLength(temp2, length(temp)+1);
if charToOEM(pchar(temp), pchar(temp2)) then
write(pchar(temp2));
end
{$endif}
else write(strConvertFromUtf8(s, outputEncoding));
{$ENDIF}
end;
procedure wln(const s: string = '');
begin
w(s);
w(LineEnding);
end;
var stacklen: integer;
stack: TLongintArray;
procedure wcolor(const s: string; color: TColorOptions);
const JSON_COLOR_OBJECT_PAREN: TMyConsoleColors = ccYellowBold;
JSON_COLOR_OBJECT_KEY: TMyConsoleColors = ccPurpleBold;
JSON_COLOR_ARRAY_PAREN: TMyConsoleColors = ccGreenBold;
{$ifdef windows}
JSON_COLOR_STRING: TMyConsoleColors = ccCyanBold; //green is ugly on windows
{$else}
JSON_COLOR_STRING: TMyConsoleColors = ccGreen;
{$endif}
JSON_STATE_ARRAY = 1;
JSON_STATE_OBJECTVALUE = 2;
JSON_STATE_OBJECTKEY = 3;
XML_COLOR_COMMENT: TMyConsoleColors = ccBlue;
XML_COLOR_TAG: TMyConsoleColors = ccYellowBold;
XML_COLOR_ATTRIB_NAME: TMyConsoleColors = ccPurpleBold;
XML_COLOR_ATTRIB_VALUE: TMyConsoleColors = ccGreenBold;
var pos, lastpos: integer;
procedure colorChange(c: TMyConsoleColors);
begin
w(copy(s, lastpos, pos - lastpos));
setTerminalColor(false, c);
lastpos:=pos;
end;
var quote: Char;
scriptSpecialCase: Boolean;
begin
case color of
cJSON: begin
if stacklen = 0 then arrayAddFast(stack, stacklen, 0);
pos := 1;
lastpos := 1;
while pos <= length(s) do begin
case s[pos] of
'{', '}': begin
if s[pos] = '{' then arrayAddFast(stack, stacklen, JSON_STATE_OBJECTKEY)
else if stacklen > 1 then dec(stacklen);
colorChange(JSON_COLOR_OBJECT_PAREN);
inc(pos);
colorChange(ccNormal);
end;
'[', ']': begin
if s[pos] = '[' then arrayAddFast(stack, stacklen, JSON_STATE_ARRAY)
else if stacklen > 1 then dec(stacklen);
colorChange(JSON_COLOR_ARRAY_PAREN);
inc(pos);
colorChange(ccNormal);
end;
',', ':': begin
case stack[stacklen-1] of
JSON_STATE_OBJECTKEY, JSON_STATE_OBJECTVALUE: begin
colorChange(JSON_COLOR_OBJECT_PAREN);
if s[pos] = ',' then stack[stacklen-1] := JSON_STATE_OBJECTKEY
else stack[stacklen-1] := JSON_STATE_OBJECTVALUE;
end;
JSON_STATE_ARRAY: colorChange(JSON_COLOR_ARRAY_PAREN);
end;
inc(pos);
colorChange(ccNormal);
end;
'"': begin
case stack[stacklen-1] of
JSON_STATE_OBJECTKEY: colorChange(JSON_COLOR_OBJECT_KEY);
else colorChange(JSON_COLOR_STRING);
end;
inc(pos);
while (pos <= length(s)) and (s[pos] <> '"') do begin
if s[pos] = '\' then inc(pos);
inc(pos);
end;
inc(pos);
end
else inc(pos);
end;
end;
colorChange(ccNormal)
end;
cXML: begin
pos := 1;
lastpos := 1;
scriptSpecialCase := false;
while pos <= length(s) do begin
case s[pos] of
'<': if scriptSpecialCase and not striBeginsWith(@s[pos], '</script') then inc(pos)
else begin
colorChange(XML_COLOR_TAG);
if (pos + 1) <= length(s) then begin
case s[pos+1] of
'/', '?': inc(pos,2);
'!': if strBeginsWith(@s[pos], '<!--') then begin
colorChange(XML_COLOR_COMMENT);
inc(pos,3);
while (pos + 3 <= length(s)) and ((s[pos] <> '-') or (s[pos+1] <> '-')or (s[pos+2] <> '>')) do inc(pos);
inc(pos);
continue;
end;
end;
end;
scriptSpecialCase := striBeginsWith(@s[pos], '<script');
while (pos <= length(s)) and not (s[pos] in ['>','/','?',#0..#32]) do inc(pos);
while (pos <= length(s)) do begin
case s[pos] of
'>','/','?': begin
colorChange(XML_COLOR_TAG);
if s[pos] <> '>' then inc(pos);
break;
end;
#0..#32: ;
else begin
colorChange(XML_COLOR_ATTRIB_NAME);
while (pos <= length(s)) and not (s[pos] in ['=','/','>']) do inc(pos);
colorChange(XML_COLOR_TAG);
if s[pos] <> '=' then break;
inc(pos);
while (pos <= length(s)) and (s[pos] in [#0..#32]) do inc(pos);
colorChange(XML_COLOR_ATTRIB_VALUE);
if (pos <= length(s)) then
case s[pos] of
'''', '"': begin
quote := s[pos];
inc(pos);
while (pos <= length(s)) and (s[pos] <> quote) do inc(pos);
inc(pos);
end;
else while (pos <= length(s)) and not (s[pos] in [#0..#32]) do inc(pos);
end;
continue;
end;
end;
inc(pos);
end;
inc(pos);
colorChange(ccNormal);
end;
else inc(pos);
end;
end;
colorChange(ccNormal)
end;
else w(s);
end;
end;
var firstItem: boolean = true;
procedure writeItem(const s: string; color: TColorOptions = cNever);
begin
if not firstItem then begin
w(outputSeparator);
end;
wcolor(s, color);
firstItem := false;
end;
procedure writeVarName(const s: string; color: TColorOptions = cNever);
begin
writeItem(s, color);
firstItem := true; //prevent another line break / separator
end;
var firstGroup: boolean = true;
procedure writeBeginGroup;
begin
case outputFormat of
ofXMLWrapped: begin
wcolor('<e>', cXML);
end;
ofJsonWrapped: if not firstGroup then wcolor(', ' + LineEnding, cJSON);
end;
firstGroup := false;
end;
procedure writeEndGroup;
begin
case outputFormat of
ofXMLWrapped: begin
wcolor('</e>' + LineEnding, cXML);
end;
end;
end;
{procedure printBeginValueGroup;
begin
end;
procedure printBeginValue(varname: string);
begin
case outputFormat of
ofXMLWrapped: w('<e>');
end;
firstValue := false;
end;
procedure printInnerValueSeparator;
begin
if not firstValue then begin
w(outputSeparator);
//w(outputArraySeparator[outputFormat]);
end;
firstValue := false;
end;
procedure printEndValue;
begin
end;
procedure printEndValueGroup;
begin
end; }
function joined(s: array of string): string; //for command line help
var
i: Integer;
begin
if length(s) = 0 then exit('');
result := s[0];
for i:=1 to high(s) do result := result + LineEnding + s[i];
end;
function strLoadFromFileChecked(const fn: string): string;
begin
result := strLoadFromFileUTF8(fn);
if strBeginsWith(result, '#!') then result := strAfter(result, #10);
if Result = '' then raise EXidelException.Create('File '+fn+' is empty.');
end;
function strReadFromStdin: string;
var s:string;
begin
result:='';
while not EOF(Input) do begin
ReadLn(s);
result+=s+LineEnding;
end;
end;
function setTextEncoding(var t: TextFile; e: string): integer;
var
codepage: Integer;
str: String;
begin
codepage := -1;
str:=UpperCase(e);
case str of
'UTF-8', 'UTF8': codepage := CP_UTF8;
'CP1252', 'ISO-8859-1', 'LATIN1', 'ISO-8859-15': codepage := 1252;
'UTF-16BE', 'UTF16BE': codepage := CP_UTF16BE;
'UTF16', 'UTF-16', 'UTF-16LE', 'UTF16LE': codepage := CP_UTF16;
'UTF-32BE', 'UTF32BE': codepage := CP_UTF32BE;
'UTF32', 'UTF-32', 'UTF-32LE', 'UTF32LE': codepage := CP_UTF32;
'OEM': codepage := CP_OEMCP;
'INPUT': ;//none
else if strBeginsWith(str, 'CP') then codepage := StrToIntDef(strAfter(str, 'CP'), -1)
else writeln(stderr, 'Unknown encoding: ',e)
end;
result := codepage;
if codepage <> -1 then
SetTextCodePage(t, codepage);
end;
procedure setOutputEncoding(e: string);
var
codepage: Integer;
begin
codepage := setTextEncoding(output, e);
if codepage <> -1 then begin
hasOutputEncoding := oeConvert;
//SetTextCodePage(StdErr, codepage);
end else begin
hasOutputEncoding := oePassRaw;
SetTextCodePage(Output, CP_ACP); //all our strings claim to be ACP (=UTF8) so there should be no conversion?
//SetTextCodePage(StdErr, CP_ACP);
end;
end;
type
{ TOptionReaderWrapper }
TOptionReaderWrapper = class
function read(const name: string; out value: string): boolean; virtual; abstract;
function read(const name: string; out value: integer): boolean; virtual; abstract;
function read(const name: string; out value: boolean): boolean; virtual; abstract;
function read(const name: string; out value: Extended): boolean; virtual; abstract;
function read(const name: string; out value: IXQValue): boolean; virtual;
function read(const name: string; out inputformat: TInputFormat): boolean; virtual;
end;
{ TOptionReaderFromCommandLine }
TOptionReaderFromCommandLine = class(TOptionReaderWrapper)
constructor create(cmdLine: TCommandLineReader);
function read(const name: string; out value: string): boolean; override;
function read(const name: string; out value: integer): boolean; override;
function read(const name: string; out value: boolean): boolean; override;
function read(const name: string; out value: Extended): boolean; override;
private
acmdLine: TCommandLineReader;
end;
{ TOptionReaderFromObject }
TOptionReaderFromObject = class(TOptionReaderWrapper)
constructor create(aobj: TXQValueObject);
function read(const name: string; out value: string): boolean; override;
function read(const name: string; out value: integer): boolean; override;
function read(const name: string; out value: boolean): boolean; override;
function read(const name: string; out value: Extended): boolean; override;
function read(const name: string; out value: IXQValue): boolean; override;
private
obj: TXQValueObject;
end;
type
{ TData }
{ TDataObject }
TDataObject = class(TInterfacedObject, IData)
{private todo: optimize
fparsed: TTreeDocument;
function GetParsed: TTreeDocument;
public}
private
frawdata: string;
fbaseurl, fdisplaybaseurl: string;
fcontenttype: string;
frecursionLevel: integer;
finputformat: TInputFormat;
fheaders: TStringList;
public
function rawData: string;
function baseUri: string;
function displayBaseUri: string;
function contentType: string;
function headers: TStringList;
function recursionLevel: integer;
function inputFormat: TInputFormat;
constructor create(somedata: string; aurl: string; acontenttype: string = '');
destructor Destroy; override;
//property parsed:TTreeDocument read GetParsed;
end;
TDataProcessing = class;
TProcessingContext = class;
{ TFollowTo }
TFollowTo = class
nextAction: integer; //the next action after the action yielding the data, so an action does not process its own follows
inputFormat: TInputFormat;
class function createFromRetrievalAddress(data: string): TFollowTo;
function clone: TFollowTo; virtual; abstract;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; virtual; abstract;
procedure replaceVariables; virtual;
function equalTo(ft: TFollowTo): boolean; virtual; abstract;
procedure readOptions(reader: TOptionReaderWrapper); virtual;
procedure assign(other: TFollowTo); virtual;
end;
{ THTTPRequest }
THTTPRequest = class(TFollowTo)
private
variablesReplaced: boolean;
public
url: string;
method: string;
data: string;
header: string;
multipart: string;
rawURL: boolean;
constructor create(aurl: string);
function clone: TFollowTo; override;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; override;
procedure replaceVariables; override;
function equalTo(ft: TFollowTo): boolean; override;
procedure readOptions(reader: TOptionReaderWrapper); override;
end;
{ TFileRequest }
TFileRequest = class(TFollowTo)
url: string;
constructor create(aurl: string);
function clone: TFollowTo; override;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; override;
procedure replaceVariables; override;
function equalTo(ft: TFollowTo): boolean; override;
end;
{ TDirectDataRequest }
TDirectDataRequest = class(TFollowTo)
data: string;
constructor create(adata: string);
function clone: TFollowTo; override;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; override;
function equalTo(ft: TFollowTo): boolean; override;
//procedure replaceVariables; do not replace vars in direct data
end;
{ TStdinDataRequest }
TStdinDataRequest = class(TFollowTo)
function clone: TFollowTo; override;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; override;
function equalTo(ft: TFollowTo): boolean; override;
end;
{ TFollowToProcessedData }
TFollowToProcessedData = class(TFollowTo)
data: IData;
constructor create(d: IData);
function clone: TFollowTo; override;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; override;
function equalTo(ft: TFollowTo): boolean; override;
end;
TFollowToXQVObject = class(TFollowTo)
v: IXQValue;
basedata: IData;
constructor create(const abasedata: IData; const av: IXQValue);
function clone: TFollowTo; override;
function retrieve(parent: TProcessingContext; arecursionLevel: integer): IData; override;
function equalTo(ft: TFollowTo): boolean; override;
end;
{TFollowXQV = class(TFollowTo)
xqv: TXQValue;
//can be url/http-request, file(?), data
//object with arbitrary options
//sequence of previous
end;}
{ TFollowToList }
TFollowToList = class(TFpObjectList)
constructor Create;
procedure merge(l: TFollowToList; nextAction: integer = 0);
function first: TFollowTo;
procedure add(ft: TFollowTo);
procedure merge(dest: IXQValue; basedata: IData; parent: TProcessingContext);
function containsEqual(ft: TFollowTo): boolean;
private
procedure addBasicUrl(absurl: string; baseurl: string; inputFormat: TInputFormat);
procedure addObject(absurl: string; baseurl: string; options: TXQValueObject; fallBackInputFormat: TInputFormat);
end;
{ TDataProcessing }
TDataProcessing = class
parent: TProcessingContext;
function process(data: IData): TFollowToList; virtual; abstract;
procedure readOptions(reader: TOptionReaderWrapper); virtual;
procedure initFromCommandLine(cmdLine: TCommandLineReader); virtual;
procedure mergeWithObject(obj: TXQValueObject); virtual;
function clone(newparent: TProcessingContext): TDataProcessing; virtual; abstract;
end;
{ TDownload }
TDownload = class(TDataProcessing)
downloadTarget: string;
function process(data: IData): TFollowToList; override;
procedure readOptions(reader: TOptionReaderWrapper); override;
function clone(newparent: TProcessingContext): TDataProcessing; override;
end;
{ TExtraction }
TExtraction = class(TDataProcessing)
extract: string;
extractQueryCache: IXQuery;
extractExclude, extractInclude: TStringArray;
extractKind: TExtractionKind;
templateActions: TStringArray;
defaultName: string;
printVariables: set of (pvLog, pvCondensedLog, pvFinal);
printTypeAnnotations, hideVariableNames: boolean;
printedNodeFormat: TTreeNodeSerialization;
printedJSONFormat: (jisDefault, jisPretty, jisCompact);
inputFormat: TInputFormat;
constructor create;
procedure readOptions(reader: TOptionReaderWrapper); override;
procedure setVariables(v: string);
procedure printExtractedValue(value: IXQValue; invariable: boolean);
procedure printCmdlineVariable(const name: string; const value: IXQValue);
procedure printExtractedVariables(vars: TXQVariableChangeLog; state: string; showDefaultVariable: boolean);
procedure printExtractedVariables(parser: THtmlTemplateParser; showDefaultVariableOverride: boolean);
function process(data: IData): TFollowToList; override;
procedure assignOptions(other: TExtraction);
function clone(newparent: TProcessingContext): TDataProcessing; override;
private
currentFollowList: TFollowToList;
currentData: IData;
procedure pageProcessed(unused: TMultipageTemplateReader; parser: THtmlTemplateParser);
end;
{ TFollowToWrapper }
TFollowToWrapper = class(TDataProcessing)
followTo: TFollowTo;
procedure readOptions(reader: TOptionReaderWrapper); override;
function process(data: IData): TFollowToList; override;
function clone(newparent: TProcessingContext): TDataProcessing; override;
destructor Destroy; override;
end;
{ TProcessingContext }
//Processing is done in processing contexts
//A processing context can have its own data sources (TFollowTo or data sources of a nested processing context) or receive the data from its parent
//To every data source actions are applied (e.g. tdownload or textraction). These actions can also yield new data sources (e.g. follow := assignments or nested processing contexts with yieldDataToParent)
//The expression in follow is evaluated and the resulting data processed in the context followTo
//Then processing continues in nextSibling
//Remaining unprocessed data is passed to the parent
TProcessingContext = class(TDataProcessing)
dataSources: array of TDataProcessing; //data sources, e.g. a list of URLs
actions: array of TDataProcessing; //actions e.g. a download target
follow: string;
followKind: TExtractionKind;
followQueryCache: IXQuery;
followExclude, followInclude: TStringArray;
followTo: TProcessingContext;
followMaxLevel: integer;
followInputFormat: TInputFormat;
nextSibling: TProcessingContext;
wait: Extended;
userAgent: string;
proxy: string;
printReceivedHeaders: boolean;
errorHandling: string;
loadCookies, saveCookies: string;
silent, printPostData: boolean;
ignoreNamespace: boolean;
compatibilityNoExtendedStrings,compatibilityNoJSON, compatibilityNoJSONliterals, compatibilityOnlyJSONObjects, compatibilityNoExtendedJson, compatibilityStrictTypeChecking, compatibilityStrictNamespaces: boolean;
compatibilityDotNotation: TXQPropertyDotNotation;
noOptimizations: boolean;
yieldDataToParent: boolean;
procedure printStatus(s: string);
procedure readOptions(reader: TOptionReaderWrapper); override;
procedure mergeWithObject(obj: TXQValueObject); override;
procedure addNewDataSource(source: TDataProcessing);
procedure readNewDataSource(data: TFollowTo; options: TOptionReaderWrapper);
procedure addNewAction(action: TDataProcessing);
procedure readNewAction(action: TDataProcessing; options: TOptionReaderWrapper);
procedure assignOptions(other: TProcessingContext);
procedure assignActions(other: TProcessingContext);
function clone(newparent: TProcessingContext): TDataProcessing; override;
function last: TProcessingContext; //returns the last context in this sibling/follow chain
procedure insertFictiveDatasourceIfNeeded; //if no data source is given in an expression (or an subexpression), but an aciton is there, <empty/> is added as data source
function process(data: IData): TFollowToList; override;
class function replaceEnclosedExpressions(expr: string): string;
function replaceEnclosedExpressions(data: IData; expr: string): string;
destructor destroy; override;
private
stupidHTTPReactionHackFlag: integer;
procedure loadDataForQueryPreParse(const data: IData);
procedure loadDataForQuery(const data: IData; const query: IXQuery);
function evaluateQuery(const query: IXQuery; const data: IData; const allowWithoutReturnValue: boolean = false): IXQValue;
procedure httpReact (sender: TInternetAccess; var method: string; var url: TDecodedUrl; var data:TInternetAccessDataBlock; var reaction: TInternetAccessReaction);
end;
type EInvalidArgument = Exception;
constructor TFollowToXQVObject.create(const abasedata: IData; const av: IXQValue);
begin
basedata := abasedata;
v := av;
end;
function TFollowToXQVObject.clone: TFollowTo;
begin
result := TFollowToXQVObject.create(basedata, v);
end;
function TFollowToXQVObject.retrieve(parent: TProcessingContext; arecursionLevel: integer): IData;
var
temp: TProcessingContext;
fl: TFollowToList;
begin
if parent = nil then exit(nil);
temp := TProcessingContext.Create();
fl := TFollowToList.Create;
temp.assignOptions(parent); //do not copy actions/data sources. they would apply to basedata, not to dest
temp.parent := parent;
temp.follow := parent.follow; //need to copy follow and follow-to, so it follows to the new data
temp.followKind := parent.followKind;
temp.followTo := parent.followTo;
temp.followInputFormat := parent.followInputFormat;
temp.nextSibling := parent.nextSibling;
temp.mergeWithObject(v as TXQValueObject);
fl := temp.process(basedata);
case fl.count of
0: ;
1: result := fl.first.retrieve(temp, arecursionLevel );
else raise Exception.Create('Invalid follow to count: ' + inttostr(fl.Count));
end;
temp.followTo := nil;
temp.nextSibling := nil;
temp.Free;
end;
function TFollowToXQVObject.equalTo(ft: TFollowTo): boolean;
begin
if not (ft is TFollowToXQVObject) then exit(false);
result := false;//not working: xpathparser.StaticContext.compareDeepAtomic(v, TFollowToXQVObject(ft).v, xpathparser.StaticContext.collation) = 0;
end;
{ TOptionReaderWrapper }
function TOptionReaderWrapper.read(const name: string; out value: IXQValue): boolean;
begin
result := false;
end;
function TOptionReaderWrapper.read(const name: string; out inputformat: TInputFormat): boolean;
var
temp: String;
begin
result := read('input-format', temp);
if result then
case temp of
'auto': inputFormat:=ifAuto;
'xml': inputFormat:=ifXML;
'html': inputFormat:=ifHTML;
'xml-strict': inputFormat:=ifXMLStrict;
'json': inputFormat := ifJSON;
'json-strict': inputFormat := ifJSONStrict
else raise EXidelException.Create('Invalid input-format: '+temp);
end;
end;
{ TDataObject }
function TDataObject.rawData: string;
begin
result := frawdata;
end;
function TDataObject.baseUri: string;
begin
result := fbaseurl;
end;
function TDataObject.displayBaseUri: string;
begin
result := fdisplaybaseurl;
end;
function TDataObject.contentType: string;
begin
result := fcontenttype;
end;
function TDataObject.headers: TStringList;
begin
result := fheaders;
end;
function TDataObject.recursionLevel: integer;
begin
result := frecursionLevel;
end;
function TDataObject.inputFormat: TInputFormat;
const FormatMap: array[TInternetToolsFormat] of TInputFormat = ( ifXML, ifHTML, ifJSON, ifXML );
var
enc: TSystemCodePage;
begin
if finputformat = ifAuto then begin
finputformat := FormatMap[guessFormat(rawData, baseUri, contentType)];
if (finputformat in [ifJSON,ifJSONStrict]) and (hasOutputEncoding <> oePassRaw) then begin
//convert json to utf-8, because the regex parser does not match non-utf8 (not even with . escape)
//it might be useful to convert other data, but the x/html parser does its own encoding detection
enc := strEncodingFromContentType(contentType);
if enc = CP_NONE then
if isInvalidUTF8(frawData) and not strContains(frawData, #0) then enc := CP_WINDOWS1252;
if (enc <> CP_UTF8) and (enc <> CP_NONE) then frawdata := strConvertToUtf8(frawData, enc);
end;
end;
result := finputFormat;
end;
{ TFollowToProcessedData }
constructor TFollowToProcessedData.create(d: IData);
begin
data := d;
end;
function TFollowToProcessedData.clone: TFollowTo;
begin
result := TFollowToProcessedData.Create(data);
result.inputFormat := inputFormat;
end;
function TFollowToProcessedData.retrieve(parent: TProcessingContext; arecursionLevel: integer): IData;
begin
result := data;
if data <> nil then begin
(result as TDataObject).finputFormat := self.inputFormat;
(result as TDataObject).frecursionLevel := arecursionLevel;
end;
end;
function TFollowToProcessedData.equalTo(ft: TFollowTo): boolean;
begin
result := (ft is TFollowToProcessedData) and (TFollowToProcessedData(ft).data = data);
end;
{ TOptionReaderFromObject }
constructor TOptionReaderFromObject.create(aobj: TXQValueObject);
begin
obj := aobj;
end;
function TOptionReaderFromObject.read(const name: string; out value: string): boolean;
var
temp: TXQValue;
begin
result := obj.hasProperty(name, @temp);
if result then value := temp.toString;
end;
function TOptionReaderFromObject.read(const name: string; out value: integer): boolean;
var
temp: TXQValue;
begin
result := obj.hasProperty(name, @temp);
if result then value := temp.toInt64;
end;
function TOptionReaderFromObject.read(const name: string; out value: boolean): boolean;
var
temp: TXQValue;
begin
result := obj.hasProperty(name, @temp);
if result then value := temp.toBoolean;
end;
function TOptionReaderFromObject.read(const name: string; out value: Extended): boolean;
var
temp: TXQValue;
begin
result := obj.hasProperty(name, @temp);
if result then value := temp.toFloat;
end;
function TOptionReaderFromObject.read(const name: string; out value: IXQValue): boolean;
var
temp: TXQValue;
begin
result := obj.hasProperty(name, @temp);
if result then value := temp as TXQValue;
end;
{ TOptionReaderFromCommandLine }
constructor TOptionReaderFromCommandLine.create(cmdLine: TCommandLineReader);
begin
acmdLine := cmdLine;
end;
function TOptionReaderFromCommandLine.read(const name: string; out value: string): boolean;
begin
value := acmdLine.readString(name);
result := acmdLine.existsProperty(name);
end;
function TOptionReaderFromCommandLine.read(const name: string; out value: integer): boolean;
begin
value := acmdLine.readInt(name);
result := acmdLine.existsProperty(name);
end;
function TOptionReaderFromCommandLine.read(const name: string; out value: boolean): boolean;
begin
value := acmdLine.readFlag(name);
result := acmdLine.existsProperty(name);
end;
function TOptionReaderFromCommandLine.read(const name: string; out value: Extended): boolean;
begin
value := acmdLine.readFloat(name);
result := acmdLine.existsProperty(name);
end;
{ TDownload }
function TDownload.process(data: IData): TFollowToList;
var
temp, realUrl: String;
j: LongInt;
realPath: String;
realFile: String;
downloadTo: String;
color: TColorOptions;
begin
result := nil;
if cgimode or not allowFileAccess then
raise EXidelException.Create('Download not permitted');
realUrl := data.baseUri;
if guessType(realUrl) = rtRemoteURL then realurl := decodeURL(realUrl).path;
j := strRpos('/', realUrl);
if j = 0 then begin
realPath := '';
realFile := realUrl;
end else begin
realPath := copy(realUrl, 1, j);
realFile := copy(realUrl, j + 1, length(realUrl) - j)
end;
while strBeginsWith(realPath, '/') do delete(realPath,1,1);
downloadTo := parent.replaceEnclosedExpressions(data, Self.downloadTarget);
if striBeginsWith(downloadTo, 'http://') then delete(downloadTo, 1, length('http://'));
if striBeginsWith(downloadTo, 'https://') then delete(downloadTo, 1, length('https://'));
{$ifdef win32}
downloadTo := StringReplace(downloadTo, '\' , '/', [rfReplaceAll]);
{$endif}
//If downloadTo is a file : save with that name
//If downloadTo is a directory and does not end with / : save with basename
//If downloadTo is a directory and does end with / : save with path and basename
//If downloadTo is - : print to stdout
//example: Download abc/def/index.html
// foo/bar/xyz save in directory foo/bar with name xyz
// foo/bar/ save in directory foo/bar/abc/def with name index.html
// foo/bar/. save in directory foo/bar with name index.html
// foo save in current directory with name foo
// ./ save in current directory/abc/def with name index.html
// ./. save in current directory with name index.html
// . save in current directory with name index.html
// - print to stdout
if downloadTo = '-' then begin
color := colorizing;
if color in [cAlways, cAuto] then
case data.inputFormat of
ifHTML, ifXML, ifXMLStrict: color := cXML;
ifJSON, ifJSONStrict: color := cJSON;
end;
wcolor(data.rawdata, color);
exit;
end;
if strEndsWith(downloadTo, '/.') then downloadTo := downloadTo + '/' + realFile
else if strEndsWith(downloadTo, '/') then downloadTo := downloadTo + '/' + realPath + realFile
else if DirectoryExists(downloadTo) or (downloadTo = '.' { <- redunant check, but safety first }) then downloadTo := downloadTo + '/' + realFile;
if strEndsWith(downloadTo, '/') or (downloadTo = '') then downloadTo += 'index.html'; //sometimes realFile is empty
parent.printStatus('**** Save as: '+downloadTo+' ****');
if pos('/', downloadTo) > 0 then
ForceDirectories(StringReplace(StringReplace(copy(downloadTo, 1, strRpos('/', downloadTo)-1), '//', '/', [rfReplaceAll]), '/', DirectorySeparator, [rfReplaceAll]));
strSaveToFileUTF8(StringReplace(downloadTo, '/', DirectorySeparator, [rfReplaceAll]), data.rawdata);
end;
procedure TDownload.readOptions(reader: TOptionReaderWrapper);
begin
reader.read('download', downloadTarget);
end;
function TDownload.clone(newparent: TProcessingContext): TDataProcessing;
begin
result := TDownload.Create;
result.parent := newparent;
TDownload(result).downloadTarget:=downloadTarget;
end;
{ THTTPRequest }
constructor THTTPRequest.create(aurl: string);
begin
url := aurl;
end;
function THTTPRequest.clone: TFollowTo;
begin
result := THTTPRequest.create(url);
THTTPRequest(result).method:=method;
THTTPRequest(result).data:=data;
THTTPRequest(result).header:=header;
THTTPRequest(result).multipart:=multipart;
THTTPRequest(result).variablesReplaced:=variablesReplaced;
THTTPRequest(result).rawURL:=rawURL;
result.assign(self);
end;
function THTTPRequest.retrieve(parent: TProcessingContext; arecursionLevel: integer): IData;
var escapedURL: string;
var
i: Integer;
d: TDataObject;
begin
if not allowInternetAccess then raise EXidelException.Create('Internet access not permitted');
if assigned(onPrepareInternet) then internet := onPrepareInternet(parent.userAgent, parent.proxy, @parent.httpReact);
if (parent.loadCookies <> '') then begin
internet.cookies.loadFromFile(parent.loadCookies);
parent.loadCookies := ''; //only need to load them once?
end;
escapedURL := url;
if not rawURL then escapedURL := TInternetAccess.urlEncodeData(url, ueXPathHTML4);
parent.printStatus('**** Retrieving ('+method+'): '+escapedURL+' ****');
if parent.printPostData and (data <> '') then parent.printStatus(data);
result := TDataObject.create('', escapedURL);
if assigned(onRetrieve) then begin
parent.stupidHTTPReactionHackFlag := 0;
(result as TDataObject).frawdata := onRetrieve(method, escapedURL, data, header);
case parent.stupidHTTPReactionHackFlag of
1: (result as TDataObject).frawdata := '';
2: exit(nil);
end;
if assigned(internet) then begin
(result as TDataObject).fbaseurl := internet.lastUrl;
(result as TDataObject).fdisplaybaseurl := internet.lastUrl;
end;
end;
if parent.printReceivedHeaders and assigned(internet) then begin
parent.printStatus('** Headers: (status: '+inttostr(internet.lastHTTPResultCode)+')**');
for i:=0 to internet.lastHTTPHeaders.Count-1 do
wln(internet.lastHTTPHeaders[i]);
end;
if Assigned(internet) then begin
d := (result as TDataObject);
d.fcontenttype := internet.getLastContentType;
d.fheaders := TStringList.Create;
for i := 0 to internet.lastHTTPHeaders.count - 1 do
d.fheaders.Add(internet.lastHTTPHeaders[i]);
end;
with result as TDataObject do begin
finputFormat := self.inputFormat;
frecursionLevel := arecursionLevel;
end;
end;
procedure THTTPRequest.replaceVariables;
procedure parseFormMime();
var mime: TMIMEMultipartData;
forms: TStringArray;
i: Integer;
p: SizeInt;
name: String;
value: String;
paren: Char;
nvalue: String;
temp: String;
filename: String;
contenttype: String;
kind: Char;
t: Integer;
begin
if data <> '' then raise EXidelException.Create('Cannot mix urlencoded and multipart data');
forms := strSplit(multipart, #0, false);
for i := 0 to high(forms) do begin
p := pos('=', forms[i]);
name := copy(forms[i], 1, p-1);
value := strCopyFrom(forms[i], p+1);
filename := '';
contenttype := '';
kind := 'x';
if length(value) > 0 then begin
if value[1] in ['<','@'] then begin
kind := value[1];
delete(value, 1, 1);
end else kind := 'x';
if value[1] in ['"', ''''] then begin
paren := value[1];
nvalue := '';
t := 2;
while (t <= length(value)) do begin
if value[t] = '\' then begin
inc(t);
nvalue += value[t];
end else if value[t] = paren then break
else nvalue += value[t];
inc(t);
end;
delete(value, 1, t+1);
end else begin
p := pos(';', value);
if p = 0 then p := length(value) + 1;
nvalue := copy(value, 1, p-1);
delete(value, 1, p);
end;
if kind in ['<', '@'] then begin
if kind = '@' then filename := nvalue;
nvalue := strLoadFromFileUTF8(nvalue);
end;
if value <> '' then begin
for temp in strSplit(value, ';', false) do begin
value := temp;
case strSplitGet('=', value) of
'filename': filename := value;
'type': contenttype := value;
else raise EXidelException.Create('Unknown option in '+forms[i]);
end;
end;
end;
end;
mime.addFormData(name, nvalue, filename, contenttype, '');
end;
data := mime.compose(header);
header := TMIMEMultipartData.HeaderForBoundary(header);
end;
begin
if variablesReplaced then exit; //this method is still supposed to be only called once
url := TProcessingContext.replaceEnclosedExpressions(url);
method := TProcessingContext.replaceEnclosedExpressions(method);
data := TProcessingContext.replaceEnclosedExpressions(data);
header := TProcessingContext.replaceEnclosedExpressions(header);
multipart := TProcessingContext.replaceEnclosedExpressions(multipart);
if multipart <> '' then parseFormMime();
variablesReplaced := true;
end;
function THTTPRequest.equalTo(ft: TFollowTo): boolean;
begin
result := (ft is THTTPRequest) and (THTTPRequest(ft).url = url) and (THTTPRequest(ft).method = method) and (THTTPRequest(ft).data = data) and (THTTPRequest(ft).header = header) and (THTTPRequest(ft).multipart = multipart);
end;
function isStdin(s: string): boolean;
begin
result := (s = '-') or (s = 'stdin:///') or (s = 'stdin:') or (s = 'stdin://');
end;
procedure closeMultiArgs(var oldValue: string; separator: string); forward;
procedure THTTPRequest.readOptions(reader: TOptionReaderWrapper);
var temp: string;
tempxq: IXQValue;
h: IXQValue;
begin
inherited;
if method <> '' then exit; //already initialized, must abort to keep stdin working (todo: allow postfix data/method options?)
reader.read('raw-url', rawURL);
reader.read('header', header);
if reader is TOptionReaderFromObject then begin
variablesReplaced := true;
if reader.read('headers', tempxq) then begin
for h in tempxq do begin
if header <> '' then header := header + #13#10;
header += h.toString;
end;
end;
end;
method:='GET';
if reader.read('post', data) then
method:='POST';
if reader.read('form', multipart) then
method:='POST';
if reader.read('method', temp) then begin
method:=temp;
if isStdin(method) then
method := trim(strReadFromStdin);
end;
if reader is TOptionReaderFromCommandLine then closeMultiArgs(data, '&');
header := trim(header);
if isStdin(data) then
data := strReadFromStdin;
end;
{ TFileRequest }
constructor TFileRequest.create(aurl: string);
begin
url := aurl;
end;
function TFileRequest.clone: TFollowTo;
begin
result := TFileRequest.create(url);
result.assign(self);
end;
function TFileRequest.retrieve(parent: TProcessingContext; arecursionLevel: integer): IData;
begin
if not allowFileAccess then raise EXidelException.Create('File access not permitted');
parent.printStatus('**** Retrieving: '+url+' ****');
result := TDataObject.create(strLoadFromFileUTF8(url), url);
with result as TDataObject do begin
fbaseurl:=fileNameExpandToURI(fbaseurl);
finputFormat := self.inputFormat;
frecursionLevel := arecursionLevel;
end;
end;
procedure TFileRequest.replaceVariables;
begin
url := TProcessingContext.replaceEnclosedExpressions(url);
end;
function TFileRequest.equalTo(ft: TFollowTo): boolean;
begin
result := (ft is TFileRequest) and (TFileRequest(ft).url = url);
end;
{ TDirectDataRequest }
constructor TDirectDataRequest.create(adata: string);
begin
data := adata;
end;
function TDirectDataRequest.clone: TFollowTo;
begin
result := TDirectDataRequest.create(data);
result.assign(self);
end;
function TDirectDataRequest.retrieve(parent: TProcessingContext; arecursionLevel: integer): IData;
var
partialData: String;
begin
partialData := data;
if length(partialData) > 80 then begin SetLength(partialData, 80); partialData += '...'; end;
result := TDataObject.Create(data, 'data:,'+partialData);
with result as TDataObject do begin
fbaseurl := GetCurrentDir+DirectorySeparator;
finputFormat := self.inputFormat;
frecursionLevel := arecursionLevel;
end;
//if length(data) > length(result.fullurl) then (result as TDataObject).ffullurl := (result as TDataObject).ffullurl + '...';
end;
function TDirectDataRequest.equalTo(ft: TFollowTo): boolean;
begin
if data = '<empty/>' then exit(false); //it is just a placeholder anyways
result := (ft is TDirectDataRequest) and (TDirectDataRequest(ft).data = data);
end;
constructor TDataObject.create(somedata: string; aurl: string; acontenttype: string);
begin
frawdata := somedata;
fbaseurl:=aurl;
fdisplaybaseurl:=aurl;
fcontenttype := acontenttype;
end;
destructor TDataObject.Destroy;
begin
fheaders.free;
inherited Destroy;
end;
{ TStdinDataRequest }
function TStdinDataRequest.clone: TFollowTo;
begin
result := TStdinDataRequest.create;
result.assign(self);
end;
function TStdinDataRequest.retrieve(parent: TProcessingContext; arecursionLevel: integer): IData;
begin
result := TDataObject.Create(strReadFromStdin(), 'stdin:///');
with Result as TDataObject do begin
fbaseurl := GetCurrentDir + DirectorySeparator;
finputFormat := self.inputFormat;
frecursionLevel := arecursionLevel;
end;
end;
function TStdinDataRequest.equalTo(ft: TFollowTo): boolean;
begin
result := false; //always different??
end;
class function TFollowTo.createFromRetrievalAddress(data: string): TFollowTo;
begin
data := trim(data);
if cgimode then
exit(TDirectDataRequest.create(data));
if isStdin(data) then
exit(TStdinDataRequest.create());
case guessType(data) of
rtRemoteURL: result := THTTPRequest.Create(data);
rtFile: result := TFileRequest.create(data);
rtEmpty, rtXML, rtJSON: result := TDirectDataRequest.create(data);
else raise EXidelException.Create('Impossible 232');
end;
//todo: handle completely empty data ''
end;
procedure TFollowTo.replaceVariables;
begin
//empty
end;
procedure TFollowTo.readOptions(reader: TOptionReaderWrapper);
begin
reader.read('input-format', inputFormat);
end;
procedure TFollowTo.assign(other: TFollowTo);
begin
inputFormat:=other.inputFormat;
end;
{ TFollowToWrapper }
procedure TFollowToWrapper.readOptions(reader: TOptionReaderWrapper);
begin
followTo.readOptions(reader);
end;
function TFollowToWrapper.process(data: IData): TFollowToList;
var
res: TFollowTo;
begin
res := followTo.clone;
res.replaceVariables();
result := TFollowToList.Create;
Result.Add(res);
end;
function TFollowToWrapper.clone(newparent: TProcessingContext): TDataProcessing;
begin
result := TFollowToWrapper.Create;
result.parent := newparent;
TFollowToWrapper(result).followTo := followTo.clone;
end;
destructor TFollowToWrapper.Destroy;
begin
followTo.free;
inherited Destroy;
end;
{ TFollowToList }
constructor TFollowToList.Create;
begin
inherited;
OwnsObjects:=true;
end;
procedure TFollowToList.merge(l: TFollowToList; nextAction: integer = 0);
var
i: Integer;
begin
if l = nil then exit;
for i := 0 to l.Count-1 do begin
TFollowTo(l[i]).nextAction := nextAction;
inherited add(TFollowTo(l[i]));
end;
l.OwnsObjects:=false;
l.free;
end;
function TFollowToList.first: TFollowTo;
begin
result := TFollowTo(inherited first);
end;
var globalDuplicationList: TFollowToList;
procedure TFollowToList.add(ft: TFollowTo);
begin
if (globalDuplicationList <> nil) and (self <> globalDuplicationList) then begin
if globalDuplicationList.containsEqual(ft) then begin ft.free; exit; end;
globalDuplicationList.add(ft.clone);
end;
inherited add(ft);
end;
procedure TFollowToList.merge(dest: IXQValue; basedata: IData; parent: TProcessingContext);
var x: IXQValue;
temp: TProcessingContext;
tempv: TXQValue;
n: TTreeNode;
keys: TStringList;
isPureDataSource: Boolean;
i: Integer;
oldCount: Integer;
begin
if dest.kind <> pvkSequence then
dest := xpathparser.evaluateXPath2('pxp:resolve-html(., $url)', dest);
oldCount := count;
case dest.kind of
pvkUndefined: exit;
pvkObject: begin
keys := TStringList.Create;
(dest as TXQValueObject).enumerateKeys(keys);
isPureDataSource := true;
for i := 0 to keys.Count - 1 do
case keys[i] of
'header', 'headers', 'post', 'data', 'url', 'form', 'method', 'input-format': ;
else begin
isPureDataSource := false;
break;
end;
end;
keys.free;
if isPureDataSource then begin
if (dest as TXQValueObject).hasProperty('url', @tempv) then
addObject( tempv.toString, basedata.baseUri, dest as TXQValueObject, parent.followInputFormat)
else if (dest as TXQValueObject).hasProperty('data', @tempv) then
addObject(tempv.toString, basedata.baseUri, dest as TXQValueObject, parent.followInputFormat );
end else add(TFollowToXQVObject.create(basedata, dest));
end;
pvkSequence: begin
for x in dest do
merge(x, basedata, parent);
exit;
end;
pvkNode: raise EXidelException.Create('Assert failure: Expected resolved url for following, but got raw '+dest.toXQuery());
else addBasicUrl(dest.toString, basedata.baseUri, parent.followInputFormat);
end;
end;
function TFollowToList.containsEqual(ft: TFollowTo): boolean;
var
i: Integer;
begin
for i := 0 to count-1 do
if (self[i] as TFollowTo).equalto(ft) then exit(true);
exit(false);
end;
procedure TFollowToList.addBasicUrl(absurl: string; baseurl: string; inputFormat: TInputFormat);
var
ft: TFollowTo;
begin
if (guessType(baseurl) in [rtFile, rtRemoteURL]) and (guessType(absurl) = rtFile) then
absurl := strResolveURI(absurl, baseurl);
ft := TFollowTo.createFromRetrievalAddress(absurl);
ft.inputFormat := inputFormat;
Add(ft);
end;
procedure TFollowToList.addObject(absurl: string; baseurl: string; options: TXQValueObject; fallBackInputFormat: TInputFormat);
var
followTo: TFollowTo;
reader: TOptionReaderFromObject;
begin
if (guessType(baseurl) in [rtFile, rtRemoteURL]) and (guessType(absurl) = rtFile) then
absurl := strResolveURI(absurl, baseurl);
followTo := TFollowTo.createFromRetrievalAddress(absurl);
followTo.inputFormat := fallBackInputFormat;
reader := TOptionReaderFromObject.create(options);
followTo.readOptions(reader);
reader.free;
add(followTo);
end;
procedure TDataProcessing.readOptions(reader: TOptionReaderWrapper);
begin
//empty
end;
procedure TDataProcessing.initFromCommandLine(cmdLine: TCommandLineReader);
var
temp: TOptionReaderFromCommandLine;
begin
temp := TOptionReaderFromCommandLine.Create(cmdLine);
readOptions(temp);
temp.free;
end;
procedure TDataProcessing.mergeWithObject(obj: TXQValueObject);
var
temp: TOptionReaderFromObject;
begin
temp := TOptionReaderFromObject.create(obj);
readOptions(temp);
temp.free;
end;
{ TExtraction }
constructor TExtraction.create;
begin
printVariables:=[pvCondensedLog];
end;
function extractKindFromString(v: string): TExtractionKind;
begin
case v of
'auto': result := ekAuto;
'xpath': result :=ekXPath3;
'xquery': result :=ekXQuery3;
'xpath2': result :=ekXPath2;
'xquery1': result :=ekXQuery1;
'xpath3': result :=ekXPath3;
'xquery3': result :=ekXQuery3;
'css': result :=ekCSS;
'template', 'pattern', 'html-pattern': result :=ekPatternHTML;
'xml-pattern': result := ekPatternXML;
'multipage': result :=ekMultipage;
else raise EXidelException.Create('Unknown kind for the extract expression: '+v);
end;
end;
procedure TExtraction.readOptions(reader: TOptionReaderWrapper);
var
tempstr: string;
begin
reader.read('extract', extract); //todo. option: extract-file
if not cgimode and strBeginsWith(extract, '@') then extract := strLoadFromFileChecked(strCopyFrom(extract, 2));
extract:=trim(extract);
if reader.read('extract-exclude', tempstr) then extractExclude := strSplit(tempstr, ',', false);
if reader.read('extract-include', tempstr) then extractInclude := strSplit(tempstr, ',', false);
if reader.read('extract-kind', tempstr) then if extract <> '' then extractKind := extractKindFromString(tempstr);
if reader.read('template-file', tempstr) then begin
extract := strLoadFromFileChecked(tempstr);
extractKind := ekMultipage;
end;
if reader.read('template-action', tempstr) then templateActions := strSplit(tempstr, ',', false);
reader.read('default-variable-name', defaultName);
reader.read('print-type-annotations', printTypeAnnotations);
reader.read('hide-variable-names', hideVariableNames);
if reader.read('print-variables', tempstr) then setVariables(tempstr);
if reader.read('printed-node-format', tempstr) then begin
case tempstr of
'text': printedNodeFormat:=tnsText;
'xml': printedNodeFormat:=tnsXML;
'html': printedNodeFormat:=tnsHTML;
else raise EInvalidArgument.create('Unknown node format option: '+tempstr);
end;
end else if reader.read('output-format', tempstr) then
case tempstr of
'xml': printedNodeFormat:=tnsXML;
'html': printedNodeFormat:=tnsHTML;
end;
if reader.read('printed-json-format', tempstr) then begin
case tempstr of
'pretty': printedJSONFormat := jisPretty;
'compact': printedJSONFormat := jisCompact;
end;
end;
reader.read('input-format', inputFormat);
end;
procedure TExtraction.setVariables(v: string);
var
tempSplitted: TStringArray;
begin
printVariables:=[];
tempSplitted := strSplit(v, ',');
if arrayIndexOf(tempSplitted, 'log') >= 0 then include(printVariables, pvLog);
if arrayIndexOf(tempSplitted, 'condensed-log') >= 0 then include(printVariables, pvCondensedLog);
if arrayIndexOf(tempSplitted, 'final') >= 0 then include(printVariables, pvFinal);
end;
{ TProcessingRequest }
procedure TProcessingContext.printStatus(s: string);
begin
if not silent then writeln(stderr, s);
end;
procedure TProcessingContext.readOptions(reader: TOptionReaderWrapper);
var
tempstr: string;
tempbool: boolean;
begin
if allowInternetAccess then begin
reader.read('wait', wait);
reader.read('user-agent', userAgent);
reader.read('proxy', proxy);
//reader.read('post', Post);
//reader.read('method', method); moved to
reader.read('print-received-headers', printReceivedHeaders);
reader.read('error-handling', errorHandling);
reader.read('load-cookies', loadCookies);
reader.read('save-cookies', saveCookies);
end;
if reader.read('output-encoding', tempstr) then setOutputEncoding(tempstr); //allows object returned by extract to change the output-encoding
reader.read('silent', silent);
reader.read('verbose', printPostData);
{if cmdLine.readString('follow-file') <> '' then follow := strLoadFromFileChecked(cmdLine.readString('follow-file'))
else begin
follow := cmdLine.readString('follow');
if follow = '-' then follow :=strReadFromStdin;
end;} //handled in variableRead
reader.read('follow', follow);
if not cgimode and strBeginsWith(follow, '@') then follow := strLoadFromFileChecked(strCopyFrom(follow, 2));
if reader.read('follow-kind', tempstr) then followKind := extractKindFromString(tempstr);
reader.read('follow-exclude', tempstr); followExclude := strSplit(tempstr, ',', false);
reader.read('follow-include', tempstr); followInclude := strSplit(tempstr, ',', false);
reader.read('follow-level', followMaxLevel);
reader.read('input-format', followInputFormat);
reader.read('no-json', compatibilityNoJSON);
reader.read('no-json-literals', compatibilityNoJSONliterals);
reader.read('dot-notation', tempstr);
case tempstr of
'on': compatibilityDotNotation := xqpdnAllowFullDotNotation;
'off': compatibilityDotNotation := xqpdnDisallowDotNotation;
'unambiguous': compatibilityDotNotation := xqpdnAllowUnambiguousDotNotation;
end;
if reader.read('no-dot-notation', tempbool) then
if tempbool = true then
compatibilityDotNotation := xqpdnDisallowDotNotation;
reader.read('only-json-objects', compatibilityOnlyJSONObjects);
reader.read('no-extended-json', compatibilityNoExtendedJson);
reader.read('strict-type-checking', compatibilityStrictTypeChecking);
reader.read('strict-namespaces', compatibilityStrictNamespaces);
reader.read('no-extended-strings', compatibilityNoExtendedStrings);
reader.read('ignore-namespaces', ignoreNamespace);
reader.read('no-optimizations', noOptimizations);
//deprecated: if (length(extractions) > 0) and (extractions[high(extractions)].extractKind = ekMultipage) and (length(urls) = 0) then
// arrayAdd(urls, '<empty/>');
// if cmdLine.readString('data') <> '' then arrayAdd(urls, cmdLine.readString('data'));
end;
procedure TProcessingContext.mergeWithObject(obj: TXQValueObject);
var
tempreader: TOptionReaderFromObject;
temp: TXQValue;
i: integer;
begin
inherited;
tempreader := TOptionReaderFromObject.create(obj);
readOptions(tempreader);
if length(actions) > 0 then
for i := 0 to high(actions) do
actions[i].readOptions(tempreader);
{todo:
if length(extractions) > 0 then
extractions[high(extractions)].mergeWithObject(obj);
if obj.hasProperty('download', @temp) then arrayAdd(downloads, temp.toString);
if obj.hasProperty('follow-file', @temp) then follow := strLoadFromFileChecked(temp.toString)
setlength(urls, 0);
if (length(extractions) > 0) and (extractions[high(extractions)].extractKind = ekMultipage) and (length(urls) = 0) then begin
arrayAdd(urls, '<empty/>');
arrayAdd(urlsLevel, stepLevel);
end; }
if obj.hasProperty('url', @temp) then
readNewDataSource(TFollowTo.createFromRetrievalAddress(temp.toString), tempreader)
else if obj.hasProperty('data', @temp) then
readNewDataSource(TFollowTo.createFromRetrievalAddress(temp.toString), tempreader);
tempreader.free;
end;
procedure TProcessingContext.addNewDataSource(source: TDataProcessing);
begin
SetLength(dataSources, length(dataSources) + 1);
dataSources[high(dataSources)] := source;
dataSources[high(dataSources)].parent := self;
end;
procedure TProcessingContext.readNewDataSource(data: TFollowTo; options: TOptionReaderWrapper);
begin
addNewDataSource(TFollowToWrapper.Create);
TFollowToWrapper(dataSources[high(dataSources)]).followTo := data;
if options <> nil then
TFollowToWrapper(dataSources[high(dataSources)]).readOptions(options);
end;
procedure TProcessingContext.addNewAction(action: TDataProcessing);
begin
SetLength(actions, length(actions) + 1);
actions[high(actions)] := action;
actions[high(actions)].parent := self;
end;
procedure TProcessingContext.readNewAction(action: TDataProcessing; options: TOptionReaderWrapper);
begin
addNewAction(action);
actions[high(actions)].readOptions(options);
end;
procedure TProcessingContext.assignOptions(other: TProcessingContext);
begin
//neither dataSources nor actions: array of TDataProcessing; ?? todo
wait := other.wait;
userAgent := other.userAgent;
proxy := other.proxy;
printReceivedHeaders:=other.printReceivedHeaders;
errorHandling:=errorHandling;
silent := other.silent;
printPostData := other.printPostData;
compatibilityNoExtendedStrings := other.compatibilityNoExtendedStrings;
compatibilityNoJSON := other.compatibilityNoJSON;
compatibilityNoJSONliterals := other.compatibilityNoJSONliterals;
compatibilityDotNotation := other.compatibilityDotNotation;
compatibilityOnlyJSONObjects := other.compatibilityOnlyJSONObjects;
compatibilityNoExtendedJson := other.compatibilityNoExtendedJson;
compatibilityStrictTypeChecking := other.compatibilityStrictTypeChecking;
compatibilityStrictNamespaces := other.compatibilityStrictNamespaces;
ignoreNamespace:=other.ignoreNamespace;
noOptimizations:=other.noOptimizations;
followExclude := other.followExclude;
followInclude := other.followInclude;
followMaxLevel := other.followMaxLevel;
end;
procedure TProcessingContext.assignActions(other: TProcessingContext);
var i: integer;
begin
setlength(actions, length(other.actions));
for i := 0 to high(actions) do
actions[i] := other.actions[i].clone(self);
end;
function TProcessingContext.clone(newparent: TProcessingContext): TDataProcessing;
var
i: Integer;
begin
result := TProcessingContext.Create;
result.parent := newparent;
TProcessingContext(result).assignOptions(self);
TProcessingContext(result).assignActions(self);
setlength(TProcessingContext(result).dataSources, length(dataSources));
for i := 0 to high(TProcessingContext(result).dataSources) do
TProcessingContext(result).dataSources[i] := dataSources[i].clone(TProcessingContext(result));
if nextSibling <> nil then begin
TProcessingContext(result).nextSibling := nextSibling.clone(TProcessingContext(result)) as TProcessingContext;
end;
TProcessingContext(result).followKind := followKind;
TProcessingContext(result).followInputFormat := followInputFormat;
TProcessingContext(result).follow := follow;
if followTo <> nil then
if followTo = self then TProcessingContext(result).followTo := TProcessingContext(result)
else TProcessingContext(result).followTo := TProcessingContext(followTo.clone(TProcessingContext(result)));
end;
function TProcessingContext.last: TProcessingContext;
begin
if nextSibling <> nil then exit(nextSibling.last);
if followTo <> nil then exit(followTo.last);
exit(self);
end;
procedure TProcessingContext.insertFictiveDatasourceIfNeeded;
var
i: Integer;
needDatasource: Boolean;
begin
if Length(dataSources) > 0 then exit();
if Length(actions) = 0 then exit();
needDatasource := false;
for i := 0 to high(actions) do
if not (actions[i] is TProcessingContext) then begin
needDatasource := true;
break;
end;
if needDatasource then
readNewDataSource(TFollowTo.createFromRetrievalAddress('<empty/>'), nil)
else for i := 0 to high(actions) do
if actions[i] is TProcessingContext then
TProcessingContext(actions[i]).insertFictiveDatasourceIfNeeded;
end;
function TProcessingContext.process(data: IData): TFollowToList;
var next, res: TFollowToList;
procedure subProcess(data: IData; skipActions: integer = 0);
function makeHeaders: ixqvalue;
var
headers: TStringList;
begin
headers := data.headers;
if headers = nil then exit(xqvalue());
result := xqvalue(headers);
end;
var
i: Integer;
decoded: TDecodedUrl;
followKind: TExtractionKind;
begin
if data = nil then exit;
if follow <> '' then printStatus('**** Processing: '+data.displayBaseUri+' ****')
else for i := skipActions to high(actions) do
if actions[i] is TExtraction then begin
printStatus('**** Processing: '+data.displayBaseUri+' ****');
break; //useless printing message if no extraction is there
end;
//printStatus(strFromPtr(self) + data.rawdata);
//alreadyProcessed.Add(urls[0]+#1+post);
htmlparser.variableChangeLog.add('url', data.baseUri);
decoded := decodeURL(data.baseUri);
htmlparser.variableChangeLog.add('host', decoded.host + IfThen(decoded.port <> '' , ':' + decoded.port, ''));
htmlparser.variableChangeLog.add('path', decoded.path);
data.inputFormat; //auto deteect format and convert json to utf-8
htmlparser.variableChangeLog.add('raw', data.rawData);
htmlparser.variableChangeLog.add('headers', makeHeaders);
if yieldDataToParent then begin
if res = nil then res := TFollowToList.Create;
res.add(TFollowToProcessedData.create(data));
end;
for i := skipActions to high(actions) do
next.merge(actions[i].process(data), i + 1);
if follow <> '' then begin
if res = nil then res := TFollowToList.Create;
htmlparser.OutputEncoding := eUTF8; //todo correct encoding?
followKind := self.followKind;
globalDefaultInputFormat := followInputFormat;
if followKind = ekAuto then followKind := guessExtractionKind(follow);
if followKind in [ekPatternHTML, ekPatternXML] then begin
if followKind = ekPatternHTML then htmlparser.TemplateParser.parsingModel := pmHTML
else htmlparser.TemplateParser.parsingModel := pmStrict;
htmlparser.QueryEngine.ParsingOptions.StringEntities:=xqseIgnoreLikeXPath;
htmlparser.parseTemplate(follow); //todo reuse existing parser
htmlparser.parseHTML(data); //todo: optimize
for i:=0 to htmlparser.variableChangeLog.count-1 do
if ((length(followInclude) = 0) and (arrayIndexOf(followExclude, htmlparser.variableChangeLog.getName(i)) = -1)) or
((length(followInclude) > 0) and (arrayIndexOf(followInclude, htmlparser.variableChangeLog.getName(i)) > -1)) then
res.merge(htmlparser.variableChangeLog.get(i), data, self);
end else begin
//assume xpath like
xpathparser.StaticContext. BaseUri := data.baseUri;
xpathparser.ParsingOptions.StringEntities:=xqseDefault;
loadDataForQueryPreParse(data);
if followQueryCache = nil then
case followKind of
ekXQuery1: followQueryCache := xpathparser.parseXQuery1(follow, xpathparser.StaticContext);
ekXQuery3: followQueryCache := xpathparser.parseXQuery3(follow, xpathparser.StaticContext);
ekCSS: followQueryCache := xpathparser.parseCSS3(follow);
ekXPath2: followQueryCache := xpathparser.parseXPath2(follow, xpathparser.StaticContext);
else{ekXPath3: }followQueryCache := xpathparser.parseXPath3(follow, xpathparser.StaticContext);
end;
loadDataForQuery(data, followQueryCache);
res.merge(evaluateQuery(followQueryCache, data), data, self);
end;
if followTo <> nil then begin
if data.recursionLevel + 1 <= followMaxLevel then
for i := 0 to res.Count - 1 do
followto.process(TFollowTo(res[i]).retrieve(self, data.recursionLevel+1)).free;
res.Clear;
end;
end;
end;
var
i: Integer;
curRecursionLevel: Integer;
begin
//init
xpathparser.ParsingOptions.AllowExtendedStrings:= not compatibilityNoExtendedStrings;
xpathparser.ParsingOptions.AllowJSON:=not compatibilityNoJSON;
xpathparser.ParsingOptions.AllowJSONLiterals:=not compatibilityNoJSONliterals;
xpathparser.ParsingOptions.AllowPropertyDotNotation:=compatibilityDotNotation;
xpathparser.StaticContext.objectsRestrictedToJSONTypes:=compatibilityOnlyJSONObjects;
xpathparser.StaticContext.jsonPXPExtensions:=not compatibilityNoExtendedJson;
xpathparser.StaticContext.strictTypeChecking:=compatibilityStrictTypeChecking;
xpathparser.StaticContext.useLocalNamespaces:=not compatibilityStrictNamespaces;
htmlparser.ignoreNamespaces := ignoreNamespace;
//apply all actions to all data source
next := TFollowToList.Create;
res := nil;
if data <> nil then subProcess(data);
for i := 0 to high(dataSources) do
next.merge(dataSources[i].process(nil));
if (length(actions) = 0) and (follow = '') then begin
//nothing is to be done
if res <> nil then res.free; //does this ever happen?
result := next; //yield data to caller (??)
next := nil;
end else begin
//normal processing
if (data = nil) and (length(dataSources) = 0) and (length(actions) > 0) then
for i := 0 to high(actions) do
if actions[i] is TProcessingContext then //evaluate subexpressions, even if there is no data source (they might have their own sources)
next.merge(actions[i].process(nil), i + 1);
curRecursionLevel := 0;
if data <> nil then curRecursionLevel:=data.recursionLevel+1;
while next.Count > 0 do begin
if curRecursionLevel <= followMaxLevel then begin
subProcess(next.First.retrieve(self, curRecursionLevel), next.first.nextAction);
if wait > 0.001 then Sleep(trunc(wait * 1000));
end;
next.Delete(0);
end;
result := res;
end;
if nextSibling <> nil then begin
res := nextSibling.process(nil);
if result = nil then result := res
else result.merge(res);
end;
if (saveCookies <> '') and (internet <> nil) then internet.cookies.saveToFile(saveCookies);
next.free;
end;
function translateDeprecatedStrings(expr: string): string;
var
regex: TWrappedRegExpr;
a: array[0..2] of IXQValue;
begin
if mycmdline.readFlag('deprecated-string-options') then begin
a[0] := xqvalue(expr);
a[1] := xqvalue('([$][a-zA-Z0-9-]);');
a[2] := xqvalue('{$1}');
expr := xqFunctionReplace(3, @a[0]).toString;
end;
result := expr;
end;
class function TProcessingContext.replaceEnclosedExpressions(expr: string): string;
begin
result := htmlparser.replaceEnclosedExpressions(translateDeprecatedStrings(expr));
end;
type
TXQueryEngineBreaker = class(TXQueryEngine)
function parserEnclosedExpressionsString(s: string): IXQuery;
end;
function TXQueryEngineBreaker.parserEnclosedExpressionsString(s: string): IXQuery;
begin
result := parseXStringNullTerminated(s);
end;
function TProcessingContext.replaceEnclosedExpressions(data: IData; expr: string): string;
var
standard: Boolean;
i: Integer;
temp: IXQuery;
begin
expr := translateDeprecatedStrings(expr);
//see htmlparser.replaceEnclosedExpressions(expr)
standard := true;
for i:=1 to length(expr) do
if expr[i] in ['{', '}' ] then begin
standard := false;
break;
end;
if standard then exit(expr);
loadDataForQueryPreParse(data);
temp := TXQueryEngineBreaker(xpathparser).parserEnclosedExpressionsString(expr);
loadDataForQuery(data, temp);
result := evaluateQuery(temp, data).toString;
end;
destructor TProcessingContext.destroy;
var
i: Integer;
begin
for i := 0 to high(dataSources) do dataSources[i].free;
for i := 0 to high(actions) do actions[i].free;
nextSibling.free;
if followTo <> self then followTo.free;
inherited destroy;
end;
function parseJSON(const data: IData): IXQValue;
begin
case data.inputFormat of //todo: cache?
ifJSON: result := xquery_json.parseJSON(data.rawData, [pjoAllowMultipleTopLevelItems, pjoLiberal, pjoAllowTrailingComma]);
ifJSONStrict: result := xquery_json.parseJSON(data.rawData, []);
else result := xqvalue();
end;
end;
procedure TProcessingContext.loadDataForQueryPreParse(const data: IData);
begin
if data.inputFormat in [ifJSON,ifJSONStrict] then begin //we need to set json before parsing, or it fails
//this used htmlparser.VariableChangelog.get('raw') rather than data. why??
htmlparser.VariableChangelog.add('json', parseJSON(data));
currentRoot := nil;
end;
end;
procedure TProcessingContext.loadDataForQuery(const data: IData; const query: IXQuery);
var
f: TInputFormat;
begin
f := data.inputFormat;
if (query.Term = nil) or (f in [ifJSON,ifJSONStrict]) then exit;
if (self = nil) or (noOptimizations) or (xqcdFocusItem in query.Term.getContextDependencies) then begin
htmlparser.parseHTMLSimple(data);
currentRoot := htmlparser.HTMLTree;
end;
end;
function TProcessingContext.evaluateQuery(const query: IXQuery; const data: IData; const allowWithoutReturnValue: boolean): IXQValue;
begin
if query.Term = nil then exit(xqvalue());
if allowWithoutReturnValue and ((query.Term is TXQTermModule) and (TXQTermModule(query.Term).children[high(TXQTermModule(query.Term).children)] = nil)) then
TXQTermModule(query.Term).children[high(TXQTermModule(query.Term).children)] := TXQTermSequence.Create; //allows to process queries without return value, e.g. "declare variable $a := 1"
if not (data.inputFormat in [ifJSON,ifJSONStrict]) then result := query.evaluate(currentRoot)
else result := query.evaluate(htmlparser.variableChangeLog.get('json'));
end;
procedure TProcessingContext.httpReact(sender: TInternetAccess; var method: string; var url: TDecodedUrl;
var data: TInternetAccessDataBlock; var reaction: TInternetAccessReaction);
begin
stupidHTTPReactionHackFlag := 0;
case TInternetAccess.reactFromCodeString(errorHandling, sender.lastHTTPResultCode, reaction) of
'retry': Sleep(trunc(wait*1000));
'ignore': stupidHTTPReactionHackFlag := 1;
'skip': stupidHTTPReactionHackFlag := 2;
end;
end;
var hasRawWrapper: boolean = false;
procedure needRawWrapper;
procedure setHeaderFooter(const h, f: string);
begin
if outputFormat = ofJsonWrapped then wcolor(h, cJSON)
else wcolor(h, cXML);
if outputSeparator = LineEnding then wln();
if not mycmdline.existsProperty('output-footer') then outputFooter := f + LineEnding;
end;
var
le: string;
begin
if hasRawWrapper then exit;
hasRawWrapper := true;
if not mycmdline.existsProperty('output-header') then begin
if not mycmdline.existsProperty('output-separator') then le := LineEnding
else le := '';
case outputFormat of
ofRawHTML: setHeaderFooter('<html><body>', le + '</body></html>');
ofRawXML: setHeaderFooter('<xml>', le + '</xml>');
ofJsonWrapped: setHeaderFooter('[', le + ']');
ofXMLWrapped: setHeaderFooter('<seq>', '</seq>');
end;
end;
end;
function bashStrEscape(s: string): string;
begin
if not strContains(s, #13) and not strContains(s, #10) then
exit('''' + StringReplace(s, '''', '''' + '"' + '''' + '"' + '''' {<- 5 individual characters} , [rfReplaceAll]) + '''');
exit ('$''' + StringReplace(StringReplace(StringReplace(StringReplace(s,
'\', '\\', [rfReplaceAll]),
'''', '\''', [rfReplaceAll]),
#10, '\n', [rfReplaceAll]),
#13, '\r', [rfReplaceAll])
+ '''');
end;
function windowsCmdEscape(s: string): string;
begin
result := StringsReplace(s, [#10, #13, '%', '^', '&', '<', '>', '|', '"', ',', ';', '(', ')', '"', '=' ],
['', '', windowsCmdPercentageEscape + '%', '^^', '^&', '^<', '^>', '^|', '^"', '^,', '^;', '^(', '^)', '^"', '^='],
[rfReplaceAll]);
end;
procedure TExtraction.printExtractedValue(value: IXQValue; invariable: boolean);
function cmdescape(s: string): string;
begin
case outputFormat of
ofAdhoc, ofRawHTML, ofRawXML: exit(s);
ofBash: exit(bashStrEscape(s));
ofWindowsCmd: exit(windowsCmdEscape(s));
else raise EXidelException.Create('Invalid output format');
end;
end;
function escape(s: string): string;
begin
case outputFormat of
ofAdhoc: exit(s);
ofRawHTML: exit(htmlStrEscape(s));
ofRawXML, ofXMLWrapped: exit(xmlStrEscape(s));
ofBash: exit(bashStrEscape(s));
ofWindowsCmd: exit(windowsCmdEscape(s));
else raise EXidelException.Create('Invalid output format');
end;
end;
function singletonToString(const v: IXQValue): string;
begin
case v.kind of
pvkNode: begin
if (outputFormat <> ofAdhoc) and (printTypeAnnotations or (not (v.toNode.typ in [tetOpen,tetDocument]) or (printedNodeFormat = tnsText))) and not invariable then needRawWrapper;
case printedNodeFormat of
tnsText: result := escape(v.toString);
tnsXML: result := cmdescape(v.toNode.outerXML());
tnsHTML: result := cmdescape(v.toNode.outerHTML());
else raise EInvalidArgument.Create('Unknown node print format');
end;
if printTypeAnnotations then
if (printedNodeFormat = tnsText) or (v.toNode.typ = tetText) then
result := 'text{' + xqvalue(result).toXQuery + '}';
end;
pvkObject, pvkArray: begin
if (outputFormat <> ofAdhoc) and not invariable then needRawWrapper;
result := escape(v.jsonSerialize(printedNodeFormat, (printedJSONFormat = jisPretty) or (not invariable and (printedJSONFormat <> jisCompact))));
end;
else if not printTypeAnnotations then begin
if (outputFormat <> ofAdhoc) and not invariable then needRawWrapper;
exit(escape(v.toString));
end else result := escape(v.toXQuery)
end;
end;
procedure writeItemColor(const v: IXQValue);
var
color: TColorOptions;
begin
color := colorizing;
if (color in [cAuto,cAlways]) and (outputFormat = ofAdhoc) then
case value.get(1).kind of
pvkNode: if printedNodeFormat <> tnsText then color := cXML;
pvkArray,pvkObject: color := cJSON;
end;
writeItem(singletonToString(v), color)
end;
var
i: Integer;
temp: TXQValueObject;
x: IXQValue;
begin
case outputFormat of
ofAdhoc, ofRawHTML, ofRawXML, ofBash, ofWindowsCmd: begin
if (outputFormat in [ofBash, ofWindowsCmd]) and not invariable then begin
printCmdlineVariable(defaultName, value);
exit;
end;
case value.getSequenceCount of
0: begin
if not printTypeAnnotations then begin
if invariable {and (outputFormat in [ofBash, ofWindowsCmd]) }then writeItem('');
exit;
end;
if (outputFormat <> ofAdhoc) and not invariable then needRawWrapper;
writeItem(escape('()'));
end;
1: writeItemColor(value.get(1));
else begin
if (outputFormat <> ofAdhoc) and not invariable then needRawWrapper;
if not printTypeAnnotations then begin
for x in value do writeItemColor(x);
end else begin
writeItem(escape('(') + singletonToString(value.get(1)) + escape(', '));
for i := 2 to value.getSequenceCount - 1 do
writeItem(singletonToString(value.get(i)) + escape(', '));
writeItem(singletonToString(value.get(value.getSequenceCount)) + escape(')'));
end;
end;
end;
end;
ofJsonWrapped: begin
wcolor(value.jsonSerialize(printedNodeFormat, printedJSONFormat <> jisCompact), cJSON);
end;
ofXMLWrapped: begin
wcolor(value.xmlSerialize(printedNodeFormat, 'seq', 'e', 'object'), cXML);
end;
end;
end;
var usedCmdlineVariables: array of record
name: string;
count: longint;
value: IXQValue;
end;
procedure TExtraction.printCmdlineVariable(const name: string; const value: IXQValue);
var
i: Integer;
v: IXQValue;
begin
if value is TXQValueSequence then begin
for v in value do
printCmdlineVariable(name, v);
exit;
end;
for i := 0 to high(usedCmdlineVariables) do
if usedCmdlineVariables[i].name = name then begin
if usedCmdlineVariables[i].count = 1 then
case outputFormat of
ofBash: writeItem(name+'[0]="$'+name+'"');
ofWindowsCmd: printCmdlineVariable(name+'[0]', usedCmdlineVariables[i].value);
end;
printCmdlineVariable(name+'['+IntToStr(usedCmdlineVariables[i].count)+']', value);
usedCmdlineVariables[i].count+=1;
exit;
end;
case outputFormat of
ofBash: writeVarName(name+'=');
ofWindowsCmd: writeVarName('SET '+name+'=');
end;
printExtractedValue(value, true);
SetLength(usedCmdlineVariables, length(usedCmdlineVariables)+1);
usedCmdlineVariables[high(usedCmdlineVariables)].name:=name;
usedCmdlineVariables[high(usedCmdlineVariables)].count:=1;
if outputFormat = ofWindowsCmd then;
usedCmdlineVariables[high(usedCmdlineVariables)].value:=value;
end;
procedure TExtraction.printExtractedVariables(parser: THtmlTemplateParser; showDefaultVariableOverride: boolean);
var
i: Integer;
begin
if pvFinal in printVariables then
printExtractedVariables(parser.variables, '** Current variable state: **', showDefaultVariableOverride or parser.hasRealVariableDefinitions);
if pvLog in printVariables then
printExtractedVariables(parser.variableChangeLog, '** Current variable state: **', showDefaultVariableOverride or parser.hasRealVariableDefinitions);
if pvCondensedLog in printVariables then
printExtractedVariables(parser.VariableChangeLogCondensed, '** Current variable state: **', showDefaultVariableOverride or parser.hasRealVariableDefinitions);
for i := 0 to parser.variableChangeLog.count-1 do
if parser.variableChangeLog.getName(i) = '_follow' then begin
if currentFollowList = nil then currentFollowList := TFollowToList.Create;
currentFollowList.merge(parser.variableChangeLog.get(i), currentData, parent);
end;
end;
procedure TExtraction.pageProcessed(unused: TMultipageTemplateReader; parser: THtmlTemplateParser);
begin
printExtractedVariables(parser, false);
end;
function TExtraction.process(data: IData): TFollowToList;
function termContainsVariableDefinition(term: TXQTerm): boolean;
var
i: Integer;
visitor: TXQTerm_VisitorFindWeirdGlobalVariableDeclarations;
begin
if term = nil then exit(false);
visitor := TXQTerm_VisitorFindWeirdGlobalVariableDeclarations.Create;
visitor.simpleTermVisit(@term, nil);
result := visitor.hasVars;
visitor.free;
end;
var
value: IXQValue;
begin
//set flags when first processed
if isStdin(extract) then extract:=strReadFromStdin;
if extractKind = ekAuto then begin
if extract = '' then extract := '()';
extractKind := guessExtractionKind(extract);
end;
//parent.printStatus(strFromPtr(self) + data.rawdata + ' :: ' + extract);
currentFollowList := nil;
currentData:=data;
if hasOutputEncoding <> oePassRaw then htmlparser.OutputEncoding := CP_UTF8
else htmlparser.OutputEncoding := CP_NONE;
globalDefaultInputFormat := inputFormat;
case extractKind of
ekPatternHTML, ekPatternXML: begin
htmlparser.UnnamedVariableName:=defaultName;
htmlparser.QueryEngine.ParsingOptions.StringEntities:=xqseIgnoreLikeXPath;
if extractKind = ekPatternHTML then htmlparser.TemplateParser.parsingModel := pmHTML
else htmlparser.TemplateParser.parsingModel := pmStrict;
htmlparser.parseTemplate(extract); //todo reuse existing parser
htmlparser.parseHTML(data); //todo: full url is abs?
pageProcessed(nil,htmlparser);
end;
ekXPath2, ekXPath3, ekCSS, ekXQuery1, ekXQuery3: begin
xpathparser.StaticContext.BaseUri := fileNameExpandToURI(data.baseUri);
xpathparser.ParsingOptions.StringEntities:=xqseDefault;
parent.loadDataForQueryPreParse(data);
if extractQueryCache = nil then
case extractKind of
ekCSS: extractQueryCache := xpathparser.parseCSS3(extract); //todo: optimize
ekXPath2: extractQueryCache := xpathparser.parseXPath2(extract, xpathparser.StaticContext);
ekXQuery1: extractQueryCache := xpathparser.parseXQuery1(extract, xpathparser.StaticContext);
ekXPath3: extractQueryCache := xpathparser.parseXPath3(extract, xpathparser.StaticContext);
ekXQuery3: extractQueryCache := xpathparser.parseXQuery3(extract, xpathparser.StaticContext);
end;
parent.loadDataForQuery(data, extractQueryCache);
if termContainsVariableDefinition(extractQueryCache.Term) then begin
THtmlTemplateParserBreaker(htmlparser).closeVariableLog;
parent.evaluateQuery(extractQueryCache, data, true);
printExtractedVariables(htmlparser, true);
end else begin
value := parent.evaluateQuery(extractQueryCache, data, true);
writeBeginGroup;
printExtractedValue(value, false);
writeEndGroup;
htmlparser.oldVariableChangeLog.add(defaultName, value);
end;
end;
ekMultipage: if assigned (onPrepareInternet) then begin
multipage.onPageProcessed:=@pageProcessed;
multipage.internet := onPrepareInternet(parent.userAgent, parent.proxy, @parent.httpReact);
multipagetemp := TMultiPageTemplate.create();
multipagetemp.loadTemplateFromString(extract);
multipage.setTemplate(multipagetemp);
multipage.perform(templateActions);
multipage.setTemplate(nil);
multipagetemp.free;
end
else raise EXidelException.Create('Impossible');
end;
result := currentFollowList;
currentFollowList := nil;
end;
procedure TExtraction.assignOptions(other: TExtraction);
begin
extract := other.extract;
extractExclude := other.extractExclude; SetLength(extractExclude, length(extractExclude));
extractInclude := other.extractInclude; SetLength(extractInclude, length(extractInclude));
extractKind := other.extractKind;
templateActions := other.templateActions;
SetLength(templateActions, length(templateActions));
defaultName := other.defaultName;
printVariables := other.printVariables;
printTypeAnnotations := other.printTypeAnnotations;
hideVariableNames := other.hideVariableNames;
printedNodeFormat := other.printedNodeFormat;
printedJSONFormat := other.printedJSONFormat;
inputFormat := inputFormat;
end;
function TExtraction.clone(newparent: TProcessingContext): TDataProcessing;
begin
result := TExtraction.create;
result.parent := newparent;
TExtraction(result).assignOptions(self);
end;
procedure TExtraction.printExtractedVariables(vars: TXQVariableChangeLog; state: string; showDefaultVariable: boolean);
function acceptName(n: string): boolean;
begin
result := ((length(extractInclude) = 0) and (arrayIndexOf(extractExclude, n) = -1)) or
((length(extractInclude) > 0) and (arrayIndexOf(extractInclude, n) > -1));
end;
var jsonItselfAssigned: boolean;
function showVar(const i: integer): boolean;
var
n: String;
begin
n := vars.Names[i];
result := not hideVariableNames and (showDefaultVariable or (n <> defaultName) );
if result and (n = 'json') then begin
//changing properties of the default json should not output the variable name
//however, creating a new json variable should
if not vars.isPropertyChange(i) then jsonItselfAssigned := true;
result := jsonItselfAssigned;
end;
end;
var
i: Integer;
tempUsed: array of boolean;
first: boolean;
values: IXQValue;
j: Integer;
isShown: Boolean;
begin
writeBeginGroup;
jsonItselfAssigned := false;
parent.printStatus(state);
case outputFormat of
ofAdhoc: begin
for i:=0 to vars.count-1 do
if acceptName(vars.Names[i]) then begin
isShown := showVar(i);
if isShown then writeVarName(vars.Names[i] + ' := ');
printExtractedValue(vars.get(i), isShown);
end;
end;
ofRawXML: begin
if vars.count > 1 then needRawWrapper;
for i:=0 to vars.count-1 do
if acceptName(vars.Names[i]) then begin
isShown := showVar(i);
if isShown then writeVarName('<'+vars.Names[i] + '>', cXML);
printExtractedValue(vars.get(i), isShown );
if isShown then wcolor('</'+vars.Names[i] + '>', cXML);
end;
end;
ofRawHTML: begin
if vars.count > 1 then needRawWrapper;
for i:=0 to vars.count-1 do
if acceptName(vars.Names[i]) then begin
isShown := showVar(i);
if isShown then writeVarName('<span class="'+vars.Names[i] + '">', cXML);
printExtractedValue(vars.get(i), isShown );
if isShown then wcolor('</span>', cXML);
end;
end;
ofJsonWrapped:
if hideVariableNames then begin
wcolor('[', cJSON);
first := true;
for i:=0 to vars.count-1 do begin
if acceptName(vars.Names[i]) then begin
if first then first := false
else wcolor(', ' + LineEnding, cJSON);
printExtractedValue(vars.get(i), true);
end;
end;
wcolor(']' + LineEnding, cJSON);
end else begin
first := true;
writeItem('{', cJSON);
setlength(tempUsed, vars.count);
FillChar(tempUsed[0], sizeof(tempUsed[0])*length(tempUsed), 0);
for i:=0 to vars.count-1 do begin
if tempUsed[i] then continue;
if acceptName(vars.Names[i]) then begin
if not first then wcolor(', ' + LineEnding, cJSON);
first := false;
writeVarName(jsonStrEscape(vars.Names[i]) + ': ', cJSON);
values := vars.getAll(vars.Names[i]);
if values.getSequenceCount = 1 then printExtractedValue(values, true)
else begin
wcolor('[', cJSON);
printExtractedValue(values.get(1), true);
for j:=2 to values.getSequenceCount do begin
wcolor(', ', cJSON);
printExtractedValue(values.get(j), true);
end;
wcolor(']', cJSON);
end;
end;
for j := i + 1 to vars.count-1 do
if vars.Names[i] = vars.Names[j] then tempUsed[j] := true;
end;
wcolor(LineEnding + '}', cJSON);
end;
ofXMLWrapped: begin
if hideVariableNames then begin
wcolor('<seq>', cXML);
first := true;
for i:=0 to vars.count-1 do begin
if acceptName(vars.Names[i]) then begin
if first then begin first := false; wcolor('<e>', cXML);end
else wcolor('</e><e>', cXML);
printExtractedValue(vars.get(i), true);
end;
end;
if not first then wcolor('</e>', cXML);
wcolor('</seq>' + LineEnding, cXML);
end else begin
wcolor(LineEnding + '<object>' + LineEnding, cXML);
for i:=0 to vars.count-1 do
if acceptName(vars.Names[i]) then begin
wcolor('<'+vars.Names[i] + '>', cXML);
printExtractedValue(vars.Values[i], true);
wcolor('</'+vars.Names[i] + '>'+LineEnding, cXML);
end;
wcolor('</object>'+LineEnding, cXML);
end;
end;
ofBash, ofWindowsCmd:
for i:=0 to vars.count-1 do
if acceptName(vars.Names[i]) then
printCmdlineVariable(vars.Names[i], vars.Values[i]);
end;
writeEndGroup;
end;
var i: Integer;
temp: TStringArray;
j: Integer;
alternativeXMLParser: TTreeParser = nil;
{ TMultiPageTemplateBreaker }
{ THtmlTemplateParserBreaker }
procedure THtmlTemplateParserBreaker.initParsingModel(const data: IData);
var
f: TInputFormat;
tempparser: TTreeParser;
begin
f := data.inputFormat;
if f in [ifJSON,ifJSONStrict] then exit;
if (f = ifXMLStrict) <> (HTMLParser is TTreeParserDOM) then begin
if alternativeXMLParser = nil then begin
alternativeXMLParser := TTreeParserDOM.Create;
alternativeXMLParser.readComments:=true;
alternativeXMLParser.readProcessingInstructions:=true;
alternativeXMLParser.parsingModel:=pmStrict;
end;
tempparser := HTMLParser;
FHTML := alternativeXMLParser;
alternativeXMLParser := tempparser;
end;
if f = ifXML then HTMLParser.parsingModel := pmUnstrictXML
else HTMLParser.parsingModel := pmHTML;
HTMLParser.repairMissingStartTags := f = ifHTML;
HTMLParser.readProcessingInstructions := f <> ifHTML;
end;
procedure THtmlTemplateParserBreaker.parseHTML(const data: IData);
begin
initParsingModel(data);
inherited parseHTML(data.rawData, data.baseUri, data.contenttype);
end;
function strFirstNonSpace(const s: string): char;
begin
for i:=1 to length(s) do
if not (s[i] in WHITE_SPACE) then exit(s[i]);
exit(#0);
end;
procedure THtmlTemplateParserBreaker.parseHTMLSimple(const data: IData);
var temp: TTreeNode;
i: integer;
begin
(*if (strFirstNonSpace(html) in ['{', '[']) and (
striEndsWith(uri, 'json') or striEndsWith(uri, 'jsonp')
or striContains(contenttype, 'application/json') or striContains(contenttype, 'application/x-javascript')
or striContains(contenttype, 'text/javascript') or striContains(contenttype, 'text/x-javascript')
or striContains(contenttype, 'text/x-json')) then begin
xpathparser.evaluate(); StaticContext. xpathparser.findNativeModule('http://jsoniq.org/functions').findBasicFunction('parse-json').func^(xqvalue(html));
exit;
end; *)
initParsingModel(data);
inherited parseHTMLSimple(data.rawData, data.baseUri, data.contenttype);
if ignoreNamespaces then begin
temp := FHtmlTree;
while temp <> nil do begin
temp.namespace:=nil;
if temp.attributes <> nil then
for i:=temp.attributes.count-1 downto 0 do
if temp.attributes.Items[i].isNamespaceNode then
temp.attributes.Delete(i);
temp := temp.next;
end;
end;
end;
procedure THtmlTemplateParserBreaker.closeVariableLog;
begin
FreeAndNil(FVariables);
oldVariableChangeLog.takeFrom(variableChangeLog);
FreeAndNil(FVariableLogCondensed);
end;
procedure THtmlTemplateParserBreaker.parseDoc(sender: TXQueryEngine; html, uri, contenttype: string; var node: TTreeNode);
var
tempData: TDataObject;
temptemp: IData;
begin
if cgimode or (not allowFileAccess) then raise EXQEvaluationException.create('pxp:cgi', 'Using doc is not allowed in cgi mode');
tempData := TDataObject.create(html, uri, contenttype);
if (uri <> xpathparser.staticContext.baseURI) //then it is one of the explicit parse-* functions
or (strContains(contenttype, 'xml') and (globalDefaultInputFormat in [ifXML, ifXMLStrict])) //still allow to switch between xml and xml-strict for parse-xml
then
tempData.finputFormat := globalDefaultInputFormat;
temptemp := tempData;
parseHTMLSimple(temptemp);
node := HTMLTree;
end;
constructor TTemplateReaderBreaker.create;
begin
queryCache := TXQMapStringObject.Create;
queryCache.OwnsObjects := false;
onLog:=@selfLog;
end;
procedure TTemplateReaderBreaker.setTemplate(atemplate: TMultiPageTemplate);
begin
if atemplate = nil then begin
atemplate.free;
template:=nil;
exit;
end;
inherited setTemplate(atemplate);
end;
procedure TTemplateReaderBreaker.perform(actions: TStringArray);
begin
if length(template.baseActions.children) = 0 then raise EXidelException.Create('Template contains no actions!'+LineEnding+'A Multipage template should look like <action> <page url="..."> <post> post data </post> <template> single page template </template> </page> </action> ');
if length(actions) = 0 then callAction(template.baseActions.children[0])
else for i:= 0 to high(actions) do
callAction(actions[i]);
end;
procedure TTemplateReaderBreaker.selfLog(sender: TMultipageTemplateReader; logged: string; debugLevel: integer);
begin
if debugLevel <> 0 then exit;
writeln(stderr, logged);
end;
procedure traceCall(pseudoSelf: tobject; sender: TXQueryEngine; value, info: IXQValue);
begin
if not info.isUndefined then write(stderr, info.toJoinedString() + ': ');
writeln(stderr, value.toXQuery());
end;
type TXQTracer = class
log: array of record
t: TXQTerm;
args: TXQVArray;
end;
lastContext: TXQEvaluationContext;
//varLog: TXQVariableChangeLog;
logLength: integer;
all, backtrace, context, contextVariables: boolean;
procedure globalTracing(term: TXQTerm; const acontext: TXQEvaluationContext; argc: SizeInt; args: PIXQValue);
procedure printStderr(term: TXQTerm; argc: sizeint; args: PIXQValue);
procedure printStderr(term: TXQTerm; args: TXQVArray);
procedure printBacktrace;
procedure printLastContext;
destructor Destroy; override;
end;
var tracer: TXQTracer;
procedure TXQTracer.globalTracing(term: TXQTerm; const acontext: TXQEvaluationContext; argc: SizeInt; args: PIXQValue);
var
entering: Boolean;
begin
entering := argc >= 0;
if backtrace then begin;
if entering then begin
if logLength > high(log) then SetLength(log, max(logLength + 8, length(log) * 2));
log[logLength].t := term;
SetLength(log[logLength].args, argc);
for i := 0 to argc - 1 do
log[logLength].args[i] := args[i];
inc(logLength);
end else begin
while (logLength > 0) and (log[logLength - 1].t <> term) do dec(logLength);
if (logLength > 0) and (log[logLength - 1].t = term) then dec(logLength);
end;
end;
if entering then begin
if all and entering then printStderr(term, argc, args);
if self.context and entering then begin
lastContext := acontext;
{if contextVariables then
if acontext.temporaryVariables = nil then varlog.clear
else varLog.assign(acontext.temporaryVariables);}
if all then printLastContext;
end;
end;
end;
procedure TXQTracer.printStderr(term: TXQTerm; argc: sizeint; args: PIXQValue);
var i: integer;
begin
if term is TXQTermNamedFunction then begin
if TXQTermNamedFunction(term).name <> nil then write(stderr, TXQTermNamedFunction(term).name.ToString)
else write(stderr, 'unknown function');
end else if term is TXQTermBinaryOp then begin
if TXQTermBinaryOp(term).op <> nil then write(stderr, 'operator ', TXQTermBinaryOp(term).op.name)
else write(stderr, 'unknown operator');
end else if term is TXQTermDynamicFunctionCall then write('anonymous function')
else if term is TXQTermTryCatch then write('try/catch')
else write('unknown event');
write(stderr, '(');
for i := 0 to argc-1 do
if i = 0 then write(args[i].toXQuery())
else write(', ', args[i].toXQuery());
writeln(stderr, ')');
end;
procedure TXQTracer.printStderr(term: TXQTerm; args: TXQVArray);
begin
if length(args) = 0 then printStderr(term, 0, nil)
else printStderr(term, length(args), @args[0])
end;
procedure TXQTracer.printBacktrace;
var i: integer;
begin
for i := 0 to logLength - 1 do
printStderr(log[i].t, log[i].args);
end;
procedure TXQTracer.printLastContext;
//var
// vars: TXQVariableChangeLog;
begin
writeln(stderr, 'Dynamic context: ');
if lastContext.RootElement <> nil then writeln(stderr, ' root node: ', lastContext.ParentElement.toString());
if lastContext.ParentElement <> nil then writeln(stderr, ' parent node: ', lastContext.ParentElement.toString());
if lastContext.SeqValue <> nil then writeln(stderr, ' context item (.): ', lastContext.SeqValue.toXQuery());
writeln(stderr, ' position()/last(): ', lastContext.SeqIndex, ' / ', lastContext.SeqLength);
{vars := lastContext.temporaryVariables;
if contextVariables then vars := varLog;
if (vars <> nil) and (vars.count > 0) then begin
writeln(stderr, ' Local variables: ');
for i := 0 to vars.count - 1 do
writeln(stderr, ' ', vars.getName(i), ' = ', vars.get(i).toXQuery());
end;}
WriteLn(stderr, '');
end;
destructor TXQTracer.Destroy;
begin
//varLog.Free;
inherited Destroy;
end;
procedure displayError(e: Exception; printPartialMatches: boolean = false);
procedure say(s: string; color: TMyConsoleColors = ccNormal);
begin
if cgimode then write(s)
else begin
setTerminalColor(true, color);
write(stderr, s);
end;
end;
procedure sayln(s: string; color: TMyConsoleColors = ccNormal);
begin
say(s+LineEnding, color);
end;
const ParsingError = '[<- error occurs before here]';
var
message: String;
p: LongInt;
begin
case outputFormat of
ofJsonWrapped: begin
sayln('{"_error": {');
say('"_message": '+jsonStrEscape(e.Message));
if printPartialMatches then begin
sayln(', ');
sayln('"_partial-matches": [');
temp := strSplit(htmlparser.debugMatchings(50), LineEnding); //print line by line, or the output "disappears"
if length(temp) > 0 then
say(jsonStrEscape(temp[j]));
for j := 1 to high(temp) do say (', '+LineEnding+jsonStrEscape(temp[j]));
sayln(']');
end else sayln('');
sayln('}}');
//if cgimode then
// sayln(']');
end;
ofXMLWrapped{, ofRawXML, ofRawHTML}: begin
sayln('<error>');
sayln('<message>'+xmlStrEscape(e.Message)+'</message>');
if printPartialMatches then begin
sayln('<partial-matches><![CDATA[');
temp := strSplit(htmlparser.debugMatchings(50), LineEnding); //print line by line, or the output "disappears"
for j := 0 to high(temp) do sayln( temp[j]);
sayln(']]></partial-matches>');
end;
sayln('</error>');
//if cgimode then
// sayln('</seq>');
end;
else begin
sayln( 'Error:');
message := e.Message;
if not cgimode then begin
if strBeginsWith(message, 'err:') or strBeginsWith(message, 'pxp:') then begin
p := strIndexOf(message, [#13,#10]);
say(copy(message,1,p-1), ccRedBold);
delete(message, 1, p);
end;
while Length(message) > 0 do begin
p := strIndexOf(message, ParsingError);
if p <= 0 then break;
say(copy(message, 1, p - 1));
say(ParsingError, ccRedBold);
delete(message, 1, p + length(ParsingError) - 1);
end;
end;
sayln( message );
if printPartialMatches then begin
sayln('');
sayln( 'Partial matches:');
temp := strSplit(htmlparser.debugMatchings(50), LineEnding); //print line by line, or the output "disappears"
for j := 0 to high(temp) do sayln( temp[j]);
end;
end;
end;
if cgimode then flush(StdOut)
else flush(stderr);
if e is EXQEvaluationException then begin
if (tracer = nil) or not tracer.backtrace then begin
sayln('Possible backtrace:');
for i := 0 to ExceptFrameCount-1 do begin
sayln(BackTraceStrFunc(ExceptFrames[i]) + ': ' + EXQException.searchClosestFunction(ExceptFrames[i]));
end;
sayln(LineEnding + 'Call xidel with --trace-stack to get an actual backtrace')
end;
if (tracer <> nil) then begin
if tracer.backtrace then tracer.printBacktrace;
if tracer.context then tracer.printLastContext;
end;
end;
end;
type
{ TCommandLineReaderBreaker }
TPropertyArray = array of TProperty;
TCommandLineReaderBreaker = class(TCommandLineReader)
procedure overrideVar(const name, value: string);
procedure removeVar(const name: string);
procedure clearNameless;
procedure setProperties(newProperties: TPropertyArray);
function getProperties(): TPropertyArray;
procedure parseUTF8(autoReset: boolean = true);
end;
{ TCommandLineReaderBreaker }
procedure TCommandLineReaderBreaker.overrideVar(const name, value: string);
var
tempprop: PProperty;
begin
tempprop := findProperty(name);
tempprop^.strvalue:=value;
tempprop^.found:=true;
end;
procedure TCommandLineReaderBreaker.removeVar(const name: string);
var
tempprop: PProperty;
begin
tempprop := findProperty(name);
tempprop^.strvalue:=tempprop^.strvalueDefault;
tempprop^.found:=false;
end;
procedure TCommandLineReaderBreaker.clearNameless;
begin
SetLength(nameless, 0);
end;
procedure TCommandLineReaderBreaker.setProperties(newProperties: TPropertyArray);
begin
propertyArray := newProperties;
end;
function TCommandLineReaderBreaker.getProperties: TPropertyArray;
begin
result := propertyArray;
end;
procedure TCommandLineReaderBreaker.parseUTF8(autoReset: boolean = true);
{$ifndef windows}
var args: TStringArray;
i: Integer;
{$endif}
begin
if cgimode then begin
parse(autoReset);
exit;
end;
if Paramcount = 0 then exit;
{$ifdef windows}
parse({$ifndef FPC_HAS_CPSTRING} SysToUTF8{$ENDIF}(utf8string(GetCommandLineW)), true, autoReset);
{$else}
setlength(args, Paramcount);
for i:=0 to high(args) do args[i] := {$ifndef FPC_HAS_CPSTRING} SysToUTF8{$ENDIF}(paramstr(i+1));
parse(args, autoReset);
{$endif}
end;
var currentContext: TProcessingContext;
cmdlineWrapper: TOptionReaderFromCommandLine;
commandLineStack: array of array of TProperty;
commandLineStackLastPostData, commandLineStackLastFormData, commandLineLastHeader: string;
contextStack: array of TProcessingContext;
procedure pushCommandLineState;
begin
if TCommandLineReaderBreaker(mycmdline).existsProperty('post') then
TCommandLineReaderBreaker(mycmdline).overrideVar('post', commandLineStackLastPostData);
if TCommandLineReaderBreaker(mycmdline).existsProperty('form') then
TCommandLineReaderBreaker(mycmdline).overrideVar('form', commandLineStackLastFormData);
if TCommandLineReaderBreaker(mycmdline).existsProperty('header') then
TCommandLineReaderBreaker(mycmdline).overrideVar('header', commandLineLastHeader);
SetLength(commandLineStack, length(commandLineStack) + 1);
commandLineStack[high(commandLineStack)] := TCommandLineReaderBreaker(mycmdline).getProperties;
SetLength(commandLineStack[high(commandLineStack)], length(commandLineStack[high(commandLineStack)]));
SetLength(contextStack, length(contextStack) + 2);
contextStack[high(contextStack) - 1] := currentContext;
contextStack[high(contextStack)] := nil;
end;
function popCommandLineState: TProcessingContext;
begin
result := contextStack[high(contextStack) - 1];
SetLength(contextStack, length(contextStack) - 2);
TCommandLineReaderBreaker(mycmdline).setProperties(commandLineStack[high(commandLineStack)]);
SetLength(commandLineStack, high(commandLineStack));
if TCommandLineReaderBreaker(mycmdline).existsProperty('post') then
commandLineStackLastPostData := TCommandLineReaderBreaker(mycmdline).readString('post');
if TCommandLineReaderBreaker(mycmdline).existsProperty('form') then
commandLineStackLastFormData := TCommandLineReaderBreaker(mycmdline).readString('form');
if TCommandLineReaderBreaker(mycmdline).existsProperty('header') then
commandLineLastHeader := TCommandLineReaderBreaker(mycmdline).readString('header');
end;
procedure variableInterpret(pseudoself, sender: TObject; var name, value: string; const args: TStringArray; var argpos: integer);
begin
if strBeginsWith(name, 'xmlns:') then begin
value := strCopyFrom(name, length('xmlns:') + 1) + '=' + value;
name := 'xmlns';
end;
end;
procedure closeMultiArgs(var oldValue: string; separator: string);
begin
if strEndsWith(oldValue, separator) then
delete(oldValue, length(oldValue) - length(separator) + 1, length(separator));
end;
function combineMultiArgs(var oldValue: string; appendValue, separator: string): string;
begin
if (appendValue = '') then oldValue := ''
else begin
if appendValue[1] = '&' then delete(appendValue, 1, 1)
else if not strEndsWith(oldValue, separator) then oldValue := '';
oldValue := oldValue + appendValue + separator;
end;
Result := oldValue;
end;
procedure variableRead(pseudoself: TObject; sender: TObject; const name, value: string);
procedure closeAllMultiArgs;
begin
closeMultiArgs(commandLineStackLastPostData, '&');
closeMultiArgs(commandLineStackLastFormData, #0);
closeMultiArgs(commandLineLastHeader, #13#10);
end;
procedure parseVariableArg;
var
temps, temps2: String;
equalSign: SizeInt;
vars: bbutils.TStringArray;
begin
equalSign := pos('=', value);
if equalSign = 0 then temps := value
else begin
temps := copy(value, 1, equalSign - 1);
if strEndsWith(temps, ':') then delete(temps, length(temps), 1);
end;
vars := strSplit(temps, ',');
if (length(vars) <> 1) and (equalSign > 0) then raise EXidelException.Create('Cannot import multiple variables and specify a variable value at once. In '+value);
for temps2 in vars do begin
temps := trim(temps2);
if strBeginsWith(temps, '$') then delete(temps, 1, 1);
if equalSign = 0 then htmlparser.variableChangeLog.add(temps, GetEnvironmentVariable(temps))
else htmlparser.variableChangeLog.add(trim(temps), strCopyFrom(value, equalSign+1));
end;
end;
var
specialized: string;
temps: String;
begin
if (name = 'follow') or (name = 'follow-file') //follow always create new processing context
or ((name = '') and (value <> '[') and (value <> ']') //plain data/url
and (((currentContext.parent <> nil) and (currentContext.parent.followTo = currentContext)) or (length(currentContext.actions) > 0))) //only creates new context, if previous context is not a follow context and had no action yet (otherwise it becomes new data source in the previous context)
then begin
if name = 'follow-file' then
if isStdin(value) then TCommandLineReaderBreaker(sender).overrideVar('follow', '-')
else TCommandLineReaderBreaker(sender).overrideVar('follow', strLoadFromFileChecked(value));
//writeln(stderr,name,'=',value);
currentContext.readOptions(cmdlineWrapper);
TCommandLineReaderBreaker(sender).clearNameless;
if name <> '' then begin
if (length(currentContext.actions) > 0) and (currentContext.actions[high(currentContext.actions)] is TProcessingContext) then
TProcessingContext(currentContext.actions[high(currentContext.actions)]).last.yieldDataToParent := true; //a follow directly after a closing bracket like ] -f // will apply it to the last data there
//following (applying the later commands to the data read by the current context)
currentContext.followTo := TProcessingContext.Create;
currentContext.followTo.assignOptions(currentContext);
currentContext.followTo.parent := currentcontext;
currentContext := currentContext.followTo;
end else begin
//sibling (later commands form a new context, unrelated to the previous one)
currentContext.nextSibling := TProcessingContext.Create;
currentContext.nextSibling.assignOptions(currentContext);
currentContext.nextSibling.parent := currentContext.parent;
currentContext := currentContext.nextSibling;
currentContext.readNewDataSource(TFollowTo.createFromRetrievalAddress(value), cmdlineWrapper);
end;
TCommandLineReaderBreaker(sender).removeVar('follow');
TCommandLineReaderBreaker(sender).removeVar('extract');
TCommandLineReaderBreaker(sender).removeVar('download');
closeAllMultiArgs;
end else if (name = 'extract') or (name = 'extract-file') or (name = 'template-file') or (name = 'css') or (name = 'xpath') or (name = 'xquery') or (name = 'xpath2') or (name = 'xquery1') or (name = 'xpath3') or (name = 'xquery3') then begin
specialized := '';
case name of
'extract-file':
if isStdin(value) then TCommandLineReaderBreaker(sender).overrideVar('extract', '-')
else TCommandLineReaderBreaker(sender).overrideVar('extract', strLoadFromFileChecked(value));
'template-file': begin
TCommandLineReaderBreaker(sender).overrideVar('extract-kind', 'multipage');
TCommandLineReaderBreaker(sender).overrideVar('extract', strLoadFromFileChecked(value));
end;
'xpath', 'xquery', 'css', 'xpath2', 'xquery1', 'xpath3', 'xquery3': specialized:=name;
end;
if specialized <> '' then begin
TCommandLineReaderBreaker(sender).overrideVar('extract', value);
TCommandLineReaderBreaker(sender).overrideVar('extract-kind', specialized);
end;
TCommandLineReaderBreaker(sender).overrideVar(name, value);
currentContext.readNewAction(TExtraction.Create, cmdlineWrapper);
if specialized <> '' then TCommandLineReaderBreaker(sender).removeVar('extract-kind');
end else if name = 'download' then begin
TCommandLineReaderBreaker(sender).overrideVar(name, value);
currentContext.readNewAction(TDownload.Create, cmdlineWrapper)
end else if (name = 'html') or (name = 'xml') then begin
TCommandLineReaderBreaker(sender).overrideVar('input-format', name);
TCommandLineReaderBreaker(sender).overrideVar('output-format', name);
end else if name = 'post' then
TCommandLineReaderBreaker(sender).overrideVar('post', combineMultiArgs(commandLineStackLastPostData, value, '&'))
else if name = 'form' then
TCommandLineReaderBreaker(sender).overrideVar('form', combineMultiArgs(commandLineStackLastFormData, value, #0))
else if name = 'header' then
TCommandLineReaderBreaker(sender).overrideVar('header', combineMultiArgs(commandLineLastHeader, value, #13#10))
else if name = 'variable' then parseVariableArg
else if name = 'xmlns' then begin
temps:=trim(value);
i := pos('=', temps);
if i = 0 then xpathparser.StaticContext.defaultElementTypeNamespace := TNamespace.create(temps, '')
else begin
specialized := strSplitGet('=', temps);
xpathparser.StaticContext.namespaces.add(TNamespace.create(temps, specialized));
end;
end else if (name = '') or (name = 'data') then begin
if (name = '') and (value = '[') then begin
pushCommandLineState;
currentContext := TProcessingContext.Create;
currentContext.readOptions(cmdlineWrapper);
contextStack[high(contextStack)] := currentContext;
end
else if (name = '') and (value = ']') then begin
if length(contextStack) <= 1 then raise EXidelException.Create('Closing ] without opening [');
currentContext.readOptions(cmdlineWrapper);
if ( (currentContext = contextStack[high(contextStack)]) and (length(currentContext.actions) = 0) and (length(currentContext.dataSources) > 0) ) //like in [ foobar xyz ]
or ((currentContext.parent <> nil) and (currentContext.parent.follow <> '')
and (length(currentContext.actions) = 0) and (length(contextStack[high(contextStack)].dataSources) > 0)) //like in [ http://example.org -e /tmp -f foobar -f //a ]
then begin
contextStack[high(contextStack) - 1].addNewDataSource(contextStack[high(contextStack)]);
if (currentContext.parent <> nil) and (currentContext.parent.followTo = currentContext) then begin
currentContext := currentContext.parent;
currentContext.followTo.free;
currentContext.followTo := nil; //remove follow, so addresses are yielded to parent
end;
end else
contextStack[high(contextStack) - 1].addNewAction(contextStack[high(contextStack)]);
currentContext := popCommandLineState;
end else begin
closeAllMultiArgs;
currentContext.readNewDataSource(TFollowTo.createFromRetrievalAddress(value), cmdlineWrapper);
end;
end;
end;
function getVersionString: string;
begin
result := IntToStr(majorVersion)+'.'+IntToStr(minorVersion);
if buildVersion <> 0 then result += '.'+IntToStr(buildVersion);
if Result = '0.8.4' then result += ' (Balisage edition)'
end;
procedure printVersion;
begin
writeln('Xidel '+getVersionString);
{$I xidelbuilddata.inc} //more version information to print. if you do not have the file, just create an empty one or remove this line
writeln('');
writeln('http://www.videlibri.de/xidel.html');
writeln('by Benito van der Zander <benito@benibela.de>');
writeln();
end;
procedure printUsage;
{$I printUsage.inc}
var i: integer;
begin
for i := low(data) to high(data) do writeln(data[i]);
end;
procedure debugPrintContext(dp: TDataProcessing; indent: string = '');
procedure wswi(s: string);
begin
writeln(stderr, indent, s);
end;
var
pc: TProcessingContext;
i: integer;
begin
writeln(stderr, indent + dp.ClassName + strFromPtr(dp));
if dp is TProcessingContext then begin
pc := dp as TProcessingContext;;
writeln(stderr, indent + 'data sources: ');
for i := 0 to high(pc.dataSources) do
debugPrintContext(pc.dataSources[i], indent + ' ');
writeln(stderr, indent + 'actions: ');
for i := 0 to high(pc.actions) do
debugPrintContext(pc.actions[i], indent + ' ');
if pc.follow <> '' then wswi('follow: ' + pc.follow);
if pc.yieldDataToParent then wswi('yield to parent');
if pc.followTo <> nil then begin
writeln(stderr, indent + 'follow to: ');
if pc.followTo = dp then writeln(stderr, indent + ' recursion')
else debugPrintContext(pc.followTo, indent + ' ');
end;
if pc.nextSibling <> nil then begin
writeln(stderr, indent + 'Next Sibling');
debugPrintContext(pc.nextSibling, indent);
end;
end else if dp is TFollowToWrapper then begin
wswi( 'follow to wrapper: ' + TFollowToWrapper(dp).followTo.ClassName);
indent += ' ';
if TFollowToWrapper(dp).followTo is THTTPRequest then wswi(THTTPRequest(TFollowToWrapper(dp).followTo).url)
else if TFollowToWrapper(dp).followTo is TFileRequest then wswi(TFileRequest(TFollowToWrapper(dp).followTo).url)
end else if dp is TExtraction then begin
wswi('extract: '+TExtraction(dp).extract);
end else if dp is TDownload then begin
wswi('download: '+TDownload(dp).downloadTarget);
end;
end;
var baseContext: TProcessingContext;
procedure importModule(pseudoSelf: tobject; sender: TXQueryEngine; const namespace: string; const at: array of string);
var
ft: TFollowTo;
d: IData;
begin
if xpathparser.findModule(namespace) <> nil then exit;
for i := 0 to high(at) do begin
d := nil;
try
ft := TFollowTo.createFromRetrievalAddress(at[i]);
d := ft.retrieve(baseContext, 0);
ft.free;
except
end;
if d <> nil then begin
xpathparser.registerModule(xpathparser.parseXQuery3(d.rawData));
exit
end;
end;
end;
function encodingName(e: TSystemCodePage): string;
begin
case e of
CP_ASCII: result := 'US-ASCII';
CP_ACP, CP_OEMCP, CP_NONE, CP_UTF8: result := 'UTF-8';
CP_UTF7: result := 'UTF-7';
CP_WINDOWS1252, CP_LATIN1: result := 'ISO-8859-1';
28592..28605: result := 'ISO-8859-' + inttostr(e - 28590);
CP_UTF16BE, CP_UTF16: result := 'UTF-16';
CP_UTF32BE, CP_UTF32: result := 'UTF-32';
else result := 'windows-' + inttostr(e);
end;
end;
procedure blockFileAccessFunctions; forward;
procedure perform;
begin
if cgimode or (not allowFileAccess) then blockFileAccessFunctions;
//normalized formats (for use in unittests)
DecimalSeparator:='.';
ThousandSeparator:=#0;
ShortDateFormat:='YYYY-MM-DD';
LongDateFormat:='YYYY-MM-DD';
SetExceptionMask([exInvalidOp, exDenormalized, {exZeroDivide,} exOverflow, exUnderflow, exPrecision]);
registerModuleMath;
{$ifdef win32}systemEncodingIsUTF8:=getACP = CP_UTF8;{$endif}
htmlparser:=THtmlTemplateParserBreaker.create;
htmlparser.HTMLParser.readProcessingInstructions := true;
mycmdline.onCustomOptionInterpretation := TOptionInterpretationEvent(procedureToMethod(TProcedure(@variableInterpret)));
mycmdline.onOptionRead:=TOptionReadEvent(procedureToMethod(TProcedure(@variableRead)));
mycmdline.allowOverrides:=true;
mycmdLine.declareString('data', 'Data/URL/File/Stdin(-) to process (--data= prefix can be omitted)');
mycmdLine.declareString('download', 'Downloads/saves the data to a given filename (- prints to stdout, . uses the filename of the url)');
mycmdLine.beginDeclarationCategory('Extraction options:');
mycmdLine.declareString('extract', joined(['Expression to extract from the data.','If it starts with < it is interpreted as template, otherwise as XPath expression']));
mycmdline.addAbbreviation('e');
mycmdLine.declareString('extract-exclude', 'Comma separated list of variables ignored in an extract template. (black list) (default _follow)', '_follow');
mycmdLine.declareString('extract-include', 'If not empty, comma separated list of variables to use in an extract template (white list)');
mycmdLine.declareFile('extract-file', 'File containing an extract expression (for longer expressions)');
mycmdLine.declareString('extract-kind', 'How the extract expression is evaluated. Can be auto (automatically choose between xpath/template), xpath{|2|3}, xquery{|1|3}, css, template or multipage', 'auto');
mycmdLine.declareString('css', 'Abbreviation for --extract-kind=css --extract=...');
mycmdLine.declareString('xpath', 'Abbreviation for --extract-kind=xpath3 --extract=...');
//mycmdline.addAbbreviation('p');
mycmdLine.declareString('xquery', 'Abbreviation for --extract-kind=xquery3 --extract=...');
//mycmdline.addAbbreviation('q');
mycmdLine.declareString('xpath2', 'Abbreviation for --extract-kind=xpath2 --extract=...');
mycmdLine.declareString('xquery1', 'Abbreviation for --extract-kind=xquery1 --extract=...');
mycmdLine.declareString('xpath3', 'Abbreviation for --extract-kind=xpath3 --extract=...');
mycmdLine.declareString('xquery3', 'Abbreviation for --extract-kind=xquery3 --extract=...');
mycmdLine.declareFile('template-file', 'Abbreviation for --extract-kind=multipage --extract-file=...');
mycmdLine.declareString('template-action', 'Select which action from the multipage template should be run (multiple actions are allowed with comma separated values)');
mycmdLine.beginDeclarationCategory('Follow options:');
mycmdLine.declareString('follow', joined(['Expression selecting data from the page which will be followed.',
'If the expression returns a sequence, all its elements are followed.',
'If it is an HTML element with an resource property this property is used, e.g. from an A element it will follow to its @href property.',
'If it is an object, its url property and its other properties can override command line arguments',
'Otherwise, the string value is used as url.']));
mycmdline.addAbbreviation('f');
mycmdline.declareString('follow-kind', 'How the follow expression is evaluated. Like extract-kind');
mycmdLine.declareString('follow-exclude', 'Comma separated list of variables ignored in a follow template. (black list)');
mycmdLine.declareString('follow-include', 'Comma separated list of variables used in a follow template. (white list)');
mycmdLine.declareFile('follow-file', 'File containing a follow expression (for longer expressions)');
mycmdLine.declareInt('follow-level', 'Maximal recursion deep', 99999);
mycmdLine.declareFlag('allow-repetitions', 'Follow all links, even if that page was already visited.');
mycmdLine.beginDeclarationCategory('Extraction options:');
if allowInternetAccess then begin
mycmdLine.beginDeclarationCategory('HTTP connection options:');
mycmdLine.declareFloat('wait', 'Wait a certain count of seconds between requests');
mycmdLine.declareString('user-agent', 'Useragent used in http request', defaultUserAgent);
mycmdLine.declareString('proxy', 'Proxy used for http/s requests');
mycmdLine.declareString('post', joined(['Post request to send (url encoded). Multiple close occurrences are joined. If the new argument starts with &, it will always be joined. If it is empty, it will clear the previous parameters. ']));
mycmdline.addAbbreviation('d');
mycmdLine.declareString('form', 'Post request to send (multipart encoded). See --usage. Can be used multiple times like --post.');
mycmdline.addAbbreviation('F');
mycmdLine.declareString('method', 'HTTP method to use (e.g. GET, POST, PUT)', 'GET');
mycmdLine.declareString('header', 'Additional header to include (e.g. "Set-Cookie: a=b"). Can be used multiple times like --post.'); mycmdline.addAbbreviation('H');
mycmdLine.declareString('load-cookies', 'Load cookies from file');
mycmdLine.declareString('save-cookies', 'Save cookies to file');
mycmdLine.declareFlag('print-received-headers', 'Print the received headers');
mycmdLine.declareString('error-handling', 'How to handle http errors, e.g. 1xx=retry,200=accept,3xx=redirect,4xx=abort,5xx=skip');
mycmdLine.declareFlag('raw-url', 'Do not escape the url (preliminary)');
end;
mycmdLine.beginDeclarationCategory('Output/Input options:');
mycmdLine.declareFlag('silent','Do not print status information to stderr', 's');
mycmdline.declareFlag('verbose', 'Print more status information');
mycmdLine.declareString('default-variable-name', 'Variable name for values read in the template without explicitely given variable name', 'result');
mycmdLine.declareString('print-variables', joined(['Which of the separate variable lists are printed', 'Comma separated list of:', ' log: Prints every variable value', ' final: Prints only the final value of a variable, if there are multiple assignments to it', ' condensed-log: Like log, but removes assignments to object properties(default)']), 'condensed-log');
mycmdLine.declareFlag('print-type-annotations','Prints all variable values with type annotations (e.g. string: abc, instead of abc)');
mycmdLine.declareFlag('hide-variable-names','Do not print the name of variables defined in an extract template');
mycmdLine.declareString('variable','Declares a variable (value taken from environment if not given explicitely) (multiple variables are preliminary)');
mycmdLine.declareString('xmlns','Declares a namespace');
mycmdLine.declareString('printed-node-format', 'Format of an extracted node: text, html or xml');
mycmdline.declareString('printed-json-format', 'Format of JSON items: pretty or compact');
mycmdLine.declareString('output-format', 'Output format: adhoc (simple human readable), xml, html, xml-wrapped (machine readable version of adhoc), json-wrapped, bash (export vars to bash), or cmd (export vars to cmd.exe) ', 'adhoc');
mycmdLine.declareString('output-encoding', 'Character encoding of the output. utf-8, latin1, utf-16be, utf-16le, oem (windows console) or input (no encoding conversion)', 'utf-8');
mycmdLine.declareString('output-declaration', 'Header for the output. (e.g. <!DOCTYPE html>, default depends on output-format)', '');
mycmdLine.declareString('output-separator', 'Separator between multiple items (default: line break)', LineEnding);
mycmdLine.declareString('output-header', '2nd header for the output. (e.g. <html>)', '');
mycmdLine.declareString('output-footer', 'Footer for the output. (e.g. </html>)', '');
mycmdLine.declareString('color', 'Coloring option (never,always,json,xml)', ifthen(cgimode, 'never', 'auto'));
mycmdLine.declareString('stdin-encoding', 'Character encoding of stdin', 'utf-8');
mycmdLine.declareString('input-format', 'Input format: auto, html, xml, xml-strict, json, json-strict', 'auto');
mycmdLine.declareFlag('xml','Abbreviation for --input-format=xml --output-format=xml');
mycmdLine.declareFlag('html','Abbreviation for --input-format=html --output-format=html');
mycmdLine.beginDeclarationCategory('Debug options:');
mycmdline.declareFlag('debug-arguments', 'Shows how the command line arguments were parsed');
mycmdline.declareFlag('trace', 'Traces the evaluation of all queries');
mycmdline.declareFlag('trace-stack', 'Traces the evaluation to print a backtrace in case of errors');
mycmdline.declareFlag('trace-context', 'Like trace-stack, but for the context');
//mycmdline.declareFlag('trace-context-variables', 'Like trace-stack, but for the context variables');
mycmdLine.beginDeclarationCategory('XPath/XQuery compatibility options:');
mycmdline.declareFlag('no-json', 'Disables the JSONiq syntax extensions (like [1,2,3] and {"a": 1, "b": 2})');
mycmdline.declareFlag('no-json-literals', 'Disables the json true/false/null literals');
mycmdline.declareString('dot-notation', 'Specifies if the dot operator $object.property can be used. Possible values: off, on, unambiguous (default, does not allow $obj.prop, but ($obj).prop ) ', 'unambiguous');
mycmdline.declareFlag('no-dot-notation', 'Disables the dot notation for property access, like in $object.property (deprecated)');
mycmdline.declareFlag('only-json-objects', 'Do not allow non-JSON types in object properties (like () or (1,2) instead of null and [1,2]) ');
mycmdline.declareFlag('no-extended-json', 'Disables non-jsoniq json extensions');
mycmdline.declareFlag('strict-type-checking', 'Disables weakly typing ("1" + 2 will raise an error, otherwise it evaluates to 3)');
mycmdline.declareFlag('strict-namespaces', 'Disables the usage of undeclared namespace. Otherwise foo:bar always matches an element with prefix foo.');
mycmdline.declareFlag('no-extended-strings', 'Does not allow x-prefixed strings like x"foo{1+2+3}bar"');
mycmdline.declareFlag('ignore-namespaces', 'Removes all namespaces from the input document');
mycmdline.declareFlag('no-optimizations', 'Disables optimizations');
mycmdline.declareFlag('deprecated-string-options', 'Replaces the old $foo; variables with the new {$foo} in arguments');
mycmdLine.declareFlag('version','Print version number ('+getVersionString+')');
mycmdLine.declareFlag('usage','Print help, examples and usage information');
mycmdLine.declareFlag('quiet','-quiet,-q is outdated. Use --silent,-s', 'q');
currentContext := TProcessingContext.Create;
baseContext := currentContext;
SetLength(contextStack, 1);
contextStack[0] := baseContext;
xpathparser := htmlparser.QueryEngine;
if xpathparser.StaticContext.namespaces = nil then htmlparser.QueryEngine.StaticContext.namespaces := TNamespaceList.Create;
xpathparser.StaticContext.namespaces.add(XMLNamespace_Expath_File);
xpathparser.StaticContext.namespaces.add(TNamespace.create(XMLNamespaceURL_XQTErrors, 'err'));
xpathparser.StaticContext.namespaces.add(TNamespace.create('http://jsoniq.org/function-library', 'libjn'));
xpathparser.OnParseDoc:= @htmlparser.parseDoc;
xpathparser.OnImportModule:=TXQImportModuleEvent(procedureToMethod(TProcedure(@importModule)));
xpathparser.OnTrace := TXQTraceEvent(procedureToMethod(TProcedure(@traceCall)));
cmdlineWrapper := TOptionReaderFromCommandLine.create(mycmdline);
mycmdline.parse(GetEnvironmentVariableUTF8('XIDEL_OPTIONS'), false);
TCommandLineReaderBreaker(mycmdLine).parseUTF8(false);
if Assigned(onPostParseCmdLine) then onPostParseCmdLine();
if mycmdline.readFlag('version') then
printVersion;
if mycmdline.readFlag('usage') then begin
printUsage;
baseContext.free;
exit;
end;
if mycmdline.readFlag('quiet') then begin
writeln(stderr, '-quiet,-q is outdated. Use --silent,-s');
exit;
end;
currentContext.readOptions(cmdlineWrapper);
if (length(currentContext.actions) <> 0) and not (currentContext.actions[high(currentContext.actions)] is TProcessingContext) then
currentContext.actions[high(currentContext.actions)].readOptions(cmdlineWrapper); //last options wrap back, unless in [ ]
if (currentContext.parent <> nil) and (length(currentContext.actions) = 0) and (length(currentContext.dataSources) = 0) then begin
//this allows a trailing follow to recurse
currentContext.follow := currentContext.parent.follow;
currentContext.followKind := currentContext.parent.followKind;
currentContext.followExclude := currentContext.parent.followExclude;
currentContext.followInclude := currentContext.parent.followInclude;
currentContext.followTo := currentContext;
currentContext.actions := currentContext.parent.actions;
SetLength(currentContext.actions, length(currentContext.actions));
for i := 0 to high(currentContext.actions) do
currentContext.actions[i] := currentContext.actions[i].clone(currentContext);
end;
if (currentContext.parent = nil) and (baseContext.nextSibling = currentContext) and (length(baseContext.dataSources) = 0) and (length(currentContext.actions) = 0) and (currentContext.follow = '') then begin
//wrap command lines exactly like -e query data1 data2... to data1 data2... -e query, (for e.g. xargs)
currentContext.actions := baseContext.actions;
SetLength(baseContext.actions,0);
baseContext.nextSibling := nil;
baseContext.free;
baseContext := currentContext;
end;
if (baseContext = currentContext) then begin
for i := 0 to high(baseContext.dataSources) do
if baseContext.dataSources[i] is TFollowToWrapper then
baseContext.dataSources[i].readOptions(cmdlineWrapper);
if (length(baseContext.actions) = 0) and (baseContext.follow = '') and not mycmdline.readFlag('version') then begin
if (ParamCount = 1) and FileExists(paramstr(1)) then begin
SetLength(baseContext.dataSources, 0);
SetLength(baseContext.actions, 1);
baseContext.actions[0] := TExtraction.create;
TExtraction(baseContext.actions[0]).extract := strLoadFromFileChecked(ParamStr(1));
baseContext.silent := true;
end else begin
writeln(stderr, 'No actions given.');
writeln(stderr, 'Expected at least one --extract, -e, --extract-file, --xquery, --xpath, --css, or --template-file option.');
ExitCode:=1;
end;
end;
end;
baseContext.insertFictiveDatasourceIfNeeded; //this allows data less evaluations, like xidel -e 1+2+3
if mycmdline.readFlag('debug-arguments') then
debugPrintContext(baseContext);
if allowInternetAccess and assigned(onPrepareInternet) then
onPrepareInternet(baseContext.userAgent, baseContext.proxy, @baseContext.httpReact);
cmdlineWrapper.Free;
case mycmdline.readString('color') of
'auto': colorizing := cAuto;
'never': colorizing := cNever;
'always': colorizing := cAlways;
'json': colorizing := cJSON;
'xml': colorizing := cXML;
else raise EInvalidArgument.Create('Invalid color: '+mycmdline.readString('color'));
end;
if not (colorizing in [cNever,cAlways]) or (hasOutputEncoding = oeAbsent) then begin
{$ifdef unix}
isStdinTTY := IsATTY(Input) <> 0;
isStdoutTTY := IsATTY(stdout) <> 0;
isStderrTTY := IsATTY(StdErr) <> 0;
{$endif}
{$ifdef windows}
isStdinTTY := getfiletype(StdInputHandle) = FILE_TYPE_CHAR;
isStdoutTTY := getfiletype(StdOutputHandle) = FILE_TYPE_CHAR;
isStderrTTY := getfiletype(StdErrorHandle) = FILE_TYPE_CHAR;
{$endif}
if not isStdoutTTY and (hasOutputEncoding = oeAbsent) then setOutputEncoding('utf-8');
if not isStdinTTY or mycmdline.existsProperty('stdin-encoding') then SetTextEncoding(input, mycmdline.readString('stdin-encoding'));
end;
case colorizing of
cNever: begin
isStderrTTY := false; //todo, coloring should not change this variable (but it is only used for coloring. rename it?)
isStdoutTTY := false;
end;
cAlways: begin
isStdoutTTY := true;
isStderrTTY := true;
end;
end;
case colorizing of
cAuto, cAlways: begin
case outputFormat of
ofXMLWrapped, ofRawHTML, ofRawXML: colorizing := cXML;
ofJsonWrapped: colorizing := cJSON;
end;
end;
end;
outputHeader := mycmdline.readString('output-declaration') + mycmdline.readString('output-header');
if (outputHeader <> '') and not mycmdline.existsProperty('output-header') then outputHeader += LineEnding;
outputSeparator := mycmdline.readString('output-separator');
outputFooter := mycmdline.readString('output-footer');
case mycmdLine.readString('output-format') of
'adhoc': outputFormat:=ofAdhoc;
'html': begin
outputFormat:=ofRawHTML;
if not mycmdline.existsProperty('output-declaration') then outputHeader:='<!DOCTYPE html>'+LineEnding+outputHeader;
end;
'xml': begin
outputFormat:=ofRawXML;
if not mycmdline.existsProperty('output-declaration') then outputHeader:='<?xml version="1.0" encoding="'+ encodingName(GetTextCodePage(Output))+'"?>'+LineEnding+outputHeader;
end;
'xml-wrapped': begin
outputFormat:=ofXMLWrapped;
if not mycmdline.existsProperty('output-declaration') then outputHeader:='<?xml version="1.0" encoding="'+ encodingName(GetTextCodePage(Output))+'"?>'+LineEnding+outputHeader;
end;
'json', 'json-wrapped': begin
outputFormat:=ofJsonWrapped;
if (mycmdLine.readString('output-format') = 'json') then writeln(stderr, 'Warning: Output-format json is deprecated, use json-wrapped instead');
end;
'bash': begin
outputFormat:=ofBash;
end;
'cmd': begin //legacy. remove it?
outputFormat:=ofWindowsCmd;
windowsCmdPercentageEscape := '';
end;
'cmd-bat': begin
outputFormat:=ofWindowsCmd;
windowsCmdPercentageEscape := '%'; //% must be escaped as %% in bat files
end;
'cmd-for': begin
outputFormat:=ofWindowsCmd;
windowsCmdPercentageEscape := '^'; //for /f only accepts ^%, not %%
end;
else raise EInvalidArgument.Create('Unknown output format: ' + mycmdLine.readString('output-format'));
end;
if mycmdline.readFlag('trace') or mycmdline.readFlag('trace-stack') or mycmdline.readFlag('trace-context') {or mycmdline.readFlag('trace-context-variables') }then begin
tracer := TXQTracer.Create;
tracer.all := mycmdline.readFlag('trace');
tracer.backtrace := mycmdline.readFlag('trace-stack');
tracer.context := mycmdline.readFlag('trace-context');// or mycmdline.readFlag('trace-context-variables');
//tracer.contextVariables := mycmdline.readFlag('trace-context-variables');
//if tracer.contextVariables then tracer.varLog := TXQVariableChangeLog.create();
XQOnGlobalDebugTracing := @tracer.globalTracing;
end;
if assigned(onPreOutput) then onPreOutput(guessExtractionKind(mycmdline.readString('extract')));
if outputHeader <> '' then wcolor(outputHeader, colorizing);
if outputFormat in [ofJsonWrapped, ofXMLWrapped] then needRawWrapper;
htmlparser.TemplateParser.repairMissingEndTags:=false;
htmlparser.TemplateParser.repairMissingStartTags:=false;
htmlparser.KeepPreviousVariables:=kpvKeepValues;
if allowInternetAccess then begin
multipage := TTemplateReaderBreaker.create();
multipage.parser:=htmlparser;
end;
if xqueryDefaultCollation <> '' then xpathparser.StaticContext.collation := TXQueryEngine.getCollation(xqueryDefaultCollation, '');
if not mycmdline.readFlag('allow-repetitions') then
globalDuplicationList := TFollowToList.Create;
try
baseContext.process(nil).free;
baseContext.Free;
except
on e: ETreeParseException do begin
displayError(e);
ExitCode:=1;
// if not cgimode then raise;
end;
on e: EHTMLParseException do begin
displayError(e, true);
ExitCode:=1;
// if not cgimode then raise;
end;
on e: EHTMLParseMatchingException do begin
displayError(e, true);
ExitCode:=1;
// if not cgimode then raise;
end;
on e: EXQEvaluationException do begin
ExitCode:=1;
displayError(e);
// if not cgimode then raise;
end;
on e: EXQParsingException do begin
ExitCode:=1;
displayError(e);
// if not cgimode then raise;
end;
on e: EInternetException do begin
ExitCode:=1;//e.errorCode;
displayError(e);
// if not cgimode then raise;
end;
on e: EInOutError do begin
if e.ErrorCode <> 101 then begin //disk full, caused on ended pipe (e.g. |head)
ExitCode:=1;
displayError(e);
end;
end;
end;
if allowInternetAccess then multipage.Free
else htmlparser.free;
globalDuplicationList.Free;
alternativeXMLParser.Free;
case outputFormat of
{ofJsonWrapped: wln(']');
ofXMLWrapped: begin
if not firstExtraction then wln('</e>');
wln('</seq>');
end;}
ofWindowsCmd:
for i := 0 to high(usedCmdlineVariables) do
if usedCmdlineVariables[i].count > 1 then
writeItem('SET #'+usedCmdlineVariables[i].name +'='+ inttostr(usedCmdlineVariables[i].count));
end;
if outputfooter <> '' then wcolor(outputFooter, colorizing)
else if not mycmdline.existsProperty('output-footer') and not firstItem then wln();
mycmdLine.free;
tracer.free;
end;
function xqfSystem(argc: SizeInt; args: PIXQValue): IXQValue;
const BUF_SIZE = 4096;
var
proc: TProcess;
temps: string;
builder: TStrBuilder;
Buffer: array[1..BUF_SIZE] of byte;
count: LongInt;
begin
if cgimode or not allowFileAccess then exit(xqvalue('Are you trying to hack an OSS project? Shame on you!'));
requiredArgCount(argc, 1);
proc := TProcess.Create(nil);
proc.CommandLine := args[0].toString;
builder.init(@temps);
try
proc.Options := proc.Options + [poUsePipes] - [poWaitOnExit];
proc.Execute;
repeat
count := proc.Output.Read(buffer{%H-}, BUF_SIZE);
builder.add(@buffer[1], count);
until count = 0;
builder.final;
result := xqvalue(temps);
finally
proc.free;
end;
end;
function xqfRead(argc: SizeInt; args: PIXQValue): IXQValue;
var s: string;
begin
ReadLn(s);
result := TXQValueString.create(baseSchema.untypedAtomic, s);
end;
function xqfArgc(argc: SizeInt; args: PIXQValue): IXQValue;
begin
result := xqvalue(paramcount);
end;
function xqfArgv(argc: SizeInt; args: PIXQValue): IXQValue;
begin
result := xqvalue(ParamStr(args[0].toInt64));
end;
function xqfRequest(const cxt: TXQEvaluationContext; argc: SizeInt; args: PIXQValue): IXQValue;
var
follow: TFollowToList;
fakeData, data: Idata;
fakeContext: TProcessingContext;
list: TXQVList;
obj: TXQValueObject;
pv: PIXQValue;
oldInternetConfig: TInternetConfig;
oldReact: TTransferReactEvent;
begin
requiredArgCount(argc, 1);
fakeData := TDataObject.create('', cxt.staticContext.baseURI, '');
fakeContext := TProcessingContext.Create;
if baseContext <> nil then fakeContext.assignOptions(baseContext);
follow := TFollowToList.Create;
list := TXQVList.create();
oldInternetConfig := defaultInternetConfiguration;
if assigned(internetaccess.defaultInternet) then oldReact := internetaccess.defaultInternet.OnTransferReact
else oldReact := nil;
try
htmlparser.variableChangeLog.pushAll;
for pv in args[0].GetEnumeratorPtrUnsafe do
follow.merge(pv^, fakeData, fakeContext);
while follow.Count > 0 do begin
data := follow.first.retrieve(fakeContext,0);
obj := TXQValueObject.create();
obj.setMutable('url', data.baseUri);
obj.setMutable('type', data.contenttype);
obj.setMutable('headers', xqvalue(data.headers));
obj.setMutable('raw', xqvalue(data.rawData));
if data.inputFormat in [ifJSON,ifJSONStrict] then obj.setMutable('json', parseJSON(data))
else obj.setMutable('doc', xqvalue(cxt.parseDoc(data.rawData,data.baseUri,data.contenttype)));
list.add(obj);
follow.Delete(0);
end;
finally
defaultInternetConfiguration := oldInternetConfig;
if assigned(internetaccess.defaultInternet) then begin
if assigned(internetaccess.defaultInternet.internetConfig) then
internetaccess.defaultInternet.internetConfig^ := oldInternetConfig; //this is not necessary??
internetaccess.defaultInternet.OnTransferReact := oldReact; //this is. otherwise it points to fakeContext and the next download might crash
end;
htmlparser.variableChangeLog.popAll();
follow.free;
fakeContext.Free;
xqvalueSeqSqueezed(result, list);
end;
end;
function xqFunctionJSONSafe(const context: TXQEvaluationContext; argc: SizeInt; args: PIXQValue): IXQValue;
var jn: TXQNativeModule;
begin
jn := TXQueryEngine.findNativeModule('http://jsoniq.org/functions');
result := jn.findBasicFunction('parse-json', argc).func(argc,args);
end;
function xqFunctionBlocked(const context: TXQEvaluationContext; argc: SizeInt; args: PIXQValue): IXQValue;
begin
ignore(context);
raise EXQEvaluationException.create('pxp:cgi', 'function is not allowed in cgi mode');
result := nil;
end;
function xqFunctionBlockedSimple(argc: SizeInt; args: PIXQValue): IXQValue;
begin
raise EXQEvaluationException.create('pxp:cgi', 'function is not allowed in cgi mode');
result := nil;
end;
function BigDecimalFromBase(const n: string; base: integer; negative: boolean): bigdecimal;
var cur, bdbase: bigdecimal;
c: Char;
offset: Integer;
begin
bdbase := base;
setZero(result);
setOne(cur);
for i := length(n) downto 1 do begin
c := n[i];
case c of
'0'..'9': offset := ord(c) - ord('0');
'A'..'Z': offset := ord(c) - ord('A') + 10;
'a'..'z': offset := ord(c) - ord('a') + 10;
else raise EXQEvaluationException.create('pxp:INT', 'Invalid digit in '+n);
end;
if offset >= base then raise EXQEvaluationException.create('pxp:INT', 'Invalid digit in '+n);
result := result + offset * cur;
cur := cur * bdbase;
end;
if not isZero(result) then result.signed := negative;
end;
function xqfInteger(argc: SizeInt; args: PIXQValue): IXQValue;
var
s, s0: String;
base: Integer;
negative: Boolean;
begin
s0 := args[0].toString;
s := s0;
negative := (s <> '') and (s[1] = '-');
if negative then delete(s,1,1);
base := 10;
if argc = 2 then base := args[1].toInt64;
if (s <> '') and (s[1] = '0') then delete(s, 1, 1);
if (s <> '') then
case s[1] of
'$', 'x': begin
delete(s, 1, 1);
base := 16;
end;
'o', 'q': begin
delete(s, 1, 1);
base := 8;
end;
'b': begin
delete(s, 1, 1);
base := 2;
end;
end;
if s = '' then exit(xqvalue(0));
if (base = 16) and (length(s) < 16) then exit(xqvalue(StrToInt64(ifthen(negative, '-$', '$') + s)))
else if base = 10 then result := baseSchema.integer.createValue(s0)
else result := baseSchema.integer.createValue(BigDecimalFromBase(s, base, negative))
end;
function BigDecimalToBase(bd: bigdecimal; const bdbase: bigdecimal): string;
var
quotient, remainder: BigDecimal;
temp: integer;
negative: Boolean;
begin
negative := bd.signed;
bd.signed:=false;
result := '';
while not isZero(bd) do begin
quotient.digits := nil;
divideModNoAlias(quotient, remainder, bd, bdbase, 0, [bddfFillIntegerPart, bddfNoFractionalPart]);
temp := BigDecimalToLongint(remainder);
case temp of
0..9: result := chr(ord('0') + temp) + result;
10..26+10: result := chr(ord('A') - 10 + temp) + result;
end;
bd := quotient;
end;
if negative then result := '-' + result;
end;
function xqfIntegerToBase(argc: SizeInt; args: PIXQValue): IXQValue;
var
base: Int64;
resstr: RawByteString;
begin
base := args[1].toInt64;
if (base < 2) or (base > 36) then raise EXQEvaluationException.create('pxp:INT', 'Invalid base');
if base = 10 then exit(xqvalue(args[0].toString));
resstr := '';
if (base = 16) and (args[0].kind = pvkInt64) and (args[0].toInt64 >= 0) then resstr := strTrimLeft(IntToHex(args[0].toInt64, 1), ['0'])
else resstr := BigDecimalToBase(args[0].toDecimal, base);
if resstr = '' then resstr := '0';
result := xqvalue(resstr);
end;
procedure blockFileAccessFunctions;
var fn, pxp, jn: TXQNativeModule;
i: integer;
begin
fn := TXQueryEngine.findNativeModule(XMLNamespaceURL_XPathFunctions);
fn.findComplexFunction('doc', 1).func:=@xqFunctionBlocked;
fn.findComplexFunction('doc-available', 1).func:=@xqFunctionBlocked;
for i := 1 to 2 do begin
fn.findComplexFunction('unparsed-text', i).func:=@xqFunctionBlocked;
fn.findInterpretedFunction('unparsed-text-lines', i).source:='"not available in cgi mode"';
fn.findComplexFunction('unparsed-text-available', i).func:=@xqFunctionBlocked;
end;
fn.findBasicFunction('environment-variable', 1).func:=@xqFunctionBlockedSimple;
pxp := TXQueryEngine.findNativeModule(XMLNamespaceURL_MyExtensionsMerged);
pxp.findComplexFunction('json', 1).func:=@xqFunctionJSONSafe;
jn := TXQueryEngine.findNativeModule('http://jsoniq.org/functions');
jn.findComplexFunction('json-doc', 1).func:=@xqFunctionBlocked;
end;
var
oldUnicode2AnsiMoveProc : procedure(source:punicodechar;var dest:RawByteString;cp : TSystemCodePage;len:SizeInt);
oldAnsi2UnicodeMoveProc : procedure(source:pchar;cp : TSystemCodePage;var dest:unicodestring;len:SizeInt);
procedure myUnicode2AnsiMoveProc(source:punicodechar;var dest:RawByteString;cp : TSystemCodePage;len:SizeInt);
begin
case cp of
CP_UTF32, CP_UTF32BE,
CP_UTF16, CP_UTF16BE,
CP_UTF8,
CP_WINDOWS1252, CP_LATIN1: strUnicode2AnsiMoveProc(source, dest, cp, len);
else oldUnicode2AnsiMoveProc(source, dest, cp, len);
end;
end;
procedure myAnsi2UnicodeMoveProc(source:pchar;cp : TSystemCodePage;var dest:unicodestring;len:SizeInt);
begin
case cp of
CP_UTF32, CP_UTF32BE,
CP_UTF16, CP_UTF16BE,
CP_UTF8,
CP_WINDOWS1252, CP_LATIN1: strAnsi2UnicodeMoveProc(source, cp, dest, len);
else oldAnsi2UnicodeMoveProc(source, cp, dest, len);
end;
end;
var pxp,pxpx: TXQNativeModule;
initialization
SetMultiByteConversionCodePage(CP_UTF8);
SetMultiByteRTLFileSystemCodePage(CP_UTF8);
oldUnicode2AnsiMoveProc := widestringmanager.Unicode2AnsiMoveProc;
oldAnsi2UnicodeMoveProc := widestringmanager.Ansi2UnicodeMoveProc;
widestringmanager.Unicode2AnsiMoveProc := @myUnicode2AnsiMoveProc;
widestringmanager.Ansi2UnicodeMoveProc := @myAnsi2UnicodeMoveProc;
pxp := TXQueryEngine.findNativeModule(XMLNamespaceURL_MyExtensionsMerged);
pxp.registerFunction('system', @xqfSystem, ['($arg as xs:string) as xs:string']);
pxp.registerFunction('read', @xqfRead, ['() as xs:untypedAtomic']);
pxpx := TXQueryEngine.findNativeModule(XMLNamespaceURL_MyExtensionsNew);
pxpx.registerFunction('request', @xqfRequest, ['($arg as item()*) as object()*']);
pxpx.registerFunction('argc', @xqfArgc, ['() as integer']);
pxpx.registerFunction('argv', @xqfArgv, ['($i as integer) as string']);
pxpx.registerFunction('integer', @xqfInteger, ['($arg as item()) as xs:integer', '($arg as item(), $base as xs:integer) as xs:integer']);
pxpx.registerFunction('integer-to-base', @xqfIntegerToBase, ['($arg as xs:integer, $base as xs:integer) as xs:string']);
end.
|
{ search-api
Copyright (c) 2019 mr-highball
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 search.paginated;
{$mode delphi}
interface
uses
Classes, SysUtils, search.types;
type
{ TPaginatedImpl }
(*
base class for IPaginated
*)
TPaginatedImpl = class(TInterfacedObject,IPaginated)
strict private
FOperations: TPaginationOperations;
strict protected
function GetOperations: TPaginationOperations;
//children will need to override these
function DoBack(out Error: String): Boolean;virtual;abstract;
function DoNext(out Error: String): Boolean; overload;virtual;abstract;
public
//--------------------------------------------------------------------------
//properties
//--------------------------------------------------------------------------
property SupportedOperations : TPaginationOperations read GetOperations;
//--------------------------------------------------------------------------
//methods
//--------------------------------------------------------------------------
function Back(out Error: String): Boolean; overload;
function Back: Boolean; overload;
function Next(out Error: String): Boolean; overload;
function Next: Boolean; overload;
constructor Create(Const ASupportedOperations:TPaginationOperations);virtual;
end;
implementation
{ TPaginatedImpl }
function TPaginatedImpl.GetOperations: TPaginationOperations;
begin
Result:=FOperations;
end;
function TPaginatedImpl.Back(out Error: String): Boolean;
begin
Result:=DoBack(Error);
end;
function TPaginatedImpl.Back: Boolean;
var
LError:String;
begin
Result:=DoBack(LError);
end;
function TPaginatedImpl.Next(out Error: String): Boolean;
begin
Result:=DoNext(Error);
end;
function TPaginatedImpl.Next: Boolean;
var
LError:String;
begin
Result:=DoNext(LError);
end;
constructor TPaginatedImpl.Create(
const ASupportedOperations: TPaginationOperations);
begin
FOperations:=ASupportedOperations;
end;
end.
|
unit scollapsingtoolbarlayout;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, AndroidWidget, systryparent;
type
{Draft Component code by "Lazarus Android Module Wizard" [1/3/2018 19:08:18]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jVisualControl template}
jsCollapsingToolbarLayout = class(jVisualControl)
private
FFitsSystemWindows: boolean;
procedure SetVisible(Value: Boolean);
procedure SetColor(Value: TARGBColorBridge); //background
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
procedure Refresh;
procedure UpdateLayout; override;
procedure GenEvent_OnClick(Obj: TObject);
function jCreate(): jObject;
procedure jFree();
procedure SetViewParent(_viewgroup: jObject); override;
function GetParent(): jObject;
procedure RemoveFromViewParent(); override;
function GetView(): jObject; override;
procedure SetLParamWidth(_w: integer);
procedure SetLParamHeight(_h: integer);
function GetWidth(): integer; override;
function GetHeight(): integer; override;
procedure SetLGravity(_g: integer);
procedure SetLWeight(_w: single);
procedure SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
procedure AddLParamsAnchorRule(_rule: integer);
procedure AddLParamsParentRule(_rule: integer);
procedure SetLayoutAll(_idAnchor: integer);
procedure ClearLayout();
procedure SetScrollFlag(_collapsingScrollFlag: TCollapsingScrollflag);
procedure SetCollapseMode(_collapsemode: TCollapsingMode);
procedure SetExpandedTitleColorTransparent();
procedure SetExpandedTitleColor(_color: TARGBColorBridge);
procedure SetExpandedTitleGravity(_gravity: TLayoutGravity);
procedure SetCollapsedTitleTextColor(_color: TARGBColorBridge);
procedure SetCollapsedTitleGravity(_gravity: TLayoutGravity);
procedure SetContentScrimColor(_color: TARGBColorBridge); overload;
procedure SetContentScrimColor(_color: integer); overload;
procedure SetFitsSystemWindows(_value: boolean);
published
property BackgroundColor: TARGBColorBridge read FColor write SetColor;
property FitsSystemWindows: boolean read FFitsSystemWindows write SetFitsSystemWindows;
//property OnClick: TOnNotify read FOnClick write FOnClick;
end;
function jsCollapsingToolbarLayout_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
procedure jsCollapsingToolbarLayout_jFree(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject);
procedure jsCollapsingToolbarLayout_SetViewParent(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _viewgroup: jObject);
function jsCollapsingToolbarLayout_GetParent(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject): jObject;
procedure jsCollapsingToolbarLayout_RemoveFromViewParent(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject);
function jsCollapsingToolbarLayout_GetView(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject): jObject;
procedure jsCollapsingToolbarLayout_SetLParamWidth(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _w: integer);
procedure jsCollapsingToolbarLayout_SetLParamHeight(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _h: integer);
function jsCollapsingToolbarLayout_GetLParamWidth(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject): integer;
function jsCollapsingToolbarLayout_GetLParamHeight(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject): integer;
procedure jsCollapsingToolbarLayout_SetLGravity(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _g: integer);
procedure jsCollapsingToolbarLayout_SetLWeight(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _w: single);
procedure jsCollapsingToolbarLayout_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
procedure jsCollapsingToolbarLayout_AddLParamsAnchorRule(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _rule: integer);
procedure jsCollapsingToolbarLayout_AddLParamsParentRule(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _rule: integer);
procedure jsCollapsingToolbarLayout_SetLayoutAll(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _idAnchor: integer);
procedure jsCollapsingToolbarLayout_ClearLayoutAll(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject);
procedure jsCollapsingToolbarLayout_SetId(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _id: integer);
procedure jsCollapsingToolbarLayout_SetExpandedTitleColorTransparent(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject);
procedure jsCollapsingToolbarLayout_SetExpandedTitleColor(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _color: integer);
procedure jsCollapsingToolbarLayout_SetExpandedTitleGravity(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _gravity: integer);
procedure jsCollapsingToolbarLayout_SetCollapsedTitleTextColor(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _color: integer);
procedure jsCollapsingToolbarLayout_SetCollapsedTitleGravity(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _gravity: integer);
procedure jsCollapsingToolbarLayout_SetContentScrimColor(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _color: integer);
procedure jsCollapsingToolbarLayout_SetScrollFlag(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _collapsingScrollFlag: integer);
procedure jsCollapsingToolbarLayout_SetFitsSystemWindows(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _value: boolean);
procedure jsCollapsingToolbarLayout_SetCollapseMode(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _mode: integer);
implementation
{--------- jsCollapsingToolbarLayout --------------}
constructor jsCollapsingToolbarLayout.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if gapp <> nil then FId := gapp.GetNewId();
FMarginLeft := 0;
FMarginTop := 0;
FMarginBottom := 0;
FMarginRight := 0;
FHeight := 40; //??
FWidth := 100; //??
FLParamWidth := lpMatchParent; //lpWrapContent
FLParamHeight := lpWrapContent; //lpMatchParent
FAcceptChildrenAtDesignTime:= True;
//your code here....
end;
destructor jsCollapsingToolbarLayout.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jsCollapsingToolbarLayout.Init;
var
rToP: TPositionRelativeToParent;
rToA: TPositionRelativeToAnchorID;
begin
if not FInitialized then
begin
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jCreate(); if FjObject = nil then exit;
if FParent <> nil then
sysTryNewParent( FjPRLayout, FParent);
FjPRLayoutHome:= FjPRLayout;
jsCollapsingToolbarLayout_SetViewParent(gApp.jni.jEnv, FjObject, FjPRLayout);
jsCollapsingToolbarLayout_SetId(gApp.jni.jEnv, FjObject, Self.Id);
end;
jsCollapsingToolbarLayout_setLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject ,
FMarginLeft,FMarginTop,FMarginRight,FMarginBottom,
sysGetLayoutParams( FWidth, FLParamWidth, Self.Parent, sdW, fmarginLeft + fmarginRight ),
sysGetLayoutParams( FHeight, FLParamHeight, Self.Parent, sdH, fMargintop + fMarginbottom ));
for rToA := raAbove to raAlignRight do
begin
if rToA in FPositionRelativeToAnchor then
begin
jsCollapsingToolbarLayout_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToAnchor(rToA));
end;
end;
for rToP := rpBottom to rpCenterVertical do
begin
if rToP in FPositionRelativeToParent then
begin
jsCollapsingToolbarLayout_AddLParamsParentRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToParent(rToP));
end;
end;
if Self.Anchor <> nil then Self.AnchorId:= Self.Anchor.Id
else Self.AnchorId:= -1; //dummy
jsCollapsingToolbarLayout_SetLayoutAll(gApp.jni.jEnv, FjObject, Self.AnchorId);
if not FInitialized then
begin
FInitialized:= True;
if FColor <> colbrDefault then
View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor));
if FFitsSystemWindows then
jsCollapsingToolbarLayout_SetFitsSystemWindows(gApp.jni.jEnv, FjObject, FFitsSystemWindows);
View_SetVisible(gApp.jni.jEnv, FjObject, FVisible);
end;
end;
procedure jsCollapsingToolbarLayout.SetColor(Value: TARGBColorBridge);
begin
FColor:= Value;
if (FInitialized = True) and (FColor <> colbrDefault) then
View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor));
end;
procedure jsCollapsingToolbarLayout.SetVisible(Value : Boolean);
begin
FVisible:= Value;
if FInitialized then
View_SetVisible(gApp.jni.jEnv, FjObject, FVisible);
end;
procedure jsCollapsingToolbarLayout.UpdateLayout;
begin
if not FInitialized then exit;
ClearLayout();
inherited UpdateLayout;
init;
end;
procedure jsCollapsingToolbarLayout.Refresh;
begin
if FInitialized then
View_Invalidate(gApp.jni.jEnv, FjObject);
end;
//Event : Java -> Pascal
procedure jsCollapsingToolbarLayout.GenEvent_OnClick(Obj: TObject);
begin
if Assigned(FOnClick) then FOnClick(Obj);
end;
function jsCollapsingToolbarLayout.jCreate(): jObject;
begin
Result:= jsCollapsingToolbarLayout_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis);
end;
procedure jsCollapsingToolbarLayout.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_jFree(gApp.jni.jEnv, FjObject);
end;
procedure jsCollapsingToolbarLayout.SetViewParent(_viewgroup: jObject);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetViewParent(gApp.jni.jEnv, FjObject, _viewgroup);
end;
function jsCollapsingToolbarLayout.GetParent(): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jsCollapsingToolbarLayout_GetParent(gApp.jni.jEnv, FjObject);
end;
procedure jsCollapsingToolbarLayout.RemoveFromViewParent();
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_RemoveFromViewParent(gApp.jni.jEnv, FjObject);
end;
function jsCollapsingToolbarLayout.GetView(): jObject;
begin
//in designing component state: result value here...
if FInitialized then
Result:= jsCollapsingToolbarLayout_GetView(gApp.jni.jEnv, FjObject);
end;
procedure jsCollapsingToolbarLayout.SetLParamWidth(_w: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetLParamWidth(gApp.jni.jEnv, FjObject, _w);
end;
procedure jsCollapsingToolbarLayout.SetLParamHeight(_h: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetLParamHeight(gApp.jni.jEnv, FjObject, _h);
end;
function jsCollapsingToolbarLayout.GetWidth(): integer;
begin
Result:= FWidth;
if not FInitialized then exit;
if sysIsWidthExactToParent(Self) then
Result := sysGetWidthOfParent(FParent)
else
Result:= jsCollapsingToolbarLayout_getLParamWidth(gApp.jni.jEnv, FjObject );
end;
function jsCollapsingToolbarLayout.GetHeight(): integer;
begin
Result:= FHeight;
if not FInitialized then exit;
if sysIsHeightExactToParent(Self) then
Result := sysGetHeightOfParent(FParent)
else
Result:= jsCollapsingToolbarLayout_getLParamHeight(gApp.jni.jEnv, FjObject );
end;
procedure jsCollapsingToolbarLayout.SetLGravity(_g: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetLGravity(gApp.jni.jEnv, FjObject, _g);
end;
procedure jsCollapsingToolbarLayout.SetLWeight(_w: single);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetLWeight(gApp.jni.jEnv, FjObject, _w);
end;
procedure jsCollapsingToolbarLayout.SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject, _left ,_top ,_right ,_bottom ,_w ,_h);
end;
procedure jsCollapsingToolbarLayout.AddLParamsAnchorRule(_rule: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, _rule);
end;
procedure jsCollapsingToolbarLayout.AddLParamsParentRule(_rule: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_AddLParamsParentRule(gApp.jni.jEnv, FjObject, _rule);
end;
procedure jsCollapsingToolbarLayout.SetLayoutAll(_idAnchor: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetLayoutAll(gApp.jni.jEnv, FjObject, _idAnchor);
end;
procedure jsCollapsingToolbarLayout.ClearLayout();
var
rToP: TPositionRelativeToParent;
rToA: TPositionRelativeToAnchorID;
begin
//in designing component state: set value here...
if FInitialized then
begin
jsCollapsingToolbarLayout_clearLayoutAll(gApp.jni.jEnv, FjObject);
for rToP := rpBottom to rpCenterVertical do
if rToP in FPositionRelativeToParent then
jsCollapsingToolbarLayout_addlParamsParentRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToParent(rToP));
for rToA := raAbove to raAlignRight do
if rToA in FPositionRelativeToAnchor then
jsCollapsingToolbarLayout_addlParamsAnchorRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToAnchor(rToA));
end;
end;
procedure jsCollapsingToolbarLayout.SetScrollFlag(_collapsingScrollFlag: TCollapsingScrollflag);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetScrollFlag(gApp.jni.jEnv, FjObject, Ord(_collapsingScrollFlag) );
end;
procedure jsCollapsingToolbarLayout.SetCollapseMode(_collapsemode: TCollapsingMode);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetCollapseMode(gApp.jni.jEnv, FjObject, Ord(_collapsemode));
end;
procedure jsCollapsingToolbarLayout.SetExpandedTitleColorTransparent();
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetExpandedTitleColorTransparent(gApp.jni.jEnv, FjObject);
end;
procedure jsCollapsingToolbarLayout.SetExpandedTitleColor(_color: TARGBColorBridge);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetExpandedTitleColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, _color));
end;
procedure jsCollapsingToolbarLayout.SetExpandedTitleGravity(_gravity: TLayoutGravity);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetExpandedTitleGravity(gApp.jni.jEnv, FjObject, Ord(_gravity));
end;
procedure jsCollapsingToolbarLayout.SetCollapsedTitleTextColor(_color: TARGBColorBridge);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetCollapsedTitleTextColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, _color));
end;
procedure jsCollapsingToolbarLayout.SetCollapsedTitleGravity(_gravity: TLayoutGravity);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetCollapsedTitleGravity(gApp.jni.jEnv, FjObject, Ord(_gravity));
end;
procedure jsCollapsingToolbarLayout.SetContentScrimColor(_color: TARGBColorBridge);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetContentScrimColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, _color));
end;
procedure jsCollapsingToolbarLayout.SetContentScrimColor(_color: integer);
begin
//in designing component state: set value here...
if FInitialized then
jsCollapsingToolbarLayout_SetContentScrimColor(gApp.jni.jEnv, FjObject, _color);
end;
procedure jsCollapsingToolbarLayout.SetFitsSystemWindows(_value: boolean);
begin
//in designing component state: set value here...
FFitsSystemWindows:= _value;
if FInitialized then
jsCollapsingToolbarLayout_SetFitsSystemWindows(gApp.jni.jEnv, FjObject, _value);
end;
{-------- jsCollapsingToolbarLayout_JNI_Bridge ----------}
function jsCollapsingToolbarLayout_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _Self;
jCls:= Get_gjClass(env);
jMethod:= env^.GetMethodID(env, jCls, 'jsCollapsingToolbarLayout_jCreate', '(J)Ljava/lang/Object;');
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
end;
procedure jsCollapsingToolbarLayout_jFree(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
env^.CallVoidMethod(env, _jscollapsingtoolbarlayout, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetViewParent(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _viewgroup: jObject);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= _viewgroup;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetViewParent', '(Landroid/view/ViewGroup;)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jsCollapsingToolbarLayout_GetParent(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject): jObject;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'GetParent', '()Landroid/view/ViewGroup;');
Result:= env^.CallObjectMethod(env, _jscollapsingtoolbarlayout, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_RemoveFromViewParent(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'RemoveFromViewParent', '()V');
env^.CallVoidMethod(env, _jscollapsingtoolbarlayout, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jsCollapsingToolbarLayout_GetView(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject): jObject;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'GetView', '()Landroid/view/View;');
Result:= env^.CallObjectMethod(env, _jscollapsingtoolbarlayout, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetLParamWidth(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _w: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _w;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetLParamWidth', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetLParamHeight(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _h: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _h;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetLParamHeight', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
function jsCollapsingToolbarLayout_GetLParamWidth(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject): integer;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'GetLParamWidth', '()I');
Result:= env^.CallIntMethod(env, _jscollapsingtoolbarlayout, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
function jsCollapsingToolbarLayout_GetLParamHeight(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject): integer;
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'GetLParamHeight', '()I');
Result:= env^.CallIntMethod(env, _jscollapsingtoolbarlayout, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetLGravity(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _g: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _g;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetLGravity', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetLWeight(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _w: single);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].f:= _w;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetLWeight', '(F)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer);
var
jParams: array[0..5] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _left;
jParams[1].i:= _top;
jParams[2].i:= _right;
jParams[3].i:= _bottom;
jParams[4].i:= _w;
jParams[5].i:= _h;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetLeftTopRightBottomWidthHeight', '(IIIIII)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_AddLParamsAnchorRule(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _rule: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _rule;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsAnchorRule', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_AddLParamsParentRule(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _rule: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _rule;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsParentRule', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetLayoutAll(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _idAnchor: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _idAnchor;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetLayoutAll', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_ClearLayoutAll(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'ClearLayoutAll', '()V');
env^.CallVoidMethod(env, _jscollapsingtoolbarlayout, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetId(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _id: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _id;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'setId', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetScrollFlag(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _collapsingScrollFlag: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _collapsingScrollFlag;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetScrollFlag', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetExpandedTitleColorTransparent(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetExpandedTitleColorTransparent', '()V');
env^.CallVoidMethod(env, _jscollapsingtoolbarlayout, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetExpandedTitleColor(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _color: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _color;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetExpandedTitleColor', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetExpandedTitleGravity(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _gravity: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _gravity;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetExpandedTitleGravity', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetCollapsedTitleTextColor(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _color: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _color;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetCollapsedTitleTextColor', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetCollapsedTitleGravity(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _gravity: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _gravity;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetCollapsedTitleGravity', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetContentScrimColor(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _color: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _color;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetContentScrimColor', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetFitsSystemWindows(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _value: boolean);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].z:= JBool(_value);
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetFitsSystemWindows', '(Z)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
procedure jsCollapsingToolbarLayout_SetCollapseMode(env: PJNIEnv; _jscollapsingtoolbarlayout: JObject; _mode: integer);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].i:= _mode;
jCls:= env^.GetObjectClass(env, _jscollapsingtoolbarlayout);
jMethod:= env^.GetMethodID(env, jCls, 'SetCollapseMode', '(I)V');
env^.CallVoidMethodA(env, _jscollapsingtoolbarlayout, jMethod, @jParams);
env^.DeleteLocalRef(env, jCls);
end;
end.
|
// Histogram and Image Statistics Library
//
// efg, April 1998
UNIT HistogramLibrary;
INTERFACE
USES
Windows, // TRGBTriple
Graphics, // TCanvas
StatisticsLibrary, // TDescriptiveStatitics
ColorLibrary; // TColorPlane
TYPE
THistoArray = ARRAY[BYTE] OF INTEGER;
TRGBHistoArray =
RECORD
Red : THistoArray;
Green : THistoArray;
Blue : THistoArray;
Intensity: THistoArray;
END;
THistogram =
CLASS(TObject)
PRIVATE
FHistogram: THistoArray;
FUNCTION GetCount: INTEGER;
PUBLIC
CONSTRUCTOR Create;
PROCEDURE Clear;
PROCEDURE Increment(CONST index: BYTE);
PROCEDURE GetStatistics(VAR N: INTEGER;
VAR Minimum,Maximum: BYTE;
VAR Mode, Median: BYTE;
VAR Mean, StandardDeviation,
Skewness, Kurtosis: DOUBLE);
PROPERTY Frequency: THistoArray READ FHistogram WRITE FHistogram;
PROPERTY Count : INTEGER READ GetCount;
END;
TRGBHistograms =
CLASS
PROTECTED
FRed : THistogram;
FGreen: THistogram;
FBlue : THistogram;
FIntensity: THistogram;
PUBLIC
CONSTRUCTOR Create;
DESTRUCTOR Destroy; OVERRIDE;
PROCEDURE Increment(CONST RGBTriple: TRGBTriple);
PROPERTY Red: THistogram READ FRed;
PROPERTY Green: THistogram READ FGreen;
PROPERTY Blue: THistogram READ FBlue;
END;
TRGBStatistics =
CLASS(TObject)
PROTECTED
FRed : TDescriptiveStatistics;
FGreen: TDescriptiveStatistics;
FBlue : TDescriptiveStatistics;
FUNCTION PixelCount: INTEGER;
PUBLIC
PROPERTY Count: INTEGER READ PixelCount;
PROPERTY Red : TDescriptiveStatistics READ FRed;
PROPERTY Green: TDescriptiveStatistics READ FGreen;
PROPERTY Blue : TDescriptiveStatistics READ FBlue;
CONSTRUCTOR Create;
DESTRUCTOR Destroy; OVERRIDE;
PROCEDURE NextRGBTriple(CONST rgb: TRGBTriple);
PROCEDURE ProcessBitmap(CONST Bitmap: TBitmap);
PROCEDURE ResetValues;
END;
PROCEDURE DrawHistogram(CONST ColorPlane: TColorPlane;
CONST Histogram: THistogram;
CONST Canvas: TCanvas);
PROCEDURE GetHistogram(CONST Bitmap: TBitmap;
CONST ColorPlane: TColorPlane;
VAR Histogram: THistogram);
FUNCTION GetRGBHistograms(CONST Bitmap: TBitmap;
CONST Rect: TRect): TRGBHistograms;
// Get statistics for single image plane. Use TRGBStatistics.ProcessBitmap
// to get R, G, and B statistics for any number of 24-bit images.
PROCEDURE GetBitmapStatistics(CONST Bitmap: TBitmap;
CONST ColorPlane: TColorPlane;
VAR Statistics: TDescriptiveStatistics);
IMPLEMENTATION
USES
Dialogs, // ShowMessage
ImageProcessingPrimitives, // RGBTriple
Math, // MaxIntValue, IntPwr
SysUtils; // pByteArray, Exception
TYPE
EHistogramError = CLASS(Exception);
EStatisticsError = CLASS(Exception);
// == THistogram ======================================================
// This Histogram class is specialized for image processing applications.
// The frequency distribution is assumed to be for values ONLY in the
// range 0..255.
FUNCTION THistogram.GetCount: INTEGER;
VAR
i: BYTE;
BEGIN
RESULT := 0;
FOR i := Low(THistoArray) TO High(THistoArray) DO
INC(RESULT, FHistogram[i])
END {GetCount};
CONSTRUCTOR THistogram.Create;
BEGIN
Clear
END {Create};
PROCEDURE THistogram.Clear;
VAR
i: BYTE;
BEGIN
FOR i := Low(THistoArray) TO High(THistoArray) DO
FHistogram[i] := 0
END {Clear};
PROCEDURE THistogram.GetStatistics(VAR N: INTEGER;
VAR Minimum,Maximum: BYTE;
VAR Mode, Median: BYTE;
VAR Mean, StandardDeviation,
Skewness, Kurtosis: DOUBLE);
VAR
Cumulative : INTEGER;
i : BYTE;
MaxFrequency: INTEGER;
M2 : EXTENDED;
M3 : EXTENDED;
M3Sum : EXTENDED;
M4 : EXTENDED;
M4Sum : EXTENDED;
x : EXTENDED;
xSum : EXTENDED; // Use floats to avoid integer overflow
xSqrSum : EXTENDED;
BEGIN
N := 0;
Minimum := 0;
WHILE (FHistogram[Minimum] = 0) AND (Minimum < 255)
DO INC(Minimum);
Maximum := 255;
WHILE (FHistogram[Maximum] = 0) AND (Maximum > 0)
DO DEC(Maximum);
// Mode is value with highest frequency.
// For now, don't worry about a "tie".
Mode := Minimum;
MaxFrequency := FHistogram[Minimum];
FOR i := Minimum+1 TO Maximum DO
BEGIN
IF FHistogram[i] > MaxFrequency
THEN BEGIN
Mode := i;
MaxFrequency := FHistogram[i]
END
END;
// Calculate Mean and Standard Deviation
xSum := 0.0;
xSqrSum := 0.0;
FOR i := Minimum TO Maximum DO
BEGIN
INC(N, FHistogram[i]);
x := i;
xSum := xSum + FHistogram[i]*x;
xSqrSum := xSqrSum + FHistogram[i]*SQR(x)
END;
IF N = 0
THEN Mean := 0.0
ELSE Mean := xSum / N;
IF N < 2
THEN BEGIN
StandardDeviation := 0.0; // should be a NAN someday
Skewness := 0.0;
Kurtosis := 0.0;
END
ELSE BEGIN
StandardDeviation := SQRT( (xSqrSum - N*SQR(Mean)) / (N-1) );
// Standard Deviation is related to moment M2
M2 := SQR(StandardDeviation) * (N-1) / N;
// Calculate third and fourth moments
M3Sum := 0.0;
M4Sum := 0.0;
FOR i := Minimum TO Maximum DO
BEGIN
x := i;
M3Sum := M3Sum + FHistogram[i]*IntPower(x - Mean, 3);
M4Sum := M4Sum + FHistogram[i]*IntPower(x - Mean, 4);
END;
M3 := M3Sum / N;
M4 := M4Sum / N;
IF M2 = 0.0
THEN BEGIN
Skewness := 0.0; // eventually use NAN here
Kurtosis := 0.0;
END
ELSE BEGIN
Skewness := M3 / Power(M2, 1.5);
Kurtosis := M4 / SQR(M2)
END
END;
// Median is value with half of values above and below.
Cumulative := 0;
i := Minimum;
WHILE (Cumulative < N DIV 2) AND (i < 255) DO
BEGIN
INC(Cumulative, FHistogram[i]);
INC(i)
END;
Median := i;
END {GetStatistics};
PROCEDURE THistogram.Increment(CONST index: BYTE);
BEGIN
INC(FHistogram[index])
END {Increment};
// == RGB Histograms =================================================
CONSTRUCTOR TRGBHistograms.Create;
BEGIN
FRed := THistogram.Create;
FGreen := THistogram.Create;
FBlue := THistogram.Create;
FIntensity := THistogram.Create
END {Create};
DESTRUCTOR TRGBHistograms.Destroy;
BEGIN
FRed.Free;
FGreen.Free;
FBlue.Free;
FIntensity.Free
END {Destroy};
PROCEDURE TRGBHistograms.Increment(CONST RGBTriple: TRGBTriple);
BEGIN
WITH RGBTriple DO
BEGIN
FRed.Increment(rgbtRed);
FGreen.Increment(rgbtGreen);
FBlue.Increment(rgbtBlue)
END;
FIntensity.Increment( RGBTripleToIntensity(RGBTriple) );
END {Increment};
// == RGB Statistics =================================================
CONSTRUCTOR TRGBStatistics.Create;
BEGIN
FRed := TDescriptiveStatistics.Create;
FGreen := TDescriptiveStatistics.Create;
FBlue := TDescriptiveStatistics.Create;
FRed.ResetValues;
FGreen.ResetValues;
FBlue.ResetValues
END {Create};
DESTRUCTOR TRGBStatistics.Destroy;
BEGIN
FRed.Free;
FGreen.Free;
FBlue.Free
END {Destroy};
FUNCTION TRGBStatistics.PixelCount;
BEGIN
RESULT := FRed.Count
END {PixelCount};
// Use this method to look at given set of pixels, one-by-one
PROCEDURE TRGBStatistics.NextRGBTriple(CONST rgb: TRGBTriple);
BEGIN
WITH rgb DO
BEGIN
FRed.NextValue(rgbtRed);
FGreen.NextValue(rgbtGreen);
FBlue.NextValue(rgbtBlue);
END
END {NextRGBTriple};
// Get statistics for complete image
PROCEDURE TRGBStatistics.ProcessBitmap(CONST Bitmap: TBitmap);
VAR
i : INTEGER;
j : INTEGER;
row: pRGBTripleArray;
BEGIN
IF Bitmap.PixelFormat <> pf24bit
THEN RAISE EStatisticsError.Create('Can only process 24-bit image');
FOR j := 0 TO Bitmap.Height-1 DO
BEGIN
row := Bitmap.Scanline[j];
FOR i := 0 TO Bitmap.Width-1 DO
BEGIN
WITH row[i] DO
BEGIN
FRed.NextValue(rgbtRed);
FGreen.NextValue(rgbtGreen);
FBlue.NextValue(rgbtBlue);
END
END
END
END {ProcessBitmap};
PROCEDURE TRGBStatistics.ResetValues;
BEGIN
FRed.ResetValues;
FGreen.ResetValues;
FBlue.ResetValues
END {ResetValues};
// =====================================================================
PROCEDURE DrawHistogram(CONST ColorPlane: TColorPlane;
CONST Histogram : THistogram;
CONST Canvas : TCanvas);
CONST
MajorTickSize = 8;
VAR
BarLength: INTEGER;
Delta : INTEGER;
Color : TColor;
i : INTEGER;
j : INTEGER;
Height : INTEGER;
MaxValue : INTEGER;
Width : INTEGER;
BEGIN
Color := clBlack; {avoid compiler warning about initialization}
Height := Canvas.ClipRect.Bottom;
Width := Canvas.ClipRect.Right;
MaxValue := MaxIntValue(Histogram.Frequency);
// For now only paint on a canvas exactly 256 pixels wide. If
// MaxValue is zero, array was not filled in correctly and is ignored.
IF (Width = 256) AND (MaxValue > 0)
THEN BEGIN
FOR i := Low(THistoArray) TO High(THistoArray) DO
BEGIN
CASE ColorPlane OF
cpRGB,
cpY,
cpIntensity: Color := RGB(i, i, i);
cpRed: Color := RGB(i, 0, 0);
cpGreen: Color := RGB(0, i, 0);
cpBlue: Color := RGB(0, 0, i);
cpHueHSV:
// Rescale Hue from 0..255 to 0..359
Color := RGBTripleToColor( HSVtoRGBTriple(MulDiv(i, 359, 255), 255, 255) );
cpSaturationHSV:
Color := clBlack;
cpValue: Color := RGB(i, i, i);
cpHueHLS:
// Rescale Hue from 0..255 to 0..359; Half Lightness
Color := RGBTripleToColor( HLStoRGBTriple(MulDiv(i, 359, 255), 128, 255) );
cpSaturationHLS:
Color := clBlack;
cpLightness: Color := RGB(i, i, i);
cpCyan: Color := RGB(i, i, i);
cpMagenta: Color := RGB(i, i, i);
cpYellow: Color := RGB(i, i, i);
cpBlack: Color := RGB(255-i, 255-i, 255-i)
END;
Canvas.Pen.Color := Color;
BarLength := ROUND(Height*Histogram.Frequency[i] / MaxValue);
Canvas.MoveTo(i, Height-1);
Canvas.LineTo(i, Height-1-BarLength)
END;
Canvas.Pen.Color := clDkGray;
// Vertical Lines for visual estimation
FOR i := 0 TO 25 DO
BEGIN
Canvas.MoveTo(10*i, Height-1);
IF i MOD 5 = 0
THEN Delta := MajorTickSize
ELSE Delta := MajorTickSize DIV 2;
Canvas.LineTo(10*i, Height-1-Delta);
END;
// Horizontal Lines
FOR j := 0 TO 4 DO
BEGIN
Canvas.MoveTo( 0, j*Height DIV 5);
Canvas.LineTo(Width-1, j*Height DIV 5);
END;
Canvas.Brush.Style := bsClear;
Canvas.TextOut(2,2, 'Max = ' + IntToStr(MaxValue));
Canvas.TextOut(2, Height-Canvas.TextHeight('X') - MajorTickSize, '0');
Canvas.TextOut(Width-Canvas.TextWidth('250 '),
Height-Canvas.TextHeight('X') - MajorTickSize, '250')
END
END {DrawHistogram};
PROCEDURE GetHistogram(CONST Bitmap : TBitmap;
CONST ColorPlane: TColorPlane;
VAR Histogram : THistogram);
VAR
C,M,Y,K: INTEGER; // CMYK color space
H,S,V : INTEGER; // HSV color
i : INTEGER;
index : INTEGER;
j : INTEGER;
L : INTEGER;
Row : pRGBTripleArray;
BEGIN
IF (Bitmap.PixelFormat <> pf24bit)
THEN RAISE EHistogramError.Create('GetHistogram: ' +
'Bitmap must be 24-bit.');
index := 0; // avoid compiler warning about initialization
Histogram.Clear;
// Step through each row of image.
FOR j := Bitmap.Height-1 DOWNTO 0 DO
BEGIN
Row := Bitmap.Scanline[j];
FOR i := Bitmap.Width-1 DOWNTO 0 DO
BEGIN
CASE ColorPlane OF
cpY: index := RGBTripleToY(Row[i]);
cpRGB,
cpIntensity: index := RGBTripleToIntensity(Row[i]);
cpRed: index := Row[i].rgbtRed;
cpGreen: index := Row[i].rgbtGreen;
cpBlue: index := Row[i].rgbtBlue;
cpHueHSV:
BEGIN
RGBTripleToHSV(Row[i], H,S,V);
// Rescale from 0..359 to 0..255
index := MulDiv(H, 255, 359)
END;
cpSaturationHSV:
BEGIN
RGBTripleToHSV(Row[i], H,S,V);
index := S
END;
cpValue:
BEGIN
RGBTripleToHSV(Row[i], H,S,V);
index := V
END;
cpHueHLS:
BEGIN
RGBTripleToHLS(Row[i], H,L,S);
index := MulDiv(H, 255, 360)
END;
cpSaturationHLS:
BEGIN
RGBTripleToHLS(Row[i], H,L,S);
index := S
END;
cpCyan:
BEGIN
RGBTripleToCMYK(Row[i], C,M,Y,K);
index := C
END;
cpMagenta:
BEGIN
RGBTripleToCMYK(Row[i], C,M,Y,K);
index := M
END;
cpYellow:
BEGIN
RGBTripleToCMYK(Row[i], C,M,Y,K);
index := Y
END;
cpBlack:
BEGIN
RGBTripleToCMYK(Row[i], C,M,Y,K);
index := K
END;
cpLightness:
BEGIN
index := RGBTripleToLightness(Row[i])
END
END;
// Debug color conversion problems
IF (index < 0) OR (index > 255)
THEN BEGIN
ShowMessage ('Histogram index = ' + IntToStr(index) +
' (i,j) = (' + IntToStr(i) + ', ' +
IntToStr(j) + ')');
index := 0;
END;
Histogram.Increment(index)
END
END
END {GetHistogram};
// Single function to create all three R, G and B Histograms for all or part
// of a bitmap. Use Bitmap.Canvas.ClipRect as the second parameters to look
// at the whole bitmap.
//
// The calling routine must free the resulting TRGBHistograms object.
FUNCTION GetRGBHistograms(CONST Bitmap: TBitmap;
CONST Rect: TRect): TRGBHistograms;
VAR
i : INTEGER;
j : INTEGER;
Row : pRGBTripleArray;
BEGIN
IF Bitmap.PixelFormat <> pf24bit
THEN RAISE EHistogramError.Create('GetRGBHistograms: ' +
'Bitmap must be 24-bit.');
RESULT := TRGBHistograms.Create;
// Step through each requested row of image.
FOR j := Rect.Top TO Rect.Bottom-1 DO
BEGIN
Row := Bitmap.Scanline[j];
// Look at each requested pixel within a row and increment histogram stats.
FOR i := Rect.Left TO Rect.Right-1 DO
BEGIN
RESULT.Increment(Row[i])
END
END
END {GetRGBHistograms};
PROCEDURE GetBitmapStatistics(CONST Bitmap: TBitmap;
CONST ColorPlane: TColorPlane;
VAR Statistics: TDescriptiveStatistics);
VAR
C,M,Y,K: INTEGER;
H,S,V : INTEGER; // color coordinates
i : INTEGER;
j : INTEGER;
L : INTEGER;
Row : pRGBTripleArray;
Value : INTEGER;
BEGIN
IF Bitmap.PixelFormat <> pf24bit
THEN RAISE EHistogramError.Create('GetBitmapStatistics: ' +
'Bitmap must be 24-bit color.');
// Step through each row of image.
FOR j := Bitmap.Height-1 DOWNTO 0 DO
BEGIN
Row := Bitmap.Scanline[j];
FOR i := Bitmap.Width-1 DOWNTO 0 DO
BEGIN
CASE ColorPlane OF
cpRGB,
cpIntensity: value := RGBTripleToIntensity(Row[i]);
cpRed: value := Row[i].rgbtRed;
cpGreen: value := Row[i].rgbtGreen;
cpBlue: value := Row[i].rgbtBlue;
cpHueHSV:
BEGIN
RGBTripleToHSV(Row[i], H,S,V);
value := H
END;
cpSaturationHSV:
BEGIN
RGBTripleToHSV(Row[i], H,S,V);
value := S
END;
cpValue:
BEGIN
RGBTripleToHSV(Row[i], H,S,V);
value := V
END;
cpHueHLS:
BEGIN
RGBTripleToHLS(Row[i], H,L,S);
value := H
END;
cpSaturationHLS:
BEGIN
RGBTripleToHLS(Row[i], H,L,S);
value := S
END;
cpLightness:
BEGIN
RGBTripleToHLS(Row[i], H,L,S);
value := L
END;
cpCyan:
BEGIN
RGBTripleToCMYK(Row[i], C,M,Y,K);
value := C
END;
cpMagenta:
BEGIN
RGBTripleToCMYK(Row[i], C,M,Y,K);
value := M
END;
cpYellow:
BEGIN
RGBTripleToCMYK(Row[i], C,M,Y,K);
value := Y
END;
cpBlack:
BEGIN
RGBTripleToCMYK(Row[i], C,M,Y,K);
value := K
END;
ELSE
value := 0
END;
Statistics.NextValue(value)
END
END
END {GetBitmapStatistics};
END.
|
unit SE_ValidationPlugin;
interface
uses
Windows, Graphics,
SynEdit, SynEditPlugins;
type
TGutterPainEvent = procedure(aCanvas: TCanvas; const aClip: TRect;
aFirstLine, aLastLine: Integer) of object;
TLineChangeEvent = procedure(aFirstLine, aCount: Integer) of object;
TSEValidationPlugin = class(TSynEditPlugin)
strict private
fOnGutterPaint: TGutterPainEvent;
fOnLinesInserted: TLineChangeEvent;
fOnLinesDeleted: TLineChangeEvent;
protected
procedure AfterPaint(aCanvas: TCanvas; const aClip: TRect;
aFirstLine, aLastLine: Integer); override;
procedure LinesInserted(aFirstLine, aCount: Integer); override;
procedure LinesDeleted(aFirstLine, aCount: Integer); override;
public
property OnGutterPaint: TGutterPainEvent read fOnGutterPaint write fOnGutterPaint;
property OnLinesInserted: TLineChangeEvent read fOnLinesInserted write fOnLinesInserted;
property OnLinesDeleted: TLineChangeEvent read fOnLinesDeleted write fOnLinesDeleted;
end;
implementation
procedure TSEValidationPlugin.AfterPaint(aCanvas: TCanvas; const aClip: TRect;
aFirstLine, aLastLine: Integer);
begin
if assigned(fOnGutterPaint) then
fOnGutterPaint(aCanvas, aClip, aFirstLine, aLastLine);
end;
procedure TSEValidationPlugin.LinesInserted(aFirstLine, aCount: Integer);
begin
if assigned(fOnLinesInserted) then
fOnLinesInserted(aFirstLine, aCount);
end;
procedure TSEValidationPlugin.LinesDeleted(aFirstLine, aCount: Integer);
begin
if assigned(fOnLinesDeleted) then
fOnLinesDeleted(aFirstLine, aCount);
end;
end.
|
unit ControladorEdicion;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs,LCLClasses,
Buttons, sqldb, SQLQueryGroup, StdCtrls, DbCtrls, ExtCtrls,LCLType, DateTimePicker;
const
ED_AGREGAR = 0;
ED_MODIFICAR = 1;
ED_ELIMINAR = 2;
ED_INDETERMINADO = 3;
BC_ACEPTAR = '&Aceptar';
BC_CANCELAR = '&Cancelar';
BC_CERRAR = 'Ce&rrar';
BC_GUARDAR = '&Guardar';
BC_ELIMINAR = '&Eliminar';
BC_SALIR = '&Salir';
type
//Evento que se dispara antes de aceptar o guardar. Permite realizar
//validaciones en el formulario e indicar si todo está OK para continuar
TValidateEvent = procedure(Sender : TObject; var ValidacionOK : boolean) of object;
{ TDummyControl }
//Se usa estr control de la clase TWinControl para poder implementar
//el método KeyDown que se asigna a los controles del formulario
TDummyControl = class(TWinControl)
public
procedure CustomKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
end;
{ TControladorEdicion }
TControladorEdicion = class(TLCLComponent)
procedure AceptarExecute(Sender: TObject);
procedure CancelarExecute(Sender: TObject);
procedure EliminarExecute(Sender: TObject);
procedure GuardarExecute(Sender: TObject);
procedure SalirExecute(Sender: TObject);
private
{ Private declarations }
FAccion: integer;
FAltaContinua: boolean;
FAltoBotones: integer;
FAnchoBotones: integer;
FBotonAceptar: TBitBtn;
FBotonCancelar: TBitBtn;
FControlEncabezado: TDBText;
FControlInicial: TWinControl;
FControlMostrarAccion: TLabel;
FDummyControl: TDummyControl;
FEsSubform: boolean;
FIdMaestro: LongInt;
FIdPadre: LongInt;
FOldFormActivate: TNotifyEvent;
FOnValidateForm: TValidateEvent;
FPanelEdicion: TPanel;
FParentForm: TForm;
FQueryGroup: TSQLQueryGroup;
FStrAccion: string;
procedure HabilitarControles(TWC: TWinControl; EnableFlag: boolean);
procedure AsignarKeyDown(TWC: TWinControl);
procedure SetAltaContinua(AValue: boolean);
procedure SetAltoBotones(AValue: integer);
procedure SetAnchoBotones(AValue: integer);
procedure SetBotonAceptar(AValue: TBitBtn);
procedure SetBotonCancelar(AValue: TBitBtn);
procedure SetControlEncabezado(AValue: TDBText);
procedure SetControlInicial(AValue: TWinControl);
procedure SetControlMostrarAccion(AValue: TLabel);
procedure SetEsSubform(AValue: boolean);
procedure SetIdMaestro(AValue: LongInt);
procedure SetOnValidateForm(AValue: TValidateEvent);
procedure SetPanelEdicion(AValue: TPanel);
procedure SetQueryGroup(AValue: TSQLQueryGroup);
protected
{ Protected declarations }
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure OnFormActivate(Sender: TObject);
procedure OnFormCloseQuery(Sender: TObject; var CanClose: boolean);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property IdMaestro: LongInt read FIdMaestro write SetIdMaestro;
property IdPadre: LongInt read FIdPadre;
property Accion: integer read FAccion;
property StrAccion: string read FStrAccion;
procedure nuevoRegistro(IdRegistroPadre: LongInt=-1);
procedure editarRegistro(id: integer);
procedure eliminarRegistro(id: integer; MostrarAviso: boolean);
function NuevoID(tabla: string): longint;
function ShowModal: TModalResult;
published
{ Published declarations }
property AltaContinua: boolean read FAltaContinua write SetAltaContinua default false;
property AltoBotones: integer read FAltoBotones write SetAltoBotones default 26;
property AnchoBotones: integer read FAnchoBotones write SetAnchoBotones default 86;
property BotonAceptar:TBitBtn read FBotonAceptar write SetBotonAceptar;
property BotonCancelar:TBitBtn read FBotonCancelar write SetBotonCancelar;
property ControlInicial: TWinControl read FControlInicial write SetControlInicial;
property ControlMostrarAccion: TLabel read FControlMostrarAccion write SetControlMostrarAccion;
property ControlEncabezado: TDBText read FControlEncabezado write SetControlEncabezado;
property EsSubform:boolean read FEsSubform write SetEsSubform default false;
property OnValidateForm: TValidateEvent read FOnValidateForm write SetOnValidateForm;
property PanelEdicion: TPanel read FPanelEdicion write SetPanelEdicion;
property QueryGroup: TSQLQueryGroup read FQueryGroup write SetQueryGroup;
end;
procedure Register;
implementation
procedure Register;
begin
{$I controladoredicion_icon.lrs}
RegisterComponents('Mis Componentes',[TControladorEdicion]);
end;
{ TDummyControl }
procedure TDummyControl.CustomKeyDown(Sender: TObject; var Key: word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
Key := VK_TAB;
end;
inherited KeyDown(Key, Shift);
end;
{ TControladorEdicion }
procedure TControladorEdicion.AceptarExecute(Sender: TObject);
var
TodoOK: Boolean;
begin
if Assigned(FParentForm) then
begin
//Realiza la validación del formulario
TodoOK:=true;
if Assigned(OnValidateForm) then
OnValidateForm (Self, TodoOK);
//Si no hubo errores de validación, continúo, si no no hace nada
//Se supone que los mensajes de error se emiten en el procedimiento de validación
if TodoOK then
begin
// Si es subform, los cambios se aplican en el form padre
if not FEsSubform then
begin
if Assigned(QueryGroup) then
begin
QueryGroup.Post;
if not QueryGroup.ApplyUpdates(0) then
MessageDlg('Ocurrió un error al guardar los datos', mtWarning, [mbOK], 0)
else
FParentForm.ModalResult := mrOk;
end;
end else
FParentForm.ModalResult := mrOk;
end;
end;
end;
procedure TControladorEdicion.CancelarExecute(Sender: TObject);
var
mr:TModalResult;
begin
mr:=mrCancel;
//Antes de cerrar el formulario verifico si hay datos sin guardar y pregunto
if Assigned(QueryGroup) then
begin
QueryGroup.Cancel;
//Si es un subform no chequeo los cambios pendientes, porque se
//chequea en el form principal
if (not EsSubform) and QueryGroup.UpdatesPending then
begin
mr:=MessageDlg('Aún quedan datos sin guardar. '+
'¿Desea guardar estas modificaciones antes de salir?', mtConfirmation,
mbYesNoCancel, 0);
if mr=mrYes then //Si responde si, guardo los datos
begin
if not QueryGroup.ApplyUpdates(0) then
begin //Si la grabación dio error, aviso y cancelo la salida
MessageDlg('Ha ocurrido un error al guardar los datos', mtWarning, [mbOK], 0);
mr:=mrNone;
end;
end else if mr=mrCancel then //Apretó Cancelar, aborto la salida
begin
mr:=mrNone;
end else //Respondió que no, deshago todas las ediciones
begin
QueryGroup.CancelUpdates;
mr:=mrCancel;
end;
end;
end;
if Assigned(FParentForm) then
begin
FParentForm.ModalResult := mr;
end;
end;
procedure TControladorEdicion.EliminarExecute(Sender: TObject);
var
mr: TModalResult;
begin
if Assigned(FParentForm) then
begin
mr := MessageDlg('¿Confirma la eliminación de estos datos?', mtWarning, mbYesNo, 0);
if mr = mrYes then
begin
if Assigned(QueryGroup) and Assigned(QueryGroup.QueryMaestro) then
begin
QueryGroup.QueryMaestro.Delete;
// Si es subform, los cambios se aplican en el form padre
if not FEsSubform then
begin
if QueryGroup.ApplyUpdates(0) then
mr := mrOk
else
mr := mrCancel;
end else;
mr := mrOk
end;
end
else
mr := mrNone;
FParentForm.ModalResult := mr;
end;
end;
procedure TControladorEdicion.GuardarExecute(Sender: TObject);
var
TodoOK: boolean;
begin
if Assigned(FParentForm) then
begin
//Realiza la validación del formulario
TodoOK:=true;
if Assigned(OnValidateForm) then
OnValidateForm (Self, TodoOK);
//Si no hubo errores de validación, continúo, si no no hace nada
//Se supone que los mensajes de error se emiten en el procedimiento de validación
if TodoOK then
begin
// Si es subform, los cambios se aplican en el form padre
if not FEsSubform then
begin
if Assigned(QueryGroup) then
begin
QueryGroup.Post;
if not QueryGroup.ApplyUpdates(0) then
MessageDlg('Ocurrió un error al guardar los datos', mtWarning, [mbOK], 0)
else if AltaContinua then
begin
if MessageDlg('¿Desea ingresar otro nuevo dato en este formulario?',
mtConfirmation,mbYesNo,0) = mrYes then
begin
if Assigned(ControlInicial) and ControlInicial.CanFocus then
ControlInicial.SetFocus;
nuevoRegistro(FIdPadre);
end
end
else
FParentForm.ModalResult := mrNone;
end;
end
else if AltaContinua then
begin
if MessageDlg('¿Desea ingresar otro nuevo dato en este formulario?',
mtConfirmation,mbYesNo,0) = mrYes then
begin
if Assigned(ControlInicial) and ControlInicial.CanFocus then
ControlInicial.SetFocus;
nuevoRegistro(FIdPadre);
end
else
FParentForm.ModalResult:=mrOK;
end
else
FParentForm.ModalResult := mrNone;
end;
end;
end;
procedure TControladorEdicion.SalirExecute(Sender: TObject);
begin
if Assigned (QueryGroup) then
QueryGroup.Cancel;
if Assigned(FParentForm) then
begin
FParentForm.ModalResult := mrYes;
end;
end;
procedure TControladorEdicion.OnFormActivate(Sender: TObject);
begin
if Assigned(FParentForm) then
begin
if Assigned (FOldFormActivate) then
FOldFormActivate(Self);
//Asigno el comportamiento del KeyDown a los controles del form
AsignarKeyDown(FParentForm);
if (FAccion in [ED_AGREGAR, ED_MODIFICAR]) and Assigned(FControlInicial) and
(FControlInicial.CanFocus) then
begin
FControlInicial.SetFocus;
end
else if (FAccion = ED_ELIMINAR) and Assigned(FBotonAceptar) and (FBotonAceptar.CanFocus) then
begin
FBotonAceptar.SetFocus;
end;
end;
end;
procedure TControladorEdicion.OnFormCloseQuery(Sender: TObject;
var CanClose: boolean);
var
mr:TModalResult;
begin
CanClose:=true;
//Antes de cerrar el formulario verifico si hay datos sin guardar y pregunto
if Assigned(QueryGroup) then
begin
QueryGroup.Post;
//Si es un subform no chequeo los cambios pendientes, porque se
//chequea en el form principal
if (not EsSubform) and QueryGroup.UpdatesPending then
begin
mr:=MessageDlg('Aún quedan datos sin guardar. '+
'¿Desea guardar estas modificaciones antes de salir?', mtConfirmation,
mbYesNoCancel, 0);
if mr=mrYes then //Si responde si, guardo los datos
begin
if not QueryGroup.ApplyUpdates(0) then
begin //Si la grabación dio error, aviso y cancelo la salida
MessageDlg('Ha ocurrido un error al guardar los datos', mtWarning, [mbOK], 0);
CanClose:=false;
end;
end else if mr=mrCancel then //Apretó Cancelar, aborto la salida
begin
CanClose:=false;
end;
end;
end;
end;
procedure TControladorEdicion.HabilitarControles(TWC: TWinControl;
EnableFlag: boolean);
var
i: integer;
begin
//Asigno el comportamiento de que el <ENTER> funcione como <TAB> para cambiar
//de campo en los controles de edición. Se hace en forma recursiva para todos
//los controles hijos del frame
//NOTA: No se aplica a los controles con "Tag" <> 0. Esto es para permitir
//indicar ciertos controles que no sean afectados por este procedimiento
//por ejemplo, porque la habilitación se determina por otras circunstancias
with TWC do
begin
for i := 0 to ControlCount - 1 do
begin
//Llamada recursiva
if (Controls[i] is TWinControl) and
((Controls[i] as TWinControl).ControlCount > 0) then
HabilitarControles(Controls[i] as TWinControl, EnableFlag);
if Controls[i].Tag=0 then //Saltea controles con Tag <> 0
Controls[i].Enabled := EnableFlag;
end;
end;
end;
procedure TControladorEdicion.AsignarKeyDown(TWC: TWinControl);
var
i: integer;
begin
//Asigno el comportamiento de que el <ENTER> funcione como <TAB> para cambiar
//de campo en los controles de edición. Se hace en forma recursiva para todos
//los controles hijos del frame
with TWC do
begin
for i := 0 to ControlCount - 1 do
begin
//Llamada recursiva
if (Controls[i] is TWinControl) and
((Controls[i] as TWinControl).ControlCount > 0) then
AsignarKeyDown(Controls[i] as TWinControl);
if (Controls[i] is TCustomEdit) then
(Controls[i] as TCUstomEdit).OnKeyDown := @FDummyControl.CustomKeyDown
else if (Controls[i] is TCustomComboBox) then
(Controls[i] as TCustomComboBox).OnKeyDown := @FDummyControl.CustomKeyDown
else if (Controls[i] is TCustomDateTimePicker) then
(Controls[i] as TCustomDateTimePicker).OnKeyDown := @FDummyControl.CustomKeyDown
//Ver cómo es el comportamiento del Calendar para incluirlo o no
//else if (Controls[i] is TCustomCalendar) then
// (Controls[i] as TCustomCalendar).OnKeyDown := @CustomKeyDown
else if (Controls[i] is TCustomCheckBox) then
(Controls[i] as TCustomCheckBox).OnKeyDown := @FDummyControl.CustomKeyDown;
end;
end;
end;
procedure TControladorEdicion.SetAltaContinua(AValue: boolean);
begin
if FAltaContinua=AValue then Exit;
FAltaContinua:=AValue;
end;
procedure TControladorEdicion.SetAltoBotones(AValue: integer);
begin
if FAltoBotones=AValue then Exit;
FAltoBotones:=AValue;
if FBotonAceptar <> nil then
FBotonAceptar.Height := FAltoBotones;
if FBotonCancelar <> nil then
FBotonCancelar.Height := FAltoBotones;
end;
procedure TControladorEdicion.SetAnchoBotones(AValue: integer);
begin
if FAnchoBotones = AValue then
exit;
FAnchoBotones := AValue;
if FBotonAceptar <> nil then
FBotonAceptar.Width := FAnchoBotones;
if FBotonCancelar <> nil then
FBotonCancelar.Width := FAnchoBotones;
end;
procedure TControladorEdicion.SetBotonAceptar(AValue: TBitBtn);
begin
if FBotonAceptar=AValue then Exit;
FBotonAceptar:=AValue;
if Assigned (FBotonAceptar) then
begin
FBotonAceptar.Caption:=BC_ACEPTAR;
FBotonAceptar.Glyph.Assign(CreateBitmapFromLazarusResource('btce_aceptar'));
FBotonAceptar.Height:=FAltoBotones;
FBotonAceptar.Width:=FAnchoBotones;
end;
end;
procedure TControladorEdicion.SetBotonCancelar(AValue: TBitBtn);
begin
if FBotonCancelar=AValue then Exit;
FBotonCancelar:=AValue;
if Assigned (FBotonCancelar) then
begin
FBotonCancelar.Caption:=BC_CANCELAR;
FBotonCancelar.Glyph.Assign(CreateBitmapFromLazarusResource('btce_cancelar'));
FBotonCancelar.Height:=FAltoBotones;
FBotonCancelar.Width:=FAnchoBotones;
end;
end;
procedure TControladorEdicion.SetControlEncabezado(AValue: TDBText);
begin
if FControlEncabezado=AValue then Exit;
FControlEncabezado:=AValue;
end;
procedure TControladorEdicion.SetControlInicial(AValue: TWinControl);
begin
if FControlInicial=AValue then Exit;
FControlInicial:=AValue;
end;
procedure TControladorEdicion.SetControlMostrarAccion(AValue: TLabel);
begin
if FControlMostrarAccion=AValue then Exit;
FControlMostrarAccion:=AValue;
end;
procedure TControladorEdicion.SetEsSubform(AValue: boolean);
begin
if FEsSubform=AValue then Exit;
FEsSubform:=AValue;
end;
procedure TControladorEdicion.SetIdMaestro(AValue: LongInt);
begin
if FIdMaestro=AValue then Exit;
FIdMaestro:=AValue;
end;
procedure TControladorEdicion.SetOnValidateForm(AValue: TValidateEvent);
begin
if FOnValidateForm=AValue then Exit;
FOnValidateForm:=AValue;
end;
procedure TControladorEdicion.SetPanelEdicion(AValue: TPanel);
begin
if FPanelEdicion=AValue then Exit;
FPanelEdicion:=AValue;
end;
procedure TControladorEdicion.SetQueryGroup(AValue: TSQLQueryGroup);
begin
if FQueryGroup=AValue then Exit;
FQueryGroup:=AValue;
end;
procedure TControladorEdicion.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) then
begin
if (FBotonAceptar <> nil) and (AComponent = BotonAceptar) then
BotonAceptar := nil;
if (FBotonCancelar <> nil) and (AComponent = BotonCancelar) then
BotonCancelar := nil;
if (FControlEncabezado <> nil) and (AComponent = ControlEncabezado) then
ControlEncabezado := nil;
if (FControlInicial <> nil) and (AComponent = ControlInicial) then
ControlInicial := nil;
if (FControlMostrarAccion <> nil) and (AComponent = ControlMostrarAccion) then
ControlMostrarAccion := nil;
if (FPanelEdicion <> nil) and (AComponent = PanelEdicion) then
PanelEdicion := nil;
if (FQueryGroup <> nil) and (AComponent = QueryGroup) then
QueryGroup := nil;
end;
end;
constructor TControladorEdicion.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDummyControl:=TDummyControl.Create(Self);
if (AOwner is TForm) and not (csDesigning in ComponentState) then
begin
FParentForm:=(AOwner as TForm);
//Asigno el evento OnActivate
if Assigned(FParentForm.OnActivate) then
FOldFormActivate:=FParentForm.OnActivate;
FParentForm.OnActivate:=@OnFormActivate;
//Asigno el evento OnCloseQuery
FParentForm.OnCloseQuery:=@OnFormCloseQuery;
end;
FAltoBotones:=26;
FAnchoBotones:=86;
end;
destructor TControladorEdicion.Destroy;
begin
inherited Destroy;
end;
procedure TControladorEdicion.nuevoRegistro(IdRegistroPadre: LongInt=-1);
begin
FIdPadre:=IdRegistroPadre;
FAccion := ED_AGREGAR;
FStrAccion := 'Nuevo registro';
if Assigned(FControlMostrarAccion) then
begin
FControlMostrarAccion.Caption:=FStrAccion;
FControlMostrarAccion.Font.Color := clDefault;
end;
if Assigned(FQueryGroup) and Assigned(FQueryGroup.QueryMaestro) then
begin
//Si es un subform, uso el dataset como está, no tengo que abrir nada
if not FEsSubform then
begin
if FQueryGroup.QueryMaestro.Active then
FQueryGroup.QueryMaestro.Close;
//Seteo el parámetro en (-1) para que no traiga registros, y luego agrego uno
FQueryGroup.QueryMaestro.Params.ParamByName(FQueryGroup.NombreIdMaestro).AsInteger := -1;
FQueryGroup.QueryMaestro.Prepare;
FQueryGroup.QueryMaestro.Open;
//Abro los demás Querys
FQueryGroup.Close;
FQueryGroup.Open;
end;
//Agrego el registro en blanco
FQueryGroup.QueryMaestro.Append;
//Configuro las acciones de los botones según el mode de "Alta continua"
//Configuro los botones
if Assigned (FBotonAceptar) then
begin
if FAltaContinua then
begin
FBotonAceptar.Caption:=BC_GUARDAR;
FBotonAceptar.Glyph.Assign(CreateBitmapFromLazarusResource('btce_guardar'));
FBotonAceptar.OnClick := @GuardarExecute
end
else
begin
FBotonAceptar.Caption:=BC_ACEPTAR;
FBotonAceptar.Glyph.Assign(CreateBitmapFromLazarusResource('btce_aceptar'));
FBotonAceptar.OnClick := @AceptarExecute;
end;
end;
if Assigned (FBotonCancelar) then
begin
if FAltaContinua then
begin
FBotonCancelar.Caption:=BC_SALIR;
FBotonCancelar.Glyph.Assign(CreateBitmapFromLazarusResource('btce_cerrar'));
FBotonCancelar.OnClick := @SalirExecute
end
else
begin
FBotonCancelar.Caption:=BC_CANCELAR;
FBotonCancelar.Glyph.Assign(CreateBitmapFromLazarusResource('btce_cancelar'));
FBotonCancelar.OnClick := @CancelarExecute;
end;
end;
//Habilito todos los controles del panel principal
if Assigned(FPanelEdicion) then;
HabilitarControles(FPanelEdicion, True);
end else
ShowMessage('No se ha indicado la fuente de datos principal');
end;
procedure TControladorEdicion.editarRegistro(id: integer);
begin
FIdMaestro:=id;
AltaContinua := False;
FAccion := ED_MODIFICAR;
if Assigned(FQueryGroup.QueryMaestro) then
begin
//Si es un subform, uso el registro actual, no tengo que abrir nada
if not FEsSubform then
begin
if FQueryGroup.QueryMaestro.Active then
FQueryGroup.QueryMaestro.Close;
FQueryGroup.QueryMaestro.Params.ParamByName(FQueryGroup.NombreIdMaestro).AsInteger := id;
FQueryGroup.QueryMaestro.Prepare;
FQueryGroup.QueryMaestro.Open;
//Abro los demás Querys (los cierro por si estaban abiertos)
FQueryGroup.Close;
FQueryGroup.Open;
end;
FStrAccion := 'Editando';
if Assigned(FControlMostrarAccion) then
begin
FControlMostrarAccion.Caption:=FStrAccion;
FControlMostrarAccion.Font.Color := clDefault;
end;
//Configuro los botones
if Assigned (FBotonAceptar) then
begin
FBotonAceptar.Caption:=BC_ACEPTAR;
FBotonAceptar.Glyph.Assign(CreateBitmapFromLazarusResource('btce_aceptar'));
FBotonAceptar.OnClick := @AceptarExecute;
end;
if Assigned (FBotonCancelar) then
begin
FBotonCancelar.Caption:=BC_CANCELAR;
FBotonCancelar.Glyph.Assign(CreateBitmapFromLazarusResource('btce_cancelar'));
FBotonCancelar.OnClick := @CancelarExecute;
end;
//Habilito todos los controles del panel principal
if Assigned(FPanelEdicion) then
HabilitarControles(FPanelEdicion, True);
end else
ShowMessage('No se ha indicado la fuente de datos principal');
end;
procedure TControladorEdicion.eliminarRegistro(id: integer; MostrarAviso: boolean
);
begin
FAltaContinua := False;
FIdMaestro:=id;
FAccion := ED_ELIMINAR;
if not FEsSubform then
FQueryGroup.Open;
if Assigned(FQueryGroup.QueryMaestro) then
begin
if not FEsSubform then
begin
if FQueryGroup.QueryMaestro.Active then
FQueryGroup.QueryMaestro.Close;
FQueryGroup.QueryMaestro.Params.ParamByName(FQueryGroup.NombreIdMaestro).AsInteger := id;
FQueryGroup.QueryMaestro.Prepare;
FQueryGroup.QueryMaestro.Open;
//Abro los demás Querys
FQueryGroup.Close;
FQueryGroup.Open;
end;
FStrAccion := 'Eliminando';
if Assigned(FControlMostrarAccion) then
begin
FControlMostrarAccion.Caption:=FStrAccion;
FControlMostrarAccion.Font.Color := clRed;
end;
//Configuro los botones
if Assigned (FBotonAceptar) then
begin
FBotonAceptar.Caption:=BC_ELIMINAR;
FBotonAceptar.Glyph.Assign(CreateBitmapFromLazarusResource('btce_eliminar'));
FBotonAceptar.OnClick := @EliminarExecute;
end;
if Assigned (FBotonCancelar) then
begin
FBotonCancelar.Caption:=BC_CANCELAR;
FBotonCancelar.Glyph.Assign(CreateBitmapFromLazarusResource('btce_cancelar'));
FBotonCancelar.OnClick := @CancelarExecute;
end;
//Deshabilito todos los controles del panel principal
if Assigned(FPanelEdicion) then;
HabilitarControles(FPanelEdicion, False);
//Aviso al usuario que se está por eliminar
if MostrarAviso then
begin
MessageDlg('Ha solicitado eliminar los datos mostrados. Luego de cerrar este ' +
'mensaje, si está de acuerdo, confirme la operación presionando el botón ' +
'"Eliminar" del formulario.', mtWarning, [mbClose], 0);
end;
end else
ShowMessage('No se ha indicado la fuente de datos principal');
end;
function TControladorEdicion.NuevoID(tabla: string): longint;
var
ID: integer;
sq:TSQLQuery;
begin
ID := -1;
if tabla <> '' then
begin
//Creo un SQLQuery para obtener el dato desde la base de datos
sq:=TSQLQuery.Create(Self);
try
sq.DataBase:=FQueryGroup.Database;
sq.SQL.Clear;
sq.SQL.Add('SELECT nuevo_id(''' + tabla + ''') as ID');
sq.Open;
if sq.RecordCount = 1 then
begin
ID := sq.FieldByName('ID').AsInteger;
if ID < 1 then
ID := -1;
end;
finally
sq.Free;
end;
end;
Result := ID;
end;
function TControladorEdicion.ShowModal: TModalResult;
begin
if Assigned(FParentForm) then
Result := FParentForm.ShowModal
else
Result:=mrNone;
end;
initialization
{$I bt_controladoredicion.lrs}
{$I mis_componentes.lrs}
end.
|
unit ASDBEdit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, DBCtrls;
type
TAutoSkipEvent = procedure(Sender: TObject; var bSkip : Boolean) of object;
TAutoSkipDBEdit = class(TDBEdit)
private
{ Private declarations }
FAutoSkip : Boolean;
FAutoSkipLength : Integer;
FBeforeSkip: TAutoSkipEvent;
FAfterSkip: TNotifyEvent;
procedure SetAutoSkipLength(const Value : Integer);
protected
{ Protected declarations }
procedure WMChar(); virtual;
procedure SkipToNextControl();
public
{ Public declarations }
procedure WndProc(var Message: TMessage); override;
published
{ Published declarations }
property AutoSkip : Boolean read FAutoSkip write FAutoSkip;
property AutoSkipLength : Integer read FAutoSkipLength write SetAutoSkipLength;
property BeforeSkip : TAutoSkipEvent read FBeforeSkip write FBeforeSkip;
property AfterSkip : TNotifyEvent read FAfterSkip write FAfterSkip;
end;
implementation
uses DB;
procedure TAutoSkipDBEdit.SetAutoSkipLength(const Value : Integer);
begin
if (Value <> FAutoSkipLength) then
begin
if (Assigned(Field)) then
begin
if ((Field.DataType = ftString) and (Value > Field.Size)) then
begin
if (MessageDlg('你設定的AutoSkipLength大於欄位允許的長度: ' + IntToStr(Field.Size) + ' ,要設定成欄位允許的最大長度嗎', mtInformation, [mbYes, mbNo], 0) = mrYes) then
begin
FAutoSkipLength := Field.Size;
end;
end
else
FAutoSkipLength := Value;
end
else
begin
if ((MaxLength <> 0) and (Value > MaxLength)) then
begin
ShowMessage('你設定的AutoSkipLength大於MaxLength的特性值,請檢查');
end
else
FAutoSkipLength := Value;
end;
end;
end;
procedure TAutoSkipDBEdit.SkipToNextControl();
var
aForm : TCustomForm;
aComponent, aFirstComponent : TWinControl;
iCount : Integer;
bFound : Boolean;
begin
// SendMessage(GetParentForm(Self).Handle, WM_NEXTDLGCTL, 0, 0);
bFound := False;
aForm := GetParentForm(Self);
aFirstComponent := TWinControl(aForm.Components[0]);
for iCount := 0 to aForm.ComponentCount - 1 do
begin
if (aForm.Components[iCount] is TWinControl) then
begin
aComponent := TWinControl(aForm.Components[iCount]);
if (aFirstComponent.TabOrder > aComponent.TabOrder) then
aFirstComponent := aComponent;
if ( (Self.TabOrder + 1) = aComponent.TabOrder) then
begin
aComponent.SetFocus;
bFound := True;
break;
end;
end;
end;
if (not bFound) then
aFirstComponent.SetFocus;
end;
procedure TAutoSkipDBEdit.WMChar();
var
bSkip : Boolean;
begin
bSkip := True;
if (Length(Text) >= FAutoSkipLength) then
begin
if Assigned(FBeforeSkip) then
FBeforeSkip(Self, bSkip);
if (bSkip) then
begin
SkipToNextControl();
if Assigned(FAfterSkip) then
FAfterSkip(Self);
end;
end;
end;
procedure TAutoSkipDBEdit.WndProc(var Message: TMessage);
begin
inherited WndProc(Message);
if (FAutoSkip) then
begin
case Message.Msg of
WM_CHAR :
begin
if ((Message.WParam <> VK_DELETE) and (Message.WParam <> VK_BACK)) then
WMChar();
end;
end;
end;
end;
end.
|
{***************************************************************}
{ Copyright (c) 2013 год . }
{ Тетенев Леонид Петрович, ltetenev@yandex.ru }
{ }
{***************************************************************}
unit SpravFileImages;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Imaging.pngimage,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CustomSprav, DBGridEhGrouping, ToolCtrlsEh, Data.DB, FIBDataSet, pFIBDataSet,
PrnDbgeh, Vcl.ExtCtrls, AddActions, Vcl.DBActns, Vcl.ActnList, GridsEh, DBGridEh, Vcl.ComCtrls, Vcl.DBCtrls,
Vcl.OleCtrls, SHDocVw, Vcl.ToolWin, Vcl.ActnMan, Vcl.ActnCtrls;
type
TfrSpravFileImages = class(TfrCustomSprav)
A_ShowImage: TAction;
spImage: TSplitter;
imShowImage: TImage;
procedure A_ShowImageExecute(Sender: TObject);
procedure Q_HostAfterScroll(DataSet: TDataSet);
procedure FormResize(Sender: TObject);
procedure Q_HostEndScroll(DataSet: TDataSet);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
ImageTemp: String;
public
{ Public declarations }
procedure FillHostMenu; override;
end;
implementation
{$R *.dfm}
uses
Prima, ShellList;
procedure TfrSpravFileImages.A_ShowImageExecute(Sender: TObject);
var
FileName: String;
begin
inherited;
if not ( A_ShowImage.Visible and A_ShowImage.Enabled ) then
Exit;
FileName := ImageTemp + Q_Host.FBN( 'FILE_IMAGES_NAME' ).AsString;
TFIBBlobField( Q_Host.FBN( 'FILE_BODY' )).SaveToFile( FileName );
ExecuteFile( 'mspaint.exe', FileName, ImageTemp, SW_SHOW );
end;
procedure TfrSpravFileImages.FillHostMenu;
begin
with frPrima do begin
SetMainMenuList( M_Transact, frPrima.PM,
[ A_Clipboard, A_DsLocation, A_Refresh, A_RefreshFull, A_Sp,
A_SpravAddCopy, A_Sp, A_SpravNew, A_SpravEdit, A_SpravDelete, A_Sp, A_ShowImage, A_Sp, A_ShowDelete,A_Sp,
A_Filtr, A_FiltrClear, A_Sp, A_Print, A_Sp,
A_HostGridSetup, A_ToolBarSetup, A_ShowOfStart, A_Sp, A_AutoWidth, A_Align, A_Sp, A_Close ] );
FillActionBarFromDB( Self, aTbTransact, 'Справочники',
[ A_First, A_Prior, A_Next, A_Last, A_Sp, A_Refresh, A_RefreshFull, A_Sp,
A_SpravNew, A_SpravEdit, A_SpravDelete, A_Sp, A_ShowImage, A_Sp, A_ShowDelete, A_Sp,
A_Filtr, A_FiltrClear, A_Sp, A_Print, A_Sp,
A_HostGridSetup, A_Sp, A_AutoWidth, A_Sp, A_Left, A_Centr, A_Right ] );
end;
end;
procedure TfrSpravFileImages.FormCreate(Sender: TObject);
begin
inherited;
ImageTemp := IncludeTrailingPathDelimiter( frPrima.TempDir ) + 'SpravImages\';
ForceDirectories( ImageTemp );
end;
procedure TfrSpravFileImages.FormResize(Sender: TObject);
begin
inherited;
dbgHost.Width := Self.ClientWidth div 2;
end;
procedure TfrSpravFileImages.Q_HostAfterScroll(DataSet: TDataSet);
begin
inherited;
A_ShowImage.Visible := A_SpravEdit.Visible;
A_ShowImage.Enabled := A_SpravEdit.Enabled;
end;
procedure TfrSpravFileImages.Q_HostEndScroll(DataSet: TDataSet);
var
ImgField: TFIBBlobField;
FileName: String;
begin
inherited;
ImgField:= TFIBBlobField( Q_Host.FBN( 'FILE_BODY' ));
if not ImgField.IsNull then begin
try
FileName := ImageTemp + Q_Host.FBN( 'FILE_IMAGES_NAME' ).AsString;
ImgField.SaveToFile( FileName );
sleep( 50 );
imShowImage.Picture.LoadFromFile( FileName );
finally
end;
end;
imShowImage.Refresh;
end;
end.
|
unit KSHints;
interface
uses Windows, SysUtils, Classes, Controls, Graphics;
const
TenSeconds = 10 * 1000;
type
{
<Class>TKSHintWindow
<What>保证字体和背景颜色正确
<Properties>
-
<Methods>
-
<Event>
-
}
TKSHintWindow = class(THintWindow)
private
protected
procedure Paint; override;
public
end;
THintPosition = (hpAbove, hpBellow, hpAuto);
{
<Class>THintMan
<What>为控件显示hint,机制和Application的不相同。
<Properties>
-
<Methods>
ShowHintFor-在控件的上方显示hint
<Event>
-
}
THintMan = class(TComponent)
private
FHintWindow : TKSHintWindow;
FShowHintTime : LongWord;
FHintActive : Boolean;
FDisplayTime: LongWord;
function GetColor: TColor;
function GetFont: TFont;
procedure SetColor(const Value: TColor);
procedure SetFont(const Value: TFont);
protected
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure DoApplicationMessage(var Msg: TMsg; var Handled: Boolean);
procedure ShowHintFor(Control : TControl; const AHint : string=''; Position : THintPosition=hpAuto);
procedure CloseHint;
published
property DisplayTime : LongWord read FDisplayTime write FDisplayTime default TenSeconds;
property Font : TFont read GetFont write SetFont;
property Color : TColor read GetColor write SetColor default clInfoBk;
end;
TKSHintWindowEx = class(THintWindow)
private
protected
public
procedure ActivateHint(Rect: TRect; const AHint: string); override;
end;
implementation
uses Messages, Forms;
{ THintMan }
constructor THintMan.Create(AOwner: TComponent);
begin
inherited;
FHintWindow := TKSHintWindow.Create(Self);
FHintWindow.Color := clInfoBk;
FDisplayTime := TenSeconds;
end;
destructor THintMan.Destroy;
var
MessageEvent : TMessageEvent;
begin
MessageEvent := Application.OnMessage;
if TMethod(MessageEvent).Data=Self then
Application.OnMessage:=nil;
FreeAndNil(FHintWindow);
inherited;
end;
procedure THintMan.DoApplicationMessage(var Msg: TMsg;
var Handled: Boolean);
begin
if FHintActive then
begin
with Msg do
if ((Message >= WM_KEYFIRST) and (Message <= WM_KEYLAST)) or
((Message = CM_ACTIVATE) or (Message = CM_DEACTIVATE)) or
(Message = CM_APPKEYDOWN) or (Message = CM_APPSYSCOMMAND) or
(Message = WM_COMMAND) or ((Message > WM_MOUSEMOVE) and
(Message <= WM_MOUSELAST)) or (Message = WM_NCMOUSEMOVE)
then
begin
if Message<>WM_KeyUp then
CloseHint;
end else
begin
if GetTickCount>FShowHintTime+FDisplayTime then
CloseHint;
end;
end;
end;
procedure THintMan.ShowHintFor(Control: TControl; const AHint: string; Position : THintPosition);
const
ScreenSpaceMargin = 50;
var
Rect : TRect;
P : TPoint;
HintStr : string;
begin
KillTimer(FHintWindow.Handle,1);
FHintWindow.Canvas.Font := FHintWindow.Font; // call this, assure CalcHintRect is right.
if AHint<>'' then
HintStr := AHint else
HintStr := Control.Hint;
if HintStr='' then
Exit;
Rect := FHintWindow.CalcHintRect(400,HintStr,nil);
P := Control.ClientOrigin;
OffsetRect(Rect,P.X,P.Y);
if Position=hpAuto then
begin
if Screen.Height - Rect.Bottom < ScreenSpaceMargin then
Position := hpAbove else
Position := hpBellow;
end;
case Position of
hpAbove : OffsetRect(Rect,0,-(Rect.Bottom-Rect.Top+4));
hpBellow : OffsetRect(Rect,0,Control.Height);
end;
FHintActive := True;
FHintWindow.ActivateHint(Rect,HintStr);
FShowHintTime := GetTickCount;
SetTimer(FHintWindow.Handle,1,DisplayTime,nil);
end;
procedure THintMan.CloseHint;
begin
FHintActive := False;
if (FHintWindow<> nil) and FHintWindow.HandleAllocated and
IsWindowVisible(FHintWindow.Handle) then
ShowWindow(FHintWindow.Handle, SW_HIDE);
end;
function THintMan.GetColor: TColor;
begin
Result := FHintWindow.Color;
end;
function THintMan.GetFont: TFont;
begin
Result := FHintWindow.Font;
end;
procedure THintMan.SetColor(const Value: TColor);
begin
FHintWindow.Color := Value;
end;
procedure THintMan.SetFont(const Value: TFont);
begin
FHintWindow.Font := Value;
end;
{ TKSHintWindow }
procedure TKSHintWindow.Paint;
var
R: TRect;
begin
Canvas.Font := Font;
Canvas.Brush.Color := Color;
R := ClientRect;
Inc(R.Left, 2);
Inc(R.Top, 2);
DrawText(Canvas.Handle, PChar(Caption), -1, R, DT_LEFT or DT_NOPREFIX or
DT_WORDBREAK or DrawTextBiDiModeFlagsReadingOnly);
end;
{ TKSHintWindowEx }
procedure TKSHintWindowEx.ActivateHint(Rect: TRect; const AHint: string);
var
CursorHeight : Integer;
begin
CursorHeight := GetSystemMetrics(SM_CXCURSOR);
if Rect.Bottom > Screen.DesktopHeight then
begin
OffsetRect(Rect,0,-(Rect.Bottom-Rect.Top)-CursorHeight);
end;
if Rect.Right > Screen.DesktopWidth then
begin
OffsetRect(Rect,-(Rect.Right-Rect.Left)-CursorHeight,0);
end;
inherited ActivateHint(Rect,AHInt);
end;
end.
|
Unit ALM771;
//*********************************************************
// CREADO POR : Abelardo Sulca Palomino
// Nº HPP : HPP_201103_ALM
// FECHA CREACION : 21/03/2011
// DESCRIPCION : Ventana que permite ingresar los criterios de
// consulta para el reporte de Activos Fijos Por Nº de Salida de Almacén
//*********************************************************
// HPC_201701_ALM 23/10/2017 Entrega a Control de Calidad
Interface
Uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, wwdbdatetimepicker, Buttons, ppEndUsr, ppProd,
ppClass, ppReport, ppComm, ppRelatv, ppDB, ppDBPipe, ppBands, ppCache,
ppCtrls, ppPrnabl, ppParameter, ppVar;
Type
TFRptActivosSinSalida = Class(TForm)
lblFechaTras: TLabel;
Label1: TLabel;
Label2: TLabel;
wwDBDateTimePicker_Desde: TwwDBDateTimePicker;
wwDBDateTimePicker_Hasta: TwwDBDateTimePicker;
RadioButton_SinSalida: TRadioButton;
RadioButton_SalidaInicial: TRadioButton;
Z2bbtnImprime: TBitBtn;
ppDBPipeline_ActivosSinSalida: TppDBPipeline;
ppReport_ActivosSinSalida: TppReport;
ppDesigner_ActivosSinSalida: TppDesigner;
Label3: TLabel;
GroupBox1: TGroupBox;
RadioButton_PorCodigoBarra: TRadioButton;
RadioButton_PorCodigoArticulo: TRadioButton;
RadioButton_PorDescripcion: TRadioButton;
RadioButton_SalidaAceptado: TRadioButton;
Procedure Z2bbtnImprimeClick(Sender: TObject);
Procedure FormShow(Sender: TObject);
Private
{ Private declarations }
Public
{ Public declarations }
End;
Var
FRptActivosSinSalida: TFRptActivosSinSalida;
xSQL: String;
Implementation
Uses ALMDM1;
{$R *.dfm}
Procedure TFRptActivosSinSalida.Z2bbtnImprimeClick(Sender: TObject);
Var
ls_sql_ExistsSalida, ls_sql_EstadoSalida, ls_sql_SalidaInicial: String;
ls_rpt_titulo, ls_filtro_fecha: String;
ls_sql_oderBy: String;
Begin
//se modifica el sql de acuerod a los criterios de consulta
If RadioButton_SalidaInicial.Checked Then
Begin
ls_sql_ExistsSalida := ' AND EXISTS (SELECT LOG314.NISSIT FROM LOG314 , LOG315 ';
ls_sql_EstadoSalida := ' ';
ls_sql_SalidaInicial := ' AND SALIDA.NISSIT_S = ' + quotedStr('INICIAL');
ls_rpt_titulo := 'REPORTE ACTIVOS POR Nº DE SALIDA: SALIDA EN ESTADO INICIAL';
End
Else
If RadioButton_SinSalida.Checked Then
Begin
ls_sql_ExistsSalida := ' AND NOT EXISTS (SELECT LOG314.NISSIT FROM LOG314 , LOG315 ';
ls_sql_EstadoSalida := ' ';
ls_sql_SalidaInicial := ' ';
ls_rpt_titulo := 'REPORTE ACTIVOS POR Nº DE SALIDA: ACTIVOS SIN SALIDA';
End
Else
Begin
ls_sql_ExistsSalida := ' AND EXISTS (SELECT LOG314.NISSIT FROM LOG314 , LOG315 ';
ls_sql_EstadoSalida := ' ';
ls_sql_SalidaInicial := ' AND SALIDA.NISSIT_S = ' + quotedStr('ACEPTADO');
ls_rpt_titulo := 'REPORTE ACTIVOS POR Nº DE SALIDA: SALIDA EN ESTADO ACEPTADO';
End;
//ordenado por
If RadioButton_PorCodigoBarra.Checked Then
Begin
ls_sql_oderBy := ' ORDER BY LOG332.Codbar ';
End
Else
If RadioButton_PorCodigoArticulo.Checked Then
Begin
ls_sql_oderBy := ' ORDER BY LOG332.Artid , LOG332.Codbar ';
End
Else
Begin
ls_sql_oderBy := ' ORDER BY LOG332.Artdes ';
End;
ls_filtro_fecha := 'Desde: ' + datetostr(wwDBDateTimePicker_Desde.date) + ' Hasta: ' + datetostr(wwDBDateTimePicker_Hasta.date);
xSQL := ' SELECT LOG332.Codbar CODIGO_BARRA, LOG332.Artid CODIGO_ARTICULO, LOG332.Artdes DESCRIPCION_ARTICULO, ' +
' LOG332.Nisatip TIPO_INGRESO, ' +
' LOG332.NISAID NUMERO_INGRESO, ' +
' LOG332.Nifecha FECHA_INGRESO, ' +
' LOG332.Tdaid2 TIPO_SALIDA, ' +
' LOG332.Nfac NUMERO_SALIDA, ' +
' SALIDA.NISSIT_S ESTADO_SALIDA, ' +
' SALIDA.NISAFREG_S FECHA_SALIDA, ' +
' LOG332.Otrndoc NUMERO_TRASLADO, ' +
' TRASLADO.FECTRAS_1 FECHA_TRASLADO, ' +
' TRASLADO.LOCAL_D_1 COD_LOCALIDAD_DESTINO, ' +
' TRASLADO.LOCDES_D_1 DESC_LOCALIDAD_DESTINO, ' +
QuotedStr(ls_filtro_fecha) + ' RANGO_FECHA, ' +
QuotedStr(DMALM.wUsuario) + ' USUARIO_IMPRIME, ' +
QuotedStr(ls_rpt_titulo) + ' REPORTE_TITULO ' +
' FROM LOG332, ' +
'(SELECT ACF321.ARTCODBAR ARTCODBAR_1, ACF320.NUMDOC NUMDOC_1, ' +
' ACF320.FECTRAS FECTRAS_1, ACF320.LOCAL_D LOCAL_D_1, ' +
' ACF320.LOCDES_D LOCDES_D_1 ' +
' FROM ACF320, ACF321 ' +
' WHERE ACF320.DOCREF = ACF321.DOCREF ' +
' AND ACF320.NUMDOC = ACF321.NUMDOC) TRASLADO, ' +
' (SELECT LOG314.CIAID CIAID_S, ' +
' LOG314.LOCID LOCID_S, ' +
' LOG314.TINID TINID_S, ' +
' LOG314.ALMID ALMID_S, ' +
' LOG314.TDAID TDAID_S, ' +
' LOG314.NISAID NISAID_S, ' +
' LOG315.ARTID ARTID_S, ' +
' LOG314.NISSIT NISSIT_S, ' +
' LOG314.NISAFREG NISAFREG_S ' +
' FROM LOG314 , LOG315 ' +
' WHERE LOG314.CIAID = LOG315.CIAID ' +
' AND LOG314.LOCID = LOG315.LOCID ' +
' AND LOG314.TINID = LOG315.TINID ' +
' AND LOG314.ALMID = LOG315.ALMID ' +
' AND LOG314.TDAID = LOG315.TDAID ' +
' AND LOG314.NISAID = LOG315.NISAID ' +
' AND LOG314.NISATIP = LOG315.NISATIP ' +
' AND LOG314.NISATIP = ' + quotedstr('SALIDA') + ') SALIDA ' +
' WHERE LOG332.NISSIT = ' + quotedstr('ACEPTADO') + ' ' +
' AND LOG332.CODBAR = TRASLADO.ARTCODBAR_1(+) ' +
' AND LOG332.Otrndoc = TRASLADO.NUMDOC_1(+) ' +
' AND LOG332.CIAID = SALIDA.CIAID_S(+) ' +
' AND LOG332.LOCID = SALIDA.LOCID_S(+) ' +
' AND LOG332.TINID = SALIDA.TINID_S(+) ' +
' AND LOG332.ALMID = SALIDA.ALMID_S(+) ' +
' AND LOG332.Tdaid2 = SALIDA.TDAID_S(+) ' +
' AND LOG332.Nfac = SALIDA.NISAID_S(+) ' +
' AND LOG332.ARTID = SALIDA.ARTID_S(+) ' +
ls_sql_ExistsSalida + //' AND NOT EXISTS (SELECT LOG314.NISSIT FROM LOG314 , LOG315 '+
' WHERE LOG314.CIAID = LOG315.CIAID ' +
' AND LOG314.LOCID = LOG315.LOCID ' +
' AND LOG314.TINID = LOG315.TINID ' +
' AND LOG314.ALMID = LOG315.ALMID ' +
' AND LOG314.TDAID = LOG315.TDAID ' +
' AND LOG314.NISAID = LOG315.NISAID ' +
' AND LOG314.NISATIP = LOG315.NISATIP ' +
' AND LOG314.CIAID = LOG332.CIAID ' +
' AND LOG314.LOCID = LOG332.LOCID ' +
' AND LOG314.TINID = LOG332.TINID ' +
' AND LOG314.ALMID = LOG332.ALMID ' +
' AND LOG314.TDAID = LOG332.Tdaid2 ' +
' AND LOG314.NISAID = LOG332.Nfac ' +
' AND LOG315.ARTID = LOG332.ARTID ' +
ls_sql_EstadoSalida + //AND LOG314.NISSIT = 'ACEPTADO'
' AND LOG314.NISATIP = ' + quotedstr('SALIDA') + ' ) ' +
' AND (LOG332.Nifecha >= TO_DATE(' + quotedStr(datetostr(wwDBDateTimePicker_Desde.date)) + ', ' + quotedStr('DD/MM/YYYY') + ')' +
' AND LOG332.Nifecha <= TO_DATE(' + quotedStr(datetostr(wwDBDateTimePicker_Hasta.date)) + ', ' + quotedStr('DD/MM/YYYY') + '))' +
ls_sql_SalidaInicial + //AND SALIDA.NISSIT_S = 'INICIAL'
ls_sql_oderBy;
DMALM.cdsQry8.Close;
DMALM.cdsQry8.DataRequest(xSQL);
DMALM.cdsQry8.Open;
If DMALM.cdsQry8.RecordCount = 0 Then
Begin
showmessage('No se recuperó ningún registro');
exit;
End;
ppDBPipeline_ActivosSinSalida.DataSource := DMALM.dsQry8;
ppReport_ActivosSinSalida.DataPipeline := ppDBPipeline_ActivosSinSalida;
ppReport_ActivosSinSalida.Template.FileName := wRutaRpt + '\ActivosSinSalida.rtm';
ppReport_ActivosSinSalida.Template.LoadFromFile;
//para mostrar el diseñador del reporte
//ppDesigner_ActivosSinSalida.Report := ppReport_ActivosSinSalida ;
//ppDesigner_ActivosSinSalida.ShowModal() ;
ppReport_ActivosSinSalida.Print;
End;
Procedure TFRptActivosSinSalida.FormShow(Sender: TObject);
Begin
wwDBDateTimePicker_Desde.Date := Now;
wwDBDateTimePicker_Hasta.Date := Now;
End;
End.
|
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//<< 文件名:uRockPressClass.pas <<
//<< lulei使用的个人Delphi文件 <<
//<< 该文件是pressureClass.dll delphi 引用文件 <<
//<< 该文件与 dll文件一同发布,dll不需要注册使用 <<
//<< 创建日期:2016.5.12 <<
//<< 2017.11.9 对数据的步距算法做了更改
//<< 2017.12.4 修改了接口函数的字符类型 <<
//<< 更改了RealTimeFootAge 与 Inputdata 的返回值 <<
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
unit uIRockPress;
interface
uses Classes;
type
TDefine_RockPress = class (TObject)
protected
public
//20180411
procedure SetStatuesCaption(Value:PansiChar); virtual;abstract;
function CreateBatInputD(AHandle:THandle;Caption:Pansichar;Width,Heigth,Flag:integer):THandle; virtual;abstract;
function CreateEditFootage_Data(AHandle:THandle;Caption:Pansichar;Width,Heigth,Flag:integer):THandle; virtual;abstract;
function CreateRockPressGraph(AHandle:THandle;Caption:Pansichar;Width,Heigth,Flag:integer):THandle; virtual;abstract;
function CreateEditJinDao(AHandle:THandle;Caption:Pansichar;Width,Heigth,Flag:integer):THandle; virtual;abstract;
function CreateRockLineGraph(AHandle:THandle;Caption:Pansichar;Width,Heigth,Flag:integer):THandle; virtual;abstract;
procedure SetPublic_BasicLicending(Value:Boolean;UName:Pansichar); virtual;abstract;
procedure CloseRockPressTool; virtual;abstract;
//
function GetWinFormIsExsit(WinName:Pansichar):Boolean;virtual;abstract;
function CloseActiveForm(FormStr:Pansichar):Boolean; virtual;abstract;
function SetOpenFormChangeParentPanel(WinName:Pansichar;AHandle:THandle):Boolean; virtual;abstract;
function OpenConTourChildForm(WinName:Pansichar;AHandle:THandle;Width,Heigth:integer):Boolean; virtual;abstract;
procedure GetMinAndMaxJinDao(var MinD,MaxD:integer); virtual;abstract;
//系统函数
constructor Create; virtual;abstract;
end;
TClassStateMent_RockPress = class of TDefine_RockPress;
implementation
//no context
{ TIRockPress }
end.
|
unit BasicTests;
interface
uses
DUnitX.TestFramework;
type
[TestFixture]
TBasicTests = class(TObject)
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure BasicSerializeTest;
[Test]
procedure BasicDeserializeTest;
end;
implementation
uses DelphiJSON, System.JSON, JSONComparer;
const
notSerText = 'not (de)serialized';
type
[DJSerializable]
TTestClass = class(TObject)
[DJValue('textField')]
testText: string;
testTextNotSer: string;
[DJValue('boolField')]
testBool: boolean;
[DJValue('int')]
testInt: Integer;
createdThroughJSON: boolean;
constructor Create;
[DJConstructor]
constructor CreateJSON;
end;
procedure TBasicTests.Setup;
begin
end;
procedure TBasicTests.TearDown;
begin
end;
procedure TBasicTests.BasicDeserializeTest;
const
res = '{"textField": "testText1", "boolField": true, "int": 123}';
var
tmp: TTestClass;
begin
tmp := DelphiJSON<TTestClass>.Deserialize(res);
Assert.AreEqual('testText1', tmp.testText);
Assert.AreEqual(true, tmp.testBool);
Assert.AreEqual(123, tmp.testInt);
Assert.AreEqual(notSerText, tmp.testTextNotSer);
Assert.IsTrue(tmp.createdThroughJSON);
tmp.Free;
end;
procedure TBasicTests.BasicSerializeTest;
const
res = '{"textField": "testText1", "boolField": true, "int": 123}';
var
t: TTestClass;
ser: string;
obj1: TJSONValue;
obj2: TJSONValue;
begin
t := TTestClass.Create;
t.testText := 'testText1';
t.testBool := true;
t.testInt := 123;
Assert.IsFalse(t.createdThroughJSON);
obj1 := DelphiJSON<TTestClass>.SerializeJ(t);
ser := obj1.ToJSON;
t.Free;
obj2 := TJSONObject.ParseJSONValue(res, false, true);
Assert.IsTrue(JSONEquals(obj1, obj2));
obj1.Free;
obj2.Free;
end;
{ TTestClass }
constructor TTestClass.Create;
begin
createdThroughJSON := false;
testTextNotSer := notSerText;
end;
constructor TTestClass.CreateJSON;
begin
createdThroughJSON := true;
testTextNotSer := notSerText;
end;
initialization
TDUnitX.RegisterTestFixture(TBasicTests);
end.
|
unit MainFormU;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Threading, 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.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys,
FireDAC.Phys.IB, FireDAC.Phys.IBDef, FireDAC.VCLUI.Wait, Vcl.StdCtrls,
Vcl.ExtCtrls, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.DataSet,
System.Generics.Collections;
type
IStockInfo = interface
['{6FAB5F5A-C5DF-45ED-B74B-AF0977514A13}']
function GetName: String;
function GetPercentage: Single;
function GetValue: Currency;
function ToString: String;
end;
TStockInfo = class(TInterfacedObject, IStockInfo)
private
FName: string;
FPercentage: Single;
FValue: Currency;
protected
function GetName: String;
function GetPercentage: Single;
function GetValue: Currency;
public
function ToString: String; override;
constructor Create(Name: String; Percentage: Single;
Value: Currency);
end;
TStockMonitor = class
private
FStockSymbol: string;
FFuture: IFuture<IStockInfo>;
procedure StartFuture;
function GetStockInfo(const Row: String): IStockInfo;
const
YAHOO_URL = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=snl1p2';
public
constructor Create(StockSymbol: String);
function GetFuture: IFuture<IStockInfo>;
function GetStockSymbol: String;
end;
TForm1 = class(TForm)
mmNames: TMemo;
Timer1: TTimer;
Panel1: TPanel;
Button3: TButton;
lbResults: TListBox;
edtStock: TEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button3Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
FValue: IFuture<Integer>;
FQuotes: TObjectDictionary<String, TStockMonitor>;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
System.Net.HttpClient;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
FValue := TTask.Future<Integer>(
function: Integer
begin
Sleep(Random(2000) + 1000);
Result := Random(100);
end);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if FValue.Wait(1) then
Caption := FValue.Value.ToString;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
I: Integer;
begin
if FQuotes.Count > 0 then
begin
end
else
begin
lbResults.Clear;
for I := 0 to mmNames.Lines.Count - 1 do
begin
if not mmNames.Lines[I].Trim.IsEmpty then
begin
FQuotes.Add(mmNames.Lines[I], TStockMonitor.Create(mmNames.Lines[I]));
lbResults.Items.Add('Wait...');
end
end;
end;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FQuotes.Free;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FQuotes := TObjectDictionary<String, TStockMonitor>.Create([doOwnsValues]);
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
Pair: TPair<String, TStockMonitor>;
LIdx: Integer;
begin
for Pair in FQuotes do
begin
if Pair.Value.GetFuture.Wait(1) then
begin
LIdx := mmNames.Lines.IndexOf(Pair.Key);
if LIdx > -1 then
lbResults.Items[LIdx] :=
Pair.Value.GetFuture.Value.ToString + ' - YOUR VALUE = $' +
FormatCurr('###,##0.00', Pair.Value.GetFuture.Value.GetValue *
StrToInt(edtStock.Text));
end;
end;
end;
{ TStockInfo }
constructor TStockMonitor.Create(StockSymbol: String);
begin
inherited Create;
FStockSymbol := StockSymbol;
StartFuture;
end;
function TStockMonitor.GetFuture: IFuture<IStockInfo>;
begin
Result := FFuture;
end;
function TStockMonitor.GetStockInfo(const Row: String): IStockInfo;
var
LPieces: TArray<String>;
LName: string;
LPerc: Single;
LValue: Single;
LFormatSettings: TFormatSettings;
begin
LFormatSettings.DecimalSeparator := '.';
LPieces := Row.Split([','], '"', '"', 4, TStringSplitOptions.None);
LName := LPieces[1].DeQuotedString('"');
LPerc := StrToCurr(LPieces[3].Trim.DeQuotedString('"').Replace('%', ''),
LFormatSettings);
LValue := StrToFloat(LPieces[2], LFormatSettings);
Result := TStockInfo.Create(
LName,
LPerc,
LValue
);
end;
function TStockMonitor.GetStockSymbol: String;
begin
Result := FStockSymbol;
end;
procedure TStockMonitor.StartFuture;
begin
FFuture := TTask.Future<IStockInfo>(
function: IStockInfo
var
LHTTPClient: THTTPClient;
LResp: IHTTPResponse;
LRow: string;
begin
LHTTPClient := THTTPClient.Create;
try
LResp := LHTTPClient.Get(Format(YAHOO_URL, [FStockSymbol]));
if LResp.StatusCode = 200 then
begin
LRow := LResp.ContentAsString(TEncoding.ANSI);
Result := GetStockInfo(LRow);
end
else
begin
// Result := ;
end;
finally
LHTTPClient.Free;
end;
end);
end;
{ TStockInfo }
constructor TStockInfo.Create(Name: String; Percentage: Single;
Value: Currency);
begin
inherited Create;
FName := Name;
FPercentage := Percentage;
FValue := Value;
end;
function TStockInfo.GetName: String;
begin
Result := FName;
end;
function TStockInfo.GetPercentage: Single;
begin
Result := FPercentage;
end;
function TStockInfo.GetValue: Currency;
begin
Result := FValue;
end;
function TStockInfo.ToString: String;
begin
Result :=
Format('%s $%2.2f [%2.2f%%]', [FName, FValue, FPercentage]);
end;
end.
|
unit frameBuscaCFOP;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, CFOP, Especificacao,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.Mask, RxToolEdit, RxCurrEdit;
type
TBuscaCFOP = class(TFrame)
edtCodigo: TCurrencyEdit;
StaticText1: TStaticText;
edtCFOP: TEdit;
btnBusca: TBitBtn;
edtDescricao: TEdit;
StaticText2: TStaticText;
procedure edtCFOPChange(Sender: TObject);
procedure edtCFOPEnter(Sender: TObject);
procedure edtCFOPExit(Sender: TObject);
procedure btnBuscaClick(Sender: TObject);
procedure edtDescricaoEnter(Sender: TObject);
procedure edtDescricaoExit(Sender: TObject);
procedure edtCFOPKeyPress(Sender: TObject; var Key: Char);
private
FCriou :Boolean;
FBuscando :Boolean;
FCFOP :TCFOP;
Fcodigo :integer;
FEspecificacao: TEspecificacao;
private
procedure SetCodigo (const Value: integer);
private
procedure Buscar (const CodigoCFOP :Integer);
procedure SetCFOP (const Value :TCFOP);
function buscaPorEspecificacao(codigoCFOP :String) :Integer;
procedure SetEspecificacao(const Value: TEspecificacao);
public
constructor Create(AOwner :TComponent); override;
destructor Destroy; override;
public
procedure Limpa;
public
property CFOP :TCFOP read FCFOP write SetCFOP;
property codigo :integer read Fcodigo write SetCodigo;
property Especificacao :TEspecificacao read FEspecificacao write SetEspecificacao;
end;
implementation
uses Repositorio, FabricaRepositorio, uCadastroCFOP, EspecificacaoCFOPporCodigoCFOP;
{$R *.dfm}
{ TBuscaCFOP }
procedure TBuscaCFOP.btnBuscaClick(Sender: TObject);
begin
self.Buscar(0);
end;
function TBuscaCFOP.buscaPorEspecificacao(codigoCFOP: String): Integer;
var especificao :TEspecificacaoCFOPporCodigoCFOP;
repositorio :TRepositorio;
begin
try
result := 0;
repositorio := TFabricaRepositorio.GetRepositorio(TCFOP.ClassName);
especificao := TEspecificacaoCFOPporCodigoCFOP.Create(codigoCFOP);
try
result := TCFOP(repositorio.GetPorEspecificacao(especificao)).codigo;
Except
end;
finally
FreeAndNil(repositorio);
FreeAndNil(especificao);
end;
end;
procedure TBuscaCFOP.Buscar(const CodigoCFOP: Integer);
var
Repositorio :TRepositorio;
CFOP :TCFOP;
begin
Repositorio := nil;
try
Repositorio := TFabricaRepositorio.GetRepositorio(TCFOP.ClassName);
CFOP := TCFOP(Repositorio.Get(CodigoCFOP));
{ Se tiver setado especificação pra esse frame então o objeto DEVE atender a especificação }
if Assigned(CFOP) and
Assigned(self.FEspecificacao) and
(not self.FEspecificacao.SatisfeitoPor(CFOP)) then
FreeAndNil(CFOP);
if not Assigned(CFOP) then begin
frmCadastroCFOP := nil;
try
frmCadastroCFOP := TfrmCadastroCFOP.CreateModoBusca(nil);
frmCadastroCFOP.ShowModal;
if (frmCadastroCFOP.ModalResult = mrOK) then begin
CFOP := TCFOP(Repositorio.Get(frmCadastroCFOP.cdsCODIGO.AsInteger));
if Assigned(CFOP) then begin
self.CFOP := CFOP;
self.FCriou := true;
keybd_event(VK_TAB, 0, 0, 0);
end;
end
else begin
if edtDescricao.Text = '' then
self.Limpa;
edtCFOP.SetFocus;
end;
finally
frmCadastroCFOP.Release;
frmCadastroCFOP := nil;
end;
end
else begin
self.CFOP := CFOP;
self.FCriou := true;
end;
finally
FreeAndNil(Repositorio);
end;
end;
constructor TBuscaCFOP.Create(AOwner: TComponent);
begin
inherited;
self.FCFOP := nil;
self.FCriou := false;
self.FEspecificacao := nil;
end;
destructor TBuscaCFOP.Destroy;
begin
if self.FCriou and Assigned(self.FCFOP) then
FreeAndNil(self.FCFOP);
FreeAndNil(self.FEspecificacao);
inherited;
end;
procedure TBuscaCFOP.edtCFOPChange(Sender: TObject);
begin
Limpa;
end;
procedure TBuscaCFOP.edtCFOPEnter(Sender: TObject);
begin
self.FBuscando := true;
end;
procedure TBuscaCFOP.edtCFOPExit(Sender: TObject);
begin
self.FBuscando := false;
end;
procedure TBuscaCFOP.edtCFOPKeyPress(Sender: TObject; var Key: Char);
begin
If not( key in['0'..'9',#08] ) then
key:=#0;
end;
procedure TBuscaCFOP.edtDescricaoEnter(Sender: TObject);
begin
keybd_event(VK_TAB, 0, 0, 0);
end;
procedure TBuscaCFOP.edtDescricaoExit(Sender: TObject);
begin
self.Buscar( buscaPorEspecificacao(edtCFOP.Text) );
end;
procedure TBuscaCFOP.Limpa;
begin
if Self.FCriou and Assigned(self.FCFOP) then
FreeAndNil(self.FCFOP);
self.edtCodigo.Clear;
if not FBuscando then
begin
edtCFOP.OnChange := nil;
self.edtCFOP.Clear;
edtCFOP.OnChange := edtCFOPChange;
end;
self.edtDescricao.Clear;
end;
procedure TBuscaCFOP.SetCodigo(const Value: integer);
begin
if value > 0 then
self.Buscar( Value )
else
self.Limpa;
end;
procedure TBuscaCFOP.SetEspecificacao(const Value: TEspecificacao);
begin
if Assigned(self.FEspecificacao) and Assigned(Value) then
FreeAndNil(self.FEspecificacao);
FEspecificacao := Value;
end;
procedure TBuscaCFOP.SetCFOP(const Value: TCFOP);
begin
try
if (Value = self.FCFOP) then
exit;
except
on E: EAccessViolation do
end;
if self.FCriou and Assigned(self.FCFOP) then begin
FreeAndNil(self.FCFOP);
self.FCriou := false;
end;
FCFOP := Value;
if Assigned(self.FCFOP) then begin
self.edtCFOP.OnChange := nil;
self.edtCodigo.AsInteger := self.FCFOP.codigo;
self.edtCFOP.Text := self.FCFOP.cfop;
self.edtDescricao.Text := self.FCFOP.descricao;
self.edtCFOP.OnChange := edtCFOPChange;
end;
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.Loggers.Text;
interface
{$I DUnitX.inc}
uses
{$IFDEF USE_NS}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
DUnitX.TestFramework;
type
// Simple text file logger.
TDUnitXTextFileLogger = class(TInterfacedObject, ITestLogger)
private
//FFileName : string;
protected
procedure OnTestingStarts(const threadId: TThreadID; testCount, testActiveCount: Cardinal);
procedure OnStartTestFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
procedure OnSetupFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
procedure OnEndSetupFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
procedure OnBeginTest(const threadId: TThreadID; const Test: ITestInfo);
procedure OnSetupTest(const threadId: TThreadID; const Test: ITestInfo);
procedure OnEndSetupTest(const threadId: TThreadID; const Test: ITestInfo);
procedure OnExecuteTest(const threadId: TThreadID; const Test: ITestInfo);
procedure OnTestSuccess(const threadId: TThreadID; const Test: ITestResult);
procedure OnTestError(const threadId: TThreadID; const Error: ITestError);
procedure OnTestFailure(const threadId: TThreadID; const Failure: ITestError);
procedure OnTestIgnored(const threadId: TThreadID; const AIgnored: ITestResult);
procedure OnTestMemoryLeak(const threadId: TThreadID; const Test: ITestResult);
procedure OnLog(const logType: TLogLevel; const msg : string);
procedure OnTeardownTest(const threadId: TThreadID; const Test: ITestInfo);
procedure OnEndTeardownTest(const threadId: TThreadID; const Test: ITestInfo);
procedure OnEndTest(const threadId: TThreadID; const Test: ITestResult);
procedure OnTearDownFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
procedure OnEndTearDownFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
procedure OnEndTestFixture(const threadId: TThreadID; const results: IFixtureResult);
procedure OnTestingEnds(const RunResults: IRunResults);
public
constructor Create(const AFileName: string; const overwrite : boolean = true);
end;
implementation
uses
{$IFDEF DELPHI_2010}
DUnitX.Exceptions, //ENotImplemented is not in SysUtils in D2010
{$ENDIF}
{$IFDEF USE_NS}
System.SysUtils;
{$ELSE}
SysUtils;
{$ENDIF}
{ TDUnitXTextFileLogger }
constructor TDUnitXTextFileLogger.Create(const AFileName : string; const overwrite : boolean);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnEndSetupFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnEndSetupTest(const threadId: TThreadID; const Test: ITestInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnEndTearDownFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnEndTeardownTest(const threadId: TThreadID; const Test: ITestInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnEndTest(const threadId: TThreadID; const Test: ITestResult);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnEndTestFixture(const threadId: TThreadID; const results: IFixtureResult);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnExecuteTest(const threadId: TThreadID; const Test: ITestInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnTestError(const threadId: TThreadID; const Error: ITestError);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnTestFailure(const threadId: TThreadID; const Failure: ITestError);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnTestIgnored(const threadId: TThreadID; const AIgnored: ITestResult);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnLog(const logType : TLogLevel; const msg: string);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnSetupFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnSetupTest(const threadId: TThreadID; const Test: ITestInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnBeginTest(const threadId: TThreadID; const Test: ITestInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnStartTestFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnTestSuccess(const threadId: TThreadID; const Test: ITestResult);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnTearDownFixture(const threadId: TThreadID; const fixture: ITestFixtureInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnTeardownTest(const threadId: TThreadID; const Test: ITestInfo);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnTestingEnds(const RunResults: IRunResults);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnTestingStarts(const threadId: TThreadID; testCount, testActiveCount : Cardinal);
begin
raise ENotImplemented.Create('Not Implemented');
end;
procedure TDUnitXTextFileLogger.OnTestMemoryLeak(const threadId: TThreadID; const Test: ITestResult);
begin
raise ENotImplemented.Create('Not Implemented');
end;
end.
|
unit OAuth2.Entity.AuthCode;
interface
uses
OAuth2.Contract.Entity.AuthCode,
OAuth2.Entity.Token;
type
TOAuth2AuthCodeEntity = class(TOAuth2TokenEntity, IOAuth2AuthCodeEntity)
private
{ private declarations }
FRedirectUri: string;
protected
{ protected declarations }
public
{ public declarations }
constructor Create(ARedirectUri: string);
function GetRedirectUri: string;
procedure SetRedirectUri(AUri: string);
class function New(ARedirectUri: string): IOAuth2AuthCodeEntity;
end;
implementation
{ TOAuth2AuthCodeEntity }
constructor TOAuth2AuthCodeEntity.Create(ARedirectUri: string);
begin
FRedirectUri := ARedirectUri;
end;
function TOAuth2AuthCodeEntity.GetRedirectUri: string;
begin
Result := FRedirectUri;
end;
class function TOAuth2AuthCodeEntity.New(ARedirectUri: string): IOAuth2AuthCodeEntity;
begin
Result := TOAuth2AuthCodeEntity.Create(ARedirectUri);
end;
procedure TOAuth2AuthCodeEntity.SetRedirectUri(AUri: string);
begin
FRedirectUri := AUri;
end;
end.
|
unit VariantListUnit;
interface
uses
ClonableUnit,
SysUtils,
Classes;
type
TVariantList = class;
TVariantListEnumerator = class (TListEnumerator)
protected
function GetCurrentVariant: Variant;
constructor Create(VariantList: TVariantList);
public
property Current: Variant read GetCurrentVariant;
end;
TVariantList = class (TList)
strict protected
function GetVariantByIndex(Index: Integer): Variant;
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
constructor Create;
constructor CreateFrom(
Variants: array of Variant
); overload;
constructor CreateFrom(Variants: Variant); overload;
procedure Clear; override;
function IsEmpty: Boolean;
function GetEnumerator: TVariantListEnumerator;
function IndexOf(Value: Variant): Integer;
function Add(Value: Variant): Integer; overload;
function AddObject(Instance: TObject): Integer;
procedure Remove(Value: Variant);
function ExtractFirst: Variant;
function ExtractLast: Variant;
function Contains(Value: Variant): Boolean;
function Clone: TVariantList;
property Items[Index: Integer]: Variant read GetVariantByIndex; default;
end;
implementation
uses Variants, VariantTypeUnit;
{ TVariantListEnumerator }
constructor TVariantListEnumerator.Create(VariantList: TVariantList);
begin
inherited Create(VariantList);
end;
function TVariantListEnumerator.GetCurrentVariant: Variant;
begin
Result := TVariant(GetCurrent).Value;
end;
{ TVariantList }
function TVariantList.Add(Value: Variant): Integer;
var VariantWrapper: TVariant;
begin
VariantWrapper := nil;
try
VariantWrapper := TVariant.Create(Value);
Result := Add(VariantWrapper);
except
FreeAndNil(VariantWrapper);
raise;
end;
end;
function TVariantList.AddObject(Instance: TObject): Integer;
var ObjectVariant: Variant;
begin
TVarData(ObjectVariant).VType := varByRef;
TVarData(ObjectVariant).VPointer := Instance;
Add(ObjectVariant);
end;
procedure TVariantList.Clear;
begin
inherited;
end;
function TVariantList.Clone: TVariantList;
var VariantItem: Variant;
ClonedVariantList: TVariantList;
begin
Result := TVariantList.Create;
ClonedVariantList := Result as TVariantList;
try
for VariantItem in Self do
ClonedVariantList.Add(VariantItem);
except
on e: Exception do begin
FreeAndNil(Result);
raise;
end;
end;
end;
function TVariantList.Contains(Value: Variant): Boolean;
var CurrentValue: Variant;
begin
for CurrentValue in Self do
if CurrentValue = Value then begin
Result := True;
Exit;
end;
Result := False;
end;
constructor TVariantList.Create;
begin
inherited;
end;
constructor TVariantList.CreateFrom(Variants: Variant);
var I, Low, High: Integer;
begin
Create;
if not VarIsArray(Variants) then
Add(Variants)
else begin
Low := VarArrayLowBound(Variants, 1);
High := VarArrayHighBound(Variants, 1);
for I := Low to High do
Add(Variants[I]);
end;
end;
constructor TVariantList.CreateFrom(Variants: array of Variant);
var VariantValue:Variant;
begin
Create;
for VariantValue in Variants do
Add(VariantValue);
end;
function TVariantList.ExtractFirst: Variant;
begin
Result := Self[0];
Delete(0);
end;
function TVariantList.ExtractLast: Variant;
begin
Result := Self[Count - 1];
Delete(Count - 1);
end;
function TVariantList.GetEnumerator: TVariantListEnumerator;
begin
Result := TVariantListEnumerator.Create(Self);
end;
function TVariantList.GetVariantByIndex(Index: Integer): Variant;
begin
Result := TVariant(Get(Index)).Value;
end;
function TVariantList.IndexOf(Value: Variant): Integer;
begin
for Result := 0 to Count - 1 do
if Self[Result] = Value then
Exit;
Result := -1;
end;
function TVariantList.IsEmpty: Boolean;
begin
Result := Count = 0;
end;
procedure TVariantList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if Action = lnDeleted then
TVariant(Ptr).Free;
end;
procedure TVariantList.Remove(Value: Variant);
var ValueIndex: Integer;
begin
ValueIndex := IndexOf(Value);
if ValueIndex >= 0 then
Delete(ValueIndex);
end;
end.
|
{
Implemente um programa em que o computador identifique um animal vertebrado entre 5 possibilides
(urso, avestruz, salmão, tartaruga e sapo). A ideia é que o usuário responda a algumas perguntas
com base na topologia da árvore de decisão abaixo, para que o computador faça a classificação
correta. Exemplo: O computador pergunta se o animal possui sangue quente, se o usuário responder
afirmativamente, então a próxima pergunta é se o animal é mamífero, se a resposta for negativa,
então trata-se de uma avestruz.
Vertebrados
|
----------------------------------------------------
| |
Sangue Quente Sangue Frio
| |
----------------- ---------------------------------
| | | | |
Mamíferos Pássaros Peixes Répteis Anfíbios
| | | | |
Urso Avestruz Salmão Tartaruga Sapo
}
program Vertebrados;
Uses Crt;
var
valSangue, valQuente, valFrio : Integer;
begin
writeln ('O animal possui sangue 1 (frio) ou 2 (quente)?');
readln (valSangue);
if (valSangue = 1) then
begin
writeln ('O animal eh um 1 (peixe), 2 (reptil) ou 3 (anfibio)?');
readln (valFrio);
if (valFrio = 1) then
writeln ('Ao que tudo indica o animal informado eh um SALMAO')
else
if (valFrio = 2) then
writeln ('Ao que tudo indica o animal informado eh um TARTARUGA')
else
if (valFrio = 3) then
writeln ('Ao que tudo indica o animal informado eh um SAPO')
end
else
if (valSangue = 2) then
begin
writeln ('O animal eh um 1 (mamifero) ou um 2 (passaro?)');
readln (valQuente);
if (valQuente = 1) then
writeln ('Ao que tudo indica o animal informado eh um URSO')
else
if (valQuente = 2) then
writeln ('Ao que tudo indica o animal informado eh um AVESTRUZ')
end
else
if (valSangue <1) or (valSangue >2) then
writeln ('O numero digitado eh invalido, programa encerrado.');
end.
|
unit DIOTA.Utils.Converter;
interface
uses
//System.SysUtils,
Generics.Collections;
type
{
* This class provides a set of utility methods to are used to convert between different formats.
}
TConverter = class
private
const
RADIX = Integer(3);
MAX_TRIT_VALUE = Integer((RADIX - 1) div 2);
MIN_TRIT_VALUE = Integer(-MAX_TRIT_VALUE);
NUMBER_OF_TRITS_IN_A_BYTE = Integer(5);
NUMBER_OF_TRITS_IN_A_TRYTE = Integer(3);
class var
BYTE_TO_TRITS_MAPPINGS: array[0..242] of TArray<Integer>;
TRYTE_TO_TRITS_MAPPINGS: array[0..26] of TArray<Integer>;
public
const
HIGH_INTEGER_BITS = Integer($FFFFFFFF);
HIGH_LONG_BITS = Int64($FFFFFFFFFFFFFFFF);
class constructor Initialize;
class procedure Increment(var trits: TArray<Integer>; const size: Integer);
class function Bytes(const trits: TArray<Integer>; const offset: Integer; const size: Integer): TArray<Shortint>; overload;
class function Bytes(const trits: TArray<Integer>): TArray<Shortint>; overload;
class procedure GetTrits(const bytes: TArray<Shortint>; var trits: TArray<Integer>);
class function ConvertToIntArray(integers: TList<Integer>): TArray<Integer>;
class function Trits(const trytes: String; length: Integer): TArray<Integer>; overload;
class function Trits(const trytes: Int64; length: Integer): TArray<Integer>; overload;
class function TritsString(const trytes: String): TArray<Integer>; deprecated;
class function Trits(const trytes: Int64): TArray<Integer>; overload;
class function Trits(const trytes: String): TArray<Integer>; overload;
class function CopyTrits(const input: String; var destination: TArray<Integer>): TArray<Integer>;
class function Trytes(const trits: TArray<Integer>; const offset: Integer; const size: Integer): String; overload;
class function Trytes(const trits: TArray<Integer>): String; overload;
class function TryteValue(const trits: TArray<Integer>; const offset: Integer): Integer;
class function Value(const trits: TArray<Integer>): Integer;
class function FromValue(value: Integer): TArray<Integer>;
class function LongValue(const trits: TArray<Integer>): Int64;
end;
implementation
uses
System.Math,
DIOTA.Utils.Constants;
{ TConverter }
class constructor TConverter.Initialize;
var
i, j: Integer;
trits: TArray<Integer>;
begin
SetLength(trits, NUMBER_OF_TRITS_IN_A_BYTE);
FillChar(trits[0], Length(trits), 0);
for i := Low(BYTE_TO_TRITS_MAPPINGS) to High(BYTE_TO_TRITS_MAPPINGS) do
begin
SetLength(BYTE_TO_TRITS_MAPPINGS[i], NUMBER_OF_TRITS_IN_A_BYTE);
for j := Low(BYTE_TO_TRITS_MAPPINGS[i]) to High(BYTE_TO_TRITS_MAPPINGS[i]) do
BYTE_TO_TRITS_MAPPINGS[i][j] := trits[j];
Increment(trits, NUMBER_OF_TRITS_IN_A_BYTE);
end;
for i := Low(TRYTE_TO_TRITS_MAPPINGS) to High(TRYTE_TO_TRITS_MAPPINGS) do
begin
SetLength(TRYTE_TO_TRITS_MAPPINGS[i], NUMBER_OF_TRITS_IN_A_TRYTE);
for j := Low(TRYTE_TO_TRITS_MAPPINGS[i]) to High(TRYTE_TO_TRITS_MAPPINGS[i]) do
TRYTE_TO_TRITS_MAPPINGS[i][j] := trits[j];
Increment(trits, NUMBER_OF_TRITS_IN_A_TRYTE);
end;
end;
class function TConverter.Bytes(const trits: TArray<Integer>; const offset, size: Integer): TArray<Shortint>;
var
i, j: Integer;
AValue: Integer;
ABoundary: Integer;
begin
SetLength(Result, (size + NUMBER_OF_TRITS_IN_A_BYTE - 1) div NUMBER_OF_TRITS_IN_A_BYTE);
for i := Low(Result) to High(Result) do
begin
AValue := 0;
if (size - i * NUMBER_OF_TRITS_IN_A_BYTE) < 5 then
ABoundary := size - i * NUMBER_OF_TRITS_IN_A_BYTE
else
ABoundary := NUMBER_OF_TRITS_IN_A_BYTE;
for j := ABoundary - 1 downto 0 do
AValue := AValue * RADIX + trits[offset + i * NUMBER_OF_TRITS_IN_A_BYTE + j];
Result[i] := AValue;
end;
end;
class function TConverter.Bytes(const trits: TArray<Integer>): TArray<Shortint>;
begin
Result := Bytes(trits, 0, Length(trits));
end;
class procedure TConverter.GetTrits(const bytes: TArray<Shortint>; var trits: TArray<Integer>);
var
AOffset: Integer;
i, j: Integer;
ASourceIndex: Integer;
ALength: Integer;
begin
AOffset := 0;
i := 0;
while (i < Length(bytes)) and (AOffset < Length(trits)) do
begin
if bytes[i] < 0 then
ASourceIndex := bytes[i] + Length(BYTE_TO_TRITS_MAPPINGS)
else
ASourceIndex := bytes[i];
if (Length(trits) - AOffset) < NUMBER_OF_TRITS_IN_A_BYTE then
ALength := Length(trits) - AOffset
else
ALength := NUMBER_OF_TRITS_IN_A_BYTE;
for j := 0 to ALength - 1 do
trits[AOffset + j] := BYTE_TO_TRITS_MAPPINGS[ASourceIndex][j];
Inc(AOffset, NUMBER_OF_TRITS_IN_A_BYTE);
Inc(i);
end;
while AOffset < Length(trits) do
begin
trits[AOffset] := 0;
Inc(AOffset);
end;
end;
class function TConverter.ConvertToIntArray(integers: TList<Integer>): TArray<Integer>;
begin
Result := integers.ToArray;
end;
class function TConverter.Trits(const trytes: String; length: Integer): TArray<Integer>;
var
i: Integer;
Res: TArray<Integer>;
begin
SetLength(Result, length);
FillChar(Result[0], System.Length(Result), 0);
Res := Trits(trytes);
for i := 0 to Min(length, System.Length(Res)) - 1 do
Result[i] := Res[i];
end;
class function TConverter.Trits(const trytes: Int64; length: Integer): TArray<Integer>;
var
i: Integer;
Res: TArray<Integer>;
begin
SetLength(Result, length);
FillChar(Result[0], System.Length(Result), 0);
Res := Trits(trytes);
for i := 0 to Min(length, System.Length(Res)) - 1 do
Result[i] := Res[i];
end;
class function TConverter.TritsString(const trytes: String): TArray<Integer>;
begin
Result := Trits(trytes);
end;
class function TConverter.Trits(const trytes: Int64): TArray<Integer>;
var
trits: TList<Integer>;
AAbsoluteValue: Int64;
APosition: Integer;
ARemainder: Integer;
i: Integer;
begin
trits := TList<Integer>.Create;
try
AAbsoluteValue := Abs(trytes);
APosition := 0;
while AAbsoluteValue > 0 do
begin
ARemainder := Integer(AAbsoluteValue mod RADIX);
AAbsoluteValue := AAbsoluteValue div RADIX;
if ARemainder > MAX_TRIT_VALUE then
begin
ARemainder := MIN_TRIT_VALUE;
Inc(AAbsoluteValue);
end;
trits.Insert(APosition, ARemainder);
Inc(APosition);
end;
if trytes < 0 then
for i := 0 to trits.Count - 1 do
trits[i] := -trits[i];
Result := ConvertToIntArray(trits);
finally
trits.Free;
end;
end;
class function TConverter.Trits(const trytes: String): TArray<Integer>;
var
i, j: Integer;
begin
SetLength(Result, 3 * Length(trytes));
FillChar(Result[0], Length(Result)*SizeOf(Result), 0);
for i := 0 to Length(trytes) - 1 do
for j := 0 to NUMBER_OF_TRITS_IN_A_TRYTE - 1 do
Result[i * NUMBER_OF_TRITS_IN_A_TRYTE + j] := TRYTE_TO_TRITS_MAPPINGS[Pos(trytes[i + 1], TRYTE_ALPHABET) - 1][j];
end;
class function TConverter.CopyTrits(const input: String; var destination: TArray<Integer>): TArray<Integer>;
var
i: Integer;
AIndex: Integer;
begin
for i := 0 to Length(input) - 1 do
begin
AIndex := Pos(input[i + 1], TRYTE_ALPHABET) - 1;
destination[i * 3] := TRYTE_TO_TRITS_MAPPINGS[AIndex][0];
destination[i * 3 + 1] := TRYTE_TO_TRITS_MAPPINGS[AIndex][1];
destination[i * 3 + 2] := TRYTE_TO_TRITS_MAPPINGS[AIndex][2];
end;
Result := destination;
end;
class function TConverter.Trytes(const trits: TArray<Integer>; const offset, size: Integer): String;
var
i, j: Integer;
begin
Result := '';
for i := 0 to (size + NUMBER_OF_TRITS_IN_A_TRYTE - 1) div NUMBER_OF_TRITS_IN_A_TRYTE - 1 do
begin
j := trits[offset + i * 3] + trits[offset + i * 3 + 1] * 3 + trits[offset + i * 3 + 2] * 9;
if j < 0 then
j := j + Length(TRYTE_ALPHABET);
Result := Result + TRYTE_ALPHABET[j + 1];
end;
end;
class function TConverter.Trytes(const trits: TArray<Integer>): String;
begin
Result := Trytes(trits, 0, Length(trits));
end;
class function TConverter.TryteValue(const trits: TArray<Integer>; const offset: Integer): Integer;
begin
Result := trits[offset] + trits[offset + 1] * 3 + trits[offset + 2] * 9;
end;
class function TConverter.Value(const trits: TArray<Integer>): Integer;
var
i: Integer;
begin
Result := 0;
for i := High(trits) downto 0 do
Result := Result * 3 + trits[i];
end;
class function TConverter.FromValue(value: Integer): TArray<Integer>;
var
i, j: Integer;
AAbsoluteValue: Integer;
ARemainder: Integer;
begin
if Value = 0 then
begin
SetLength(Result, 1);
Result[0] := 0;
end
else
begin
SetLength(Result, Integer(1 + Floor(Ln(2 * Max(1, Abs(value))) / Ln(3))));
FillChar(Result[0], Length(Result), 0);
i := 0;
AAbsoluteValue := Abs(value);
while AAbsoluteValue > 0 do
begin
ARemainder := AAbsoluteValue mod RADIX;
AAbsoluteValue := Integer(Floor(AAbsoluteValue / RADIX));
if ARemainder > MAX_TRIT_VALUE then
begin
ARemainder := MIN_TRIT_VALUE;
Inc(AAbsoluteValue);
end;
Result[i] := ARemainder;
Inc(i);
end;
if value < 0 then
for j := 0 to High(Result) do
Result[j] := -Result[j];
end;
end;
class function TConverter.LongValue(const trits: TArray<Integer>): Int64;
var
i: Integer;
begin
Result := 0;
for i := High(trits) downto 0 do
Result := Result * 3 + trits[i];
end;
class procedure TConverter.Increment(var trits: TArray<Integer>; const size: Integer);
var
i: Integer;
begin
for i := 0 to size - 1 do
begin
trits[i] := trits[i] + 1;
if trits[i] > TConverter.MAX_TRIT_VALUE then
trits[i] := TConverter.MIN_TRIT_VALUE
else
Break;
end;
end;
end.
|
unit U_FrmCadastroCurso;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
Buttons, StdCtrls, U_Utils, U_FrmCadastroBase, U_DtmCadastroCurso,
U_Curso;
type
{ TFrmCadastroCurso }
TFrmCadastroCurso = class(TFrmCadastroBase)
edtCodigo: TEdit;
edtNome: TEdit;
Label1: TLabel;
Label2: TLabel;
procedure btnCancelarClick(Sender: TObject);
procedure btnIncluirClick(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure edtCodigoExit(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
private
curso :TCurso;
public
end;
var
FrmCadastroCurso: TFrmCadastroCurso;
implementation
{$R *.lfm}
{ TFrmCadastroCurso }
uses
U_FrmPesquisaCadastroCurso;
procedure TFrmCadastroCurso.btnIncluirClick(Sender: TObject);
begin
edtCodigo.Text := FormatFloat('00',getCodigoValido('CURSO','COD_CURSO'));
inherited;
edtCodigo.Enabled:=False;
edtCodigo.Color:=clInfoBk;
edtNome.Enabled:= True;
edtNome.Color:=clWhite;
edtNome.SetFocus;
end;
procedure TFrmCadastroCurso.btnPesquisarClick(Sender: TObject);
begin
try
FrmPesquisaCadastroCurso := TFrmPesquisaCadastroCurso.Create(Self);
FrmPesquisaCadastroCurso.ShowModal;
if FrmPesquisaCadastroCurso.gControle = tpAlterar then
begin
edtCodigo.Text := FrmPesquisaCadastroCurso.DSGrid.DataSet.FieldByName('CODIGO').AsString;
edtCodigoExit(edtCodigo);
end;
finally
FreeAndNil(FrmPesquisaCadastroCurso);
end;
end;
procedure TFrmCadastroCurso.btnSalvarClick(Sender: TObject);
begin
if (Trim(edtNome.Text) = '') then
begin
MsgAlerta('Informe o nome!');
edtNome.SetFocus;
Exit;
end;
try
curso := TCurso.Create;
curso.codigo:= StrToInt(edtCodigo.Text);
curso.descicao:= edtNome.Text;
if DtmCadastroCurso.salvarCurso(curso,gControle) then
begin
if gControle = tpNovo then
MsgOk('Curso cadastrado com sucesso!')
else
MsgOk('Curso alterado com sucesso!');
end;
finally
FreeAndNil(curso);
end;
btnCancelarClick(btnCancelar);
inherited;
end;
procedure TFrmCadastroCurso.edtCodigoExit(Sender: TObject);
begin
if gControle = tpConsulta then
begin
if (Trim(edtCodigo.Text) <> '') then
begin
curso := DtmCadastroCurso.getCurso(StrToInt(edtCodigo.Text));
if (curso <> nil) then
begin
try
edtCodigo.Text := formatfloat('00',curso.codigo);
edtNome.Text := curso.descicao;
controleAlterar;
edtCodigo.Enabled:=False;
edtCodigo.Color:=clInfoBk;
if (curso.codigo > 0) then
begin
edtNome.Enabled:= True;
edtNome.Color:=clWhite;
edtNome.SetFocus;
end;
finally
FreeAndNil(curso);
end;
end
else
begin
MsgAlerta('Curso não encontrado!');
btnCancelarClick(btnCancelar);
end;
end;
end;
end;
procedure TFrmCadastroCurso.FormClose(Sender: TObject;
var CloseAction: TCloseAction);
begin
if gControle = tpNovo then
deletaCodigo('CURSO','COD_CURSO',StrToInt(edtCodigo.Text));
end;
procedure TFrmCadastroCurso.FormCreate(Sender: TObject);
begin
inherited;
DtmCadastroCurso := TDtmCadastroCurso.Create(Self);
end;
procedure TFrmCadastroCurso.FormDestroy(Sender: TObject);
begin
FreeAndNil(DtmCadastroCurso);
end;
procedure TFrmCadastroCurso.FormShow(Sender: TObject);
begin
self.ActiveControl := edtCodigo;
edtCodigo.SetFocus;
end;
procedure TFrmCadastroCurso.btnCancelarClick(Sender: TObject);
begin
deletaCodigo('CURSO','COD_CURSO',StrToInt(edtCodigo.Text));
edtCodigo.Clear;
edtCodigo.Enabled:= True;
edtCodigo.Color:=clWhite;
edtCodigo.SetFocus;
edtNome.Clear;
edtNome.Enabled:=False;
edtNome.Color:=clInfoBk;
inherited;
end;
end.
|
{* MPLAY.PAS
*
* Minimal Protracker module player using MIDAS Sound System
*
* Copyright 1995 Petteri Kangaslampi and Jarno Paananen
*
* This file is part of the MIDAS Sound System, and may only be
* used, modified and distributed under the terms of the MIDAS
* Sound System license, LICENSE.TXT. By continuing to use,
* modify or distribute this file you indicate that you have
* read the license and understand and accept it fully.
*}
uses midas, mfile, mplayer, modp, errors, mconfig;
{****************************************************************************\
*
* Function: toASCIIZ(dest : PChar; str : string) : PChar;
*
* Description: Converts a string to ASCIIZ format. (StrPCopy is NOT available
* in real mode!)
*
* Input: msg : string string to be converted
* dest : PChar destination buffer
*
* Returns: Pointer to the converted string;
*
\****************************************************************************}
function toASCIIZ(dest : PChar; str : string) : PChar;
var
spos, slen : integer;
i : integer;
begin
spos := 0; { string position = 0 }
slen := ord(str[0]); { string length }
{ copy string to ASCIIZ conversion buffer: }
while spos < slen do
begin
dest[spos] := str[spos+1];
spos := spos + 1;
end;
dest[spos] := chr(0); { put terminating 0 to end of string }
toASCIIZ := dest;
end;
var
module : PmpModule;
i, error, isConfig : integer;
str : array [0..256] of char;
BEGIN
{ Check that the configuration file exists: }
error := fileExists('MIDAS.CFG', @isConfig);
if error <> OK then
midasError(error);
if isConfig <> 1 then
begin
WriteLn('Configuration file not found - run MSETUP.EXE');
Halt;
end;
midasSetDefaults; { set MIDAS defaults }
midasLoadConfig('MIDAS.CFG'); { load configuration }
midasInit; { initialize MIDAS Sound System }
{ Convert command line argument to ASCIIZ and load module: }
module := midasLoadModule('C:\SCREAM\ILLUMINA.MOD', @mpMOD, NIL);
midasPlayModule(module, 0); { start playing }
WriteLn('Playing - press Enter to stop');
ReadLn;
midasStopModule(module); { stop playing }
midasFreeModule(module); { deallocate module }
midasClose; { uninitialize MIDAS }
END.
|
unit Unit_Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ToolWin, ExtCtrls, StdCtrls, Menus;
type
TfrmMain = class(TForm)
ControlBar1: TControlBar;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
Button1: TButton;
Button2: TButton;
lblBetta: TLabel;
lblEpsilon: TLabel;
Timer1: TTimer;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
ePeleng: TEdit;
eEpsilon: TEdit;
Label7: TLabel;
Label8: TLabel;
eKa: TEdit;
Label9: TLabel;
lblDeltaBetta: TLabel;
lblDeltaEpsilon: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
egDeltaRo2: TEdit;
efSigma2: TEdit;
Label23: TLabel;
Label26: TLabel;
Bevel3: TBevel;
efKoefPlacingDiagram: TEdit;
efCutLevel: TEdit;
Label1: TLabel;
Label2: TLabel;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
Label17: TLabel;
Label18: TLabel;
Label19: TLabel;
edTimer1: TEdit;
egDeltaRo1: TEdit;
procedure ToolButton2Click(Sender: TObject);
procedure ToolButton3Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
// --- Текущее модельное время -----
CurrentModelTime : integer;
TransformTimeCoef : integer; // ---- Коеффициент преобразование переменной CurrentModelTime в реальное модельное время ---
TargetPeleng : double;
TargetEpsilon : double;
CurAzimFAR_Korabel : double;
CutLevel : double;
KoefPlacingDiagram : double;
Sigma2 : double;
DeltaRo1 : double;
DeltaRo2 : double;
Hx, Hy, Hz : double;
Sh : double;
SlowFreq : integer; // ---- временная переменная ------ // ----- Медленный таймер (работает 10 раз в секунду) -----
Sync : integer; // ---- временная переменная ------ // ----- Переменная синхронизации таймеров --------
NULLValue : Double;
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses mpiDllConect;
{$R *.DFM}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
Randomize;
DecimalSeparator := '.';
TransformTimeCoef := 100;
NULLValue := 0; /// ----- Закрывачка (подставить в адресса --- нулевую переменную )----
{
var
pRockingData : PTRockingData;
// Процедуры
// Инициализация DLL - запускается один раз при запуске системы
Rocking_InitDLL (pRockingData);
// Редактирование параметров
Rocking_SetParameters ();
// Запуск качек - запускается перед каждым зондированием примерно каждые (140 - 1600 мкс) - ПО КРАЙНЕЙ МЕРЕ Я ЭТО МОГУ ОСУЩЕСТВИТЬ, НО НЕ ЧАЩЕ
Rocking_Run ();
// Получение значений поправок для электронной стабилизации при качках
Rocking_Get_Betta_Epsilon (); // Входыне и выходные параметры в структуре TRockingData
// Получение значений ошибок измерения координат в режиме прерывания обзора
Rocking_Get_Betta_Epsilon_and_TargetError (); // Входыне и выходные параметры в структуре TRockingData
// Ты можешь в данной процедуре не рассчитывать поправки по Betta и Epsilon
// Объясни назанчение данной процедуры
Rocking_ShowModelResult (); }
end;
procedure TfrmMain.ToolButton2Click(Sender: TObject);
begin
if (not mpi_RockingDLLLoaded) then exit; // ---- Если ДЛЛ не загружена тогда , пшол вон отсюда :) ----
Rocking_SetParameters();
end;
procedure TfrmMain.ToolButton3Click(Sender: TObject);
begin
if (not mpi_RockingDLLLoaded) then exit; // ---- Если ДЛЛ не загружена тогда , пшол вон отсюда :) ----
Rocking_ShowModelResult();
end;
procedure TfrmMain.Button1Click(Sender: TObject);
begin
/// ----- Ето модельные параметры --------
TargetPeleng := StrToFloat (ePeleng .Text) * pi / 180;
TargetEpsilon := StrToFloat (eEpsilon.Text) * pi / 180;
CurAzimFAR_Korabel := StrToFloat (eKa .Text) * pi / 180;
CutLevel := StrToFloat (efCutLevel .Text);
KoefPlacingDiagram := StrToFloat (efKoefPlacingDiagram.Text);
Sigma2 := StrToFloat (efSigma2 .Text);
DeltaRo1 := StrToFloat (egDeltaRo1 .Text) * pi / 180;
DeltaRo2 := StrToFloat (egDeltaRo2 .Text) * pi / 180;
Hx := 0.5;
Hy := 0.5;
Hz := 30;
Sh := 18;
// ---- Текущее модельное время ----
CurrentModelTime := 0;
// ---- внутренние переменные ----- ----
SlowFreq := 10; // ----- Медленный таймер (работает 10 раз в секунду) -----
Sync := SlowFreq; // ----- Переменная синхронизации таймеров --------
////////////////////////////////////
// ----- Инициализация , переменных структуры, некоторые переменных (тут все переменные не обизательно ложить) -----
RockingData.pIntCurrentTime := @CurrentModelTime; // ---- Текущее модельное время, с (с точностью до мкс)
RockingData.pCurAzimFAR_Korabel := @CurAzimFAR_Korabel; // ---- Текущий азимут вращения антенны ------
RockingData.pEps0 := @NULLValue; // ---- Наклон полотна -----
RockingData.pDeltaEps0 := @NULLValue; // ---- Ошибка установки наклона полотна -----
RockingData.pNju := @NULLValue; // ---- Разворот полотна (фокал )
RockingData.pDeltaNju := @NULLValue; // ---- Ошибка установки (фокала )
RockingData.CutLevel := @CutLevel; // ---- Уровень среза ------
RockingData.KoefPlacingDiagram := @KoefPlacingDiagram; // ---- Коэффициент растоновки лучей (доли от растановки)
RockingData.Sh := @Sh; // ---- Отношение сигнал/шум -----
RockingData.Sigma2 := @Sigma2; // ---- Величина квадратического отклонения ----
RockingData.DeltaRo1 := @DeltaRo1; // ---- Дискрет изменения угла отклонения по горизонтальной оси ---
RockingData.DeltaRo2 := @DeltaRo2; // ---- Дискрет изменения угла отклонения по вертикальной оси ---
// --------- Ети параметры пускай висят, они в ДЛЛ не подлючены - хотя нада былобы,---------
RockingData.Hx := @Hx; // ---- Смещение антенны относительно центра качания ----
RockingData.Hy := @Hy; // ---- Смещение антенны относительно центра качания ----
RockingData.Hz := @Hz; // ---- Смещение антенны относительно центра качания ----
RockingData.TimeTransformCoef := TransformTimeCoef;
////////////////////////////////////
Rocking_InitDLL(RockingData);
// ----- Запуск таймера ------
Timer1.Enabled := true;
end;
procedure TfrmMain.Button2Click(Sender: TObject);
begin
// ----- Не Запуск таймера ------
Timer1.Enabled := false;
end;
procedure TfrmMain.Timer1Timer(Sender: TObject);
begin
// ---- Зпускаем ДЛЛ (Тобиш внутренние ДЛЛ Качки) ------
Rocking_Run();
// ----- Если сработал медленный таймер по переменной синхронизации , тогда в средину ---------------
if (CurrentModelTime >= Sync) then begin
// -----
RockingData.TargetPeleng := TargetPeleng; // ---- Текущий пеленг цели ---------
RockingData.TargetEpsilon := TargetEpsilon; // ---- Текущий угол места цели --------
RockingData.ImpulsCount := 20;
//RockingData.ImpulsCount := Random(20);
// ------
Rocking_Get_Betta_Epsilon();
Rocking_Get_Betta_Epsilon_and_TargetError();
// -----
lblBetta.Caption := Format ('Betta: %5.3f грд', [RockingData.Betta * 180 / pi]);
lblEpsilon.Caption := Format ('Epsilon: %5.3f грд', [RockingData.Epsilon * 180 / pi]);
lblDeltaBetta.Caption := Format ('DeltaBetta: %5.3f грд', [RockingData.DeltaBetta * 180 / pi]);
lblDeltaEpsilon.Caption := Format ('DeltaEpsilon: %5.3f грд', [RockingData.DeltaEpsilon * 180 / pi]);
Label11.Caption := Format ('DeltaBetta: %5.3f грд', [RockingData.MeasureDeltaBetta * 180 / pi]);
Label12.Caption := Format ('DeltaEpsilon: %5.3f грд', [RockingData.MeasureDeltaEpsilon * 180 / pi]);
Sync := CurrentModelTime + SlowFreq;
end;
// -----
inc(CurrentModelTime);
// ----- Вывод быстрого модельно времени -------
edTimer1.Text := FloatToStr(CurrentModelTime / TransformTimeCoef);
end;
end.
|
unit uRecipe;
interface
uses
Classes,
RegularExpressions,
uDemo;
type
TRecipe = class abstract(TDemo)
strict protected
procedure Run; override;
public
function Pattern: String; virtual; abstract;
function Options: TRegexOptions; virtual;
procedure GetInputs(const Inputs: TStrings); virtual; abstract;
end;
implementation
uses
ComCtrls;
{ TRecipe }
function TRecipe.Options: TRegexOptions;
begin
Result := [];
end;
procedure TRecipe.Run;
var
Inputs: TStringList;
Regex: IRegex;
Match: IMatch;
Group: IGroup;
Input: String;
I: Integer;
GroupNames: TStringArray;
Node, MatchNode, NonMatchNode: TTreeNode;
begin
MatchNode := TreeView.Items.AddChild(nil, 'The following inputs match the regular expression:');
NonMatchNode := TreeView.Items.AddChild(nil, 'The following inputs do NOT match:');
Inputs := TStringList.Create;
try
GetInputs(Inputs);
Regex := TRegex.Create(Pattern, Options);
GroupNames := Regex.GetGroupNames;
for Input in Inputs do
begin
Match := Regex.Match(Input);
if (Match.Success) then
begin
while (Match.Success) do
begin
Node := TreeView.Items.AddChild(MatchNode, Input);
for I := 0 to Length(GroupNames) - 1 do
begin
Group := Match.Groups.ItemsByName[GroupNames[I]];
if (Group.Success) then
TreeView.Items.AddChild(Node, 'Group[' + GroupNames[I] + '] = ' + Group.Value);
end;
Match := Match.NextMatch;
end;
end
else
TreeView.Items.AddChild(NonMatchNode, Input);
end;
MatchNode.Expand(False);
NonMatchNode.Expand(False);
TreeView.Selected := MatchNode;
TreeView.TopItem := MatchNode;
finally
Inputs.Free;
end;
end;
end.
|
unit enumvalue_edit_ctrl;
interface
uses
Classes
,SysUtils
,tiObject
,mapper
,mvc_base
,widget_controllers
,app_mdl
,enumvalue_edit_view
;
type
// -----------------------------------------------------------------
// Class Objects
// -----------------------------------------------------------------
{: Enum Value edit controller. }
TEnumValueEditController = class(TMVCController)
protected
procedure DoCreateMediators; override;
procedure SetActive(const AValue: Boolean); override;
procedure HandleOKClick(Sender: TObject);
public
function Model: TMapEnumValue; reintroduce;
function View: TEnumValueEditView; reintroduce;
constructor Create(AModel: TMapEnumValue; AView: TEnumValueEditView); reintroduce; overload; virtual;
destructor Destroy; override;
end;
implementation
uses
vcl_controllers
,StdCtrls
,Controls
,Dialogs
;
{ TEnumValueEditController }
constructor TEnumValueEditController.Create(AModel: TMapEnumValue;
AView: TEnumValueEditView);
begin
inherited Create(AModel, AView);
end;
destructor TEnumValueEditController.Destroy;
begin
View.Hide;
View.Free;
inherited;
end;
procedure TEnumValueEditController.DoCreateMediators;
begin
AddController(TEditController.Create(Model, View.eName, 'EnumValueName'));
AddController(TEditController.Create(Model, View.eValue, 'EnumValue'));
View.btnOK.OnClick := self.HandleOKClick;
end;
procedure TEnumValueEditController.HandleOKClick(Sender: TObject);
var
lMsg: string;
begin
if not Model.IsValid(lMsg) then
begin
MessageDlg('Error(s): ' + sLineBreak + lMsg, mtError, [mbOK], 0);
exit;
end;
View.ModalResult := mrOk;
end;
function TEnumValueEditController.Model: TMapEnumValue;
begin
Result := inherited Model as TMapEnumValue;
end;
procedure TEnumValueEditController.SetActive(const AValue: Boolean);
begin
inherited;
if Active then
View.ShowModal;
end;
function TEnumValueEditController.View: TEnumValueEditView;
begin
result := inherited View as TEnumValueEditView;
end;
end.
|
program SwallowAirSpeedVelocity;
Uses SysUtils;
function UserInput(a : String):Double;
begin
result := StrToFloat(a);
end;
function AirSpeedVelocity(f,a,s : Double):Double;
begin
result := f*(a/100)/s;
end;
procedure YourSwallow(s:Double);
var f,a: Double;
begin
Write('Enter Frequency: ');
ReadLn(f);
Write('Enter Amplitude: ');
ReadLn(a);
WriteLn('Your Swallow f=',f:2:0,'hz, A=',a/100:4:2,'m, Air Speed = ',AirSpeedVelocity(f,a,s):4:2,'m/s');
end;
procedure Main();
var
text : String;
s: Double;
begin
s := UserInput(ParamStr(1));
text := 'Swallow f=15hz, A=0.21m, Air Speed = ';
WriteLn('African ',text,' ',AirSpeedVelocity(15,21,s):4:2,'m/s');
WriteLn('European ',text,' ',AirSpeedVelocity(14,22,s):4:2,'m/s');
YourSwallow(s);
end;
begin
Main();
end. |
unit TSTOProjectWorkSpace.Bin;
Interface
Uses Classes, SysUtils, RTLConsts,
HsInterfaceEx, HsStreamEx,
TSTOProjectWorkSpaceIntf;
Type
IBinTSTOWorkSpaceProjectSrcFolder = Interface(ITSTOWorkSpaceProjectSrcFolder)
['{4B61686E-29A0-2112-AB5B-6ADB205EB15A}']
Procedure LoadFromStream(ASource : IStreamEx);
Procedure SaveToStream(ATarget : IStreamEx);
End;
IBinTSTOWorkSpaceProjectSrcFolders = Interface(ITSTOWorkSpaceProjectSrcFolders)
['{4B61686E-29A0-2112-9D6F-585DB1EF5131}']
Function Get(Index : Integer) : IBinTSTOWorkSpaceProjectSrcFolder;
Procedure Put(Index : Integer; Const Item : IBinTSTOWorkSpaceProjectSrcFolder);
Function Add() : IBinTSTOWorkSpaceProjectSrcFolder; OverLoad;
Function Add(Const AItem : IBinTSTOWorkSpaceProjectSrcFolder) : Integer; OverLoad;
Property Items[Index : Integer] : IBinTSTOWorkSpaceProjectSrcFolder Read Get Write Put; Default;
End;
IBinTSTOWorkSpaceProject = Interface(ITSTOWorkSpaceProject)
['{4B61686E-29A0-2112-99B3-8D5D7F97AEAB}']
Procedure LoadFromStream(ASource : IStreamEx);
Procedure SaveToStream(ATarget : IStreamEx);
Function GetSrcFolders() : IBinTSTOWorkSpaceProjectSrcFolders;
Property SrcFolders : IBinTSTOWorkSpaceProjectSrcFolders Read GetSrcFolders;
End;
IBinTSTOWorkSpaceProjectGroup = Interface(ITSTOWorkSpaceProjectGroup)
['{4B61686E-29A0-2112-B1D0-7D60874C2F7A}']
Function Get(Index : Integer) : IBinTSTOWorkSpaceProject;
Procedure Put(Index : Integer; Const Item : IBinTSTOWorkSpaceProject);
Function Add() : IBinTSTOWorkSpaceProject; OverLoad;
Function Add(Const AItem : IBinTSTOWorkSpaceProject) : Integer; OverLoad;
Procedure LoadFromStream(ASource : IStreamEx);
Procedure SaveToStream(ATarget : IStreamEx);
Property Items[Index : Integer] : IBinTSTOWorkSpaceProject Read Get Write Put; Default;
End;
TBinTSTOWorkSpaceProjectGroup = Class(TObject)
Public
Class Function CreateWSProjectGroup() : IBinTSTOWorkSpaceProjectGroup;
End;
Implementation
Uses
TSTOProjectWorkSpaceImpl, TSTOProjectWorkSpace.Types;
Type
TBinTSTOWorkSpaceProjectSrcFolder = Class(TTSTOWorkSpaceProjectSrcFolder, IBinTSTOWorkSpaceProjectSrcFolder)
Private
Procedure LoadFromStreamV001(ASource : IStreamEx);
Protected
Procedure LoadFromStream(ASource : IStreamEx);
Procedure SaveToStream(ATarget : IStreamEx);
End;
TBinTSTOWorkSpaceProjectSrcFolders = Class(TTSTOWorkSpaceProjectSrcFolders, IBinTSTOWorkSpaceProjectSrcFolders)
Protected
Function GetItemClass() : TInterfacedObjectExClass; OverRide;
Function Get(Index : Integer) : IBinTSTOWorkSpaceProjectSrcFolder; OverLoad;
Procedure Put(Index : Integer; Const Item : IBinTSTOWorkSpaceProjectSrcFolder); OverLoad;
Function Add() : IBinTSTOWorkSpaceProjectSrcFolder; OverLoad;
Function Add(Const AItem : IBinTSTOWorkSpaceProjectSrcFolder) : Integer; OverLoad;
End;
TBinTSTOWorkSpaceProject = Class(TTSTOWorkSpaceProject, IBinTSTOWorkSpaceProject)
Private
Procedure LoadFromStreamV001(ASource : IStreamEx);
Procedure LoadFromStreamV002(ASource : IStreamEx);
Protected
Function GetWorkSpaceProjectSrcFoldersClass() : TTSTOWorkSpaceProjectSrcFoldersClass; OverRide;
Function GetSrcFolders() : IBinTSTOWorkSpaceProjectSrcFolders; OverLoad;
Procedure LoadFromStream(ASource : IStreamEx);
Procedure SaveToStream(ATarget : IStreamEx);
End;
TBinTSTOWorkSpaceProjectGroupImpl = Class(TTSTOWorkSpaceProjectGroup, IBinTSTOWorkSpaceProjectGroup)
Private
Procedure LoadFromStreamV001(ASource : IStreamEx);
Procedure LoadFromStreamV002(ASource : IStreamEx);
Protected
Function GetItemClass() : TInterfacedObjectExClass; OverRide;
Function Get(Index : Integer) : IBinTSTOWorkSpaceProject; OverLoad;
Procedure Put(Index : Integer; Const Item : IBinTSTOWorkSpaceProject); OverLoad;
Function Add() : IBinTSTOWorkSpaceProject; OverLoad;
Function Add(Const AItem : IBinTSTOWorkSpaceProject) : Integer; OverLoad;
Procedure LoadFromStream(ASource : IStreamEx);
Procedure SaveToStream(ATarget : IStreamEx);
End;
Class Function TBinTSTOWorkSpaceProjectGroup.CreateWSProjectGroup() : IBinTSTOWorkSpaceProjectGroup;
Begin
Result := TBinTSTOWorkSpaceProjectGroupImpl.Create();
End;
(******************************************************************************)
Procedure TBinTSTOWorkSpaceProjectSrcFolder.LoadFromStreamV001(ASource : IStreamEx);
Var lNbFile : Integer;
Begin
SrcPath := ASource.ReadAnsiString();
lNbFile := ASource.ReadWord();
While lNbFile > 0 Do
Begin
Add(ASource.ReadAnsiString());
Dec(lNbFile);
End;
End;
Procedure TBinTSTOWorkSpaceProjectSrcFolder.LoadFromStream(ASource : IStreamEx);
Begin
Case ASource.ReadByte() Of
1 : LoadFromStreamV001(ASource);
Else
Raise Exception.Create('Invalid workspace file');
End;
End;
Procedure TBinTSTOWorkSpaceProjectSrcFolder.SaveToStream(ATarget : IStreamEx);
Const
cStreamVersion = 1;
Var X : Integer;
Begin
ATarget.WriteByte(cStreamVersion);
ATarget.WriteAnsiString(SrcPath);
ATarget.WriteWord(SrcFileCount);
For X := 0 To SrcFileCount - 1 Do
ATarget.WriteAnsiString(SrcFiles[X].FileName);
End;
Function TBinTSTOWorkSpaceProjectSrcFolders.GetItemClass() : TInterfacedObjectExClass;
Begin
Result := TBinTSTOWorkSpaceProjectSrcFolder;
End;
Function TBinTSTOWorkSpaceProjectSrcFolders.Get(Index : Integer) : IBinTSTOWorkSpaceProjectSrcFolder;
Begin
Result := InHerited Items[Index] As IBinTSTOWorkSpaceProjectSrcFolder;
End;
Procedure TBinTSTOWorkSpaceProjectSrcFolders.Put(Index : Integer; Const Item : IBinTSTOWorkSpaceProjectSrcFolder);
Begin
InHerited Items[Index] := Item;
End;
Function TBinTSTOWorkSpaceProjectSrcFolders.Add() : IBinTSTOWorkSpaceProjectSrcFolder;
Begin
Result := InHerited Add() As IBinTSTOWorkSpaceProjectSrcFolder;
End;
Function TBinTSTOWorkSpaceProjectSrcFolders.Add(Const AItem : IBinTSTOWorkSpaceProjectSrcFolder) : Integer;
Begin
Result := InHerited Add(AItem);
End;
Function TBinTSTOWorkSpaceProject.GetWorkSpaceProjectSrcFoldersClass() : TTSTOWorkSpaceProjectSrcFoldersClass;
Begin
Result := TBinTSTOWorkSpaceProjectSrcFolders;
End;
Function TBinTSTOWorkSpaceProject.GetSrcFolders() : IBinTSTOWorkSpaceProjectSrcFolders;
Begin
Result := InHerited GetSrcFolders() As IBinTSTOWorkSpaceProjectSrcFolders;
End;
Procedure TBinTSTOWorkSpaceProject.LoadFromStreamV001(ASource : IStreamEx);
Var lNbPath : Byte;
lSrcFolders : IBinTSTOWorkSpaceProjectSrcFolders;
Begin
ProjectName := ASource.ReadAnsiString();
ProjectKind := TWorkSpaceProjectKind(ASource.ReadByte());
ProjectType := TWorkSpaceProjectType(ASource.ReadByte());
ZeroCrc32 := ASource.ReadDWord();
PackOutput := ASource.ReadByte() <> 0;
OutputPath := ASource.ReadAnsiString();
If ProjectType = sptScript Then
CustomScriptPath := ASource.ReadAnsiString();
lNbPath := ASource.ReadByte();
lSrcFolders := GetSrcFolders();
While lNbPath > 0 Do
Begin
lSrcFolders.Add().LoadFromStream(ASource);
Dec(lNbPath);
End;
End;
Procedure TBinTSTOWorkSpaceProject.LoadFromStreamV002(ASource : IStreamEx);
Var lNbPath : Byte;
lSrcFolders : IBinTSTOWorkSpaceProjectSrcFolders;
Begin
ProjectName := ASource.ReadAnsiString();
ProjectKind := TWorkSpaceProjectKind(ASource.ReadByte());
ProjectType := TWorkSpaceProjectType(ASource.ReadByte());
ZeroCrc32 := ASource.ReadDWord();
PackOutput := ASource.ReadByte() <> 0;
OutputPath := ASource.ReadAnsiString();
If ProjectType = sptScript Then
CustomScriptPath := ASource.ReadAnsiString();
CustomModPath := ASource.ReadAnsiString();
lNbPath := ASource.ReadByte();
lSrcFolders := GetSrcFolders();
While lNbPath > 0 Do
Begin
lSrcFolders.Add().LoadFromStream(ASource);
Dec(lNbPath);
End;
End;
Procedure TBinTSTOWorkSpaceProject.LoadFromStream(ASource : IStreamEx);
Begin
Case ASource.ReadByte() Of
1 : LoadFromStreamV001(ASource);
2 : LoadFromStreamV002(ASource);
Else
Raise Exception.Create('Invalid workspace file');
End;
End;
Procedure TBinTSTOWorkSpaceProject.SaveToStream(ATarget : IStreamEx);
Const
cStreamVersion = 2;
Var X : Integer;
lSrcFolders : IBinTSTOWorkSpaceProjectSrcFolders;
Begin
ATarget.WriteByte(cStreamVersion);
ATarget.WriteAnsiString(ProjectName);
ATarget.WriteByte(Ord(ProjectKind));
ATarget.WriteByte(Ord(ProjectType));
ATarget.WriteDWord(ZeroCrc32);
If PackOutput Then
ATarget.WriteByte(1)
Else
ATarget.WriteByte(0);
ATarget.WriteAnsiString(OutputPath);
If ProjectType = sptScript Then
ATarget.WriteAnsiString(CustomScriptPath);
ATarget.WriteAnsiString(CustomModPath);
lSrcFolders := GetSrcFolders();
ATarget.WriteByte(lSrcFolders.Count);
For X := 0 To lSrcFolders.Count - 1 Do
lSrcFolders[X].SaveToStream(ATarget);
End;
Function TBinTSTOWorkSpaceProjectGroupImpl.GetItemClass() : TInterfacedObjectExClass;
Begin
Result := TBinTSTOWorkSpaceProject;
End;
Function TBinTSTOWorkSpaceProjectGroupImpl.Get(Index : Integer) : IBinTSTOWorkSpaceProject;
Begin
Result := InHerited Items[Index] As IBinTSTOWorkSpaceProject;
End;
Procedure TBinTSTOWorkSpaceProjectGroupImpl.Put(Index : Integer; Const Item : IBinTSTOWorkSpaceProject);
Begin
InHerited Items[Index] := Item;
End;
Function TBinTSTOWorkSpaceProjectGroupImpl.Add() : IBinTSTOWorkSpaceProject;
Begin
Result := InHerited Add() As IBinTSTOWorkSpaceProject;
End;
Function TBinTSTOWorkSpaceProjectGroupImpl.Add(Const AItem : IBinTSTOWorkSpaceProject) : Integer;
Begin
Result := InHerited Add(AItem);
End;
Procedure TBinTSTOWorkSpaceProjectGroupImpl.LoadFromStreamV001(ASource : IStreamEx);
Var lNbProject : Integer;
Begin
ProjectGroupName := ASource.ReadAnsiString();
PackOutput := ASource.ReadBoolean();
OutputPath := ASource.ReadAnsiString();
lNbProject := ASource.ReadByte();
While lNbProject > 0 Do
Begin
Add().LoadFromStream(ASource);
Dec(lNbProject);
End;
End;
Procedure TBinTSTOWorkSpaceProjectGroupImpl.LoadFromStreamV002(ASource : IStreamEx);
Var lNbProject : Integer;
Begin
ProjectGroupName := ASource.ReadAnsiString();
HackFileName := ASource.ReadAnsiString();
PackOutput := ASource.ReadBoolean();
OutputPath := ASource.ReadAnsiString();
lNbProject := ASource.ReadByte();
While lNbProject > 0 Do
Begin
Add().LoadFromStream(ASource);
Dec(lNbProject);
End;
End;
Procedure TBinTSTOWorkSpaceProjectGroupImpl.LoadFromStream(ASource : IStreamEx);
Begin
Case ASource.ReadByte() Of
1 : LoadFromStreamV001(ASource);
2 : LoadFromStreamV002(ASource);
Else
Raise Exception.Create('Invalid workspace file');
End;
End;
Procedure TBinTSTOWorkSpaceProjectGroupImpl.SaveToStream(ATarget : IStreamEx);
Const
cStreamVersion = 2;
Var X : Integer;
Begin
ATarget.WriteByte(cStreamVersion);
ATarget.WriteAnsiString(ProjectGroupName);
ATarget.WriteAnsiString(HackFileName);
ATarget.WriteBoolean(PackOutput);
ATarget.WriteAnsiString(OutputPath);
ATarget.WriteByte(Count);
For X := 0 To Count - 1 Do
Get(X).SaveToStream(ATarget);
End;
(*
Procedure CreateWsProject(APath : String; AProject : ITSTOWorkSpaceProject);
Procedure RecursiveSearch(AStartPath : String; AProject : ITSTOWorkSpaceProject);
Var lSr : TSearchRec;
lMem : IMemoryStreamEx;
Begin
AStartPath := IncludeTrailingBackslash(AStartPath);
If FindFirst(AStartPath + '*.*', faAnyFile, lSr) = 0 Then
Try
Repeat
If (lSr.Attr And faDirectory <> 0) Then
Begin
If SameText(ExtractFileExt(lSr.Name), '.Src') Then
Begin
AProject.SrcFolders.Add().SrcPath := IncludeTrailingBackslash(AStartPath + lSr.Name);
RecursiveSearch(IncludeTrailingBackslash(AStartPath + lSr.Name), AProject);
End;
End
Else If SameText(lSr.Name, 'ZeroCrc.hex') Then
Begin
lMem := TMemoryStreamEx.Create();
Try
lMem.LoadFromFile(APath + lSr.Name);
AProject.ZeroCrc32 := lMem.ReadDWord();
AProject.ProjectKind := spkRoot;
Finally
lMem := Nil;
End;
End
Else
AProject.SrcFolders[AProject.SrcFolders.Count - 1].Add(lSr.Name);
Until FindNext(lSr) <> 0
Finally
FindClose(lSr);
End;
End;
Begin
AProject.ProjectName := ExtractFileName(ExcludeTrailingBackslash(APath));
RecursiveSearch(APath, AProject);
End;
Procedure CreateWsGroupProject(APath : String);
Var lSr : TSearchRec;
lPgIO : ITSTOWorkSpaceProjectGroupIO;
lProject : ITSTOWorkSpaceProject;
Begin
lPgIO := TTSTOWorkSpaceProjectGroupIO.CreateProjectGroup();
Try
lPgIO.ProjectGroupName := ExtractFileName(ExcludeTrailingBackslash(APath));
If FindFirst(APath + '*.*', faDirectory, lSr) = 0 Then
Try
Repeat
If (lSr.Attr And faDirectory <> 0) And Not SameText(lSr.Name, '.') And Not SameText(lSr.Name, '..') Then
Begin
lProject := lPgIO.Add();
lProject.ProjectName := lSr.Name;
CreateWsProject(IncludeTrailingBackslash(APath) + lSr.Name + '\', lProject);
End;
Until FindNext(lSr) <> 0
Finally
FindClose(lSr);
End;
lPgIO.SaveToFile(APath + 'WWPromo.xml');
lPgIO.SaveToFile(APath + 'WWPromo.bin');
Finally
lPgIO := Nil;
End;
End;
*)
End.
|
unit AqDrop.DB.Connection;
interface
uses
System.Classes,
System.SyncObjs,
System.SysUtils,
AqDrop.Core.Types,
AqDrop.Core.Manager,
AqDrop.Core.Collections.Intf,
AqDrop.DB.Types,
AqDrop.DB.SQL,
AqDrop.DB.Adapter,
AqDrop.DB.SQL.Intf;
type
TAqDBConnectionClass = class of TAqDBConnection;
/// ------------------------------------------------------------------------------------------------------------------
/// <summary>
/// EN-US:
/// Abstract class for connections with SGBDs.
/// PT-BR:
/// Classe abstrata base para conexões com SGBDs.
/// </summary>
/// ------------------------------------------------------------------------------------------------------------------
TAqDBConnection = class abstract(TAqManager<TObject>)
strict private
FOnwsAdapter: Boolean;
FAutoConnect: Boolean;
FTransactionCalls: UInt32;
FOnRollbackTasks: IAqIDDictionary<TProc>;
FAdapter: TAqDBAdapter;
FReaders: UInt32;
FOnFirstReaderOpened: TProc<TAqDBConnection>;
FOnLastReaderClosed: TProc<TAqDBConnection>;
procedure CheckConnectionActive;
function PrepareCommand(const pPreparingFunction: TFunc<TAqID>): TAqID; overload;
function OpenQuery(const pOpeningFunction: TFunc<IAqDBReader>): IAqDBReader; overload;
function ExecuteCommand(const pExecutionFunction: TFunc<Int64>): Int64; overload;
class var FConnections: IAqList<TAqDBConnection>;
private
class procedure _Initialize;
class procedure _Finalize;
property OnFirstReaderOpened: TProc<TAqDBConnection> read FOnFirstReaderOpened write FOnFirstReaderOpened;
property OnLastReaderClosed: TProc<TAqDBConnection> read FOnLastReaderClosed write FOnLastReaderClosed;
strict protected
procedure DoStartTransaction; virtual; abstract;
procedure DoCommitTransaction; virtual; abstract;
procedure DoRollbackTransaction; virtual; abstract;
function DoPrepareCommand(const pSQL: string;
const pParametersInitializer: TAqDBParametersHandlerMethod): TAqID; overload; virtual; abstract;
function DoPrepareCommand(const pSQLCommand: IAqDBSQLCommand;
const pParametersInitializer: TAqDBParametersHandlerMethod): TAqID; overload; virtual;
procedure DoUnprepareCommand(const pCommandID: TAqID); virtual; abstract;
function DoExecuteCommand(const pSQL: string;
const pParametersHandler: TAqDBParametersHandlerMethod): Int64; overload; virtual; abstract;
function DoExecuteCommand(const pSQLCommand: IAqDBSQLCommand;
const pParametersHandler: TAqDBParametersHandlerMethod): Int64; overload; virtual;
function DoExecuteCommand(const pCommandID: TAqID;
const pParametersHandler: TAqDBParametersHandlerMethod): Int64; overload; virtual; abstract;
function DoOpenQuery(const pSQL: string;
const pParametersHandler: TAqDBParametersHandlerMethod): IAqDBReader; overload; virtual; abstract;
function DoOpenQuery(const pSQLCommand: IAqDBSQLSelect;
const pParametersHandler: TAqDBParametersHandlerMethod): IAqDBReader; overload; virtual;
function DoOpenQuery(const pCommandID: TAqID;
const pParametersHandler: TAqDBParametersHandlerMethod): IAqDBReader; overload; virtual; abstract;
function GetActive: Boolean; virtual; abstract;
procedure SetActive(const pValue: Boolean); virtual;
function GetInTransaction: Boolean;
procedure DoConnect; virtual; abstract;
procedure DoDisconnect; virtual; abstract;
function CreateAdapter: TAqDBAdapter; virtual;
procedure RaiseImpossibleToConnect(const pEBase: Exception);
property TransactionCalls: UInt32 read FTransactionCalls;
class function GetDefaultAdapter: TAqDBAdapterClass; virtual;
class procedure ReleaseFromConnectionsList(const pConnection: TAqDBConnection);
protected
procedure SetAdapter(const pAdapter: TAqDBAdapter); overload; virtual;
procedure SetAdapter(const pAdapter: TAqDBAdapter; const pOwnsAdapter: Boolean); overload; virtual;
function ExtractAdapter: TAqDBAdapter;
procedure IncreaseReaderes;
procedure DecrementReaders;
public
/// <summary>
/// EN-US:
/// Class copnstructor.
/// PT-BR:
/// Construtor da classe.
/// </summary>
constructor Create; virtual;
/// <summary>
/// EN-US:
/// Class destructor.
/// PT-BR:
/// Destrutor da classe.
/// </summary>
destructor Destroy; override;
/// <summary>
/// EN-US:
/// Opens the connection.
/// PT-BR:
/// Abre a conexão.
/// </summary>
procedure Connect; virtual;
/// <summary>
/// EN-US:
/// Closes the connection.
/// PT-BR:
/// Fecha a conexão.
/// </summary>
procedure Disconnect; virtual;
procedure StartTransaction; virtual;
procedure CommitTransaction; virtual;
procedure RollbackTransaction; virtual;
function RegisterDoOnRollback(const pMethod: TProc): TAqID; virtual;
procedure UnregisterDoOnRollback(const pID: TAqID); virtual;
procedure RollbackAllCalls; virtual;
function PrepareCommand(const pSQL: string;
const pParametersInitializer: TAqDBParametersHandlerMethod = nil): TAqID; overload; virtual;
function PrepareCommand(const pSQLCommand: IAqDBSQLCommand;
const pParametersInitializer: TAqDBParametersHandlerMethod = nil): TAqID; overload; virtual;
procedure UnprepareCommand(const pCommandID: TAqID); virtual;
/// <summary>
/// EN-US:
/// Executes a command.
/// PT-BR:
/// Executa um comando.
/// </summary>
/// <param name="pSQL">
/// EN-US:
/// SQL instruction to be executed.
/// PT-BR:
/// Instrução SQL a ser executada.
/// </param>
/// <param name="pParametersHandler">
/// EN-US:
/// Anonymous method to handle the parameters values of the command.
/// PT-BR:
/// Método anônimo para escrita dos valores de entrada dos parâmetros.
/// </param>
/// <returns>
/// EN-US:
/// Returns the affected rows count.
/// PT-BR:
/// Retorna a quantidade de registros afetados.
/// </returns>
function ExecuteCommand(const pSQL: string;
const pParametersHandler: TAqDBParametersHandlerMethod = nil): Int64; overload; virtual;
function ExecuteCommand(const pSQLCommand: IAqDBSQLCommand;
const pParametersHandler: TAqDBParametersHandlerMethod = nil): Int64; overload; virtual;
function ExecuteCommand(const pCommandID: TAqID;
const pParametersHandler: TAqDBParametersHandlerMethod = nil): Int64; overload; virtual;
function OpenQuery(const pSQL: string;
const pParametersHandler: TAqDBParametersHandlerMethod = nil): IAqDBReader; overload;
function OpenQuery(const pSQLCommand: IAqDBSQLSelect;
const pParametersHandler: TAqDBParametersHandlerMethod = nil): IAqDBReader; overload;
function OpenQuery(const pCommandID: TAqID;
const pParametersHandler: TAqDBParametersHandlerMethod = nil): IAqDBReader; overload;
function GetAutoIncrementValue(const pGenerator: string = ''): Int64; virtual;
property AutoConnect: Boolean read FAutoConnect write FAutoConnect;
property Adapter: TAqDBAdapter read FAdapter write SetAdapter;
property Active: Boolean read GetActive write SetActive;
property InTransaction: Boolean read GetInTransaction;
end;
TAqDBPreparedQuery = class
strict private
FSQL: string;
FParametersInitializer: TAqDBParametersHandlerMethod;
public
constructor Create(const pSQL: string; const pParametersInitializer: TAqDBParametersHandlerMethod);
property SQL: string read FSQL write FSQL;
property ParametersInitializer: TAqDBParametersHandlerMethod read FParametersInitializer
write FParametersInitializer;
end;
TAqDBConnectionPool<TBaseConnection: TAqDBConnection> = class;
TAqDBPooledConnection<TBaseConnection: TAqDBConnection> = class
strict private
FMasterConnection: TAqDBConnectionPool<TBaseConnection>;
FLockerThread: TThreadID;
FConnection: TBaseConnection;
FPreparedQueries: IAqDictionary<TAqID, TAqID>;
FCalls: UInt32;
FLastUsedAt: TDateTime;
function GetIsLocked: Boolean;
public
constructor Create(const pMasterConnections: TAqDBConnectionPool<TBaseConnection>;
const pBaseConection: TBaseConnection);
destructor Destroy; override;
procedure LockConnection;
procedure ReleaseConnection;
function GetCommandID(const pMasterCommandID: TAqID): TAqID;
property Connection: TBaseConnection read FConnection;
property LockerThread: TThreadID read FLockerThread;
property Locked: Boolean read GetIsLocked;
property PreparedQueries: IAqDictionary<TAqID, TAqID> read FPreparedQueries;
property LastUsedAt: TDateTime read FLastUsedAt;
end;
TAqDBFlushContextsThread<TBaseConnection: TAqDBConnection> = class(TThread)
strict private
FAutoFlushContextsTime: UInt32;
FPool: IAqList<TAqDBPooledConnection<TBaseConnection>>;
procedure SetAutoFlushContextsTime(const pValue: UInt32);
protected
procedure Execute; override;
public
constructor Create(const pPool: IAqList<TAqDBPooledConnection<TBaseConnection>>);
property AutoFlushContextsTime: UInt32 read FAutoFlushContextsTime write SetAutoFlushContextsTime;
end;
TAqDBConnectionPool<TBaseConnection: TAqDBConnection> = class(TAqDBConnection)
strict private
FPool: IAqList<TAqDBPooledConnection<TBaseConnection>>;
FConnectionBuilder: TFunc<TBaseConnection>;
FPreparedQueries: IAqIDDictionary<TAqDBPreparedQuery>;
FFlushContextsThread: TAqDBFlushContextsThread<TBaseConnection>;
procedure SolvePoolAndExecute(const pMethod: TProc<TAqDBPooledConnection<TBaseConnection>>);
function GetActiveConnections: Int32;
function GetAutoFlushContextsTime: UInt32;
procedure SetAutoFlushContextsTime(const pValue: UInt32);
procedure FreeFlushContextThread;
strict protected
procedure DoStartTransaction; override;
procedure DoCommitTransaction; override;
procedure DoRollbackTransaction; override;
function DoPrepareCommand(const pSQL: string;
const pParametersInitializer: TAqDBParametersHandlerMethod): TAqID; override;
function DoPrepareCommand(const pSQLCommand: IAqDBSQLCommand;
const pParametersInitializer: TAqDBParametersHandlerMethod): TAqID; override;
procedure DoUnprepareCommand(const pCommandID: TAqID); override;
function DoExecuteCommand(const pSQL: string;
const pTratadorParametros: TAqDBParametersHandlerMethod): Int64; override;
function DoExecuteCommand(const pSQLCommand: IAqDBSQLCommand;
const pTratadorParametros: TAqDBParametersHandlerMethod): Int64; override;
function DoExecuteCommand(const pCommandID: TAqID;
const pTratadorParametros: TAqDBParametersHandlerMethod): Int64; override;
function DoOpenQuery(const pSQL: string;
const pTratadorParametros: TAqDBParametersHandlerMethod): IAqDBReader; override;
function DoOpenQuery(const pSQLCommand: IAqDBSQLSelect;
const pTratadorParametros: TAqDBParametersHandlerMethod): IAqDBReader; override;
function DoOpenQuery(const pCommandID: TAqID;
const pTratadorParametros: TAqDBParametersHandlerMethod): IAqDBReader; override;
function GetActive: Boolean; override;
function CreateNewContext: TAqDBPooledConnection<TBaseConnection>; virtual;
procedure DoConnect; override;
procedure DoDisconnect; override;
{TODO 3 -oTatu -cIncompleto: reativar}
// function GetInTransaction: Boolean; override;
class function GetDefaultAdapter: TAqDBAdapterClass; override;
protected
procedure SetAdapter(const pAdapter: TAqDBAdapter); override;
property PreparedQueries: IAqIDDictionary<TAqDBPreparedQuery> read FPreparedQueries;
property Pool: IAqList<TAqDBPooledConnection<TBaseConnection>> read FPool;
public
constructor Create(const pConnectionBuilder: TFunc<TBaseConnection>); reintroduce; virtual;
destructor Destroy; override;
procedure StartTransaction; override;
procedure CommitTransaction; override;
procedure RollbackTransaction; override;
function RegisterDoOnRollback(const pMethod: TProc): TAqID; override;
procedure UnregisterDoOnRollback(const pID: TAqID); override;
procedure RollbackAllCalls; override;
property ActiveConnections: Int32 read GetActiveConnections;
property AutoFlushContextsTime: UInt32 read GetAutoFlushContextsTime write SetAutoFlushContextsTime;
end;
implementation
uses
System.DateUtils,
AqDrop.Core.Exceptions,
AqDrop.Core.Helpers,
AqDrop.Core.Collections;
{ TAqDBConnection }
function TAqDBConnection.OpenQuery(const pSQL: string;
const pParametersHandler: TAqDBParametersHandlerMethod): IAqDBReader;
begin
Result := OpenQuery(
function: IAqDBReader
begin
Result := DoOpenQuery(pSQL, pParametersHandler);
end);
end;
procedure TAqDBConnection.CheckConnectionActive;
begin
if not Active then
begin
if not FAutoConnect then
begin
raise EAqInternal.Create('Connection is not active.');
end;
Connect;
end;
end;
function TAqDBConnection.OpenQuery(const pCommandID: TAqID;
const pParametersHandler: TAqDBParametersHandlerMethod): IAqDBReader;
begin
Result := OpenQuery(
function: IAqDBReader
begin
Result := DoOpenQuery(pCommandID, pParametersHandler);
end);
end;
function TAqDBConnection.OpenQuery(const pSQLCommand: IAqDBSQLSelect;
const pParametersHandler: TAqDBParametersHandlerMethod): IAqDBReader;
begin
Result := OpenQuery(
function: IAqDBReader
begin
Result := DoOpenQuery(pSQLCommand, pParametersHandler);
end);
end;
function TAqDBConnection.OpenQuery(const pOpeningFunction: TFunc<IAqDBReader>): IAqDBReader;
begin
try
CheckConnectionActive;
Result := pOpeningFunction;
except
on E: Exception do
begin
E.RaiseOuterException(EAqInternal.Create('It wasn''t possible to open the query.'));
end;
end;
end;
procedure TAqDBConnection.Connect;
begin
if not Active then
begin
SetActive(True);
end;
end;
procedure TAqDBConnection.StartTransaction;
begin
try
CheckConnectionActive;
if FTransactionCalls = 0 then
begin
DoStartTransaction;
end;
Inc(FTransactionCalls);
except
on E: Exception do
begin
E.RaiseOuterException(EAqInternal.Create('It wasn''t possible to start the transaction.'));
end;
end;
end;
procedure TAqDBConnection.CommitTransaction;
begin
try
CheckConnectionActive;
if FTransactionCalls = 0 then
begin
raise EAqInternal.Create('There is no transaction to commit.');
end;
Dec(FTransactionCalls);
if FTransactionCalls = 0 then
begin
DoCommitTransaction;
if Assigned(FOnRollbackTasks) then
begin
FOnRollbackTasks.Clear;
end;
end;
except
on E: Exception do
begin
E.RaiseOuterException(EAqInternal.Create('It wasn''t possible to commit the transaction.'));
end;
end;
end;
constructor TAqDBConnection.Create;
begin
inherited;
SetAdapter(CreateAdapter);
FConnections.ExecuteLockedForWriting(
procedure
begin
FConnections.Add(Self);
end);
end;
function TAqDBConnection.CreateAdapter: TAqDBAdapter;
var
lAdapterClass: TAqDBAdapterClass;
begin
lAdapterClass := GetDefaultAdapter;
if Assigned(lAdapterClass) then
begin
Result := lAdapterClass.Create;
end else begin
Result := nil;
end;
end;
procedure TAqDBConnection.Disconnect;
begin
if Active then
begin
SetActive(False);
end;
end;
procedure TAqDBConnection.UnprepareCommand(const pCommandID: TAqID);
begin
DoUnprepareCommand(pCommandID);
end;
procedure TAqDBConnection.UnregisterDoOnRollback(const pID: TAqID);
begin
if Assigned(FOnRollbackTasks) then
begin
FOnRollbackTasks.Remove(pID);
end;
end;
class procedure TAqDBConnection._Finalize;
begin
{$IFNDEF AUTOREFCOUNT}
while FConnections.Count > 0 do
begin
FConnections.Last.Free;
end;
{$ENDIF}
end;
class procedure TAqDBConnection._Initialize;
begin
FConnections := TAqList<TAqDBConnection>.Create(TAqLockerType.lktMultiReaderExclusiveWriter);
end;
procedure TAqDBConnection.DecrementReaders;
begin
if FReaders > 0 then
begin
Dec(FReaders);
if Assigned(FOnLastReaderClosed) and (FReaders = 0) then
begin
FOnLastReaderClosed(Self);
end;
end;
end;
destructor TAqDBConnection.Destroy;
begin
if FOnwsAdapter then
begin
FAdapter.Free;
end;
ReleaseFromConnectionsList(Self);
inherited;
end;
function TAqDBConnection.ExecuteCommand(const pExecutionFunction: TFunc<Int64>): Int64;
begin
Result := 0;
try
CheckConnectionActive;
Result := pExecutionFunction;
except
on E: Exception do
begin
E.RaiseOuterException(EAqInternal.Create('It wasn''t possible to execute the command.'));
end;
end;
end;
function TAqDBConnection.ExecuteCommand(const pSQL: string;
const pParametersHandler: TAqDBParametersHandlerMethod): Int64;
begin
Result := ExecuteCommand(
function: Int64
begin
Result := DoExecuteCommand(pSQL, pParametersHandler);
end);
end;
function TAqDBConnection.GetAutoIncrementValue(const pGenerator: string): Int64;
var
lReader: IAqDBReader;
lQuery: string;
begin
lQuery := Adapter.SQLSolver.GetAutoIncrementQuery(pGenerator);
if lQuery.IsEmpty then
begin
Result := 0;
end else begin
lReader := OpenQuery(lQuery);
if not lReader.Next then
begin
raise EAqInternal.Create('It wasn''t possible to get the generator value.');
end;
Result := lReader.Values[0].AsInt64;
end;
end;
class function TAqDBConnection.GetDefaultAdapter: TAqDBAdapterClass;
begin
Result := TAqDBAdapter;
end;
function TAqDBConnection.GetInTransaction: Boolean;
begin
Result := FTransactionCalls > 0;
end;
procedure TAqDBConnection.IncreaseReaderes;
begin
if Assigned(FOnFirstReaderOpened) and (FReaders = 0) then
begin
FOnFirstReaderOpened(Self);
end;
Inc(FReaders);
end;
function TAqDBConnection.PrepareCommand(const pSQLCommand: IAqDBSQLCommand;
const pParametersInitializer: TAqDBParametersHandlerMethod = nil): TAqID;
begin
Result := PrepareCommand(
function: TAqID
begin
Result := DoPrepareCommand(pSQLCommand, pParametersInitializer);
end);
end;
function TAqDBConnection.PrepareCommand(const pPreparingFunction: TFunc<TAqID>): TAqID;
begin
Result := 0;
try
CheckConnectionActive;
Result := pPreparingFunction;
except
on E: Exception do
begin
E.RaiseOuterException(EAqInternal.Create('It wasn''t possible to prepare the command.'));
end;
end;
end;
function TAqDBConnection.DoOpenQuery(const pSQLCommand: IAqDBSQLSelect;
const pParametersHandler: TAqDBParametersHandlerMethod): IAqDBReader;
begin
Result := DoOpenQuery(FAdapter.SQLSolver.SolveSelect(pSQLCommand), pParametersHandler);
end;
function TAqDBConnection.DoExecuteCommand(const pSQLCommand: IAqDBSQLCommand;
const pParametersHandler: TAqDBParametersHandlerMethod): Int64;
begin
Result := DoExecuteCommand(FAdapter.SQLSolver.SolveCommand(pSQLCommand), pParametersHandler);
end;
function TAqDBConnection.DoPrepareCommand(const pSQLCommand: IAqDBSQLCommand;
const pParametersInitializer: TAqDBParametersHandlerMethod): TAqID;
begin
Result := DoPrepareCommand(FAdapter.SQLSolver.SolveCommand(pSQLCommand), pParametersInitializer);
end;
procedure TAqDBConnection.RaiseImpossibleToConnect(const pEBase: Exception);
begin
pEBase.RaiseOuterException(EAqFriendly.Create('It wasn''t possible to stablish a connection to the DB.'));
end;
class procedure TAqDBConnection.ReleaseFromConnectionsList(const pConnection: TAqDBConnection);
begin
FConnections.ExecuteLockedForWriting(
procedure
var
lI: Int32;
begin
lI := FConnections.IndexOf(pConnection);
if lI >= 0 then
begin
FConnections.Delete(lI);
end;
end);
end;
procedure TAqDBConnection.RollbackAllCalls;
begin
while FTransactionCalls > 0 do
begin
RollbackTransaction;
end;
end;
procedure TAqDBConnection.RollbackTransaction;
var
lTask: TProc;
begin
try
CheckConnectionActive;
if FTransactionCalls = 0 then
begin
raise EAqInternal.Create('There are no transaction to revert.');
end;
Dec(FTransactionCalls);
if FTransactionCalls = 0 then
begin
if Assigned(FOnRollbackTasks) and (FOnRollbackTasks.Count > 0) then
begin
for lTask in FOnRollbackTasks.Values do
begin
lTask();
end;
FOnRollbackTasks.Clear;
end;
DoRollbackTransaction;
end;
except
on E: Exception do
begin
E.RaiseOuterException(EAqInternal.Create('It wasn''t possible to rollback the transaction.'));
end;
end;
end;
function TAqDBConnection.PrepareCommand(const pSQL: string;
const pParametersInitializer: TAqDBParametersHandlerMethod = nil): TAqID;
begin
Result := PrepareCommand(
function: TAqID
begin
Result := DoPrepareCommand(pSQL, pParametersInitializer);
end);
end;
procedure TAqDBConnection.SetAdapter(const pAdapter: TAqDBAdapter);
begin
SetAdapter(pAdapter, True);
end;
procedure TAqDBConnection.SetActive(const pValue: Boolean);
begin
inherited;
if pValue xor Active then
begin
if pValue then
begin
DoConnect;
end else begin
DoDisconnect;
end;
end;
end;
procedure TAqDBConnection.SetAdapter(const pAdapter: TAqDBAdapter; const pOwnsAdapter: Boolean);
begin
if FOnwsAdapter then
begin
FAdapter.Free;
end;
FAdapter := pAdapter;
FOnwsAdapter := pOwnsAdapter;
end;
function TAqDBConnection.ExecuteCommand(const pCommandID: TAqID;
const pParametersHandler: TAqDBParametersHandlerMethod): Int64;
begin
Result := ExecuteCommand(
function: Int64
begin
Result := DoExecuteCommand(pCommandID, pParametersHandler);
end);
end;
function TAqDBConnection.ExtractAdapter: TAqDBAdapter;
begin
Result := FAdapter;
FAdapter := nil;
FOnwsAdapter := False;
end;
function TAqDBConnection.ExecuteCommand(const pSQLCommand: IAqDBSQLCommand;
const pParametersHandler: TAqDBParametersHandlerMethod): Int64;
begin
Result := ExecuteCommand(
function: Int64
begin
Result := DoExecuteCommand(pSQLCommand, pParametersHandler);
end);
end;
function TAqDBConnection.RegisterDoOnRollback(const pMethod: TProc): TAqID;
begin
if not Assigned(FOnRollbackTasks) then
begin
FOnRollbackTasks := TAqIDDictionary<TProc>.Create;
end;
Result := FOnRollbackTasks.Add(pMethod);
end;
{ TAqDBConnectionPool<TBaseConnection> }
procedure TAqDBConnectionPool<TBaseConnection>.CommitTransaction;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
pContext.Connection.CommitTransaction;
end);
end;
constructor TAqDBConnectionPool<TBaseConnection>.Create(const pConnectionBuilder: TFunc<TBaseConnection>);
var
lBaseContext: TAqDBPooledConnection<TBaseConnection>;
begin
FConnectionBuilder := pConnectionBuilder;
FPreparedQueries := TAqIDDictionary<TAqDBPreparedQuery>.Create(True);
FPool := TAqList<TAqDBPooledConnection<TBaseConnection>>.Create(True, TAqLockerType.lktMultiReaderExclusiveWriter);
inherited Create;
lBaseContext := CreateNewContext;
if not Assigned(Adapter) then
begin
SetAdapter(lBaseContext.Connection.ExtractAdapter);
end;
AutoFlushContextsTime := 3 * SecsPerMin;
end;
function TAqDBConnectionPool<TBaseConnection>.CreateNewContext: TAqDBPooledConnection<TBaseConnection>;
var
lConnection: TAqDBConnection;
begin
FPool.BeginWrite;
try
Result := nil;
try
lConnection := FConnectionBuilder();
try
lConnection.Connect;
if Assigned(Adapter) then
begin
lConnection.SetAdapter(Adapter, False);
end;
except
lConnection.Free;
raise;
end;
Result := TAqDBPooledConnection<TBaseConnection>.Create(Self, lConnection);
ReleaseFromConnectionsList(lConnection);
FPool.Add(Result);
except
Result.Free;
raise;
end;
finally
FPool.EndWrite;
end;
end;
destructor TAqDBConnectionPool<TBaseConnection>.Destroy;
begin
FreeFlushContextThread;
inherited;
end;
class function TAqDBConnectionPool<TBaseConnection>.GetDefaultAdapter: TAqDBAdapterClass;
begin
Result := nil;
end;
procedure TAqDBConnectionPool<TBaseConnection>.RollbackAllCalls;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
pContext.Connection.RollbackAllCalls;
end);
end;
procedure TAqDBConnectionPool<TBaseConnection>.RollbackTransaction;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
pContext.Connection.RollbackTransaction;
end);
end;
function TAqDBConnectionPool<TBaseConnection>.GetActive: Boolean;
begin
FPool.BeginRead;
try
Result := FPool.First.Connection.Active;
finally
FPool.EndRead;
end;
end;
function TAqDBConnectionPool<TBaseConnection>.GetActiveConnections: Int32;
begin
FPool.BeginRead;
try
Result := FPool.Count;
finally
FPool.EndRead;
end;
end;
function TAqDBConnectionPool<TBaseConnection>.GetAutoFlushContextsTime: UInt32;
begin
if Assigned(FFlushContextsThread) then
begin
Result := 0;
end else begin
Result := FFlushContextsThread.AutoFlushContextsTime;
end;
end;
//function TAqDBConnectionPool<TBaseConnection>.GetInTransaction: Boolean;
//var
// lResult: Boolean;
//begin
// SolvePoolAndExecute(
// procedure(const pContext: TAqDBPooledConnection)
// begin
// lResult := pContext.Connection.InTransaction;
// end);
//end;
function TAqDBConnectionPool<TBaseConnection>.DoOpenQuery(const pSQLCommand: IAqDBSQLSelect;
const pTratadorParametros: TAqDBParametersHandlerMethod): IAqDBReader;
var
lResult: IAqDBReader;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
lResult := pContext.Connection.OpenQuery(pSQLCommand, pTratadorParametros);
end);
Result := lResult;
end;
function TAqDBConnectionPool<TBaseConnection>.RegisterDoOnRollback(const pMethod: TProc): TAqID;
var
lResult: TAqID;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
lResult := pContext.Connection.RegisterDoOnRollback(pMethod);
end);
Result := lResult;
end;
function TAqDBConnectionPool<TBaseConnection>.DoOpenQuery(const pCommandID: TAqID;
const pTratadorParametros: TAqDBParametersHandlerMethod): IAqDBReader;
var
lResult: IAqDBReader;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
lResult := pContext.Connection.OpenQuery(pContext.GetCommandID(pCommandID), pTratadorParametros);
end);
Result := lResult;
end;
function TAqDBConnectionPool<TBaseConnection>.DoOpenQuery(const pSQL: string;
const pTratadorParametros: TAqDBParametersHandlerMethod): IAqDBReader;
var
lResult: IAqDBReader;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
lResult := pContext.Connection.OpenQuery(pSQL, pTratadorParametros);
end);
Result := lResult;
end;
procedure TAqDBConnectionPool<TBaseConnection>.DoStartTransaction;
begin
raise EAqInternal.Create('The fisical transaction methods of this class cannot be called.');
end;
procedure TAqDBConnectionPool<TBaseConnection>.DoConnect;
var
lContext: TAqDBPooledConnection<TBaseConnection>;
begin
FPool.BeginRead;
try
for lContext in FPool do
begin
lContext.Connection.Active := True;
end;
finally
FPool.EndRead;
end;
end;
procedure TAqDBConnectionPool<TBaseConnection>.DoCommitTransaction;
begin
raise EAqInternal.Create('The fisical transaction methods of this class cannot be called.');
end;
procedure TAqDBConnectionPool<TBaseConnection>.DoDisconnect;
begin
FPool.BeginWrite;
try
FPool.First.Connection.Active := False;
while FPool.Count > 1 do
begin
FPool.Delete(FPool.Count - 1);
end;
finally
FPool.EndWrite;
end;
end;
procedure TAqDBConnectionPool<TBaseConnection>.DoUnprepareCommand(const pCommandID: TAqID);
var
lContext: TAqDBPooledConnection<TBaseConnection>;
lContextCommandID: TAqID;
begin
FPool.BeginRead;
try
for lContext in FPool do
begin
if lContext.PreparedQueries.TryGetValue(pCommandID, lContextCommandID) then
begin
lContext.Connection.UnprepareCommand(lContextCommandID);
lContext.PreparedQueries.Remove(pCommandID);
end;
end;
FPreparedQueries.Remove(pCommandID);
finally
FPool.EndRead;
end;
end;
procedure TAqDBConnectionPool<TBaseConnection>.FreeFlushContextThread;
begin
if Assigned(FFlushContextsThread) then
begin
FFlushContextsThread.Terminate;
FFlushContextsThread.WaitFor;
FreeAndNil(FFlushContextsThread);
end;
end;
function TAqDBConnectionPool<TBaseConnection>.DoExecuteCommand(const pSQLCommand: IAqDBSQLCommand;
const pTratadorParametros: TAqDBParametersHandlerMethod): Int64;
var
lResult: Int64;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
lResult := pContext.Connection.ExecuteCommand(pSQLCommand, pTratadorParametros);
end);
Result := lResult;
end;
function TAqDBConnectionPool<TBaseConnection>.DoExecuteCommand(const pCommandID: TAqID;
const pTratadorParametros: TAqDBParametersHandlerMethod): Int64;
var
lResult: Int64;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
lResult := pContext.Connection.ExecuteCommand(pContext.GetCommandID(pCommandID), pTratadorParametros);
end);
Result := lResult;
end;
function TAqDBConnectionPool<TBaseConnection>.DoExecuteCommand(const pSQL: string;
const pTratadorParametros: TAqDBParametersHandlerMethod): Int64;
var
lResult: Int64;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
lResult := pContext.Connection.ExecuteCommand(pSQL, pTratadorParametros);
end);
Result := lResult;
end;
function TAqDBConnectionPool<TBaseConnection>.DoPrepareCommand(const pSQLCommand: IAqDBSQLCommand;
const pParametersInitializer: TAqDBParametersHandlerMethod): TAqID;
begin
Result := DoPrepareCommand(FPool.First.Connection.Adapter.SQLSolver.SolveCommand(pSQLCommand),
pParametersInitializer);
end;
function TAqDBConnectionPool<TBaseConnection>.DoPrepareCommand(const pSQL: string;
const pParametersInitializer: TAqDBParametersHandlerMethod): TAqID;
begin
Result := FPreparedQueries.Add(TAqDBPreparedQuery.Create(pSQL, pParametersInitializer));
end;
procedure TAqDBConnectionPool<TBaseConnection>.DoRollbackTransaction;
begin
raise EAqInternal.Create('The fisical transaction methods of this class cannot be called.');
end;
procedure TAqDBConnectionPool<TBaseConnection>.SolvePoolAndExecute(
const pMethod: TProc<TAqDBPooledConnection<TBaseConnection>>);
var
lI: Int32;
lLockedContext: TAqDBPooledConnection<TBaseConnection>;
lAvailableContext: TAqDBPooledConnection<TBaseConnection>;
lThreadID: TThreadID;
begin
FPool.BeginWrite;
try
lI := FPool.Count;
lLockedContext := nil;
lAvailableContext := nil;
lThreadID := TThread.CurrentThread.ThreadID;
{TODO 3 -oTatu -cMelhoria: colocar contextos locados em um dictionary a parte da lista de contextos disponíveis.}
while not Assigned(lLockedContext) and (lI > 0) do
begin
Dec(lI);
if FPool[lI].Locked and (FPool[lI].LockerThread = lThreadID) then
begin
lLockedContext := FPool[lI];
end else if not FPool[lI].Locked then
begin
lAvailableContext := FPool[lI];
end;
end;
if not Assigned(lLockedContext) then
begin
if Assigned(lAvailableContext) then
begin
lLockedContext := lAvailableContext;
end else begin
lLockedContext := CreateNewContext;
end;
end;
lLockedContext.LockConnection;
finally
FPool.EndWrite;
end;
try
pMethod(lLockedContext);
finally
lLockedContext.ReleaseConnection;
end;
end;
procedure TAqDBConnectionPool<TBaseConnection>.StartTransaction;
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
pContext.Connection.StartTransaction;
end);
end;
procedure TAqDBConnectionPool<TBaseConnection>.UnregisterDoOnRollback(const pID: TAqID);
begin
SolvePoolAndExecute(
procedure(pContext: TAqDBPooledConnection<TBaseConnection>)
begin
pContext.Connection.UnregisterDoOnRollback(pID);
end);
end;
procedure TAqDBConnectionPool<TBaseConnection>.SetAutoFlushContextsTime(const pValue: UInt32);
begin
if pValue = 0 then
begin
FreeFlushContextThread;
end else begin
if not Assigned(FFlushContextsThread) then
begin
FFlushContextsThread := TAqDBFlushContextsThread<TBaseConnection>.Create(FPool);
end;
FFlushContextsThread.AutoFlushContextsTime := pValue;
end;
end;
procedure TAqDBConnectionPool<TBaseConnection>.SetAdapter(const pAdapter: TAqDBAdapter);
var
lContext: TAqDBPooledConnection<TBaseConnection>;
begin
FPool.BeginRead;
try
inherited;
for lContext in FPool do
begin
lContext.Connection.SetAdapter(pAdapter, False);
end;
finally
FPool.EndRead;
end;
end;
{ TAqDBPooledConnection<TBaseConnection> }
constructor TAqDBPooledConnection<TBaseConnection>.Create(
const pMasterConnections: TAqDBConnectionPool<TBaseConnection>; const pBaseConection: TBaseConnection);
begin
FMasterConnection := pMasterConnections;
FConnection := pBaseConection;
FPreparedQueries := TAqDictionary<TAqID, TAqID>.Create;
FConnection.OnFirstReaderOpened :=
procedure(pConnection: TAqDBConnection)
begin
Self.LockConnection;
end;
FConnection.OnLastReaderClosed :=
procedure(pConnection: TAqDBConnection)
begin
Self.ReleaseConnection;
end;
end;
destructor TAqDBPooledConnection<TBaseConnection>.Destroy;
begin
FConnection.Free;
inherited;
end;
function TAqDBPooledConnection<TBaseConnection>.GetCommandID(const pMasterCommandID: TAqID): TAqID;
var
lPreparedQuery: TAqDBPreparedQuery;
begin
if not FPreparedQueries.TryGetValue(pMasterCommandID, Result) then
begin
if not FMasterConnection.PreparedQueries.TryGetValue(pMasterCommandID, lPreparedQuery) then
begin
raise EAqInternal.CreateFmt('Command from ID %d not found.', [pMasterCommandID]);
end;
Result := FConnection.PrepareCommand(lPreparedQuery.SQL, lPreparedQuery.ParametersInitializer);
try
FPreparedQueries.Add(pMasterCommandID, Result);
except
FConnection.UnprepareCommand(Result);
raise;
end;
end;
end;
function TAqDBPooledConnection<TBaseConnection>.GetIsLocked: Boolean;
begin
Result := FLockerThread <> 0;
end;
procedure TAqDBPooledConnection<TBaseConnection>.ReleaseConnection;
begin
Self.FMasterConnection.Pool.BeginWrite;
try
if FCalls > 0 then
begin
Dec(FCalls);
if not FConnection.InTransaction and (FCalls = 0) then
begin
FLockerThread := 0;
FLastUsedAt := Now;
end;
end;
finally
Self.FMasterConnection.Pool.EndWrite;
end;
end;
procedure TAqDBPooledConnection<TBaseConnection>.LockConnection;
begin
Self.FMasterConnection.Pool.BeginWrite;
try
if (FLockerThread <> 0) and (FLockerThread <> TThread.CurrentThread.ThreadID) then
begin
raise EAqInternal.Create('This context is already locked to another thread.');
end;
FLockerThread := TThread.CurrentThread.ThreadID;
Inc(FCalls);
finally
Self.FMasterConnection.Pool.EndWrite;
end;
end;
{ TAqDBFlushContextsThread<TBaseConnection> }
constructor TAqDBFlushContextsThread<TBaseConnection>.Create(
const pPool: IAqList<TAqDBPooledConnection<TBaseConnection>>);
begin
inherited Create(False);
FPool := pPool;
end;
procedure TAqDBFlushContextsThread<TBaseConnection>.Execute;
var
lNextAttempt: TDateTime;
lI: Int32;
lContext: TAqDBPooledConnection<TBaseConnection>;
lDateTimeCut: TDateTime;
begin
lNextAttempt := 0;
while not Terminated do
begin
if lNextAttempt <= Now then
begin
lDateTimeCut := Now.IncSecond(-FAutoFlushContextsTime);
FPool.BeginWrite;
try
lI := 0;
while not Terminated and (lI < FPool.Count - 1) do
begin
lContext := FPool[lI];
if lContext.Locked or (lContext.LastUsedAt > lDateTimeCut) then
begin
Inc(lI);
end else begin
FPool.Delete(lI);
end;
end;
finally
FPool.EndWrite;
end;
lNextAttempt := Now.IncSecond((FAutoFlushContextsTime div 4) + 1);
end;
Sleep(10);
end;
end;
procedure TAqDBFlushContextsThread<TBaseConnection>.SetAutoFlushContextsTime(
const pValue: UInt32);
begin
FPool.BeginRead;
try
FAutoFlushContextsTime := pValue;
finally
FPool.EndRead;
end;
end;
{ TAqDBPreparedQuery }
constructor TAqDBPreparedQuery.Create(const pSQL: string;
const pParametersInitializer: TAqDBParametersHandlerMethod);
begin
FSQL := pSQL;
FParametersInitializer := pParametersInitializer;
end;
initialization
TAqDBConnection._Initialize;
finalization
TAqDBConnection._Finalize;
end.
|
program OpgaveMultidimensioneleArrays;
TYPE tweeDim = array[0..9, 0..9] of integer;
var min, max, kolom: integer;
var arr: tweeDim;
function GemiddeldeVanKolom(pArr: tweeDim; pKolom: integer): real;
var rij: integer;
begin
GemiddeldeVanKolom := 0;
for rij := 0 to 9 do
begin
GemiddeldeVanKolom := GemiddeldeVanKolom + pArr[rij, pKolom];
end;
GemiddeldeVanKolom := GemiddeldeVanKolom / 10;
end;
procedure SchrijfArray(pArr: tweeDim);
var rij, kolom: integer;
begin
writeln();
for rij := 0 to 9 do
begin
for kolom := 0 to 9 do
begin
write(pArr[rij, kolom], ' ');
end;
writeln();
end;
writeln();
end;
procedure VulArrayMetRandomGetallen(var pArr: tweeDim; min, max: integer);
var rij, kolom: integer;
begin
for rij := 0 to 9 do
begin
for kolom := 0 to 9 do
begin
pArr[rij, kolom] := RANDOM(max - min + 1) + min;
end;
end;
end;
begin
RANDOMIZE;
writeln('Geef de minimumwaarde die getallen uit de array kunnen aannemen:');
readln(min);
writeln('Geef de maximumwaarde die getallen uit de array kunnen aannemen:');
readln(max);
VulArrayMetRandomgetallen(arr, min, max);
SchrijfArray(arr);
writeln('Van welke kolom wil je het gemiddelde kennen? (kolom 1 heeft index 0)');
readln(kolom);
while (kolom < 0) AND (kolom > 9) do
begin
writeln('Ongeldige kolomindex. Kies een waarde van 0 tot en met 9');
readln(kolom);
end;
writeln(GemiddeldeVanKolom(arr, kolom):0:2);
writeln();
writeln('Druk op <ENTER> om het programma te stoppen.');
readln();
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus, System.UITypes,
System.Actions, Vcl.ActnList;
type
TForm1 = class(TForm)
Button1: TButton;
MainMenu1: TMainMenu;
ools1: TMenuItem;
UpdateDatabase1: TMenuItem;
Button2: TButton;
Phone1: TMenuItem;
IncludeCountryCode1: TMenuItem;
ExcludeCountryCode1: TMenuItem;
ActionList1: TActionList;
ConnSQLiteAction: TAction;
ConnFirebirdAction: TAction;
ConnRemoteDBAction: TAction;
Connections1: TMenuItem;
ConnSQLiteAction1: TMenuItem;
ConnFirebirdAction1: TMenuItem;
ConnRemoteDBAction1: TMenuItem;
procedure Button1Click(Sender: TObject);
procedure UpdateDatabase1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure IncludeCountryCode1Click(Sender: TObject);
procedure ExcludeCountryCode1Click(Sender: TObject);
procedure ConnSQLiteActionExecute(Sender: TObject);
procedure ConnFirebirdActionExecute(Sender: TObject);
procedure ConnRemoteDBActionExecute(Sender: TObject);
procedure ConnSQLiteActionUpdate(Sender: TObject);
procedure ConnFirebirdActionUpdate(Sender: TObject);
procedure ConnRemoteDBActionUpdate(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
uses
Forms.CustomerList, Forms.CountryList, Modules.Connections,
PhoneTools;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
CustomersForm: TCustomersForm;
begin
CustomersForm := TCustomersForm.Create(Application);
try
CustomersForm.ShowModal;
finally
CustomersForm.Free;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
CountriesForm: TCountriesForm;
begin
CountriesForm := TCountriesForm.Create(Application);
try
CountriesForm.ShowModal;
finally
CountriesForm.Free;
end;
end;
procedure TForm1.ConnFirebirdActionExecute(Sender: TObject);
begin
Connections.DefaultConnection := Connections.FirebirdConnection;
end;
procedure TForm1.ConnFirebirdActionUpdate(Sender: TObject);
begin
TAction(Sender).Checked := Connections.DefaultConnection = Connections.FirebirdConnection;
end;
procedure TForm1.ConnRemoteDBActionExecute(Sender: TObject);
begin
Connections.DefaultConnection := Connections.RemoteDBConnection;
end;
procedure TForm1.ConnRemoteDBActionUpdate(Sender: TObject);
begin
TAction(Sender).Checked := Connections.DefaultConnection = Connections.RemoteDBConnection;
end;
procedure TForm1.ConnSQLiteActionExecute(Sender: TObject);
begin
Connections.DefaultConnection := Connections.SQLiteConnection;
end;
procedure TForm1.ConnSQLiteActionUpdate(Sender: TObject);
begin
TAction(Sender).Checked := Connections.DefaultConnection = Connections.SQLiteConnection;
end;
procedure TForm1.ExcludeCountryCode1Click(Sender: TObject);
begin
if MessageDlg('Exclude country code from all phone numbers?', mtConfirmation, [mbYes, mbNo], 0, mbNo) = mrYes then
begin
TPhoneTools.UpdateCountryCodes(false);
ShowMessage('Phone numbers updated.');
end;
end;
procedure TForm1.IncludeCountryCode1Click(Sender: TObject);
begin
if MessageDlg('Include country code from all phone numbers?', mtConfirmation, [mbYes, mbNo], 0, mbNo) = mrYes then
begin
TPhoneTools.UpdateCountryCodes(true);
ShowMessage('Phone numbers updated.');
end;
end;
procedure TForm1.UpdateDatabase1Click(Sender: TObject);
begin
Connections.UpdateDatabase;
ShowMessage('Database updated succesfully.');
end;
end.
|
unit OAuth2.Contract.ResponseType;
interface
uses
Web.HTTPApp,
OAuth2.Contract.Entity.AccessToken,
OAuth2.Contract.Entity.RefreshToken;
type
IOAuth2ResponseType = interface
['{7511A628-DCD8-45EB-98CC-4B709551D0E3}']
procedure SetAccessToken(AAccessToken: IOAuth2AccessTokenEntity);
procedure SetRefreshToken(ARefreshToken: IOAuth2RefreshTokenEntity);
function GenerateHttpResponse(AResponse: TWebResponse): TWebResponse;
procedure SetEncryptionKey(const AKey: string = '');
end;
implementation
end.
|
program ShittyPathMakingTool;
{==============================================================================]
Some stupid tool to generate paths..
It will have to do for now, it's kind of a bitch to use tho.
Start instructions..:
> Start it once to boot up smart... log in and whatnots..
> Target smart with Simba's targeting thingy.
Usage instructions..:
Do not move in the following process, and have compass at North..:
> Left-click on objects (marked as squares) [3+ is good with 2+ of different types is best]
> Right-Click to select the actual point you wanna walk to `Goal`.
> Click "Done".. Your first step has just been made.
Now you can click through the minimap, so walk to the `Goal` point you just set..
> Click the button that now says `DISABLED` to start blocking input again (so you don't walk around)
> Repeat the process above..
When you are done, you can print the path you just made by clocking `PRINT`
If you make mistakes, simply press clear to reset that step.
Restart the tool (stop + start the script) to make a new path ^____-
[==============================================================================}
{$hints off}
{$define SMART}
{$I SRL/OSR.simba}
{$DEFINE OW:SMARTDEBUG}
{$I ObjectWalk/Walker.simba}
type
EButtonType = (btCapture, btClear, btDone, btPrintPath);
var
client2:TClient;
isCapturing:Boolean = True;
isCompleted: Boolean;
Buttons: array [EButtonType] of TBox = [
[706,02,762,18],
[715,20,762,36],
[722,38,762,54],
[726,56,762,72]
];
var
Walker: TObjectWalk;
path:TMMPath;
DTM:TMMDTM;
Goal:TPoint;
function ToString(X:TMMDTM): String; override;
var i:Int32;
begin
Result := '[';
for i:=0 to High(X) do
begin
Result += '['+ToString(X[i].typ)+','+ToString(X[i].x)+','+ToString(X[i].y)+']';
if i <> High(X) then Result += ',';
end;
Result += ']';
end;
function ToString(X:TPoint): String; override;
begin
Result := '['+ToString(X.x)+','+ToString(X.y)+']';
end;
procedure Init();
begin
client2.Init(PluginPath);
client2.getIOManager.SetTarget2(GetNativeWindow());
srl.Debugging := False;
Smart.EnableDrawing := True;
//Smart.JavaPath := 'D:\Java7-32\bin\javaw.exe';
Smart.Init();
mouse.SetSpeed(39);
Walker.Init();
end;
procedure ReDrawInterface();
begin
if isCapturing then
begin
smart.Image.DrawTPA(TPAFromBox(Buttons[btCapture]), $009900);
smart.Image.DrawBox(Buttons[btCapture], 1);
smart.Image.DrawText('ENABLED',Point(Buttons[btCapture].x1+3,Buttons[btCapture].y1+3), $FFFFFF);
end else
begin
smart.Image.DrawTPA(TPAFromBox(Buttons[btCapture]), $000099);
smart.Image.DrawBox(Buttons[btCapture], 1);
smart.Image.DrawText('DISABLED',Point(Buttons[btCapture].x1+3,Buttons[btCapture].y1+3), $FFFFFF);
end;
begin
smart.Image.DrawTPA(TPAFromBox(Buttons[btClear]), $333333);
smart.Image.DrawBox(Buttons[btClear], 1);
smart.Image.DrawText('CLEAR',Point(Buttons[btClear].x1+3,Buttons[btClear].y1+3), $FFFFFF);
end;
begin
smart.Image.DrawTPA(TPAFromBox(Buttons[btDone]), $333333);
smart.Image.DrawBox(Buttons[btDone], 1);
smart.Image.DrawText('DONE',Point(Buttons[btDone].x1+3,Buttons[btDone].y1+3), $FFFFFF);
end;
begin
smart.Image.DrawTPA(TPAFromBox(Buttons[btPrintPath]), $333333);
smart.Image.DrawBox(Buttons[btPrintPath], 1);
smart.Image.DrawText('PRINT',Point(Buttons[btPrintPath].x1+3,Buttons[btPrintPath].y1+3), $FFFFFF);
end;
end;
procedure RedrawObjects();
var i:Int32;
begin
Walker.DebugMinimap(smart.Image);
for i:=0 to High(DTM) do
smart.Image.DrawCircle(Point(dtm[i].x,dtm[i].y), 3, False, $FFFFFF);
if Goal <> [0,0] then
smart.Image.DrawCircle(Point(Goal.x,Goal.y), 3, True, 255);
end;
procedure ToggleCapture();
begin
isCapturing := not isCapturing;
end;
procedure ClearDTM();
begin
SetLength(DTM, 0);
Goal := [0,0];
end;
procedure FinalizeDTM();
begin
if (Goal <> [0,0]) then
begin
Mouse.Click(goal, mouse_Left);
SetLength(path, Length(path)+1);
path[high(path)].Objects := DTM;
path[high(path)].Dest := [goal];
WriteLn('---------------------------------------------------------');
WriteLn('Path[',high(path),'].Objects := ', path[high(path)].Objects,';');
WriteLn('Path[',high(path),'].Dest := ', path[high(path)].Dest,';');
WriteLn('---------------------------------------------------------');
SetLength(DTM,0);
Goal := [0,0];
minimap.WaitFlag();
end else
WriteLn('Path is incomplete, select goal by right-clicking where you want to walk');
end;
procedure OutputPath();
var i:Int32;
begin
ClearDebug();
WriteLn('SetLength(path, ', Length(path),');');
for i:=0 to High(path) do
begin
WriteLn('Path[',i,'].Objects := ', path[i].Objects ,';');
WriteLn('Path[',i,'].Dest := ', path[i].Dest ,';');
end;
end;
procedure SelectObject(pos:TPoint; clickType:Int32);
var
i,h:Int32;
TPA:TPointArray;
begin
if clickType = 0 then
begin
for i:=0 to High(MMObjRecords) do
begin
TPA := Minimap.FindObj(MMObjRecords[i]);
SortTPAFrom(TPA, pos);
if (Length(TPA) > 0) and (Distance(TPA[0],pos) <= 2) then
begin
h := Length(DTM);
SetLength(DTM, h+1);
DTM[h].x := TPA[0].x;
DTM[h].y := TPA[0].y;
DTM[h].typ := EMinimapObject(i);
WriteLn('Selected: ', DTM[h]);
Exit();
end;
end;
end else
begin
WriteLn('Goal set to ', pos);
Goal := pos;
end;
end;
procedure HandleClick();
var
i,click:Int32 = -1;
pos:TPoint;
function ValidClick(pos:TPoint): Boolean;
var v,W,H:Int32;
begin
client2.GetIOManager.GetPosition(v,v);
if v > 30000 then Exit(False);
client2.GetIOManager.GetDimensions(W,H);
Result := (pos.x >= 0) and (pos.x < W) and (pos.y >= 0) and (pos.y < H);
end;
begin
client2.GetIOManager.GetMousePos(pos.x,pos.y);
if client2.GetIOManager.IsMouseButtonDown(0) then
click := 0
else if (client2.GetIOManager.IsMouseButtonDown(1)) then
click := 1;
if (click = -1) then Exit;
while client2.GetIOManager.IsMouseButtonDown(click) do Wait(5);
if (not ValidClick(pos)) then Exit;
if pos.InBox(Buttons[btCapture]) and (click = 0) then
begin
ToggleCapture();
ReDrawInterface();
Exit();
end else if pos.InBox(Buttons[btClear]) and (click = 0) then
begin
ClearDTM();
Exit();
end else if pos.InBox(Buttons[btDone]) and (click = 0) then
begin
FinalizeDTM();
ReDrawInterface();
Exit();
end else if pos.InBox(Buttons[btPrintPath]) and (click = 0) then
begin
OutputPath();
Exit();
end;
if (not isCapturing) then
Mouse.Click(pos, ([1,0][click]))
else
begin
SelectObject(pos, click);
end;
end;
var lastTick:UInt64;
begin
Init();
ReDrawInterface();
Walker.DebugMinimap(smart.Image,,False);
lastTick := GetTickCount64();
while True do
begin
HandleClick();
if GetTickCount64() - lastTick > 64 then
begin
RedrawObjects();
lastTick := GetTickCount64();
end;
end;
end.
|
unit fmSplash;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, JvExControls,
JvAnimatedImage, JvGIFCtrl, PngImage1, jpeg;
type
TfSplash = class(TForm)
Image1: TImage;
Cargando: TJvGIFAnimator;
lMensaje: TLabel;
lVersion: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure CargandoStop(Sender: TObject);
private
procedure SetMensaje(const Value: string);
procedure OnMessageShowedSC;
public
property Mensaje: string write SetMensaje;
end;
procedure ShowSplash;
procedure MensajeSplash(const mensaje: string);
implementation
uses
BusCommunication, SCMain, dmConfiguracion;
{$R *.dfm}
var splash: TfSplash;
{ TfSplash }
procedure MensajeSplash(const mensaje: string);
begin
splash.Mensaje := mensaje;
end;
procedure ShowSplash;
begin
splash := TfSplash.Create(Application);
AnimateWindow(splash.Handle, 500, AW_BLEND);
end;
procedure TfSplash.FormCreate(Sender: TObject);
begin
inherited;
Bus.RegisterEvent(MessageSCShowed, OnMessageShowedSC);
Cargando.Animate := true;
lVersion.Caption := '4.4'; //Configuracion.Sistema.Version;
end;
procedure TfSplash.OnMessageShowedSC;
begin
Visible := false;
Cargando.Animate := false;
Bus.UnregisterEvent(MessageSCShowed, OnMessageShowedSC);
end;
procedure TfSplash.SetMensaje(const Value: string);
begin
lMensaje.Caption := Value;
lMensaje.Repaint;
end;
procedure TfSplash.CargandoStop(Sender: TObject);
begin
Close;
end;
procedure TfSplash.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
Action := caFree;
splash := nil;
end;
end.
|
{
GL Sample renderer
Copyright (C) 2010 Torsten Spaete
Licensed under Mozilla Public License
}
unit mainform;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
FileUtil,
LResources,
Forms,
Controls,
Graphics,
Dialogs,
ExtCtrls,
ComCtrls,
Menus,
Windows,
// 3rd party
dglopengl,
// Own
GLTexture,
sampleloader,
GLSL;
type
TFloatRect = record
Left, Top,
Right, Bottom : Single;
end;
{ TfrmMain }
TfrmMain = class(TForm)
IdleTimer1: TIdleTimer;
MenuItem1: TMenuItem;
PopupMenu1: TPopupMenu;
StatusBar1: TStatusBar;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
procedure FormResize(Sender: TObject);
procedure IdleTimer1Timer(Sender: TObject);
procedure MenuItem1Click(Sender: TObject);
private
{ private declarations }
FNotSupported : Boolean;
FDC: HDC;
FRC: HGLRC;
FGLInited : Boolean;
FNumSamples: integer;
FSamples: array of PSample;
FSelSample: integer;
FCurSample: integer;
FSamChange: Boolean;
FNoGLSL: Boolean;
FTextureRect : TFloatRect;
FVideoTex: TTexture;
FVideoTexY: TTexture;
FVideoTexU: TTexture;
FVideoTexV: TTexture;
FYuvShader: TGLSL;
FUseGLSL: boolean;
FPixelShaderFile,
FVertShaderFile : String;
FTextureFilter : Integer;
FGLSLSupported: Boolean;
FNonPowerOfTwoSupported : Boolean;
FMaxTextureSize : Integer;
procedure ReleaseTextures;
procedure ReleaseShaders;
procedure SetupOpenGL;
procedure SetTextureFilter(AMode : GLUint);
procedure DrawFrame;
procedure UpdateSample;
public
{ public declarations }
procedure PosChanged(var AMsg : TWMWindowPosChanged); message WM_WINDOWPOSCHANGED;
published
property NotSupported : Boolean read FNotSupported;
end;
var
frmMain: TfrmMain;
implementation
uses
OVRConversion, dshowtypes, glsldebugform;
function FloatRect(ALeft, ATop, ARight, ABottom : Single) : TFloatRect;
begin
Result.Left := ALeft;
Result.Top := ATop;
Result.Right := ARight;
Result.Bottom := ABottom;
end;
function GetNonPowerOfTwo(AValue, AMax : Integer) : Integer;
begin
Result := 2;
while (Result < AValue) and (Result < AMax) do
Result := Result * 2;
end;
function NonPowerOfTwo(AWidth, AHeight, AMax : Integer) : TRect;
begin
Result.Left := 0;
Result.Top := 0;
Result.Right := GetNonPowerOfTwo(AWidth, AMax);
Result.Bottom := GetNonPowerOfTwo(AHeight, AMax);
end;
function FileToString(AFilename: string): string;
var
F: TextFile;
S: string;
begin
Result := '';
if FileExists(AFilename) then
begin
AssignFile(F, AFilename);
Reset(F);
while not EOF(F) do
begin
ReadLn(F, S);
Result := Result + S + #13#10;
end;
CloseFile(F);
end;
end;
function ExtensionAreSupported(missingExtensions : TStrings; const reqExtension : array of String) : Boolean;
var
extensions : String;
i : Integer;
begin
if missingExtensions = nil then missingExtensions := TStringList.Create;
extensions := uppercase(glGetString(GL_EXTENSIONS));
For I := 0 to Length(reqExtension)-1 do
begin
if Pos(uppercase(reqExtension[I]), extensions) <= 0 then
missingExtensions.Add(reqExtension[I]);
end;
Result := missingExtensions.Count = 0;
end;
{ TfrmMain }
procedure TfrmMain.FormCreate(Sender: TObject);
var
missingExtensions : TStrings;
s : String;
doshutdown : Boolean;
i : Integer;
begin
FNotSupported := False;
// Initialize samples
FNumSamples := 0;
SetLength(FSamples, 0);
FCurSample := -1;
FSelSample := -1;
FSamChange := False;
FNoGLSL := False;
FGLInited := False;
FTextureRect := FloatRect(0,0,0,0);
// Load samples
LoadSamples(IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) +
'samples', FSamples, FNumSamples);
if FNumSamples > 0 then
FSelSample := 0;
// Initialize video texture data
FVideoTex := nil;
FVideoTexY := nil;
FVideoTexU := nil;
FVideoTexV := nil;
// Initialize opengl
FDC := GetDC(Handle);
FRC := CreateRenderingContext(FDC, [opDoubleBuffered], 32, 24, 0, 0, 0, 0);
ActivateRenderingContext(FDC, FRC);
SetupOpenGL;
FNonPowerOfTwoSupported := dglCheckExtension('GL_ARB_texture_rectangle');
FMaxTextureSize := 0;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, @FMaxTextureSize);
// Shut down
missingExtensions := TStringList.Create;
{
doshutdown := not ExtensionAreSupported(missingExtensions, [
'GL_ARB_shader_objects',
'GL_ARB_vertex_shader',
'GL_ARB_fragment_shader',
'GL_ARB_shading_language_100',
'GL_ARB_texture_rectangle']);
}
doshutdown := False;
FGLSLSupported :=
dglCheckExtension('GL_ARB_shader_objects') and
dglCheckExtension('GL_ARB_vertex_shader') and
dglCheckExtension('GL_ARB_fragment_shader') and
dglCheckExtension('GL_ARB_shading_language_100');
s := 'The following opengl extension are not supported by your graphics card but needed for this application to run:'+#13#10;
for I := 0 to missingExtensions.Count-1 do
s := s + missingExtensions[i] + #13#10;
missingExtensions.Free;
if doshutdown then
begin
MessageBox(Handle, PChar(s), 'GL Sample Renderer', MB_OK or MB_ICONEXCLAMATION);
FNotSupported := True;
end;
// No texture filtering by default
FTextureFilter := 1;
// Initialize GLSL
FUseGLSL := False;
FPixelShaderFile := '';
FVertShaderFile := '';
// Display status panel GL+GLSL Version+Vendor
StatusBar1.Panels[3].Text :=
glGetString(GL_VERSION) + ' ' + glGetString(GL_VENDOR);
FGLInited := True;
end;
procedure TfrmMain.ReleaseTextures;
begin
// Release video texture and memory (RGBA texture)
if FVideoTex <> nil then
FreeAndNil(FVideoTex);
// Release video texture and memory (Y texture)
if FVideoTexY <> nil then
FreeAndNil(FVideoTexY);
// Release video texture and memory (U or UV texture)
if FVideoTexU <> nil then
FreeAndNil(FVideoTexU);
// Release video texture and memory (V texture)
if FVideoTexV <> nil then
FreeAndNil(FVideoTexV);
end;
procedure TfrmMain.ReleaseShaders;
begin
// Release GLSL
if FYuvShader <> nil then
FreeAndNil(FYuvShader);
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
var
I: integer;
begin
// Release shaders
ReleaseShaders;
// Release textures
ReleaseTextures;
// Release sample memory
FSelSample := -1;
FCurSample := -1;
for I := 0 to FNumSamples - 1 do
begin
FreeMem(FSamples[I]^.Data, FSamples[I]^.Header.DataLength);
Dispose(FSamples[I]);
end;
SetLength(FSamples, 0);
FNumSamples := 0;
// Release opengl
DeactivateRenderingContext;
DestroyRenderingContext(FRC);
end;
procedure TfrmMain.FormKeyUp(Sender: TObject; var Key: word; Shift: TShiftState);
begin
if Key = VK_SPACE then
begin
// Toggle samples
Inc(FSelSample);
if FSelSample > FNumSamples - 1 then
FSelSample := 0;
end;
if Key = Ord('F') then
begin
Inc(FTextureFilter);
if FTextureFilter > 1 then FTextureFilter := 0;
end;
if (Key = Ord('G')) and (FGLSLSupported) then
begin
FNoGLSL := (not FNoGLSL);
FSamChange := True;
end;
if Key = Ord('R') then
begin
FSamChange := True;
end;
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
end;
procedure TfrmMain.SetupOpenGL;
begin
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glClearColor(1, 1, 1, 1);
glDisable(GL_CULL_FACE);
glHint(GL_POLYGON_SMOOTH_HINT,GL_NICEST);
end;
procedure TfrmMain.IdleTimer1Timer(Sender: TObject);
begin
if not FGLInited then Exit;
DrawFrame;
end;
procedure TfrmMain.MenuItem1Click(Sender: TObject);
begin
if not frmGLSLDebug.Visible then
frmGLSLDebug.Show;
end;
procedure DrawQuad(W, H : Integer; TR : TFloatRect);
begin
glBegin(GL_QUADS);
glTexCoord2f(TR.Left, TR.Top); glVertex3f(0, 0, 0);
glTexCoord2f(TR.Right, TR.Top); glVertex3f(W, 0, 0);
glTexCoord2f(TR.Right, TR.Bottom); glVertex3f(W, H, 0);
glTexCoord2f(TR.Left, TR.Bottom); glVertex3f(0, H, 0);
glEnd;
end;
function OGLTextureFormatToString(AFormat : GLuint) : String;
begin
case AFormat of
GL_LUMINANCE: Result := 'GL_LUMINANCE';
GL_LUMINANCE_ALPHA: Result := 'GL_LUMINANCE_ALPHA';
GL_LUMINANCE8: Result := 'GL_LUMINANCE8';
GL_RGB: Result := 'GL_RGB';
GL_RGB8: Result := 'GL_RGB8';
GL_RGBA: Result := 'GL_RGBA';
GL_RGBA8: Result := 'GL_RGBA8';
GL_BGR: Result := 'GL_BGR';
GL_BGRA: Result := 'GL_BGRA';
else
Result := IntToStr(AFormat);
end;
end;
function OGLTextureTargetToString(ATarget : GLuint) : String;
begin
case ATarget of
GL_TEXTURE_2D: Result := 'GL_TEXTURE_2D';
GL_TEXTURE_RECTANGLE: Result := 'GL_TEXTURE_RECTANGLE';
else
Result := IntToStr(ATarget);
end;
end;
function OGLTextureTypeToString(AType : GLuint) : String;
begin
case AType of
GL_UNSIGNED_BYTE: Result := 'GL_UNSIGNED_BYTE';
GL_UNSIGNED_INT_8_8_8_8: Result := 'GL_UNSIGNED_INT_8_8_8_8';
GL_UNSIGNED_INT_8_8_8_8_REV: Result := 'GL_UNSIGNED_INT_8_8_8_8_REV';
else
Result := IntToStr(AType);
end;
end;
procedure ShowTextureInfos(ATexture : TTexture);
begin
frmGLSLDebug.memDebug.Lines.Add('Texture dimension: ' + Format('%d x %d',[ATexture.Width, ATexture.Height]));
frmGLSLDebug.memDebug.Lines.Add(Format('Texture format: %s / %s',[OGLTextureFormatToString(ATexture.InternalFormat), OGLTextureFormatToString(ATexture.TexFormat)]));
frmGLSLDebug.memDebug.Lines.Add(Format('Texture target: %s',[OGLTextureTargetToString(ATexture.Target)]));
frmGLSLDebug.memDebug.Lines.Add(Format('Texture type: %s',[OGLTextureTypeToString(ATexture.TexType)]));
end;
procedure CreateTexturesBySubtype(const ASubType : TGUID; const ATexWidth, ATexHeight : Integer; var AYTex, AUTex, AVTex : TTexture);
var
S, S2 : Integer;
begin
if (IsEqualGuid(ASubType, MEDIASUBTYPE_YUY2) or
IsEqualGuid(ASubType, MEDIASUBTYPE_YUYV) or
IsEqualGuid(ASubType, MEDIASUBTYPE_YVYU) or
IsEqualGuid(ASubType, MEDIASUBTYPE_UYVY)) then
begin
// Create Y texture
AYTex := TTexture.Create(GL_TEXTURE_RECTANGLE, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, ATexWidth, ATexHeight);
// Create UV texture
AUTex := TTexture.Create(GL_TEXTURE_RECTANGLE, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, ATexWidth div 2, ATexHeight);
end
else if IsEqualGuid(ASubType, MEDIASUBTYPE_YV12) then
begin
S := ATexWidth * ATexHeight;
S2 := (ATexWidth div 2) * (ATexHeight div 2);
// Create Y texture
AYTex := TTexture.Create(GL_TEXTURE_RECTANGLE, GL_LUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE, ATexWidth, ATexHeight);
// Create U texture
AUTex := TTexture.Create(GL_TEXTURE_RECTANGLE, GL_LUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE, ATexWidth div 2, ATexHeight div 2, S2, S + S2);
// Create V texture
AVTex := TTexture.Create(GL_TEXTURE_RECTANGLE, GL_LUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE, ATexWidth div 2, ATexHeight div 2, S2, S);
end;
end;
procedure TfrmMain.UpdateSample;
var
W, H: integer;
s : String;
d : Int64;
NPOT : TRect;
TW, TH : Integer;
begin
if FSelSample > -1 then
begin
if ((FSelSample <> FCurSample) or FSamChange) and (FSamples[FSelSample] <> nil) then
begin
// Save texture dimensions
W := FSamples[FSelSample]^.Header.VIH.bmiHeader.biWidth;
H := FSamples[FSelSample]^.Header.VIH.bmiHeader.biHeight;
if FNonPowerOfTwoSupported then
begin
TW := W;
TH := H;
FTextureRect := FloatRect(0,0,TW,TH);
end
else
begin
NPOT := NonPowerOfTwo(W, H, FMaxTextureSize);
TW := NPOT.Right;
TH := NPOT.Bottom;
FTextureRect := FloatRect(0,0,(1 / TW) * W,(1 / TH) * H);
end;
// Release textures
ReleaseTextures;
// Release shaders
ReleaseShaders;
// Use GLSL ?
FUseGLSL := (IsEqualGuid(FSamples[FSelSample]^.Header.SubType, MEDIASUBTYPE_YUY2) or
IsEqualGuid(FSamples[FSelSample]^.Header.SubType, MEDIASUBTYPE_YUYV) or
IsEqualGuid(FSamples[FSelSample]^.Header.SubType, MEDIASUBTYPE_YVYU) or
IsEqualGuid(FSamples[FSelSample]^.Header.SubType, MEDIASUBTYPE_UYVY) or
IsEqualGuid(FSamples[FSelSample]^.Header.SubType, MEDIASUBTYPE_YV12)
) and (not FNoGLSL) and FGLSLSupported;
// Clear debug infos
frmGLSLDebug.memDebug.Lines.Clear;
// Show infos
frmGLSLDebug.memDebug.Lines.Add('OpenGL Version: ' + glGetString(GL_VERSION));
frmGLSLDebug.memDebug.Lines.Add('OpenGL Vendor: ' + glGetString(GL_VENDOR));
frmGLSLDebug.memDebug.Lines.Add('OpenGL Max Texture Size: ' + IntToStr(FMaxTextureSize));
if FGLSLSupported then
frmGLSLDebug.memDebug.Lines.Add('GLSL Version: ' + glGetString(GL_SHADING_LANGUAGE_VERSION));
frmGLSLDebug.memDebug.Lines.Add('');
frmGLSLDebug.memDebug.Lines.Add('Sample dimension: ' + Format('%d x %d',[W, H]));
frmGLSLDebug.memDebug.Lines.Add('Sample bitcount: ' + Format('%d',[FSamples[FSelSample]^.Header.VIH.bmiHeader.biBitCount]));
frmGLSLDebug.memDebug.Lines.Add('Sample size: ' + Format('%d',[FSamples[FSelSample]^.Header.DataLength]));
frmGLSLDebug.memDebug.Lines.Add('Sample format: ' + Format('%s',[SubTypeToString(FSamples[FSelSample]^.Header.SubType)]));
frmGLSLDebug.memDebug.Lines.Add('');
// Create texture if it does not exists
if FUseGLSL then
begin
// Create required textures (Y-U-V)
CreateTexturesBySubtype(FSamples[FSelSample]^.Header.SubType, W, H, FVideoTexY, FVideoTexU, FVideoTexV);
end
else
begin
// Create RGBA texture
if FNonPowerOfTwoSupported then
FVideoTex := TTexture.Create(GL_TEXTURE_RECTANGLE, GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE, TW, TH, TW * TH * 4)
else
FVideoTex := TTexture.Create(GL_TEXTURE_2D, GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE, TW, TH, TW * TH * 4);
end;
if FUseGLSL then
begin
if FVideoTexY <> nil then
begin
frmGLSLDebug.memDebug.Lines.Add('Texture 0 (Y):');
ShowTextureInfos(FVideoTexY);
frmGLSLDebug.memDebug.Lines.Add('');
end;
if FVideoTexU <> nil then
begin
frmGLSLDebug.memDebug.Lines.Add('Texture 1 (U or UV):');
ShowTextureInfos(FVideoTexU);
frmGLSLDebug.memDebug.Lines.Add('');
end;
if FVideoTexV <> nil then
begin
frmGLSLDebug.memDebug.Lines.Add('Texture 2 (V):');
ShowTextureInfos(FVideoTexV);
frmGLSLDebug.memDebug.Lines.Add('');
end;
// Create new yuv shader object
FYuvShader := TGLSL.Create;
// Update shader filenames
if IsEqualGuid(FSamples[FSelSample]^.Header.SubType, MEDIASUBTYPE_YUY2) or
IsEqualGuid(FSamples[FSelSample]^.Header.SubType, MEDIASUBTYPE_YUYV) then
FPixelShaderFile := 'glsl\yuy2.frag'
else if IsEqualGuid(FSamples[FSelSample]^.Header.SubType, MEDIASUBTYPE_YVYU) then
FPixelShaderFile := 'glsl\yvyu.frag'
else if IsEqualGuid(FSamples[FSelSample]^.Header.SubType, MEDIASUBTYPE_UYVY) then
FPixelShaderFile := 'glsl\uyvy.frag'
else if IsEqualGuid(FSamples[FSelSample]^.Header.SubType, MEDIASUBTYPE_YV12) then
FPixelShaderFile := 'glsl\yv12.frag'
else
FPixelShaderFile := '';
if FVertShaderFile <> '' then
begin
frmGLSLDebug.memDebug.Lines.Add('Vertex shader "'+FVertShaderFile+'":');
s := FYuvShader.UploadVertexShader(
FileToString(IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) +
FVertShaderFile));
frmGLSLDebug.memDebug.Lines.Add(s);
frmGLSLDebug.memDebug.Lines.Add('');
end;
if FPixelShaderFile <> '' then
begin
frmGLSLDebug.memDebug.Lines.Add('Pixel shader "'+FPixelShaderFile+'":');
s := FYuvShader.UploadPixelShader(
FileToString(IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) +
FPixelShaderFile));
s := StringReplace(s, #10, #13#10, [rfReplaceAll]);
frmGLSLDebug.memDebug.Lines.Add(s);
frmGLSLDebug.memDebug.Lines.Add('');
end;
// Upload sample textures Y and U and or V
d := GetTickCount;
if FVideoTexY <> nil then
FVideoTexY.Upload(FSamples[FSelSample]^.Data);
if FVideoTexU <> nil then
FVideoTexU.Upload(FSamples[FSelSample]^.Data);
if FVideoTexV <> nil then
FVideoTexV.Upload(FSamples[FSelSample]^.Data);
frmGLSLDebug.memDebug.Lines.Add(Format('Texture upload done in: %d msecs',[GetTickCount-d]));
end
else
begin
frmGLSLDebug.memDebug.Lines.Add('Texture 0 (RGBA):');
ShowTextureInfos(FVideoTex);
frmGLSLDebug.memDebug.Lines.Add('');
// Convert format to RGB
d := GetTickCount;
Convert(FSamples[FSelSample]^.Header.VIH,
FSamples[FSelSample]^.Header.SubType,
FSamples[FSelSample]^.Data,
FSamples[FSelSample]^.Header.DataLength,
FVideoTex.Data, TW);
frmGLSLDebug.memDebug.Lines.Add(Format('Software color conversion done in: %d msecs',[GetTickCount-d]));
// Upload texture
d := GetTickCount;
FVideoTex.Upload(FVideoTex.Data);
frmGLSLDebug.memDebug.Lines.Add(Format('Texture upload done in: %d msecs',[GetTickCount-d]));
end;
// Save cur sample
FCurSample := FSelSample;
FSamChange := False;
// Set caption
StatusBar1.Panels[1].Text := SubTypeToString(FSamples[FSelSample]^.Header.SubType);
if FUseGLSL then
StatusBar1.Panels[1].Text := StatusBar1.Panels[1].Text + ' (GLSL)';
end;
end;
end;
function GLErrorToString(ACode: TGLenum): string;
begin
case ACode of
GL_NO_ERROR: Result := 'No error';
GL_INVALID_ENUM: Result := 'Invalid enum';
GL_INVALID_VALUE: Result := 'Invalid value';
GL_INVALID_OPERATION: Result := 'Invalid operation';
GL_STACK_OVERFLOW: Result := 'Stack overflow';
GL_STACK_UNDERFLOW: Result := 'Stack underflow';
GL_OUT_OF_MEMORY: Result := 'Out of memory';
else
Result := 'Unknown ' + IntToStr(ACode);
end;
end;
function TexFilterToString(AFilter : Integer) : String;
begin
case AFilter of
0: Result := 'Off';
1: Result := 'Bilinear';
else
Result := 'Unknown';
end;
end;
procedure TfrmMain.SetTextureFilter(AMode : GLUint);
begin
if FTextureFilter = 1 then
begin
glTexParameteri(AMode, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(AMode, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
end
else
begin
glTexParameteri(AMode, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(AMode, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
end;
end;
procedure TfrmMain.DrawFrame;
var
W, H: integer;
TH: integer;
begin
W := ClientWidth;
H := ClientHeight;
TH := FSamples[FSelSample]^.Header.VIH.bmiHeader.biHeight;
glViewPort(0, 0, W, H);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
glOrtho(0, W, H, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glLoadIdentity;
UpdateSample;
glColor3f(1.0, 1.0, 1.0);
if (FUseGLSL) then
begin
if FVideoTexY <> nil then
begin
FVideoTexY.Bind(0);
SetTextureFilter(FVideoTexY.Target);
end;
if FVideoTexU <> nil then
begin
FVideoTexU.Bind(1);
SetTextureFilter(FVideoTexU.Target);
end;
if FVideoTexV <> nil then
begin
FVideoTexV.Bind(2);
SetTextureFilter(FVideoTexV.Target);
end;
FYuvShader.Bind;
FYuvShader.SetParameter1i('Ytex', 0);
FYuvShader.SetParameter1i('Utex', 1);
FYuvShader.SetParameter1i('Vtex', 2);
FYuvShader.SetParameter1f('TextureDimH', TH);
end
else
begin
FVideoTex.Bind;
SetTextureFilter(FVideoTex.Target);
end;
DrawQuad(W, H - Statusbar1.Height, FTextureRect);
if FUseGLSL then
begin
FYuvShader.Unbind;
if FVideoTexV <> nil then
FVideoTexV.Unbind(2);
if FVideoTexU <> nil then
FVideoTexU.Unbind(1);
if FVideoTexY <> nil then
FVideoTexY.Unbind(0);
end
else
FVideoTex.Unbind;
SwapBuffers(FDC);
glFinish;
StatusBar1.Panels[5].Text := GLErrorToString(glGetError());
StatusBar1.Panels[7].Text := TexFilterToString(FTextureFilter);
end;
procedure TfrmMain.PosChanged(var AMsg : TWMWindowPosChanged);
begin
inherited;
end;
initialization
{$I mainform.lrs}
end.
|
unit UPicScrollBox;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2007 by Bradford Technologies, Inc. }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,Menus,
StdCtrls,Extctrls,ComCtrls, TMultiP;
type
TPicScrollBox = class(TScrollBox)
private
FIsLoading: Boolean;
FCancelLoad: Boolean;
FMLImage: TPMultiImage; //use it to load images
FImages : TStringList; //TList;
FVerticalSpace: integer;
FHorizontalSpace: integer;
FThumbHeight: integer;
FThumbWidth: integer;
FImageDirectory: string;
FOwnerStatusBar: TStatusBar;
FPopup: TPopupMenu;
FActiveImage: TObject; //clicked on image
procedure SetImageDirectory(const Value: string);
procedure SetCancelLoad(Const Value: Boolean);
function GetImageCount: Integer;
procedure FileFound(Sender : TObject;FileName : string);
procedure ViewPicture(Sender : TObject);
protected
function CreateThumbnail(N: Integer; FileName: string; Bitmap: TBitmap): TImage;
procedure LoadImages; virtual;
procedure UnLoadImages;
Function CreateImagePopup(Sender: TObject): TPopupMenu;
procedure OnSaveImageImage(Senter: TObject);
procedure OnRemoveFromList(Sender: TObject);
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure MouseDownOnImage(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure DragImageStart(Sender: TObject; var DragObject: TDragObject);
function CreateThumbnailImage(var BitMap: TBitMap; IWidth, IHeight: Integer): Boolean;
procedure DisplayImageFiles;
procedure LoadImageList(imgList: TStringList);
property ImageDirectory : string read FImageDirectory write SetImageDirectory;
property StatusBar: TStatusBar read FOwnerStatusBar write FOwnerStatusBar;
property ImageCount: Integer read GetImageCount;
property IsLoading: Boolean read FIsLoading;
property CancelLoad: Boolean read FCancelLoad write SetCancelLoad;
end;
implementation
uses
DLL96v1,DLLsp96, ildibcls,
UUtil1, UFileFinder, UDrag, UStrings, UImageView, UStatus;
Const
FrameWidth = 190;
FrameHeight = 210;
ImageWidth = 180;
ImageHeight = 180;
Spacer = 10;
{ TPicScrollBox }
constructor TPicScrollBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FImages := TStringList.Create;
FThumbWidth := ImageWidth;
FThumbHeight := ImageHeight;
FVerticalSpace := Spacer;
FHorizontalSpace := Spacer;
HorzScrollBar.Increment := FrameWidth;
HorzScrollBar.Smooth := True;
HorzScrollBar.Tracking := True;
FActiveImage := nil;
FIsLoading := False;
FCancelLoad := False;
FPopup := CreateImagePopup(self);
end;
destructor TPicScrollBox.Destroy;
var
i: Integer;
begin
for i := 0 to FImages.count-1 do //free the TImages
if FImages.Objects[i] <> nil then
TImage(FImages.Objects[i]).Free;
FImages.Clear; //clear the ref to objects & strings
FImages.Free; //free the list holder
if assigned(FPopup) then
FPopup.Free;
inherited Destroy;
end;
Function TPicScrollBox.CreateImagePopup(Sender: TObject): TPopupMenu;
Var
MI: TMenuItem;
begin
result := TPopupMenu.Create(self);
MI := TMenuItem.Create(result);
MI.Caption := 'Save Image As...';
MI.OnClick := OnSaveImageImage;
result.Items.Add(MI);
(*
MI := TMenuItem.Create(result);
MI.Caption := 'Remove From List';
MI.OnClick := OnRemoveFromList;
result.Items.Add(MI);
*)
end;
//have to use FActiveImage since Sender is not who need
procedure TPicScrollBox.OnSaveImageImage(Senter: TObject);
begin
ViewPicture(FActiveImage);
end;
//NOTE: This does not work correctly - disable for now
procedure TPicScrollBox.OnRemoveFromList(Sender: TObject);
var
i, imgIndx: Integer;
TP: TPanel;
begin
imgIndx := FImages.IndexOfObject(FActiveImage);
if imgIndx > -1 then
begin
//delete the image panel from the TscrollBox
i := 0;
if Fimages.Count > 0 then
while (i < FImages.Count) do
begin
TP := TPanel(FindComponent(concat('PHOTO',inttoStr(i))));
if assigned(TP) then TP.Free;
Inc(i);
end;
//Delete the filePath from the TStringList
FImages.Delete(imgIndx);
DisplayImageFiles;
end;
end;
procedure TPicScrollBox.UnLoadImages;
var
TP: TPanel;
i: Integer;
begin
i := 0;
if Fimages.Count > 0 then
while (i < FImages.Count) do
begin
TP := TPanel(FindComponent(concat('PHOTO',inttoStr(i))));
if assigned(TP) then TP.Free;
Inc(i);
end;
FImages.Clear;
end;
function TPicScrollBox.CreateThumbnail(N: Integer; FileName: string; Bitmap: TBitmap): TImage;
var
ImageFrame: TPanel;
ImageName: TStaticText;
Image: TImage;
begin
ImageFrame := TPanel.Create(Self);
ImageFrame.visible := False;
ImageFrame.parent := self;
ImageFrame.Name := 'PHOTO'+IntToStr(N); //count from 1
ImageFrame.top := 0;
ImageFrame.Left := N * FrameWidth;
ImageFrame.height := FrameHeight;
ImageFrame.width := FrameWidth;
ImageFrame.BevelInner := bvNone;
ImageFrame.BevelOuter := bvRaised;
ImageFrame.BevelWidth := 2;
ImageName := TStaticText.Create(ImageFrame); //text is owned by panel
ImageName.parent := ImageFrame;
ImageName.Align := alBottom;
ImageName.Alignment := taCenter;
ImageName.height := 15;
ImageName.Caption := ExtractFileName(FileName);
Image := TImage.Create(ImageFrame); //image is owned by Panel
Image.parent := ImageFrame;
Image.left := 5;
Image.top := 5;
Image.height := FThumbHeight;
Image.width := FThumbWidth;
Image.stretch:= true;
Image.picture.bitmap := bitmap;
ImageFrame.visible := True;
Image.OnDblClick := ViewPicture;
Image.OnMouseDown := MouseDownOnImage;
Image.OnStartDrag := DragImageStart;
Image.DragMode := dmManual;
result := Image;
end;
procedure TPicScrollBox.MouseDownOnImage(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Pt: TPoint;
N: Integer;
fPath: String;
begin
if (sender is TImage) and (ssRight in Shift) then
begin
FActiveImage := Sender;
Pt := (Sender as TImage).ClientToScreen(Point(X,Y));
FPopup.Popup(Pt.x, Pt.y);
end
else if (sender is TImage) and not (ssDouble in Shift) then
begin
//before allowing a drag, make sure the file is still there
N := FImages.IndexOfObject(sender);
fPath := FImages.Strings[N];
if not FileExists(fPath) then
ShowAlert(atWarnAlert, 'You cannot drag this image. The file has been moved from its original location: "' + fPath + '"')
else
TImage(Sender).BeginDrag(False, 5);
end;
end;
procedure TPicScrollBox.DragImageStart(Sender: TObject;var DragObject: TDragObject);
var
Image2Drag: TDragImage;
N: Integer;
begin
if sender is TImage then //if we are the image that wants to drag
begin
N := FImages.IndexOfObject(sender);
if N > -1 then
begin
Image2Drag := TDragImage.create;
Image2Drag.ImageCell := nil;
Image2Drag.IsThumbImage := True;
Image2Drag.ImageFilePath := FImages.Strings[N];
DragObject := Image2Drag; //send it off
end;
end;
end;
Function TPicScrollBox.CreateThumbNailImage(var BitMap: TBitMap; IWidth, IHeight: Integer): Boolean;
begin
Result:= true;
Bitmap := TBitmap.Create;
Bitmap.Width:= IWidth;
Bitmap.Height:= IHeight;
Bitmap.HandleType:= bmDIB;
if GetDeviceCaps(FMLImage.Picture.Bitmap.Canvas.Handle, BITSPIXEL) >= 15 then
Bitmap.PixelFormat := pf24bit;
{Delete the lines needed to shrink}
SetStretchBltMode(Bitmap.Canvas.Handle,STRETCH_DELETESCANS);
{Resize it}
Bitmap.Canvas.Copyrect(Rect(0,0,IWidth,IHeight),
FMLImage.Picture.bitmap.Canvas,
Rect(0,0,FMLImage.Picture.bitmap.Width,
FMLImage.Picture.bitmap.Height));
{Copy the palette}
Bitmap.Palette:= CopyPalette(FMLImage.Picture.Bitmap.Palette);
end;
procedure TPicScrollBox.FileFound(Sender: TObject; FileName: string);
begin
StatusBar.Panels[1].Text := 'Found: '+ ExtractFileName(FileName);
FImages.Add(FileName);
end;
//This is for the custom sort routine - requires a reg function
function SortFileNames(List: TStringList; Index1, Index2: Integer): Integer;
var
NStr1, NStr2: String;
begin
NStr1 := GetNameOnly(List[Index1]);
NStr2 := GetNameOnly(List[Index2]);
result := CompareText(NStr1, NStr2);
end;
procedure TPicScrollBox.DisplayImageFiles;
var
i,j: integer;
Bitmap: TBitmap;
fileName: String;
begin
//alpha sort the filenames
FImages.CustomSort(SortFileNames);
StatusBar.Panels[0].Text := IntToStr(ImageCount)+ ' Images Found';
Application.ProcessMessages;
//now display in sorted order
i := 0;
while (not FCancelLoad) and (i < FImages.Count) do
begin
fileName := FImages.Strings[i];
StatusBar.Panels[1].Text := 'Processing# '+IntToStr(i)+ ' Image: '+ ExtractFileName(fileName);
Application.ProcessMessages;
try
FMLImage := TPMultiImage.create(self);
FMLImage.Visible := False;
FMLImage.parent := Self.parent;
try
FMLImage.ImageName:=fileName;
for j:=0 to 10 do Application.ProcessMessages;
if CreateThumbNailImage(Bitmap, FThumbWidth, FThumbHeight) then
begin
FImages.Objects[i] := CreateThumbnail(i, FileName, Bitmap);
Bitmap.Free;
end;
except
StatusBar.Panels[1].Text := 'Could not load image' + ExtractFileName(filename);
end;
StatusBar.Panels[1].Text := '';
finally
FMLImage.Free;
end;
inc(i);
end;
end;
procedure TPicScrollBox.LoadImages;
var
filter: String;
begin
UnLoadImages;
FileFinder.OnFileFound := FileFound;
// Filter := GraphicFileMask(TGraphic); //registered formats in Delphi
Filter := SupportedImageFormats; //see UStrings
FIsLoading := True;
CancelLoad := False;
FileFinder.Find(FImageDirectory, False, Filter); //gathered image files
DisplayImageFiles; //now disply them in alpha-numeric order
FIsLoading := False;
end;
procedure TPicScrollBox.LoadImageList(imgList: TStringList);
var
i: Integer;
begin
if assigned(imgList) then
begin
UnLoadImages;
FIsLoading := True;
CancelLoad := False;
for i := 0 to imgList.count-1 do
if not CancelLoad then
FImages.Add(imgList.Strings[i]);
DisplayImageFiles; //now disply them in alpha-numeric order
FIsLoading := False;
end;
end;
procedure TPicScrollBox.SetImageDirectory(const Value: string);
begin
FImageDirectory := Value;
LoadImages;
end;
function TPicScrollBox.GetImageCount: Integer;
begin
result := FImages.count;
end;
procedure TPicScrollBox.ViewPicture(Sender: TObject);
var
imgIndx: Integer;
imgPath: String;
viewForm: TImageViewer;
begin
imgPath := '';
imgIndx := FImages.IndexOfObject(sender);
if imgIndx > -1 then
imgPath := FImages.Strings[imgIndx];
if FileExists(imgPath) then
begin
viewForm := TImageViewer.Create(self);
viewForm.LoadImageFromFile(imgPath);
viewForm.ImageDesc := ExtractFileName(imgPath);
viewForm.Show;
end
else
ShowAlert(atWarnAlert, 'Cannot display this image. The file has been moved form it original location: "' + imgPath + '"');
end;
procedure TPicScrollBox.SetCancelLoad(const Value: Boolean);
begin
FCancelLoad := Value;
If FileFinder.IsFinding and FCancelLoad then
FileFinder.Continue := False;
end;
end.
|
{**********************************************************************************}
{ }
{ Project vkDBF - dbf ntx clipper compatibility delphi component }
{ }
{ This Source Code Form is subject to the terms of the Mozilla Public }
{ License, v. 2.0. If a copy of the MPL was not distributed with this }
{ file, You can obtain one at http://mozilla.org/MPL/2.0/. }
{ }
{ The Initial Developer of the Original Code is Vlad Karpov (KarpovVV@protek.ru). }
{ }
{ Contributors: }
{ Sergey Klochkov (HSerg@sklabs.ru) }
{ }
{ You may retrieve the latest version of this file at the Project vkDBF home page, }
{ located at http://sourceforge.net/projects/vkdbf/ }
{ }
{**********************************************************************************}
unit VKDBFCDX;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
db, VKDBFParser, DBCommon, VKDBFIndex;
const
CDX_HEADER_SIZE = 1024;
CDX_BUFFER_SIZE = 512;
DATA_POOL_SIZE = CDX_BUFFER_SIZE - 12; //500
COMPACT_DATA_POOL_SIZE = CDX_BUFFER_SIZE - 24; //488
type
CDX_HEADER = packed Record
root: DWord; {byte offset to root node} //0 4
next_page: DWord; {byte offset to next free block //4 4
(-1 if not present)}
version: DWord; {Increments on modification} //8 4
key_size: Word; {length of key} //12 2
options: Byte; {bit field: //14 1
1 unique
8 FOR clause
32 compact index
64 compound index}
signature: Byte; //15 1
reserve0: array [0..477] of Byte; //16 478
charset: array [0..7] of AnsiChar; //494 8
desc: Word; {0 = ascending; 1=descending} //502 2
reserve1: Word; //504 2
for_len: Word; {length of FOR clause} //506 2
reserve2: Word; //508 2
key_len: Word; {length of index expression} //510 2
key_pool: array[0..pred(CDX_BUFFER_SIZE)] of AnsiChar; //512 512
end; //1024
pCDX_HEADER = ^CDX_HEADER;
CDX_BUFFER = packed Record
attribute: Word; {Node attribute (any of the //0 2
following numeric values or
their sums):
0 – index node
1 – root node
2 – leaf node }
count: Word; {Number of keys present //2 2
(0, 1 or many)}
left: DWord; {Pointer to node directly to left //4 4
of current node (on same level,
-1 if not present)}
right: DWord; {Pointer to node directly to right //8 4
of current node (on same level;
-1 if not present)}
case Byte of //12
0:(
free_space: Word; {free space in compact_data} //12 2
rec_no_msk: DWord; {bit mask for record number} //14 4
dup_cnt_msk: Byte; {bit mask for duplicate byte count} //18 1
trl_cnt_msk: Byte; {bit mask for trailing bytes count} //19 1
rec_no_cntb: Byte; {num bits used for record number} //20 1
dup_cntb: Byte; {num bits used for duplicate count} //21 1
trl_cntb: Byte; {num bits used for trail count} //22 1
cnt_bytes: Byte; {bytes needed for recno+dups+trail} //23 1
compact_data: {Data pool for compact recno+dups+trail} //24 488
array [0..pred(COMPACT_DATA_POOL_SIZE)] of AnsiChar;
);
1:(
data_pool: {Data pool for recno+key} //12 500
array [0..pred(DATA_POOL_SIZE)] of AnsiChar;
);
end; //512
pCDX_BUFFER = ^CDX_BUFFER;
{TVKCDXOrder}
TVKCDXOrder = class(TVKDBFOrder)
end;
{TVKCDXBag}
TVKCDXBag = class(TVKDBFIndexBag)
end;
{TVKCDXIndex}
TVKCDXIndex = class(TIndex)
end;
implementation
uses
VKDBFDataSet;
end.
|
unit CABAPI;
interface
uses Classes;
function CABIsFile (const CABFileName: String): Boolean;
function CABIsMultiPart (const CABFileName: String): Boolean;
function CABGetFileCount (const CABFileName: String): Integer;
procedure CABGetFileList (const CABFileName: String; List: TStringList);
procedure CABExtractFile (const CABFileName, DestPath, FileName: String);
procedure CABExtractMultipleFiles (const CABFileName, DestPath: String; List: TStringList);
implementation
uses Windows, SysUtils, FileCtrl;
const
// FDI Errors
FDINone = 0; // ok
FDICabinetNotFound = 1; // bad filename passed to FDICopy
FDINotACabinet = 2; // File not in CAB format
FDIUnknownCABVersion = 3; // unknown CAB file version
FDICorruptCAB = 4; // Cabinet file is corrupt
FDIAllocFail = 5; // Out of memory
FDIBadCompressType = 6; // Unknown compression type
FDIMDIFail = 7; // decompression error
FDITargetFile = 8; // error writing to dest file
FDIReserveMismatch = 9; // reserve size mismatch
FDIWrongCabinet = 10; // incorrect CAB returned
FDIUserAbort = 11; // user aborted
// FDI notify codes
ncCABInfo = 0; // General information about cabinet
ncPartialFile = 1; // First file in cabinet is continuation
ncCopyFile = 2; // File to be copied
ncCloseFileInfo = 3; // close the file, set relevant info
ncNextCabinet = 4; // File continued to next cabinet
ncEnumerate = 5; // Enumeration status
type
TERF = record
ErrCode, ErrNo: Integer;
ErrorPresent: Bool;
end;
TFDICabinetInfo = record
cbCabinet: Integer; // size of the archive
cFolders: Word; // number of folders
cFiles: Word; // number of files
setID: Word; // application-defined magic #
iCabinet: Word; // number of cabinet in set
fReserve: Integer; // has reserved area?
hasprev: Integer; // chained to previous?
hasnext: Integer; // chained to next?
end;
TFDINotification = record
FileSize: Integer; // uncomp size of the file (ncCopyFile only)
FileName: PChar; // name of a file in the CAB
psz2: PChar;
psz3: PChar;
AppValue: Pointer; // application supplied value
fd: Integer; // file handle
Date: Word; // file's 16-bit FAT date
Time: Word; // file's 16-bit FAT time
Attribs: Word; // file's 16-bit FAT attributes
setID: Word; // application-defined magic #
iCabinet: Word; // number of this CAB
iFolder: Word; // number of current 'folder'
FDIError: Integer; // error code, if any
end;
var
erf: TERF;
CABLib: HModule;
Info: TFDICabinetInfo;
DestinationPath: String;
FDICreate: function (pAlloc, pFree, pOpen, pRead, pWrite, pClose, pSeek: Pointer; cpuType: Integer; var erf: TERF): THandle; cdecl;
FDIDestroy: function (h: THandle): Bool; cdecl;
FDIIsCabinet: function (h: THandle; fd: Integer; var info: TFDICabinetInfo): Bool; cdecl;
FDICopy: function (h: THandle; CabName, CabPath: PChar; Flags: Integer; pNotify, pEncrypt, pUser: Pointer): Bool; cdecl;
// These are the callback routines used by FDI/FCI interface
function MyAlloc (Bytes: Integer): Pointer; cdecl;
begin
Result := AllocMem (Bytes);
end;
function MyFree (P: Pointer): Pointer; cdecl;
begin
FreeMem (P);
Result := Nil;
end;
function MyOpen (FileName: PChar; Mode: Integer): Integer; cdecl;
begin
Result := _lopen (FileName, Mode);
end;
function MyClose (fd: Integer): Integer; cdecl;
begin
Result := _lclose (fd);
end;
function MyRead (fd: Integer; buff: Pointer; bytes: Integer): Integer; cdecl;
begin
Result := _lread (fd, buff, bytes);
end;
function MyWrite (fd: Integer; buff: Pointer; bytes: Integer): Integer; cdecl;
begin
Result := _lwrite (fd, buff, bytes);
end;
function MySeek (fd: Integer; pos, mode: Integer): Integer; cdecl;
begin
Result := _llseek (fd, pos, mode);
end;
// These routines simplify the otherwise baroque API
function NewFDIContext: THandle;
begin
Result := FDICreate (@MyAlloc, @MyFree, @MyOpen, @MyRead, @MyWrite, @MyClose, @MySeek, 0, erf);
end;
function CABIsFile (const CABFileName: String): Boolean;
var
fd: Integer;
Context: THandle;
begin
Result := False;
Context := NewFDIContext;
if Context <> 0 then try
fd := MyOpen (PChar (CABFileName), of_Read);
if fd <> -1 then try
Result := FDIIsCabinet (Context, fd, info);
finally
MyClose (fd);
end;
finally
FDIDestroy (Context);
end;
end;
function CABIsMultiPart (const CABFileName: String): Boolean;
begin
Result := False;
if CABIsFile (CABFileName) then Result := (Info.iCabinet > 0) or (Info.hasPrev <> 0) or (Info.hasNext <> 0);
end;
function CABGetFileCount (const CABFileName: String): Integer;
begin
Result := 0;
if CABIsFile (CABFileName) then Result := Info.cFiles;
end;
function GetFileListCallback (NotifyType: Integer; var Info: TFDINotification): Integer; cdecl;
var
S: String;
List: TStringList;
begin
Result := 0;
List := Info.AppValue;
if NotifyType = ncCopyFile then begin
S := Info.FileName;
S := S + '|' + IntToStr (Info.FileSize);
S := S + '|' + IntToStr (MakeLong (Info.Time, Info.Date));
List.Add (S);
end;
end;
procedure CABGetFileList (const CABFileName: String; List: TStringList);
var
Context: THandle;
begin
List.Clear;
if CABIsFile (CABFileName) then begin
Context := NewFDIContext;
if Context <> 0 then try
FDICopy (Context, PChar (ExtractFileName (CABFileName)),
PChar (ExtractFilePath (CABFileName)),
0, @GetFileListCallback, Nil, List);
finally
FDIDestroy (Context);
end;
end;
end;
function FileExtractSingleCallback (NotifyType: Integer; var Info: TFDINotification): Integer; cdecl;
var
Path: String;
TargetFile: PChar;
FileTime: TFileTime;
begin
Result := 0;
TargetFile := Info.AppValue;
case NotifyType of
ncCopyFile: // Is this the file we want to extract?
if StrIComp (TargetFile, Info.FileName) = 0 then begin
Path := DestinationPath + ExtractFileDir (Info.FileName);
if not DirectoryExists (Path) then CreateDir (Path);
Result := _lcreat (PChar (DestinationPath + StrPas (Info.FileName)), 0);
Exit;
end;
ncCloseFileInfo: // Is this the file we want to close?
begin
Result := 1;
// This check is probably redundant, cos we only decompressed
// a single file but let's play safe....
if StrIComp (TargetFile, Info.FileName) = 0 then begin
DosDateTimeToFileTime (Info.Date, Info.Time, FileTime);
SetFileTime (Info.fd, Nil, Nil, @FileTime);
MyClose (Info.fd);
end;
end;
end;
end;
procedure CABExtractFile (const CABFileName, DestPath, FileName: String);
var
Context: THandle;
begin
if CABIsFile (CABFileName) then begin
Context := NewFDIContext;
if Context <> 0 then try
DestinationPath := DestPath;
if DestinationPath [Length (DestinationPath)] <> '\' then DestinationPath := DestinationPath + '\';
FDICopy (Context, PChar (ExtractFileName (CABFileName)),
PChar (ExtractFilePath (CABFileName)),
0, @FileExtractSingleCallback, Nil, PChar (FileName));
finally
FDIDestroy (Context);
end;
end;
end;
function FileExtractMultipleCallback (NotifyType: Integer; var Info: TFDINotification): Integer; cdecl;
var
Path: String;
List: TStringList;
FileTime: TFileTime;
begin
Result := 0;
List := Info.AppValue;
case NotifyType of
ncCopyFile: // Do we want to extract this file?
if List.IndexOf (Info.FileName) <> -1 then begin
Path := DestinationPath + ExtractFileDir (Info.FileName);
if not DirectoryExists (Path) then CreateDir (Path);
Result := _lcreat (PChar (DestinationPath + StrPas (Info.FileName)), 0);
Exit;
end;
ncCloseFileInfo: // Do we want to close this file?
begin
Result := 1;
if List.IndexOf (Info.FileName) <> -1 then begin
DosDateTimeToFileTime (Info.Date, Info.Time, FileTime);
SetFileTime (Info.fd, Nil, Nil, @FileTime);
MyClose (Info.fd);
end;
end;
end;
end;
procedure CABExtractMultipleFiles (const CABFileName, DestPath: String; List: TStringList);
var
Context: THandle;
begin
if CABIsFile (CABFileName) then begin
Context := NewFDIContext;
if Context <> 0 then try
DestinationPath := DestPath;
if DestinationPath [Length (DestinationPath)] <> '\' then DestinationPath := DestinationPath + '\';
FDICopy (Context, PChar (ExtractFileName (CABFileName)),
PChar (ExtractFilePath (CABFileName)),
0, @FileExtractMultipleCallback, Nil, List);
finally
FDIDestroy (Context);
end;
end;
end;
// Load CABINET.DLL and get pointers to the various entry points...
procedure CABLoad;
begin
CABLib := LoadLibrary ('cabinet.dll');
if CABLib = 0 then raise Exception.Create ('Can''t find CABINET.DLL');
@FDICreate := GetProcAddress (CABLib, 'FDICreate');
@FDIDestroy := GetProcAddress (CABLib, 'FDIDestroy');
@FDIIsCabinet := GetProcAddress (CABLib, 'FDIIsCabinet');
@FDICopy := GetProcAddress (CABLib, 'FDICopy');
end;
procedure CABUnload;
begin
if CABLib <> 0 then FreeLibrary (CABLib);
end;
initialization
CABLoad;
finalization
CABUnload;
end.
|
{-------------------------------------------------------------------------------
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: SynHighlighterVBScript.pas, released 2000-04-18.
The Original Code is based on the lbVBSSyn.pas file from the
mwEdit component suite by Martin Waldenburg and other developers, the Initial
Author of this file is Luiz C. Vaz de Brito.
Unicode translation by Maël Hörz.
All Rights Reserved.
Contributors to the SynEdit and mwEdit projects are listed in the
Contributors.txt file.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
$Id: SynHighlighterVBScript.pas,v 1.14.2.6 2005/12/16 17:13:16 maelh Exp $
You may retrieve the latest version of this file at the SynEdit home page,
located at http://SynEdit.SourceForge.net
Known Issues:
-------------------------------------------------------------------------------}
{
@abstract(Provides a VBScript highlighter for SynEdit)
@author(Luiz C. Vaz de Brito, converted to SynEdit by David Muir <david@loanhead45.freeserve.co.uk>)
@created(20 January 1999, converted to SynEdit April 18, 2000)
@lastmod(2000-06-23)
The SynHighlighterVBScript unit provides SynEdit with a VisualBasic Script (.vbs) highlighter.
Thanks to Primoz Gabrijelcic and Martin Waldenburg.
}
unit SynHighlighterVBScript;
{$I SynEdit.inc}
interface
uses
System.SysUtils,
System.Classes,
System.Generics.Defaults,
System.Generics.Collections,
Vcl.Graphics,
SynEditTypes,
SynEditHighlighter,
//++ CodeFolding
System.RegularExpressions,
SynEditCodeFolding;
//++ CodeFolding
const
SYNS_AttrConst = 'Constant';
type
TtkTokenKind = (tkSymbol, tkKey, tkComment, tkConst, tkIdentifier, tkNull,
tkNumber, tkSpace, tkString, tkFunction, tkUnknown);
PIdentFuncTableFunc = ^TIdentFuncTableFunc;
TIdentFuncTableFunc = function (Index: Integer): TtkTokenKind of object;
type
// TSynVBScriptSyn = class(TSynCustomHighLighter)
//++ CodeFolding
TSynVBScriptSyn = class(TSynCustomCodeFoldingHighlighter)
//-- CodeFolding
private
FTokenID: TtkTokenKind;
fCommentAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fKeyAttri: TSynHighlighterAttributes;
fNumberAttri: TSynHighlighterAttributes;
fSpaceAttri: TSynHighlighterAttributes;
fStringAttri: TSynHighlighterAttributes;
fSymbolAttri: TSynHighlighterAttributes;
fFunctionAttri: TSynHighlighterAttributes;
fCOnstAttri: TSynHighlighterAttributes;
FKeywords: TDictionary<String, TtkTokenKind>;
//++ CodeFolding
RE_BlockBegin : TRegEx;
RE_BlockEnd : TRegEx;
//-- CodeFolding
procedure DoAddKeyword(AKeyword: string; AKind: integer);
function IdentKind(MayBe: PWideChar): TtkTokenKind;
procedure ApostropheProc;
procedure CRProc;
procedure DateProc;
procedure GreaterProc;
procedure IdentProc;
procedure REMProc;
procedure LFProc;
procedure LowerProc;
procedure NullProc;
procedure NumberProc;
procedure SpaceProc;
procedure StringProc;
procedure SymbolProc;
procedure UnknownProc;
protected
function GetSampleSource: string; override;
function IsFilterStored: Boolean; override;
public
class function GetLanguageName: string; override;
class function GetFriendlyLanguageName: string; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
override;
function GetEol: Boolean; override;
function GetTokenID: TtkTokenKind;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetTokenKind: integer; override;
procedure Next; override;
//++ CodeFolding
procedure ScanForFoldRanges(FoldRanges: TSynFoldRanges;
LinesToScan: TStrings; FromLine: Integer; ToLine: Integer); override;
procedure AdjustFoldRanges(FoldRanges: TSynFoldRanges;
LinesToScan: TStrings); override;
//-- CodeFolding
published
property CommentAttri: TSynHighlighterAttributes read fCommentAttri
write fCommentAttri;
property ConstAttri: TSynHighlighterAttributes read fCOnstAttri
write fConstAttri;
property FunctionAttri: TSynHighlighterAttributes read fFunctionAttri
write fFunctionAttri;
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri
write fIdentifierAttri;
property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri;
property NumberAttri: TSynHighlighterAttributes read fNumberAttri
write fNumberAttri;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri
write fSpaceAttri;
property StringAttri: TSynHighlighterAttributes read fStringAttri
write fStringAttri;
property SymbolAttri: TSynHighlighterAttributes read fSymbolAttri
write fSymbolAttri;
end;
implementation
uses
SynEditMiscProcs,
SynEditStrConst;
const
Keywords: string =
'and, as, boolean, byref, byte, byval, call, case, class, const, currency,' +
'default, description , dim, do, double, each, else, elseif, empty, end,' +
'endif, enum, eqv, error, event, exit, explicit, false, firstindex , for,' +
'function, get, global , goto, helpcontext , helpfile , if, ignorecase, imp,' +
'implements, in, integer, is, length , let, like, long, loop, lset, me, mod,' +
'new, next, not, nothing, null, number , on, option, optional, or, paramarray,' +
'pattern, preserve, private, property, public, raiseevent, redim, resume,' +
'rset, select, set, shared, single, source , static, sub, submatches, then,' +
'to, true, type, typeof, until, value, variant, wend, while, with, xor';
FunctionConsts: string =
'vbabort, vbabortretryignore, vbapplicationmodal, vbarray, vbbinarycompare,' +
'vbblack, vbblue, vbboolean, vbbyte, vbcancel, vbcr, vbcritical, vbcrlf,' +
'vbcurrency, vbcyan, vbdatabasecompare, vbdataobject, vbdate, vbdecimal,' +
'vbdefaultbutton1, vbdefaultbutton2, vbdefaultbutton3, vbdefaultbutton4,' +
'vbdouble, vbempty, vberror, vbexclamation, vbfalse, vbfirstfourdays,' +
'vbfirstfullweek, vbfirstjan1, vbformfeed, vbfriday, vbgeneraldate, vbgreen,' +
'vbignore, vbinformation, vbinteger, vblf, vblong, vblongdate, vblongtime,' +
'vbmagenta, vbmonday, vbmsgboxhelpbutton, vbmsgboxright, vbmsgboxrtlreading,' +
'vbmsgboxsetforeground, vbnewline, vbno, vbnull, vbnullchar, vbnullstring,' +
'vbobject, vbobjecterror, vbok, vbokcancel, vbokonly, vbquestion, vbred,' +
'vbretry, vbretrycancel, vbsaturday, vbshortdate, vbshorttime, vbsingle,' +
'vbstring, vbsunday, vbsystemmodal, vbtab, vbtextcompare, vbthursday, vbtrue,' +
'vbtuesday, vbusedefault, vbusesystem, vbusesystemdayofweek, vbvariant,' +
'vbverticaltab, vbwednesday, vbwhite, vbyellow, vbyes, vbyesno, vbyesnocancel';
Functions: string =
'abs, anchor, array, asc, ascb, ascw, atn, cbool, cbyte, ccur, cdate, cdbl,' +
'chr, chrb, chrw, cint, class_initialize, class_terminate, clear, clng, cos,' +
'createcomponent, createobject, csng, cstr, date, dateadd,' +
'datediff, datepart, dateserial, datevalue, day, debug, dictionary, document,' +
'element, erase, err, escape, eval, execute, executeglobal, exp,' +
'filesystemobject, filter, fix, form, formatcurrency, formatdatetime,' +
'formatnumber, formatpercent, getlocale, getobject, getref,' +
'getresource, hex, history, hour, inputbox, instr, instrb, instrrev, int,' +
'isarray, isdate, isempty, isnull, isnumeric, isobject, join, lbound, lcase,' +
'left, leftb, len, lenb, link, loadpicture, location, log, ltrim, mid, midb,' +
'minute, month, monthname, msgbox, navigator, now, oct, raise, randomize,' +
'regexp, rem, replace, rgb, right, rightb, rnd, round, rtrim, scriptengine,' +
'scriptenginebuildversion, scriptenginemajorversion, scriptengineminorversion,' +
'second, setlocale, sgn, sin, space, split, sqr, step, stop, strcomp, string,' +
'strreverse, tan, test, textstream, time, timer, timeserial, timevalue, trim,' +
'typename, ubound, ucase, unescape, vartype, weekday, weekdayname, window,' +
'write, writeline, year';
procedure TSynVBScriptSyn.DoAddKeyword(AKeyword: string; AKind: Integer);
begin
if not FKeywords.ContainsKey(AKeyword) then
FKeywords.Add(AKeyword, TtkTokenKind(AKind));
end;
function TSynVBScriptSyn.IdentKind(MayBe: PWideChar): TtkTokenKind;
var
S: String;
begin
fToIdent := MayBe;
while IsIdentChar(MayBe^) do
Inc(Maybe);
fStringLen := Maybe - fToIdent;
SetString(S, fToIdent, fStringLen);
if FKeywords.ContainsKey(S) then
Result := FKeywords[S]
else
Result := tkIdentifier;
end;
constructor TSynVBScriptSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fCaseSensitive := False;
// Create the keywords dictionary case-insensitive
FKeywords := TDictionary<String, TtkTokenKind>.Create(TIStringComparer.Ordinal);
fCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment, SYNS_FriendlyAttrComment);
fCommentAttri.Style := [fsItalic];
AddAttribute(fCommentAttri);
fConstAttri := TSynHighlighterAttributes.Create(SYNS_AttrConst, SYNS_AttrConst);
fConstAttri.Style := [fsbold];
AddAttribute(fConstAttri);
fFunctionAttri := TSynHighlighterAttributes.Create(SYNS_AttrSystem, SYNS_FriendlyAttrSystem);
AddAttribute(fFunctionAttri);
fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier, SYNS_FriendlyAttrIdentifier);
AddAttribute(fIdentifierAttri);
fKeyAttri := TSynHighlighterAttributes.Create(SYNS_AttrReservedWord, SYNS_FriendlyAttrReservedWord);
fKeyAttri.Style := [fsBold];
AddAttribute(fKeyAttri);
fNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber, SYNS_FriendlyAttrNumber);
AddAttribute(fNumberAttri);
fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace, SYNS_FriendlyAttrSpace);
AddAttribute(fSpaceAttri);
fStringAttri := TSynHighlighterAttributes.Create(SYNS_AttrString, SYNS_FriendlyAttrString);
AddAttribute(fStringAttri);
fSymbolAttri := TSynHighlighterAttributes.Create(SYNS_AttrSymbol, SYNS_FriendlyAttrSymbol);
AddAttribute(fSymbolAttri);
SetAttributesOnChange(DefHighlightChange);
fDefaultFilter := SYNS_FilterVBScript;
EnumerateKeywords(Ord(tkKey), KeyWords, IsIdentChar, DoAddKeyword);
EnumerateKeywords(Ord(tkConst), FunctionConsts, IsIdentChar, DoAddKeyword);
EnumerateKeywords(Ord(tkFunction), Functions, IsIdentChar, DoAddKeyword);
//++ CodeFolding
RE_BlockBegin := TRegEx.Create('\b^(sub |function |private sub |private function |class )\b', [roIgnoreCase]);
RE_BlockEnd := TRegEx.Create('\b^(end sub|end function|end class)\b', [roIgnoreCase]);
//-- CodeFolding
end;
destructor TSynVBScriptSyn.Destroy;
begin
fKeywords.Free;
inherited Destroy;
end;
//++ CodeFolding
Const
FT_Standard = 1; // begin end, class end, record end
FT_Comment = 11;
FT_CodeDeclaration = 16;
FT_CodeDeclarationWithBody = 17;
FT_Implementation = 18;
procedure TSynVBScriptSyn.ScanForFoldRanges(FoldRanges: TSynFoldRanges;
LinesToScan: TStrings; FromLine: Integer; ToLine: Integer);
var
CurLine: String;
Line: Integer;
ok: Boolean;
function BlockDelimiter(Line: Integer): Boolean;
var
Index: Integer;
mcb: TMatchCollection;
mce: TMatchCollection;
match: TMatch;
begin
Result := False;
mcb := RE_BlockBegin.Matches(CurLine);
if mcb.Count > 0 then
begin
// Char must have proper highlighting (ignore stuff inside comments...)
Index := mcb.Item[0].Index;
if GetHighlighterAttriAtRowCol(LinesToScan, Line, Index) <> fCommentAttri then
begin
ok := False;
// And ignore lines with both opening and closing chars in them
for match in Re_BlockEnd.Matches(CurLine) do
if match.Index > Index then
begin
OK := True;
Break;
end;
if not OK then begin
FoldRanges.StartFoldRange(Line + 1, FT_Standard);
Result := True;
end;
end;
end
else
begin
mce := RE_BlockEnd.Matches(CurLine);
if mce.Count > 0 then
begin
Index := mce.Item[0].Index;
if GetHighlighterAttriAtRowCol(LinesToScan, Line, Index) <> fCommentAttri then
begin
FoldRanges.StopFoldRange(Line + 1, FT_Standard);
Result := True;
end;
end;
end;
end;
function FoldRegion(Line: Integer): Boolean;
var
S: string;
begin
Result := False;
S := TrimLeft(CurLine);
if Uppercase(Copy(S, 1, 7)) = '''REGION' then
begin
FoldRanges.StartFoldRange(Line + 1, FoldRegionType);
Result := True;
end
else if Uppercase(Copy(S, 1, 10)) = '''ENDREGION' then
begin
FoldRanges.StopFoldRange(Line + 1, FoldRegionType);
Result := True;
end;
end;
begin
for Line := FromLine to ToLine do
begin
// Deal first with Multiline statements
CurLine := LinesToScan[Line];
// Skip empty lines
if CurLine = '' then begin
FoldRanges.NoFoldInfo(Line + 1);
Continue;
end;
// Find Fold regions
if FoldRegion(Line) then
Continue;
// Find begin or end (Fold Type 1)
if not BlockDelimiter(Line) then
FoldRanges.NoFoldInfo(Line + 1);
end; //for Line
end;
procedure TSynVBScriptSyn.AdjustFoldRanges(FoldRanges: TSynFoldRanges;
LinesToScan: TStrings);
{
Provide folding for procedures and functions included nested ones.
}
Var
i, j, SkipTo: Integer;
ImplementationIndex: Integer;
FoldRange: TSynFoldRange;
mc: TMatchCollection;
begin
ImplementationIndex := - 1;
for i := FoldRanges.Ranges.Count - 1 downto 0 do
begin
if FoldRanges.Ranges.List[i].FoldType = FT_Implementation then
ImplementationIndex := i
else if FoldRanges.Ranges.List[i].FoldType = FT_CodeDeclaration then
begin
if ImplementationIndex >= 0 then begin
// Code declaration in the Interface part of a unit
FoldRanges.Ranges.Delete(i);
Dec(ImplementationIndex);
continue;
end;
// Examine the following ranges
SkipTo := 0;
j := i + 1;
while J < FoldRanges.Ranges.Count do begin
FoldRange := FoldRanges.Ranges.List[j];
Inc(j);
case FoldRange.FoldType of
// Nested procedure or function
FT_CodeDeclarationWithBody:
begin
SkipTo := FoldRange.ToLine;
continue;
end;
FT_Standard:
// possibly begin end;
if FoldRange.ToLine <= SkipTo then
Continue
else
begin
mc := RE_BlockBegin.Matches(LinesToScan[FoldRange.FromLine - 1]);
if mc.Count > 0 then
begin
if mc.Item[0].Value.ToLower = 'begin' then
begin
// function or procedure followed by begin end block
// Adjust ToLine
FoldRanges.Ranges.List[i].ToLine := FoldRange.ToLine;
FoldRanges.Ranges.List[i].FoldType := FT_CodeDeclarationWithBody;
break
end else
begin
// class or record declaration follows, so
FoldRanges.Ranges.Delete(i);
break;
end;
end else
Assert(False, 'TSynVBSSyn.AdjustFoldRanges');
end;
else
begin
if FoldRange.ToLine <= SkipTo then
Continue
else begin
// Otherwise delete
// eg. function definitions within a class definition
FoldRanges.Ranges.Delete(i);
break
end;
end;
end;
end;
end;
end;
if ImplementationIndex >= 0 then
// Looks better without it
//FoldRanges.Ranges.List[ImplementationIndex].ToLine := LinesToScan.Count;
FoldRanges.Ranges.Delete(ImplementationIndex);
end;
//-- CodeFolding
procedure TSynVBScriptSyn.ApostropheProc;
begin
fTokenID := tkComment;
repeat
inc(Run);
until IsLineEnd(Run);
end;
procedure TSynVBScriptSyn.CRProc;
begin
fTokenID := tkSpace;
inc(Run);
if fLine[Run] = #10 then inc(Run);
end;
procedure TSynVBScriptSyn.DateProc;
begin
fTokenID := tkString;
repeat
if IsLineEnd(Run) then break;
inc(Run);
until FLine[Run] = '#';
if not IsLineEnd(Run) then inc(Run);
end;
procedure TSynVBScriptSyn.GreaterProc;
begin
fTokenID := tkSymbol;
Inc(Run);
if fLine[Run] = '=' then Inc(Run);
end;
procedure TSynVBScriptSyn.IdentProc;
begin
fTokenID := IdentKind((fLine + Run));
inc(Run, fStringLen);
while IsIdentChar(fLine[Run]) do
inc(Run);
end;
procedure TSynVBScriptSyn.LFProc;
begin
fTokenID := tkSpace;
inc(Run);
end;
procedure TSynVBScriptSyn.LowerProc;
begin
fTokenID := tkSymbol;
Inc(Run);
if CharInSet(fLine[Run], ['=', '>']) then Inc(Run);
end;
procedure TSynVBScriptSyn.NullProc;
begin
fTokenID := tkNull;
inc(Run);
end;
procedure TSynVBScriptSyn.NumberProc;
function IsNumberChar: Boolean;
begin
case fLine[Run] of
'0'..'9', '.', 'e', 'E':
Result := True;
else
Result := False;
end;
end;
begin
inc(Run);
fTokenID := tkNumber;
while IsNumberChar do inc(Run);
end;
procedure TSynVBScriptSyn.SpaceProc;
begin
inc(Run);
fTokenID := tkSpace;
while (FLine[Run] <= #32) and not IsLineEnd(Run) do inc(Run);
end;
procedure TSynVBScriptSyn.StringProc;
begin
fTokenID := tkString;
if (FLine[Run + 1] = #34) and (FLine[Run + 2] = #34) then inc(Run, 2);
repeat
if IsLineEnd(Run) then break;
inc(Run);
until FLine[Run] = #34;
if not IsLineEnd(Run) then inc(Run);
end;
procedure TSynVBScriptSyn.SymbolProc;
begin
inc(Run);
fTokenID := tkSymbol;
end;
procedure TSynVBScriptSyn.UnknownProc;
begin
inc(Run);
fTokenID := tkIdentifier;
end;
procedure TSynVBScriptSyn.Next;
begin
fTokenPos := Run;
case fLine[Run] of
#39: ApostropheProc;
#13: CRProc;
'#': DateProc;
'>': GreaterProc;
'A'..'Q', 'S'..'Z', 'a'..'q', 's'..'z', '_': IdentProc;
'R', 'r': REMProc;
#10: LFProc;
'<': LowerProc;
#0: NullProc;
'0'..'9': NumberProc;
#1..#9, #11, #12, #14..#32: SpaceProc;
#34: StringProc;
'&', '{', '}', ':', ',', '=', '^', '-',
'+', '.', '(', ')', ';', '/', '*': SymbolProc;
else UnknownProc;
end;
inherited;
end;
function TSynVBScriptSyn.GetDefaultAttribute(Index: integer):
TSynHighlighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT: Result := fCommentAttri;
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
SYN_ATTR_KEYWORD: Result := fKeyAttri;
SYN_ATTR_STRING: Result := fStringAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
SYN_ATTR_SYMBOL: Result := fSymbolAttri;
else
Result := nil;
end;
end;
function TSynVBScriptSyn.GetEol: Boolean;
begin
Result := Run = fLineLen + 1;
end;
function TSynVBScriptSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function TSynVBScriptSyn.GetTokenAttribute: TSynHighlighterAttributes;
begin
case fTokenID of
tkComment: Result := fCommentAttri;
tkConst: Result := fCOnstAttri;
tkIdentifier: Result := fIdentifierAttri;
tkFunction: Result := fFunctionAttri;
tkKey: Result := fKeyAttri;
tkNumber: Result := fNumberAttri;
tkSpace: Result := fSpaceAttri;
tkString: Result := fStringAttri;
tkSymbol: Result := fSymbolAttri;
tkUnknown: Result := fIdentifierAttri;
else Result := nil;
end;
end;
function TSynVBScriptSyn.GetTokenKind: integer;
begin
Result := Ord(fTokenId);
end;
function TSynVBScriptSyn.IsFilterStored: Boolean;
begin
Result := fDefaultFilter <> SYNS_FilterVBScript;
end;
class function TSynVBScriptSyn.GetLanguageName: string;
begin
Result := SYNS_LangVBSScript;
end;
function TSynVBScriptSyn.GetSampleSource: string;
begin
Result := ''' Syntax highlighting'#13#10 +
'function printNumber()'#13#10 +
' number = 12345'#13#10 +
' document.write("The number is " + number)'#13#10 +
' for i = 0 to 10'#13#10 +
' x = x + 1.0'#13#10 +
' next'#13#10 +
'end function';
end;
class function TSynVBScriptSyn.GetFriendlyLanguageName: string;
begin
Result := SYNS_FriendlyLangVBSScript;
end;
procedure TSynVBScriptSyn.REMProc;
begin
if CharInSet(FLine[Run+1], ['E', 'e']) and
CharInSet(FLine[Run+2], ['M', 'm']) and (FLine[Run+3] <= #32) then
ApostropheProc
else
begin
fTokenID := tkIdentifier;
IdentProc;
end;
end;
initialization
RegisterPlaceableHighlighter(TSynVBScriptSyn);
end.
|
{
En los datos de entrada se proporcionan dos tiempos como enteros de la forma hhmm donde hh representa las horas (menos de 24) y mm los minutos (menos de 60).
Determine la suma de estos dos tiempos, y exhiba el resultado en la forma d hhmm, donde d es dias, ya sea cero o uno.
Ejemplo de entrada : 1345 2153.
Ejemplo de salida : 1 1138.
}
program pr2ej17;
var
num1, num2, hh1, hh2, mm1, mm2, suma, res : integer;
begin
readln(num1, num2);
(* hallo las horas y minutos asociadas a num1 *)
hh1 := num1 div 100;
mm1 := num1 mod 100;
(* hallo las horas y minutos asociadas a num2 *)
hh2 := num2 div 100;
mm2 := num2 mod 100;
(* llevo num1 de base 60 a base 10 *)
num1 := 60*hh1 + mm1;
(* llevo num2 de base 60 a base 10 *)
num2 := 60*hh2 + mm2;
(* los sumo en base 10 *)
suma := num1 + num2;
(* expreso la suma en base 24 (días) / 60 (minutos) *)
res := suma mod 60; {pongo los dos ultimos digitos}
res := ((suma div 60) mod 24)*100 + res; {pongo las horas del dia}
write(((suma div 60) div 24), ' ', res);
end. |
unit MapData;
interface
const
MaxHeight = 39;
MaxWidth = 49;
BLOCK_FREE = 0;
BLOCK_WALL = 1;
BLOCK_STEEL_WALL = 2;
BLOCK_HEAD = 3;
BLOCK_FIRST_PLAYER = 4;
BLOCK_SECOND_PLAYER = 5;
BLOCK_ENEMY = 6;
procedure Clean;
function IsFreeWay(ObjSide, ObjX, ObjY, WCount, HCount: Integer): Boolean;
var
Map: TMapData;
implementation
uses
Helper;
function IsFreeWay(ObjSide, ObjX, ObjY, WCount, HCount: Integer): Boolean;
var
CollisionObjX, CollisionObjY: Integer;
SmallBlockX, SmallBlockY: Integer;
begin
case ObjSide of
SIDE_TOP:
begin
CollisionObjX := ObjX;
CollisionObjY := ObjY - 1;
SmallBlockX := CollisionObjX + 1;
SmallBlockY := CollisionObjY;
end;
SIDE_BOTTOM:
begin
CollisionObjX := ObjX;
CollisionObjY := ObjY + HCount;
SmallBlockX := CollisionObjX + 1;
SmallBlockY := CollisionObjY;
end;
SIDE_LEFT:
begin
CollisionObjX := ObjX - 1;
CollisionObjY := ObjY;
SmallBlockX := CollisionObjX;
SmallBlockY := CollisionObjY + 1;
end;
SIDE_RIGHT:
begin
CollisionObjX := ObjX + WCount;
CollisionObjY := ObjY;
SmallBlockX := CollisionObjX;
SmallBlockY := CollisionObjY + 1;
end;
end;
Result := (Map[CollisionObjY, CollisionObjX] = BLOCK_FREE) and (Map[SmallBlockY, SmallBlockX] = BLOCK_FREE);
end;
procedure Clean;
var
i, j: Integer;
begin
for i := 0 to MaxWidth do
for j := 0 to MaxHeight do
Map[i, j] := 0;
end;
end.
|
unit LoteNFe;
interface
uses
RetornoLoteNFe;
type
TLoteNFe = class
private
FCodigo :Integer;
FCodigoNotaFiscal :Integer;
FData :TDateTime;
FRetorno :TRetornoLoteNFe;
procedure SetCodigo(const Value: Integer);
private
function GetCodigo :Integer;
function GetCodigoNotaFiscal :Integer;
function GetData :TDateTime;
function GetRetornoLoteNFe :TRetornoLoteNFe;
public
constructor CriaLoteEmProcessamento(CodigoNotaFiscal :Integer);
constructor CriaParaRepositorio(Codigo :Integer;
CodigoNotaFiscal :Integer;
Data :TDateTime);
destructor Destroy; override;
public
property Codigo :Integer read GetCodigo write SetCodigo;
property CodigoNotaFiscal :Integer read GetCodigoNotaFiscal write FCodigoNotaFiscal;
property Data :TDateTime read GetData;
property Retorno :TRetornoLoteNFe read GetRetornoLoteNFe;
public
procedure AdicionarRetornoLote(Status :String; Motivo :String; Recibo :String);
end;
implementation
uses
ExcecaoParametroInvalido,
SysUtils,
Repositorio,
FabricaRepositorio;
{ TLoteNFe }
procedure TLoteNFe.AdicionarRetornoLote(Status, Motivo, Recibo: String);
begin
FreeAndNil(self.FRetorno);
self.FRetorno := TRetornoLoteNFe.Create(self.FCodigo, Status, Motivo, Recibo);
end;
constructor TLoteNFe.CriaLoteEmProcessamento(CodigoNotaFiscal :Integer);
begin
if (CodigoNotaFiscal <= 0) then
raise TExcecaoParametroInvalido.Create(self.ClassName, 'CriaLoteEmProcessamento(CodigoNotaFiscal :Integer)', 'CodigoNotaFiscal');
self.FCodigo := 0;
self.FCodigoNotaFiscal := CodigoNotaFiscal;
self.FData := Now;
self.FRetorno := nil;
end;
constructor TLoteNFe.CriaParaRepositorio(Codigo, CodigoNotaFiscal: Integer;
Data: TDateTime);
begin
self.FCodigo := Codigo;
self.FCodigoNotaFiscal := CodigoNotaFiscal;
self.FData := Data;
self.FRetorno := nil;
end;
destructor TLoteNFe.Destroy;
begin
FreeAndNil(self.FRetorno);
inherited;
end;
function TLoteNFe.GetCodigo: Integer;
begin
result := self.FCodigo;
end;
function TLoteNFe.GetCodigoNotaFiscal: Integer;
begin
result := self.FCodigoNotaFiscal;
end;
function TLoteNFe.GetData: TDateTime;
begin
result := self.FData;
end;
function TLoteNFe.GetRetornoLoteNFe: TRetornoLoteNFe;
var
Repositorio :TRepositorio;
begin
if not Assigned(self.FRetorno) then begin
Repositorio := nil;
try
Repositorio := TFabricaRepositorio.GetRepositorio(TRetornoLoteNFe.ClassName);
self.FRetorno := (Repositorio.Get(self.FCodigo) as TRetornoLoteNFe);
finally
FreeAndNil(Repositorio);
end;
end;
result := self.FRetorno;
end;
procedure TLoteNFe.SetCodigo(const Value: Integer);
begin
self.FCodigo := Value;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Androidapi.JNI.JavaTypes;
interface
uses Androidapi.Jni,
Androidapi.JNIBridge;
type
{Class forward declarations}
JObject = interface;//java.lang.Object
JClassLoader = interface;//java.lang.ClassLoader
JInputStream = interface;//java.io.InputStream
JByteArrayInputStream = interface;//java.io.ByteArrayInputStream
JNumber = interface;//java.lang.Number
JInteger = interface;//java.lang.Integer
JBoolean = interface;//java.lang.Boolean
JByte = interface;//java.lang.Byte
JEnumeration = interface;//java.util.Enumeration
JCalendar = interface;//java.util.Calendar
JAbstractCollection = interface;//java.util.AbstractCollection
JAbstractSet = interface;//java.util.AbstractSet
JHashSet = interface;//java.util.HashSet
JAbstractList = interface;//java.util.AbstractList
JSerializable = interface;//java.io.Serializable
JEnum = interface;//java.lang.Enum
JThread_State = interface;//java.lang.Thread$State
JThread_UncaughtExceptionHandler = interface;//java.lang.Thread$UncaughtExceptionHandler
JFileDescriptor = interface;//java.io.FileDescriptor
JFile = interface;//java.io.File
JArrayList = interface;//java.util.ArrayList
JRunnable = interface;//java.lang.Runnable
JCloseable = interface;//java.io.Closeable
JWriter = interface;//java.io.Writer
JIterable = interface;//java.lang.Iterable
JCollection = interface;//java.util.Collection
JList = interface;//java.util.List
JOutputStream = interface;//java.io.OutputStream
Jlang_Class = interface;//java.lang.Class
JThrowable = interface;//java.lang.Throwable
JException = interface;//java.lang.Exception
JJSONException = interface;//org.json.JSONException
JUUID = interface;//java.util.UUID
JAbstractMap = interface;//java.util.AbstractMap
JHashMap = interface;//java.util.HashMap
JRandom = interface;//java.util.Random
JAnnotation = interface;//java.lang.annotation.Annotation
JThread = interface;//java.lang.Thread
JDate = interface;//java.util.Date
JFilterOutputStream = interface;//java.io.FilterOutputStream
JPrintStream = interface;//java.io.PrintStream
JRuntimeException = interface;//java.lang.RuntimeException
JObserver = interface;//java.util.Observer
JFloat = interface;//java.lang.Float
JDouble = interface;//java.lang.Double
JPrintWriter = interface;//java.io.PrintWriter
JIterator = interface;//java.util.Iterator
JListIterator = interface;//java.util.ListIterator
JByteArrayOutputStream = interface;//java.io.ByteArrayOutputStream
JStackTraceElement = interface;//java.lang.StackTraceElement
JFileOutputStream = interface;//java.io.FileOutputStream
JAbstractStringBuilder = interface;//java.lang.AbstractStringBuilder
JStringBuilder = interface;//java.lang.StringBuilder
JCharSequence = interface;//java.lang.CharSequence
JGregorianCalendar = interface;//java.util.GregorianCalendar
JJSONTokener = interface;//org.json.JSONTokener
JMap = interface;//java.util.Map
JLocale = interface;//java.util.Locale
JTimeZone = interface;//java.util.TimeZone
JFileFilter = interface;//java.io.FileFilter
JEnumSet = interface;//java.util.EnumSet
Jutil_Observable = interface;//java.util.Observable
JFilenameFilter = interface;//java.io.FilenameFilter
JJSONObject = interface;//org.json.JSONObject
JString = interface;//java.lang.String
JSet = interface;//java.util.Set
JShort = interface;//java.lang.Short
JThreadGroup = interface;//java.lang.ThreadGroup
JComparator = interface;//java.util.Comparator
JJSONArray = interface;//org.json.JSONArray
JLong = interface;//java.lang.Long
JFileInputStream = interface;//java.io.FileInputStream
JStringBuffer = interface;//java.lang.StringBuffer
JObjectClass = interface(IJavaClass)
['{83BD30EE-FE9B-470D-AD6C-23AEAABB7FFA}']
{Methods}
function init: JObject; cdecl;
end;
[JavaSignature('java/lang/Object')]
JObject = interface(IJavaInstance)
['{32321F8A-4001-4BF8-92E7-6190D070988D}']
{Methods}
function equals(o: JObject): Boolean; cdecl;
function getClass: Jlang_Class; cdecl;
function hashCode: Integer; cdecl;
procedure notify; cdecl;
procedure notifyAll; cdecl;
function toString: JString; cdecl;
procedure wait; cdecl; overload;
procedure wait(millis: Int64); cdecl; overload;
procedure wait(millis: Int64; nanos: Integer); cdecl; overload;
end;
TJObject = class(TJavaGenericImport<JObjectClass, JObject>) end;
JClassLoaderClass = interface(JObjectClass)
['{453BE0D7-B813-4C83-A30C-F24C026FD112}']
{Methods}
function getSystemClassLoader: JClassLoader; cdecl;
function getSystemResourceAsStream(resName: JString): JInputStream; cdecl;
function getSystemResources(resName: JString): JEnumeration; cdecl;
end;
[JavaSignature('java/lang/ClassLoader')]
JClassLoader = interface(JObject)
['{17B43D0A-2016-44ED-84B5-9EAB55AF8FDD}']
{Methods}
procedure clearAssertionStatus; cdecl;
function getParent: JClassLoader; cdecl;
function getResourceAsStream(resName: JString): JInputStream; cdecl;
function getResources(resName: JString): JEnumeration; cdecl;
function loadClass(className: JString): Jlang_Class; cdecl;
procedure setClassAssertionStatus(cname: JString; enable: Boolean); cdecl;
procedure setDefaultAssertionStatus(enable: Boolean); cdecl;
procedure setPackageAssertionStatus(pname: JString; enable: Boolean); cdecl;
end;
TJClassLoader = class(TJavaGenericImport<JClassLoaderClass, JClassLoader>) end;
JInputStreamClass = interface(JObjectClass)
['{8D8C2F8A-AD54-42D0-ADA4-FC30FD95A933}']
{Methods}
function init: JInputStream; cdecl;
end;
[JavaSignature('java/io/InputStream')]
JInputStream = interface(JObject)
['{5FD3C203-8A19-42A2-8FD2-643501DF62BC}']
{Methods}
function available: Integer; cdecl;
procedure close; cdecl;
procedure mark(readlimit: Integer); cdecl;
function markSupported: Boolean; cdecl;
function read: Integer; cdecl; overload;
function read(buffer: TJavaArray<Byte>): Integer; cdecl; overload;
function read(buffer: TJavaArray<Byte>; offset: Integer; length: Integer): Integer; cdecl; overload;
procedure reset; cdecl;
function skip(byteCount: Int64): Int64; cdecl;
end;
TJInputStream = class(TJavaGenericImport<JInputStreamClass, JInputStream>) end;
JByteArrayInputStreamClass = interface(JInputStreamClass)
['{1C0763C7-3F23-4531-A6E1-65AF97251C2F}']
{Methods}
function init(buf: TJavaArray<Byte>): JByteArrayInputStream; cdecl; overload;
function init(buf: TJavaArray<Byte>; offset: Integer; length: Integer): JByteArrayInputStream; cdecl; overload;
end;
[JavaSignature('java/io/ByteArrayInputStream')]
JByteArrayInputStream = interface(JInputStream)
['{D8AE245D-6831-48AC-A6F5-1E480815A22D}']
{Methods}
function available: Integer; cdecl;
procedure close; cdecl;
procedure mark(readlimit: Integer); cdecl;
function markSupported: Boolean; cdecl;
function read: Integer; cdecl; overload;
function read(buffer: TJavaArray<Byte>; offset: Integer; length: Integer): Integer; cdecl; overload;
procedure reset; cdecl;
function skip(byteCount: Int64): Int64; cdecl;
end;
TJByteArrayInputStream = class(TJavaGenericImport<JByteArrayInputStreamClass, JByteArrayInputStream>) end;
JNumberClass = interface(JObjectClass)
['{9A30B143-2018-4C7B-9E9B-316F62D643C5}']
{Methods}
function init: JNumber; cdecl;
end;
[JavaSignature('java/lang/Number')]
JNumber = interface(JObject)
['{DFF915A9-AFBE-4EDA-89AC-D0FE32A85482}']
{Methods}
function byteValue: Byte; cdecl;
function doubleValue: Double; cdecl;
function floatValue: Single; cdecl;
function intValue: Integer; cdecl;
function longValue: Int64; cdecl;
function shortValue: SmallInt; cdecl;
end;
TJNumber = class(TJavaGenericImport<JNumberClass, JNumber>) end;
JIntegerClass = interface(JNumberClass)
['{DA48E911-AB80-4875-993F-316B9F310559}']
{Property Methods}
function _GetMAX_VALUE: Integer;
function _GetMIN_VALUE: Integer;
function _GetSIZE: Integer;
function _GetTYPE: Jlang_Class;
{Methods}
function init(value: Integer): JInteger; cdecl; overload;
function init(string_: JString): JInteger; cdecl; overload;
function bitCount(i: Integer): Integer; cdecl;
function decode(string_: JString): JInteger; cdecl;
function getInteger(string_: JString): JInteger; cdecl; overload;
function getInteger(string_: JString; defaultValue: Integer): JInteger; cdecl; overload;
function getInteger(string_: JString; defaultValue: JInteger): JInteger; cdecl; overload;
function highestOneBit(i: Integer): Integer; cdecl;
function lowestOneBit(i: Integer): Integer; cdecl;
function numberOfLeadingZeros(i: Integer): Integer; cdecl;
function numberOfTrailingZeros(i: Integer): Integer; cdecl;
function parseInt(string_: JString): Integer; cdecl; overload;
function parseInt(string_: JString; radix: Integer): Integer; cdecl; overload;
function reverse(i: Integer): Integer; cdecl;
function reverseBytes(i: Integer): Integer; cdecl;
function rotateLeft(i: Integer; distance: Integer): Integer; cdecl;
function rotateRight(i: Integer; distance: Integer): Integer; cdecl;
function signum(i: Integer): Integer; cdecl;
function toBinaryString(i: Integer): JString; cdecl;
function toHexString(i: Integer): JString; cdecl;
function toOctalString(i: Integer): JString; cdecl;
function toString(i: Integer): JString; cdecl; overload;
function toString(i: Integer; radix: Integer): JString; cdecl; overload;
function valueOf(string_: JString): JInteger; cdecl; overload;
function valueOf(string_: JString; radix: Integer): JInteger; cdecl; overload;
function valueOf(i: Integer): JInteger; cdecl; overload;
{Properties}
property MAX_VALUE: Integer read _GetMAX_VALUE;
property MIN_VALUE: Integer read _GetMIN_VALUE;
property SIZE: Integer read _GetSIZE;
property &TYPE: Jlang_Class read _GetTYPE;
end;
[JavaSignature('java/lang/Integer')]
JInteger = interface(JNumber)
['{A07D13BE-2418-4FCB-8CEB-F4160E5884D5}']
{Methods}
function byteValue: Byte; cdecl;
function compareTo(object_: JInteger): Integer; cdecl;
function doubleValue: Double; cdecl;
function equals(o: JObject): Boolean; cdecl;
function floatValue: Single; cdecl;
function hashCode: Integer; cdecl;
function intValue: Integer; cdecl;
function longValue: Int64; cdecl;
function shortValue: SmallInt; cdecl;
function toString: JString; cdecl; overload;
end;
TJInteger = class(TJavaGenericImport<JIntegerClass, JInteger>) end;
JBooleanClass = interface(JObjectClass)
['{CD51CE90-BCDA-4291-99B0-7BC70033C3CB}']
{Property Methods}
function _GetFALSE: JBoolean;
function _GetTRUE: JBoolean;
function _GetTYPE: Jlang_Class;
{Methods}
function init(string_: JString): JBoolean; cdecl; overload;
function init(value: Boolean): JBoolean; cdecl; overload;
function getBoolean(string_: JString): Boolean; cdecl;
function parseBoolean(s: JString): Boolean; cdecl;
function toString(value: Boolean): JString; cdecl; overload;
function valueOf(string_: JString): JBoolean; cdecl; overload;
function valueOf(b: Boolean): JBoolean; cdecl; overload;
{Properties}
property FALSE: JBoolean read _GetFALSE;
property TRUE: JBoolean read _GetTRUE;
property &TYPE: Jlang_Class read _GetTYPE;
end;
[JavaSignature('java/lang/Boolean')]
JBoolean = interface(JObject)
['{21EAFAED-5848-48C2-9998-141B57439F6F}']
{Methods}
function booleanValue: Boolean; cdecl;
function compareTo(that: JBoolean): Integer; cdecl;
function equals(o: JObject): Boolean; cdecl;
function hashCode: Integer; cdecl;
function toString: JString; cdecl; overload;
end;
TJBoolean = class(TJavaGenericImport<JBooleanClass, JBoolean>) end;
JByteClass = interface(JNumberClass)
['{EDEFB599-A2A8-49AD-B413-C2FCEBD19B11}']
{Property Methods}
function _GetMAX_VALUE: Byte;
function _GetMIN_VALUE: Byte;
function _GetSIZE: Integer;
function _GetTYPE: Jlang_Class;
{Methods}
function init(value: Byte): JByte; cdecl; overload;
function init(string_: JString): JByte; cdecl; overload;
function decode(string_: JString): JByte; cdecl;
function parseByte(string_: JString): Byte; cdecl; overload;
function parseByte(string_: JString; radix: Integer): Byte; cdecl; overload;
function toString(value: Byte): JString; cdecl; overload;
function valueOf(string_: JString): JByte; cdecl; overload;
function valueOf(string_: JString; radix: Integer): JByte; cdecl; overload;
function valueOf(b: Byte): JByte; cdecl; overload;
{Properties}
property MAX_VALUE: Byte read _GetMAX_VALUE;
property MIN_VALUE: Byte read _GetMIN_VALUE;
property SIZE: Integer read _GetSIZE;
property &TYPE: Jlang_Class read _GetTYPE;
end;
[JavaSignature('java/lang/Byte')]
JByte = interface(JNumber)
['{882439AC-111F-445F-B6CD-2E1E8D793CDE}']
{Methods}
function byteValue: Byte; cdecl;
function compareTo(object_: JByte): Integer; cdecl;
function doubleValue: Double; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function floatValue: Single; cdecl;
function hashCode: Integer; cdecl;
function intValue: Integer; cdecl;
function longValue: Int64; cdecl;
function shortValue: SmallInt; cdecl;
function toString: JString; cdecl; overload;
end;
TJByte = class(TJavaGenericImport<JByteClass, JByte>) end;
JEnumerationClass = interface(IJavaClass)
['{5E393BCD-3EF2-4764-A59C-37B4D44C289A}']
end;
[JavaSignature('java/util/Enumeration')]
JEnumeration = interface(IJavaInstance)
['{8F9F8780-E6BE-4B67-A4F5-8EC28E1AE2EE}']
{Methods}
function hasMoreElements: Boolean; cdecl;
function nextElement: JObject; cdecl;
end;
TJEnumeration = class(TJavaGenericImport<JEnumerationClass, JEnumeration>) end;
JCalendarClass = interface(JObjectClass)
['{51237FAA-7CDF-4E7E-9AE8-282DC2A930A1}']
{Property Methods}
function _GetALL_STYLES: Integer;
function _GetAM: Integer;
function _GetAM_PM: Integer;
function _GetAPRIL: Integer;
function _GetAUGUST: Integer;
function _GetDATE: Integer;
function _GetDAY_OF_MONTH: Integer;
function _GetDAY_OF_WEEK: Integer;
function _GetDAY_OF_WEEK_IN_MONTH: Integer;
function _GetDAY_OF_YEAR: Integer;
function _GetDECEMBER: Integer;
function _GetDST_OFFSET: Integer;
function _GetERA: Integer;
function _GetFEBRUARY: Integer;
function _GetFIELD_COUNT: Integer;
function _GetFRIDAY: Integer;
function _GetHOUR: Integer;
function _GetHOUR_OF_DAY: Integer;
function _GetJANUARY: Integer;
function _GetJULY: Integer;
function _GetJUNE: Integer;
function _GetLONG: Integer;
function _GetMARCH: Integer;
function _GetMAY: Integer;
function _GetMILLISECOND: Integer;
function _GetMINUTE: Integer;
function _GetMONDAY: Integer;
function _GetMONTH: Integer;
function _GetNOVEMBER: Integer;
function _GetOCTOBER: Integer;
function _GetPM: Integer;
function _GetSATURDAY: Integer;
function _GetSECOND: Integer;
function _GetSEPTEMBER: Integer;
function _GetSHORT: Integer;
function _GetSUNDAY: Integer;
function _GetTHURSDAY: Integer;
function _GetTUESDAY: Integer;
function _GetUNDECIMBER: Integer;
function _GetWEDNESDAY: Integer;
function _GetWEEK_OF_MONTH: Integer;
function _GetWEEK_OF_YEAR: Integer;
function _GetYEAR: Integer;
function _GetZONE_OFFSET: Integer;
{Methods}
function getAvailableLocales: TJavaObjectArray<JLocale>; cdecl;
function getInstance: JCalendar; cdecl; overload;
function getInstance(locale: JLocale): JCalendar; cdecl; overload;
function getInstance(timezone: JTimeZone): JCalendar; cdecl; overload;
function getInstance(timezone: JTimeZone; locale: JLocale): JCalendar; cdecl; overload;
{Properties}
property ALL_STYLES: Integer read _GetALL_STYLES;
property AM: Integer read _GetAM;
property AM_PM: Integer read _GetAM_PM;
property APRIL: Integer read _GetAPRIL;
property AUGUST: Integer read _GetAUGUST;
property DATE: Integer read _GetDATE;
property DAY_OF_MONTH: Integer read _GetDAY_OF_MONTH;
property DAY_OF_WEEK: Integer read _GetDAY_OF_WEEK;
property DAY_OF_WEEK_IN_MONTH: Integer read _GetDAY_OF_WEEK_IN_MONTH;
property DAY_OF_YEAR: Integer read _GetDAY_OF_YEAR;
property DECEMBER: Integer read _GetDECEMBER;
property DST_OFFSET: Integer read _GetDST_OFFSET;
property ERA: Integer read _GetERA;
property FEBRUARY: Integer read _GetFEBRUARY;
property FIELD_COUNT: Integer read _GetFIELD_COUNT;
property FRIDAY: Integer read _GetFRIDAY;
property HOUR: Integer read _GetHOUR;
property HOUR_OF_DAY: Integer read _GetHOUR_OF_DAY;
property JANUARY: Integer read _GetJANUARY;
property JULY: Integer read _GetJULY;
property JUNE: Integer read _GetJUNE;
property LONG: Integer read _GetLONG;
property MARCH: Integer read _GetMARCH;
property MAY: Integer read _GetMAY;
property MILLISECOND: Integer read _GetMILLISECOND;
property MINUTE: Integer read _GetMINUTE;
property MONDAY: Integer read _GetMONDAY;
property MONTH: Integer read _GetMONTH;
property NOVEMBER: Integer read _GetNOVEMBER;
property OCTOBER: Integer read _GetOCTOBER;
property PM: Integer read _GetPM;
property SATURDAY: Integer read _GetSATURDAY;
property SECOND: Integer read _GetSECOND;
property SEPTEMBER: Integer read _GetSEPTEMBER;
property SHORT: Integer read _GetSHORT;
property SUNDAY: Integer read _GetSUNDAY;
property THURSDAY: Integer read _GetTHURSDAY;
property TUESDAY: Integer read _GetTUESDAY;
property UNDECIMBER: Integer read _GetUNDECIMBER;
property WEDNESDAY: Integer read _GetWEDNESDAY;
property WEEK_OF_MONTH: Integer read _GetWEEK_OF_MONTH;
property WEEK_OF_YEAR: Integer read _GetWEEK_OF_YEAR;
property YEAR: Integer read _GetYEAR;
property ZONE_OFFSET: Integer read _GetZONE_OFFSET;
end;
[JavaSignature('java/util/Calendar')]
JCalendar = interface(JObject)
['{2C0409E5-97A4-47CA-9E75-6ACB1CA4515E}']
{Methods}
procedure add(field: Integer; value: Integer); cdecl;
function after(calendar: JObject): Boolean; cdecl;
function before(calendar: JObject): Boolean; cdecl;
procedure clear; cdecl; overload;
procedure clear(field: Integer); cdecl; overload;
function clone: JObject; cdecl;
function compareTo(anotherCalendar: JCalendar): Integer; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(field: Integer): Integer; cdecl;
function getActualMaximum(field: Integer): Integer; cdecl;
function getActualMinimum(field: Integer): Integer; cdecl;
function getDisplayName(field: Integer; style: Integer; locale: JLocale): JString; cdecl;
function getDisplayNames(field: Integer; style: Integer; locale: JLocale): JMap; cdecl;
function getFirstDayOfWeek: Integer; cdecl;
function getGreatestMinimum(field: Integer): Integer; cdecl;
function getLeastMaximum(field: Integer): Integer; cdecl;
function getMaximum(field: Integer): Integer; cdecl;
function getMinimalDaysInFirstWeek: Integer; cdecl;
function getMinimum(field: Integer): Integer; cdecl;
function getTime: JDate; cdecl;
function getTimeInMillis: Int64; cdecl;
function getTimeZone: JTimeZone; cdecl;
function hashCode: Integer; cdecl;
function isLenient: Boolean; cdecl;
function isSet(field: Integer): Boolean; cdecl;
procedure roll(field: Integer; value: Integer); cdecl; overload;
procedure roll(field: Integer; increment: Boolean); cdecl; overload;
procedure &set(field: Integer; value: Integer); cdecl; overload;
procedure &set(year: Integer; month: Integer; day: Integer); cdecl; overload;
procedure &set(year: Integer; month: Integer; day: Integer; hourOfDay: Integer; minute: Integer); cdecl; overload;
procedure &set(year: Integer; month: Integer; day: Integer; hourOfDay: Integer; minute: Integer; second: Integer); cdecl; overload;
procedure setFirstDayOfWeek(value: Integer); cdecl;
procedure setLenient(value: Boolean); cdecl;
procedure setMinimalDaysInFirstWeek(value: Integer); cdecl;
procedure setTime(date: JDate); cdecl;
procedure setTimeInMillis(milliseconds: Int64); cdecl;
procedure setTimeZone(timezone: JTimeZone); cdecl;
function toString: JString; cdecl;
end;
TJCalendar = class(TJavaGenericImport<JCalendarClass, JCalendar>) end;
JAbstractCollectionClass = interface(JObjectClass)
['{27541496-F538-45DB-BFC7-9ED05E5680C3}']
end;
[JavaSignature('java/util/AbstractCollection')]
JAbstractCollection = interface(JObject)
['{4A5BA15A-2B07-4768-AA91-4BA9C93882C1}']
{Methods}
function add(object_: JObject): Boolean; cdecl;
function addAll(collection: JCollection): Boolean; cdecl;
procedure clear; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
function containsAll(collection: JCollection): Boolean; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function remove(object_: JObject): Boolean; cdecl;
function removeAll(collection: JCollection): Boolean; cdecl;
function retainAll(collection: JCollection): Boolean; cdecl;
function size: Integer; cdecl;
function toArray: TJavaObjectArray<JObject>; cdecl; overload;
function toArray(contents: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload;
function toString: JString; cdecl;
end;
TJAbstractCollection = class(TJavaGenericImport<JAbstractCollectionClass, JAbstractCollection>) end;
JAbstractSetClass = interface(JAbstractCollectionClass)
['{C8EA147C-D0DB-4E27-B8B5-77A04711A2F3}']
end;
[JavaSignature('java/util/AbstractSet')]
JAbstractSet = interface(JAbstractCollection)
['{A520B68E-843E-46B8-BBB3-1A40DE9E92CE}']
{Methods}
function equals(object_: JObject): Boolean; cdecl;
function hashCode: Integer; cdecl;
function removeAll(collection: JCollection): Boolean; cdecl;
end;
TJAbstractSet = class(TJavaGenericImport<JAbstractSetClass, JAbstractSet>) end;
JHashSetClass = interface(JAbstractSetClass)
['{7828E4D4-4F9F-493D-869E-92BE600444D5}']
{Methods}
function init: JHashSet; cdecl; overload;
function init(capacity: Integer): JHashSet; cdecl; overload;
function init(capacity: Integer; loadFactor: Single): JHashSet; cdecl; overload;
function init(collection: JCollection): JHashSet; cdecl; overload;
end;
[JavaSignature('java/util/HashSet')]
JHashSet = interface(JAbstractSet)
['{A57B696D-8331-4C96-8759-7F2009371640}']
{Methods}
function add(object_: JObject): Boolean; cdecl;
procedure clear; cdecl;
function clone: JObject; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function remove(object_: JObject): Boolean; cdecl;
function size: Integer; cdecl;
end;
TJHashSet = class(TJavaGenericImport<JHashSetClass, JHashSet>) end;
JAbstractListClass = interface(JAbstractCollectionClass)
['{4495F751-BABA-4349-8D4B-997761ED3876}']
end;
[JavaSignature('java/util/AbstractList')]
JAbstractList = interface(JAbstractCollection)
['{2E98325B-7293-4E06-A775-240FDD287E27}']
{Methods}
procedure add(location: Integer; object_: JObject); cdecl; overload;
function add(object_: JObject): Boolean; cdecl; overload;
function addAll(location: Integer; collection: JCollection): Boolean; cdecl;
procedure clear; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(location: Integer): JObject; cdecl;
function hashCode: Integer; cdecl;
function indexOf(object_: JObject): Integer; cdecl;
function iterator: JIterator; cdecl;
function lastIndexOf(object_: JObject): Integer; cdecl;
function listIterator: JListIterator; cdecl; overload;
function listIterator(location: Integer): JListIterator; cdecl; overload;
function remove(location: Integer): JObject; cdecl;
function &set(location: Integer; object_: JObject): JObject; cdecl;
function subList(start: Integer; end_: Integer): JList; cdecl;
end;
TJAbstractList = class(TJavaGenericImport<JAbstractListClass, JAbstractList>) end;
JSerializableClass = interface(IJavaClass)
['{BFE14BCE-11F1-41B5-A14F-3217521E82BA}']
end;
[JavaSignature('java/io/Serializable')]
JSerializable = interface(IJavaInstance)
['{D24AB8DC-4E6F-411D-9C40-2210F71A3B0D}']
end;
TJSerializable = class(TJavaGenericImport<JSerializableClass, JSerializable>) end;
JEnumClass = interface(JObjectClass)
['{2DB4C98D-F244-4372-9487-E9B9E2F48391}']
{Methods}
function valueOf(enumType: Jlang_Class; name: JString): JEnum; cdecl;
end;
[JavaSignature('java/lang/Enum')]
JEnum = interface(JObject)
['{0CFB5F00-FBF2-469D-806C-471A09BE1BAF}']
{Methods}
function compareTo(o: JEnum): Integer; cdecl;
function equals(other: JObject): Boolean; cdecl;
function getDeclaringClass: Jlang_Class; cdecl;
function hashCode: Integer; cdecl;
function name: JString; cdecl;
function ordinal: Integer; cdecl;
function toString: JString; cdecl;
end;
TJEnum = class(TJavaGenericImport<JEnumClass, JEnum>) end;
JThread_StateClass = interface(JEnumClass)
['{493F7CE3-3BE4-4CE5-9F96-7563BC2DC814}']
{Property Methods}
function _GetBLOCKED: JThread_State;
function _GetNEW: JThread_State;
function _GetRUNNABLE: JThread_State;
function _GetTERMINATED: JThread_State;
function _GetTIMED_WAITING: JThread_State;
function _GetWAITING: JThread_State;
{Methods}
function valueOf(name: JString): JThread_State; cdecl;
function values: TJavaObjectArray<JThread_State>; cdecl;
{Properties}
property BLOCKED: JThread_State read _GetBLOCKED;
property NEW: JThread_State read _GetNEW;
property RUNNABLE: JThread_State read _GetRUNNABLE;
property TERMINATED: JThread_State read _GetTERMINATED;
property TIMED_WAITING: JThread_State read _GetTIMED_WAITING;
property WAITING: JThread_State read _GetWAITING;
end;
[JavaSignature('java/lang/Thread$State')]
JThread_State = interface(JEnum)
['{E3910394-C461-461E-9C1D-64E9BC367F84}']
end;
TJThread_State = class(TJavaGenericImport<JThread_StateClass, JThread_State>) end;
JThread_UncaughtExceptionHandlerClass = interface(IJavaClass)
['{3E2F71F3-BF00-457C-9970-9F1DA9EA7498}']
end;
[JavaSignature('java/lang/Thread$UncaughtExceptionHandler')]
JThread_UncaughtExceptionHandler = interface(IJavaInstance)
['{C9E75389-E9B3-45FF-9EA2-D7BC024DB9DA}']
{Methods}
procedure uncaughtException(thread: JThread; ex: JThrowable); cdecl;
end;
TJThread_UncaughtExceptionHandler = class(TJavaGenericImport<JThread_UncaughtExceptionHandlerClass, JThread_UncaughtExceptionHandler>) end;
JFileDescriptorClass = interface(JObjectClass)
['{B01F2343-4F8E-4FF8-838E-8FB9CFE304E2}']
{Property Methods}
function _Geterr: JFileDescriptor;
function _Getin: JFileDescriptor;
function _Getout: JFileDescriptor;
{Methods}
function init: JFileDescriptor; cdecl;
{Properties}
property err: JFileDescriptor read _Geterr;
property &in: JFileDescriptor read _Getin;
property &out: JFileDescriptor read _Getout;
end;
[JavaSignature('java/io/FileDescriptor')]
JFileDescriptor = interface(JObject)
['{B6D7B003-DD99-4563-93A3-F902501CD6C1}']
{Methods}
procedure sync; cdecl;
function toString: JString; cdecl;
function valid: Boolean; cdecl;
end;
TJFileDescriptor = class(TJavaGenericImport<JFileDescriptorClass, JFileDescriptor>) end;
JFileClass = interface(JObjectClass)
['{D2CE81B7-01CE-468B-A2F2-B85DD35642EC}']
{Property Methods}
function _GetpathSeparator: JString;
function _GetpathSeparatorChar: Char;
function _Getseparator: JString;
function _GetseparatorChar: Char;
{Methods}
function init(dir: JFile; name: JString): JFile; cdecl; overload;
function init(path: JString): JFile; cdecl; overload;
function init(dirPath: JString; name: JString): JFile; cdecl; overload;
function createTempFile(prefix: JString; suffix: JString): JFile; cdecl; overload;
function createTempFile(prefix: JString; suffix: JString; directory: JFile): JFile; cdecl; overload;
function listRoots: TJavaObjectArray<JFile>; cdecl;
{Properties}
property pathSeparator: JString read _GetpathSeparator;
property pathSeparatorChar: Char read _GetpathSeparatorChar;
property separator: JString read _Getseparator;
property separatorChar: Char read _GetseparatorChar;
end;
[JavaSignature('java/io/File')]
JFile = interface(JObject)
['{38C3EB7E-315A-47D2-9052-1E61170EB37F}']
{Methods}
function canExecute: Boolean; cdecl;
function canRead: Boolean; cdecl;
function canWrite: Boolean; cdecl;
function compareTo(another: JFile): Integer; cdecl;
function createNewFile: Boolean; cdecl;
function delete: Boolean; cdecl;
procedure deleteOnExit; cdecl;
function equals(obj: JObject): Boolean; cdecl;
function exists: Boolean; cdecl;
function getAbsoluteFile: JFile; cdecl;
function getAbsolutePath: JString; cdecl;
function getCanonicalFile: JFile; cdecl;
function getCanonicalPath: JString; cdecl;
function getFreeSpace: Int64; cdecl;
function getName: JString; cdecl;
function getParent: JString; cdecl;
function getParentFile: JFile; cdecl;
function getPath: JString; cdecl;
function getTotalSpace: Int64; cdecl;
function getUsableSpace: Int64; cdecl;
function hashCode: Integer; cdecl;
function isAbsolute: Boolean; cdecl;
function isDirectory: Boolean; cdecl;
function isFile: Boolean; cdecl;
function isHidden: Boolean; cdecl;
function lastModified: Int64; cdecl;
function length: Int64; cdecl;
function list: TJavaObjectArray<JString>; cdecl; overload;
function list(filter: JFilenameFilter): TJavaObjectArray<JString>; cdecl; overload;
function listFiles: TJavaObjectArray<JFile>; cdecl; overload;
function listFiles(filter: JFilenameFilter): TJavaObjectArray<JFile>; cdecl; overload;
function listFiles(filter: JFileFilter): TJavaObjectArray<JFile>; cdecl; overload;
function mkdir: Boolean; cdecl;
function mkdirs: Boolean; cdecl;
function renameTo(newPath: JFile): Boolean; cdecl;
function setExecutable(executable: Boolean; ownerOnly: Boolean): Boolean; cdecl; overload;
function setExecutable(executable: Boolean): Boolean; cdecl; overload;
function setLastModified(time: Int64): Boolean; cdecl;
function setReadOnly: Boolean; cdecl;
function setReadable(readable: Boolean; ownerOnly: Boolean): Boolean; cdecl; overload;
function setReadable(readable: Boolean): Boolean; cdecl; overload;
function setWritable(writable: Boolean; ownerOnly: Boolean): Boolean; cdecl; overload;
function setWritable(writable: Boolean): Boolean; cdecl; overload;
function toString: JString; cdecl;
end;
TJFile = class(TJavaGenericImport<JFileClass, JFile>) end;
JArrayListClass = interface(JAbstractListClass)
['{0CC7FC88-8B13-4F0A-9635-26FEEED49F94}']
{Methods}
function init(capacity: Integer): JArrayList; cdecl; overload;
function init: JArrayList; cdecl; overload;
function init(collection: JCollection): JArrayList; cdecl; overload;
end;
[JavaSignature('java/util/ArrayList')]
JArrayList = interface(JAbstractList)
['{B1D54E97-F848-4301-BA5B-F32921164AFA}']
{Methods}
function add(object_: JObject): Boolean; cdecl; overload;
procedure add(index: Integer; object_: JObject); cdecl; overload;
function addAll(collection: JCollection): Boolean; cdecl; overload;
function addAll(index: Integer; collection: JCollection): Boolean; cdecl; overload;
procedure clear; cdecl;
function clone: JObject; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
procedure ensureCapacity(minimumCapacity: Integer); cdecl;
function equals(o: JObject): Boolean; cdecl;
function &get(index: Integer): JObject; cdecl;
function hashCode: Integer; cdecl;
function indexOf(object_: JObject): Integer; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function lastIndexOf(object_: JObject): Integer; cdecl;
function remove(index: Integer): JObject; cdecl; overload;
function remove(object_: JObject): Boolean; cdecl; overload;
function &set(index: Integer; object_: JObject): JObject; cdecl;
function size: Integer; cdecl;
function toArray: TJavaObjectArray<JObject>; cdecl; overload;
function toArray(contents: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload;
procedure trimToSize; cdecl;
end;
TJArrayList = class(TJavaGenericImport<JArrayListClass, JArrayList>) end;
JRunnableClass = interface(IJavaClass)
['{49A6EA8E-0ADB-4D8E-8FA3-F13D4ADCF281}']
end;
[JavaSignature('java/lang/Runnable')]
JRunnable = interface(IJavaInstance)
['{BC131B27-7A72-4CAF-BB8E-170B8359B22E}']
{Methods}
procedure run; cdecl;
end;
TJRunnable = class(TJavaGenericImport<JRunnableClass, JRunnable>) end;
JCloseableClass = interface(IJavaClass)
['{CAFF3044-E3EC-444F-AF50-403A65BFA20B}']
end;
[JavaSignature('java/io/Closeable')]
JCloseable = interface(IJavaInstance)
['{DD3E86BD-46E1-44D8-84DD-B7607A3F9C56}']
{Methods}
procedure close; cdecl;
end;
TJCloseable = class(TJavaGenericImport<JCloseableClass, JCloseable>) end;
JWriterClass = interface(JObjectClass)
['{1B3FE1C9-6FF8-45AE-89D6-267E4CC1F003}']
end;
[JavaSignature('java/io/Writer')]
JWriter = interface(JObject)
['{50C5DAA8-B851-43A7-8FF9-E827DC14E67B}']
{Methods}
function append(c: Char): JWriter; cdecl; overload;
function append(csq: JCharSequence): JWriter; cdecl; overload;
function append(csq: JCharSequence; start: Integer; end_: Integer): JWriter; cdecl; overload;
procedure close; cdecl;
procedure flush; cdecl;
procedure write(buf: TJavaArray<Char>); cdecl; overload;
procedure write(buf: TJavaArray<Char>; offset: Integer; count: Integer); cdecl; overload;
procedure write(oneChar: Integer); cdecl; overload;
procedure write(str: JString); cdecl; overload;
procedure write(str: JString; offset: Integer; count: Integer); cdecl; overload;
end;
TJWriter = class(TJavaGenericImport<JWriterClass, JWriter>) end;
JIterableClass = interface(IJavaClass)
['{EEADA3A8-2116-491E-ACC7-21F84F84D65A}']
end;
[JavaSignature('java/lang/Iterable')]
JIterable = interface(IJavaInstance)
['{ABC85F3B-F161-4206-882A-FFD5F1DEFEA2}']
{Methods}
function iterator: JIterator; cdecl;
end;
TJIterable = class(TJavaGenericImport<JIterableClass, JIterable>) end;
JCollectionClass = interface(JIterableClass)
['{2737AA1B-2E7C-406D-AF35-8B012C7D5803}']
end;
[JavaSignature('java/util/Collection')]
JCollection = interface(JIterable)
['{9E58EE70-C0A7-4660-BF62-945FAE9F5EC3}']
{Methods}
function add(object_: JObject): Boolean; cdecl;
function addAll(collection: JCollection): Boolean; cdecl;
procedure clear; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
function containsAll(collection: JCollection): Boolean; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function hashCode: Integer; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function remove(object_: JObject): Boolean; cdecl;
function removeAll(collection: JCollection): Boolean; cdecl;
function retainAll(collection: JCollection): Boolean; cdecl;
function size: Integer; cdecl;
function toArray: TJavaObjectArray<JObject>; cdecl; overload;
function toArray(array_: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload;
end;
TJCollection = class(TJavaGenericImport<JCollectionClass, JCollection>) end;
JListClass = interface(JCollectionClass)
['{8EA06296-143F-4381-9369-A77209B622F0}']
end;
[JavaSignature('java/util/List')]
JList = interface(JCollection)
['{3F85C565-F3F4-42D8-87EE-F724F72113C7}']
{Methods}
procedure add(location: Integer; object_: JObject); cdecl; overload;
function add(object_: JObject): Boolean; cdecl; overload;
function addAll(location: Integer; collection: JCollection): Boolean; cdecl; overload;
function addAll(collection: JCollection): Boolean; cdecl; overload;
procedure clear; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
function containsAll(collection: JCollection): Boolean; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(location: Integer): JObject; cdecl;
function hashCode: Integer; cdecl;
function indexOf(object_: JObject): Integer; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function lastIndexOf(object_: JObject): Integer; cdecl;
function listIterator: JListIterator; cdecl; overload;
function listIterator(location: Integer): JListIterator; cdecl; overload;
function remove(location: Integer): JObject; cdecl; overload;
function remove(object_: JObject): Boolean; cdecl; overload;
function removeAll(collection: JCollection): Boolean; cdecl;
function retainAll(collection: JCollection): Boolean; cdecl;
function &set(location: Integer; object_: JObject): JObject; cdecl;
function size: Integer; cdecl;
function subList(start: Integer; end_: Integer): JList; cdecl;
function toArray: TJavaObjectArray<JObject>; cdecl; overload;
function toArray(array_: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload;
end;
TJList = class(TJavaGenericImport<JListClass, JList>) end;
JOutputStreamClass = interface(JObjectClass)
['{769D969C-3DFB-417B-8B7E-AA5662FB1539}']
{Methods}
function init: JOutputStream; cdecl;
end;
[JavaSignature('java/io/OutputStream')]
JOutputStream = interface(JObject)
['{308A10DA-ACF9-4EC3-B4BD-D9F9CEEB29A5}']
{Methods}
procedure close; cdecl;
procedure flush; cdecl;
procedure write(buffer: TJavaArray<Byte>); cdecl; overload;
procedure write(buffer: TJavaArray<Byte>; offset: Integer; count: Integer); cdecl; overload;
procedure write(oneByte: Integer); cdecl; overload;
end;
TJOutputStream = class(TJavaGenericImport<JOutputStreamClass, JOutputStream>) end;
Jlang_ClassClass = interface(JObjectClass)
['{E1A7F20A-FD87-4D67-9469-7492FD97D55D}']
{Methods}
function forName(className: JString): Jlang_Class; cdecl; overload;
function forName(className: JString; initializeBoolean: Boolean; classLoader: JClassLoader): Jlang_Class; cdecl; overload;
end;
[JavaSignature('java/lang/Class')]
Jlang_Class = interface(JObject)
['{B056EDE6-77D8-4CDD-9864-147C201FD87C}']
{Methods}
function asSubclass(clazz: Jlang_Class): Jlang_Class; cdecl;
function cast(obj: JObject): JObject; cdecl;
function desiredAssertionStatus: Boolean; cdecl;
function getAnnotation(annotationType: Jlang_Class): JAnnotation; cdecl;
function getAnnotations: TJavaObjectArray<JAnnotation>; cdecl;
function getCanonicalName: JString; cdecl;
function getClassLoader: JClassLoader; cdecl;
function getClasses: TJavaObjectArray<Jlang_Class>; cdecl;
function getComponentType: Jlang_Class; cdecl;
function getDeclaredAnnotations: TJavaObjectArray<JAnnotation>; cdecl;
function getDeclaredClasses: TJavaObjectArray<Jlang_Class>; cdecl;
function getDeclaringClass: Jlang_Class; cdecl;
function getEnclosingClass: Jlang_Class; cdecl;
function getEnumConstants: TJavaObjectArray<JObject>; cdecl;
function getInterfaces: TJavaObjectArray<Jlang_Class>; cdecl;
function getModifiers: Integer; cdecl;
function getName: JString; cdecl;
function getResourceAsStream(resName: JString): JInputStream; cdecl;
function getSigners: TJavaObjectArray<JObject>; cdecl;
function getSimpleName: JString; cdecl;
function getSuperclass: Jlang_Class; cdecl;
function isAnnotation: Boolean; cdecl;
function isAnnotationPresent(annotationType: Jlang_Class): Boolean; cdecl;
function isAnonymousClass: Boolean; cdecl;
function isArray: Boolean; cdecl;
function isAssignableFrom(cls: Jlang_Class): Boolean; cdecl;
function isEnum: Boolean; cdecl;
function isInstance(object_: JObject): Boolean; cdecl;
function isInterface: Boolean; cdecl;
function isLocalClass: Boolean; cdecl;
function isMemberClass: Boolean; cdecl;
function isPrimitive: Boolean; cdecl;
function isSynthetic: Boolean; cdecl;
function newInstance: JObject; cdecl;
function toString: JString; cdecl;
end;
TJlang_Class = class(TJavaGenericImport<Jlang_ClassClass, Jlang_Class>) end;
JThrowableClass = interface(JObjectClass)
['{9B871585-74E6-4B49-B4C2-4DB387B0E599}']
{Methods}
function init: JThrowable; cdecl; overload;
function init(detailMessage: JString): JThrowable; cdecl; overload;
function init(detailMessage: JString; throwable: JThrowable): JThrowable; cdecl; overload;
function init(throwable: JThrowable): JThrowable; cdecl; overload;
end;
[JavaSignature('java/lang/Throwable')]
JThrowable = interface(JObject)
['{44BECA0F-21B9-45A8-B21F-8806ABE80CE2}']
{Methods}
function fillInStackTrace: JThrowable; cdecl;
function getCause: JThrowable; cdecl;
function getLocalizedMessage: JString; cdecl;
function getMessage: JString; cdecl;
function getStackTrace: TJavaObjectArray<JStackTraceElement>; cdecl;
function initCause(throwable: JThrowable): JThrowable; cdecl;
procedure printStackTrace; cdecl; overload;
procedure printStackTrace(err: JPrintStream); cdecl; overload;
procedure printStackTrace(err: JPrintWriter); cdecl; overload;
procedure setStackTrace(trace: TJavaObjectArray<JStackTraceElement>); cdecl;
function toString: JString; cdecl;
end;
TJThrowable = class(TJavaGenericImport<JThrowableClass, JThrowable>) end;
JExceptionClass = interface(JThrowableClass)
['{6E1BA58E-A106-4CC0-A40C-99F4E1188B10}']
{Methods}
function init: JException; cdecl; overload;
function init(detailMessage: JString): JException; cdecl; overload;
function init(detailMessage: JString; throwable: JThrowable): JException; cdecl; overload;
function init(throwable: JThrowable): JException; cdecl; overload;
end;
[JavaSignature('java/lang/Exception')]
JException = interface(JThrowable)
['{6EA7D981-2F3C-44C4-B9D2-F581529C08E0}']
end;
TJException = class(TJavaGenericImport<JExceptionClass, JException>) end;
JJSONExceptionClass = interface(JExceptionClass)
['{D92F06D5-D459-4309-AE86-21A7EF971C64}']
{Methods}
function init(s: JString): JJSONException; cdecl;
end;
[JavaSignature('org/json/JSONException')]
JJSONException = interface(JException)
['{236AB196-CC66-40D5-91E5-C3D202A9293C}']
end;
TJJSONException = class(TJavaGenericImport<JJSONExceptionClass, JJSONException>) end;
JUUIDClass = interface(JObjectClass)
['{F254C874-67C8-4832-9619-9F686CB8E466}']
{Methods}
function init(mostSigBits: Int64; leastSigBits: Int64): JUUID; cdecl;
function fromString(uuid: JString): JUUID; cdecl;
function nameUUIDFromBytes(name: TJavaArray<Byte>): JUUID; cdecl;
function randomUUID: JUUID; cdecl;
end;
[JavaSignature('java/util/UUID')]
JUUID = interface(JObject)
['{B280C48F-E064-4030-BFD0-FB5970A78101}']
{Methods}
function clockSequence: Integer; cdecl;
function compareTo(uuid: JUUID): Integer; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function getLeastSignificantBits: Int64; cdecl;
function getMostSignificantBits: Int64; cdecl;
function hashCode: Integer; cdecl;
function node: Int64; cdecl;
function timestamp: Int64; cdecl;
function toString: JString; cdecl;
function variant: Integer; cdecl;
function version: Integer; cdecl;
end;
TJUUID = class(TJavaGenericImport<JUUIDClass, JUUID>) end;
JAbstractMapClass = interface(JObjectClass)
['{05119E45-9501-4270-B2BB-EE7E314695CB}']
end;
[JavaSignature('java/util/AbstractMap')]
JAbstractMap = interface(JObject)
['{63FD2094-7BFB-41B4-AED8-F781B97F6EB6}']
{Methods}
procedure clear; cdecl;
function containsKey(key: JObject): Boolean; cdecl;
function containsValue(value: JObject): Boolean; cdecl;
function entrySet: JSet; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(key: JObject): JObject; cdecl;
function hashCode: Integer; cdecl;
function isEmpty: Boolean; cdecl;
function keySet: JSet; cdecl;
function put(key: JObject; value: JObject): JObject; cdecl;
procedure putAll(map: JMap); cdecl;
function remove(key: JObject): JObject; cdecl;
function size: Integer; cdecl;
function toString: JString; cdecl;
function values: JCollection; cdecl;
end;
TJAbstractMap = class(TJavaGenericImport<JAbstractMapClass, JAbstractMap>) end;
JHashMapClass = interface(JAbstractMapClass)
['{AC953BC1-405B-4CDD-93D2-FBA77D171B56}']
{Methods}
function init: JHashMap; cdecl; overload;
function init(capacity: Integer): JHashMap; cdecl; overload;
function init(capacity: Integer; loadFactor: Single): JHashMap; cdecl; overload;
function init(map: JMap): JHashMap; cdecl; overload;
end;
[JavaSignature('java/util/HashMap')]
JHashMap = interface(JAbstractMap)
['{FD560211-A7FE-4AB5-B510-BB43A31AA75D}']
{Methods}
procedure clear; cdecl;
function clone: JObject; cdecl;
function containsKey(key: JObject): Boolean; cdecl;
function containsValue(value: JObject): Boolean; cdecl;
function entrySet: JSet; cdecl;
function &get(key: JObject): JObject; cdecl;
function isEmpty: Boolean; cdecl;
function keySet: JSet; cdecl;
function put(key: JObject; value: JObject): JObject; cdecl;
procedure putAll(map: JMap); cdecl;
function remove(key: JObject): JObject; cdecl;
function size: Integer; cdecl;
function values: JCollection; cdecl;
end;
TJHashMap = class(TJavaGenericImport<JHashMapClass, JHashMap>) end;
JRandomClass = interface(JObjectClass)
['{C50FE36A-6283-4523-BF77-15BB7A7B0F92}']
{Methods}
function init: JRandom; cdecl; overload;
function init(seed: Int64): JRandom; cdecl; overload;
end;
[JavaSignature('java/util/Random')]
JRandom = interface(JObject)
['{F1C05381-73F2-4991-853B-B22575DB43D2}']
{Methods}
function nextBoolean: Boolean; cdecl;
procedure nextBytes(buf: TJavaArray<Byte>); cdecl;
function nextDouble: Double; cdecl;
function nextFloat: Single; cdecl;
function nextGaussian: Double; cdecl;
function nextInt: Integer; cdecl; overload;
function nextInt(n: Integer): Integer; cdecl; overload;
function nextLong: Int64; cdecl;
procedure setSeed(seed: Int64); cdecl;
end;
TJRandom = class(TJavaGenericImport<JRandomClass, JRandom>) end;
JAnnotationClass = interface(IJavaClass)
['{E8A654D9-AA21-468D-AEF1-9261C6E3F760}']
end;
[JavaSignature('java/lang/annotation/Annotation')]
JAnnotation = interface(IJavaInstance)
['{508C3063-7E6D-4963-B22F-27538F9D20CE}']
{Methods}
function annotationType: Jlang_Class; cdecl;
function equals(obj: JObject): Boolean; cdecl;
function hashCode: Integer; cdecl;
function toString: JString; cdecl;
end;
TJAnnotation = class(TJavaGenericImport<JAnnotationClass, JAnnotation>) end;
JThreadClass = interface(JObjectClass)
['{AC2B33CB-D349-4506-8809-B9762209222B}']
{Property Methods}
function _GetMAX_PRIORITY: Integer;
function _GetMIN_PRIORITY: Integer;
function _GetNORM_PRIORITY: Integer;
{Methods}
function init: JThread; cdecl; overload;
function init(runnable: JRunnable): JThread; cdecl; overload;
function init(runnable: JRunnable; threadName: JString): JThread; cdecl; overload;
function init(threadName: JString): JThread; cdecl; overload;
function init(group: JThreadGroup; runnable: JRunnable): JThread; cdecl; overload;
function init(group: JThreadGroup; runnable: JRunnable; threadName: JString): JThread; cdecl; overload;
function init(group: JThreadGroup; threadName: JString): JThread; cdecl; overload;
function init(group: JThreadGroup; runnable: JRunnable; threadName: JString; stackSize: Int64): JThread; cdecl; overload;
function activeCount: Integer; cdecl;
function currentThread: JThread; cdecl;
procedure dumpStack; cdecl;
function enumerate(threads: TJavaObjectArray<JThread>): Integer; cdecl;
function getAllStackTraces: TJavaObjectArray<JMap>; cdecl;
function getDefaultUncaughtExceptionHandler: JThread_UncaughtExceptionHandler; cdecl;
function holdsLock(object_: JObject): Boolean; cdecl;
function interrupted: Boolean; cdecl;
procedure setDefaultUncaughtExceptionHandler(handler: JThread_UncaughtExceptionHandler); cdecl;
procedure sleep(time: Int64); cdecl; overload;
procedure sleep(millis: Int64; nanos: Integer); cdecl; overload;
procedure yield; cdecl;
{Properties}
property MAX_PRIORITY: Integer read _GetMAX_PRIORITY;
property MIN_PRIORITY: Integer read _GetMIN_PRIORITY;
property NORM_PRIORITY: Integer read _GetNORM_PRIORITY;
end;
[JavaSignature('java/lang/Thread')]
JThread = interface(JObject)
['{8E288CBE-F5A4-4D6E-98B7-D0B5075A0FCA}']
{Methods}
procedure checkAccess; cdecl;
function countStackFrames: Integer; cdecl;//Deprecated
procedure destroy; cdecl;//Deprecated
function getContextClassLoader: JClassLoader; cdecl;
function getId: Int64; cdecl;
function getName: JString; cdecl;
function getPriority: Integer; cdecl;
function getStackTrace: TJavaObjectArray<JStackTraceElement>; cdecl;
function getState: JThread_State; cdecl;
function getThreadGroup: JThreadGroup; cdecl;
function getUncaughtExceptionHandler: JThread_UncaughtExceptionHandler; cdecl;
procedure interrupt; cdecl;
function isAlive: Boolean; cdecl;
function isDaemon: Boolean; cdecl;
function isInterrupted: Boolean; cdecl;
procedure join; cdecl; overload;
procedure join(millis: Int64); cdecl; overload;
procedure join(millis: Int64; nanos: Integer); cdecl; overload;
procedure resume; cdecl;//Deprecated
procedure run; cdecl;
procedure setContextClassLoader(cl: JClassLoader); cdecl;
procedure setDaemon(isDaemon: Boolean); cdecl;
procedure setName(threadName: JString); cdecl;
procedure setPriority(priority: Integer); cdecl;
procedure setUncaughtExceptionHandler(handler: JThread_UncaughtExceptionHandler); cdecl;
procedure start; cdecl;
procedure stop; cdecl; overload;//Deprecated
procedure stop(throwable: JThrowable); cdecl; overload;//Deprecated
procedure suspend; cdecl;//Deprecated
function toString: JString; cdecl;
end;
TJThread = class(TJavaGenericImport<JThreadClass, JThread>) end;
JDateClass = interface(JObjectClass)
['{37EABF6D-C7EE-4AB5-BE8B-5E439112E116}']
{Methods}
function init: JDate; cdecl; overload;
function init(year: Integer; month: Integer; day: Integer): JDate; cdecl; overload;//Deprecated
function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer): JDate; cdecl; overload;//Deprecated
function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer; second: Integer): JDate; cdecl; overload;//Deprecated
function init(milliseconds: Int64): JDate; cdecl; overload;
function init(string_: JString): JDate; cdecl; overload;//Deprecated
function UTC(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer; second: Integer): Int64; cdecl;//Deprecated
function parse(string_: JString): Int64; cdecl;//Deprecated
end;
[JavaSignature('java/util/Date')]
JDate = interface(JObject)
['{282E2836-B390-44E4-A14F-EF481460BDF7}']
{Methods}
function after(date: JDate): Boolean; cdecl;
function before(date: JDate): Boolean; cdecl;
function clone: JObject; cdecl;
function compareTo(date: JDate): Integer; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function getDate: Integer; cdecl;//Deprecated
function getDay: Integer; cdecl;//Deprecated
function getHours: Integer; cdecl;//Deprecated
function getMinutes: Integer; cdecl;//Deprecated
function getMonth: Integer; cdecl;//Deprecated
function getSeconds: Integer; cdecl;//Deprecated
function getTime: Int64; cdecl;
function getTimezoneOffset: Integer; cdecl;//Deprecated
function getYear: Integer; cdecl;//Deprecated
function hashCode: Integer; cdecl;
procedure setDate(day: Integer); cdecl;//Deprecated
procedure setHours(hour: Integer); cdecl;//Deprecated
procedure setMinutes(minute: Integer); cdecl;//Deprecated
procedure setMonth(month: Integer); cdecl;//Deprecated
procedure setSeconds(second: Integer); cdecl;//Deprecated
procedure setTime(milliseconds: Int64); cdecl;
procedure setYear(year: Integer); cdecl;//Deprecated
function toGMTString: JString; cdecl;//Deprecated
function toLocaleString: JString; cdecl;//Deprecated
function toString: JString; cdecl;
end;
TJDate = class(TJavaGenericImport<JDateClass, JDate>) end;
JFilterOutputStreamClass = interface(JOutputStreamClass)
['{4273682E-2DA8-4BA9-BFC7-A9356DC43D40}']
{Methods}
function init(out_: JOutputStream): JFilterOutputStream; cdecl;
end;
[JavaSignature('java/io/FilterOutputStream')]
JFilterOutputStream = interface(JOutputStream)
['{B0DB7F97-9758-43B1-8FC4-19A12503CD3F}']
{Methods}
procedure close; cdecl;
procedure flush; cdecl;
procedure write(buffer: TJavaArray<Byte>; offset: Integer; length: Integer); cdecl; overload;
procedure write(oneByte: Integer); cdecl; overload;
end;
TJFilterOutputStream = class(TJavaGenericImport<JFilterOutputStreamClass, JFilterOutputStream>) end;
JPrintStreamClass = interface(JFilterOutputStreamClass)
['{4B5683E3-32D0-4225-9A80-FB961D9B334F}']
{Methods}
function init(out_: JOutputStream): JPrintStream; cdecl; overload;
function init(out_: JOutputStream; autoFlush: Boolean): JPrintStream; cdecl; overload;
function init(out_: JOutputStream; autoFlush: Boolean; enc: JString): JPrintStream; cdecl; overload;
function init(file_: JFile): JPrintStream; cdecl; overload;
function init(file_: JFile; csn: JString): JPrintStream; cdecl; overload;
function init(fileName: JString): JPrintStream; cdecl; overload;
function init(fileName: JString; csn: JString): JPrintStream; cdecl; overload;
end;
[JavaSignature('java/io/PrintStream')]
JPrintStream = interface(JFilterOutputStream)
['{8B23171F-06EF-4D87-A463-863F687A7918}']
{Methods}
function append(c: Char): JPrintStream; cdecl; overload;
function append(charSequence: JCharSequence): JPrintStream; cdecl; overload;
function append(charSequence: JCharSequence; start: Integer; end_: Integer): JPrintStream; cdecl; overload;
function checkError: Boolean; cdecl;
procedure close; cdecl;
procedure flush; cdecl;
procedure print(chars: TJavaArray<Char>); cdecl; overload;
procedure print(c: Char); cdecl; overload;
procedure print(d: Double); cdecl; overload;
procedure print(f: Single); cdecl; overload;
procedure print(i: Integer); cdecl; overload;
procedure print(l: Int64); cdecl; overload;
procedure print(o: JObject); cdecl; overload;
procedure print(str: JString); cdecl; overload;
procedure print(b: Boolean); cdecl; overload;
procedure println; cdecl; overload;
procedure println(chars: TJavaArray<Char>); cdecl; overload;
procedure println(c: Char); cdecl; overload;
procedure println(d: Double); cdecl; overload;
procedure println(f: Single); cdecl; overload;
procedure println(i: Integer); cdecl; overload;
procedure println(l: Int64); cdecl; overload;
procedure println(o: JObject); cdecl; overload;
procedure println(str: JString); cdecl; overload;
procedure println(b: Boolean); cdecl; overload;
procedure write(buffer: TJavaArray<Byte>; offset: Integer; length: Integer); cdecl; overload;
procedure write(oneByte: Integer); cdecl; overload;
end;
TJPrintStream = class(TJavaGenericImport<JPrintStreamClass, JPrintStream>) end;
JRuntimeExceptionClass = interface(JExceptionClass)
['{58C58616-58EF-4783-92DB-5AE4F2A079A7}']
{Methods}
function init: JRuntimeException; cdecl; overload;
function init(detailMessage: JString): JRuntimeException; cdecl; overload;
function init(detailMessage: JString; throwable: JThrowable): JRuntimeException; cdecl; overload;
function init(throwable: JThrowable): JRuntimeException; cdecl; overload;
end;
[JavaSignature('java/lang/RuntimeException')]
JRuntimeException = interface(JException)
['{7CEA4E55-B247-4073-A601-7C2C6D8BEE22}']
end;
TJRuntimeException = class(TJavaGenericImport<JRuntimeExceptionClass, JRuntimeException>) end;
JObserverClass = interface(IJavaClass)
['{8582EA20-ECD9-4C10-95BD-2C89B4D5BA6E}']
end;
[JavaSignature('java/util/Observer')]
JObserver = interface(IJavaInstance)
['{452A1BDA-4B4E-406E-B455-BC56F012C1B7}']
{Methods}
procedure update(observable: Jutil_Observable; data: JObject); cdecl;
end;
TJObserver = class(TJavaGenericImport<JObserverClass, JObserver>) end;
JFloatClass = interface(JNumberClass)
['{E2E64017-238D-4910-8DF8-BD66A034BDFE}']
{Property Methods}
function _GetMAX_EXPONENT: Integer;
function _GetMAX_VALUE: Single;
function _GetMIN_EXPONENT: Integer;
function _GetMIN_NORMAL: Single;
function _GetMIN_VALUE: Single;
function _GetNEGATIVE_INFINITY: Single;
function _GetNaN: Single;
function _GetPOSITIVE_INFINITY: Single;
function _GetSIZE: Integer;
function _GetTYPE: Jlang_Class;
{Methods}
function init(value: Single): JFloat; cdecl; overload;
function init(value: Double): JFloat; cdecl; overload;
function init(string_: JString): JFloat; cdecl; overload;
function compare(float1: Single; float2: Single): Integer; cdecl;
function floatToIntBits(value: Single): Integer; cdecl;
function floatToRawIntBits(value: Single): Integer; cdecl;
function intBitsToFloat(bits: Integer): Single; cdecl;
function isInfinite(f: Single): Boolean; cdecl; overload;
function isNaN(f: Single): Boolean; cdecl; overload;
function parseFloat(string_: JString): Single; cdecl;
function toHexString(f: Single): JString; cdecl;
function toString(f: Single): JString; cdecl; overload;
function valueOf(string_: JString): JFloat; cdecl; overload;
function valueOf(f: Single): JFloat; cdecl; overload;
{Properties}
property MAX_EXPONENT: Integer read _GetMAX_EXPONENT;
property MAX_VALUE: Single read _GetMAX_VALUE;
property MIN_EXPONENT: Integer read _GetMIN_EXPONENT;
property MIN_NORMAL: Single read _GetMIN_NORMAL;
property MIN_VALUE: Single read _GetMIN_VALUE;
property NEGATIVE_INFINITY: Single read _GetNEGATIVE_INFINITY;
property NaN: Single read _GetNaN;
property POSITIVE_INFINITY: Single read _GetPOSITIVE_INFINITY;
property SIZE: Integer read _GetSIZE;
property &TYPE: Jlang_Class read _GetTYPE;
end;
[JavaSignature('java/lang/Float')]
JFloat = interface(JNumber)
['{F13BF843-909A-4866-918B-B1B2B1A8F483}']
{Methods}
function byteValue: Byte; cdecl;
function compareTo(object_: JFloat): Integer; cdecl;
function doubleValue: Double; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function floatValue: Single; cdecl;
function hashCode: Integer; cdecl;
function intValue: Integer; cdecl;
function isInfinite: Boolean; cdecl; overload;
function isNaN: Boolean; cdecl; overload;
function longValue: Int64; cdecl;
function shortValue: SmallInt; cdecl;
function toString: JString; cdecl; overload;
end;
TJFloat = class(TJavaGenericImport<JFloatClass, JFloat>) end;
JDoubleClass = interface(JNumberClass)
['{1B133955-7ECE-4429-97CD-9118396AC3AE}']
{Property Methods}
function _GetMAX_EXPONENT: Integer;
function _GetMAX_VALUE: Double;
function _GetMIN_EXPONENT: Integer;
function _GetMIN_NORMAL: Double;
function _GetMIN_VALUE: Double;
function _GetNEGATIVE_INFINITY: Double;
function _GetNaN: Double;
function _GetPOSITIVE_INFINITY: Double;
function _GetSIZE: Integer;
function _GetTYPE: Jlang_Class;
{Methods}
function init(value: Double): JDouble; cdecl; overload;
function init(string_: JString): JDouble; cdecl; overload;
function compare(double1: Double; double2: Double): Integer; cdecl;
function doubleToLongBits(value: Double): Int64; cdecl;
function doubleToRawLongBits(value: Double): Int64; cdecl;
function isInfinite(d: Double): Boolean; cdecl; overload;
function isNaN(d: Double): Boolean; cdecl; overload;
function longBitsToDouble(bits: Int64): Double; cdecl;
function parseDouble(string_: JString): Double; cdecl;
function toHexString(d: Double): JString; cdecl;
function toString(d: Double): JString; cdecl; overload;
function valueOf(string_: JString): JDouble; cdecl; overload;
function valueOf(d: Double): JDouble; cdecl; overload;
{Properties}
property MAX_EXPONENT: Integer read _GetMAX_EXPONENT;
property MAX_VALUE: Double read _GetMAX_VALUE;
property MIN_EXPONENT: Integer read _GetMIN_EXPONENT;
property MIN_NORMAL: Double read _GetMIN_NORMAL;
property MIN_VALUE: Double read _GetMIN_VALUE;
property NEGATIVE_INFINITY: Double read _GetNEGATIVE_INFINITY;
property NaN: Double read _GetNaN;
property POSITIVE_INFINITY: Double read _GetPOSITIVE_INFINITY;
property SIZE: Integer read _GetSIZE;
property &TYPE: Jlang_Class read _GetTYPE;
end;
[JavaSignature('java/lang/Double')]
JDouble = interface(JNumber)
['{81639AF9-E21C-4CB0-99E6-1E7F013E11CC}']
{Methods}
function byteValue: Byte; cdecl;
function compareTo(object_: JDouble): Integer; cdecl;
function doubleValue: Double; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function floatValue: Single; cdecl;
function hashCode: Integer; cdecl;
function intValue: Integer; cdecl;
function isInfinite: Boolean; cdecl; overload;
function isNaN: Boolean; cdecl; overload;
function longValue: Int64; cdecl;
function shortValue: SmallInt; cdecl;
function toString: JString; cdecl; overload;
end;
TJDouble = class(TJavaGenericImport<JDoubleClass, JDouble>) end;
JPrintWriterClass = interface(JWriterClass)
['{0176F2C9-CDCB-40D9-B26E-E983BE269B0D}']
{Methods}
function init(out_: JOutputStream): JPrintWriter; cdecl; overload;
function init(out_: JOutputStream; autoFlush: Boolean): JPrintWriter; cdecl; overload;
function init(wr: JWriter): JPrintWriter; cdecl; overload;
function init(wr: JWriter; autoFlush: Boolean): JPrintWriter; cdecl; overload;
function init(file_: JFile): JPrintWriter; cdecl; overload;
function init(file_: JFile; csn: JString): JPrintWriter; cdecl; overload;
function init(fileName: JString): JPrintWriter; cdecl; overload;
function init(fileName: JString; csn: JString): JPrintWriter; cdecl; overload;
end;
[JavaSignature('java/io/PrintWriter')]
JPrintWriter = interface(JWriter)
['{1C7483CD-045F-4478-A223-A9FBBF9C1D80}']
{Methods}
function append(c: Char): JPrintWriter; cdecl; overload;
function append(csq: JCharSequence): JPrintWriter; cdecl; overload;
function append(csq: JCharSequence; start: Integer; end_: Integer): JPrintWriter; cdecl; overload;
function checkError: Boolean; cdecl;
procedure close; cdecl;
procedure flush; cdecl;
procedure print(charArray: TJavaArray<Char>); cdecl; overload;
procedure print(ch: Char); cdecl; overload;
procedure print(dnum: Double); cdecl; overload;
procedure print(fnum: Single); cdecl; overload;
procedure print(inum: Integer); cdecl; overload;
procedure print(lnum: Int64); cdecl; overload;
procedure print(obj: JObject); cdecl; overload;
procedure print(str: JString); cdecl; overload;
procedure print(bool: Boolean); cdecl; overload;
procedure println; cdecl; overload;
procedure println(chars: TJavaArray<Char>); cdecl; overload;
procedure println(c: Char); cdecl; overload;
procedure println(d: Double); cdecl; overload;
procedure println(f: Single); cdecl; overload;
procedure println(i: Integer); cdecl; overload;
procedure println(l: Int64); cdecl; overload;
procedure println(obj: JObject); cdecl; overload;
procedure println(str: JString); cdecl; overload;
procedure println(b: Boolean); cdecl; overload;
procedure write(buf: TJavaArray<Char>); cdecl; overload;
procedure write(buf: TJavaArray<Char>; offset: Integer; count: Integer); cdecl; overload;
procedure write(oneChar: Integer); cdecl; overload;
procedure write(str: JString); cdecl; overload;
procedure write(str: JString; offset: Integer; count: Integer); cdecl; overload;
end;
TJPrintWriter = class(TJavaGenericImport<JPrintWriterClass, JPrintWriter>) end;
JIteratorClass = interface(IJavaClass)
['{2E525F5D-C766-4F79-B800-BA5FFA909E90}']
end;
[JavaSignature('java/util/Iterator')]
JIterator = interface(IJavaInstance)
['{435EBC1F-CFE0-437C-B49B-45B5257B6953}']
{Methods}
function hasNext: Boolean; cdecl;
function next: JObject; cdecl;
procedure remove; cdecl;
end;
TJIterator = class(TJavaGenericImport<JIteratorClass, JIterator>) end;
JListIteratorClass = interface(JIteratorClass)
['{7541F5DD-8E71-44AE-ACD9-142ED2D42810}']
end;
[JavaSignature('java/util/ListIterator')]
JListIterator = interface(JIterator)
['{B66BDA33-5CDD-43B1-B320-7353AE09C418}']
{Methods}
procedure add(object_: JObject); cdecl;
function hasNext: Boolean; cdecl;
function hasPrevious: Boolean; cdecl;
function next: JObject; cdecl;
function nextIndex: Integer; cdecl;
function previous: JObject; cdecl;
function previousIndex: Integer; cdecl;
procedure remove; cdecl;
procedure &set(object_: JObject); cdecl;
end;
TJListIterator = class(TJavaGenericImport<JListIteratorClass, JListIterator>) end;
JByteArrayOutputStreamClass = interface(JOutputStreamClass)
['{2F08E462-5F49-4A89-9ACD-F0A5CD01C3A8}']
{Methods}
function init: JByteArrayOutputStream; cdecl; overload;
function init(size: Integer): JByteArrayOutputStream; cdecl; overload;
end;
[JavaSignature('java/io/ByteArrayOutputStream')]
JByteArrayOutputStream = interface(JOutputStream)
['{6AD653C4-3A67-4CCD-9B53-2E57D0DC0727}']
{Methods}
procedure close; cdecl;
procedure reset; cdecl;
function size: Integer; cdecl;
function toByteArray: TJavaArray<Byte>; cdecl;
function toString: JString; cdecl; overload;
function toString(hibyte: Integer): JString; cdecl; overload;//Deprecated
function toString(enc: JString): JString; cdecl; overload;
procedure write(buffer: TJavaArray<Byte>; offset: Integer; len: Integer); cdecl; overload;
procedure write(oneByte: Integer); cdecl; overload;
procedure writeTo(out_: JOutputStream); cdecl;
end;
TJByteArrayOutputStream = class(TJavaGenericImport<JByteArrayOutputStreamClass, JByteArrayOutputStream>) end;
JStackTraceElementClass = interface(JObjectClass)
['{21CBE31F-4A81-4CB3-ADB1-EA9B3166692E}']
{Methods}
function init(cls: JString; method: JString; file_: JString; line: Integer): JStackTraceElement; cdecl;
end;
[JavaSignature('java/lang/StackTraceElement')]
JStackTraceElement = interface(JObject)
['{3304B89A-29EB-4B53-943F-E70F4252E8FF}']
{Methods}
function equals(obj: JObject): Boolean; cdecl;
function getClassName: JString; cdecl;
function getFileName: JString; cdecl;
function getLineNumber: Integer; cdecl;
function getMethodName: JString; cdecl;
function hashCode: Integer; cdecl;
function isNativeMethod: Boolean; cdecl;
function toString: JString; cdecl;
end;
TJStackTraceElement = class(TJavaGenericImport<JStackTraceElementClass, JStackTraceElement>) end;
JFileOutputStreamClass = interface(JOutputStreamClass)
['{4808736C-4C9B-46DF-A1B6-EB94324D9666}']
{Methods}
function init(file_: JFile): JFileOutputStream; cdecl; overload;
function init(file_: JFile; append: Boolean): JFileOutputStream; cdecl; overload;
function init(fd: JFileDescriptor): JFileOutputStream; cdecl; overload;
function init(path: JString): JFileOutputStream; cdecl; overload;
function init(path: JString; append: Boolean): JFileOutputStream; cdecl; overload;
end;
[JavaSignature('java/io/FileOutputStream')]
JFileOutputStream = interface(JOutputStream)
['{3D49DAFB-A222-4001-9DBE-7FAE66E23404}']
{Methods}
procedure close; cdecl;
function getFD: JFileDescriptor; cdecl;
procedure write(buffer: TJavaArray<Byte>; byteOffset: Integer; byteCount: Integer); cdecl; overload;
procedure write(oneByte: Integer); cdecl; overload;
end;
TJFileOutputStream = class(TJavaGenericImport<JFileOutputStreamClass, JFileOutputStream>) end;
JAbstractStringBuilderClass = interface(JObjectClass)
['{A3321EF2-EA76-44CD-90CE-DFDADB9936BD}']
end;
[JavaSignature('java/lang/AbstractStringBuilder')]
JAbstractStringBuilder = interface(JObject)
['{39A0E6C5-8F79-44ED-BECB-02252CA2F5C0}']
{Methods}
function capacity: Integer; cdecl;
function charAt(index: Integer): Char; cdecl;
function codePointAt(index: Integer): Integer; cdecl;
function codePointBefore(index: Integer): Integer; cdecl;
function codePointCount(start: Integer; end_: Integer): Integer; cdecl;
procedure ensureCapacity(min: Integer); cdecl;
procedure getChars(start: Integer; end_: Integer; dst: TJavaArray<Char>; dstStart: Integer); cdecl;
function indexOf(string_: JString): Integer; cdecl; overload;
function indexOf(subString: JString; start: Integer): Integer; cdecl; overload;
function lastIndexOf(string_: JString): Integer; cdecl; overload;
function lastIndexOf(subString: JString; start: Integer): Integer; cdecl; overload;
function length: Integer; cdecl;
function offsetByCodePoints(index: Integer; codePointOffset: Integer): Integer; cdecl;
procedure setCharAt(index: Integer; ch: Char); cdecl;
procedure setLength(length: Integer); cdecl;
function subSequence(start: Integer; end_: Integer): JCharSequence; cdecl;
function substring(start: Integer): JString; cdecl; overload;
function substring(start: Integer; end_: Integer): JString; cdecl; overload;
function toString: JString; cdecl;
procedure trimToSize; cdecl;
end;
TJAbstractStringBuilder = class(TJavaGenericImport<JAbstractStringBuilderClass, JAbstractStringBuilder>) end;
JStringBuilderClass = interface(JAbstractStringBuilderClass)
['{D9FACB66-EE60-4BCB-B5B2-248751CCF1B4}']
{Methods}
function init: JStringBuilder; cdecl; overload;
function init(capacity: Integer): JStringBuilder; cdecl; overload;
function init(seq: JCharSequence): JStringBuilder; cdecl; overload;
function init(str: JString): JStringBuilder; cdecl; overload;
end;
[JavaSignature('java/lang/StringBuilder')]
JStringBuilder = interface(JAbstractStringBuilder)
['{F8A75A66-EA10-4337-9ECC-B0CA4FF4D9C5}']
{Methods}
function append(b: Boolean): JStringBuilder; cdecl; overload;
function append(c: Char): JStringBuilder; cdecl; overload;
function append(i: Integer): JStringBuilder; cdecl; overload;
function append(l: Int64): JStringBuilder; cdecl; overload;
function append(f: Single): JStringBuilder; cdecl; overload;
function append(d: Double): JStringBuilder; cdecl; overload;
function append(obj: JObject): JStringBuilder; cdecl; overload;
function append(str: JString): JStringBuilder; cdecl; overload;
function append(sb: JStringBuffer): JStringBuilder; cdecl; overload;
function append(chars: TJavaArray<Char>): JStringBuilder; cdecl; overload;
function append(str: TJavaArray<Char>; offset: Integer; len: Integer): JStringBuilder; cdecl; overload;
function append(csq: JCharSequence): JStringBuilder; cdecl; overload;
function append(csq: JCharSequence; start: Integer; end_: Integer): JStringBuilder; cdecl; overload;
function appendCodePoint(codePoint: Integer): JStringBuilder; cdecl;
function delete(start: Integer; end_: Integer): JStringBuilder; cdecl;
function deleteCharAt(index: Integer): JStringBuilder; cdecl;
function insert(offset: Integer; b: Boolean): JStringBuilder; cdecl; overload;
function insert(offset: Integer; c: Char): JStringBuilder; cdecl; overload;
function insert(offset: Integer; i: Integer): JStringBuilder; cdecl; overload;
function insert(offset: Integer; l: Int64): JStringBuilder; cdecl; overload;
function insert(offset: Integer; f: Single): JStringBuilder; cdecl; overload;
function insert(offset: Integer; d: Double): JStringBuilder; cdecl; overload;
function insert(offset: Integer; obj: JObject): JStringBuilder; cdecl; overload;
function insert(offset: Integer; str: JString): JStringBuilder; cdecl; overload;
function insert(offset: Integer; ch: TJavaArray<Char>): JStringBuilder; cdecl; overload;
function insert(offset: Integer; str: TJavaArray<Char>; strOffset: Integer; strLen: Integer): JStringBuilder; cdecl; overload;
function insert(offset: Integer; s: JCharSequence): JStringBuilder; cdecl; overload;
function insert(offset: Integer; s: JCharSequence; start: Integer; end_: Integer): JStringBuilder; cdecl; overload;
function replace(start: Integer; end_: Integer; str: JString): JStringBuilder; cdecl;
function reverse: JStringBuilder; cdecl;
function toString: JString; cdecl;
end;
TJStringBuilder = class(TJavaGenericImport<JStringBuilderClass, JStringBuilder>) end;
JCharSequenceClass = interface(IJavaClass)
['{85DCA69A-F296-4BB4-8FE2-5ECE0EBE6611}']
end;
[JavaSignature('java/lang/CharSequence')]
JCharSequence = interface(IJavaInstance)
['{D026566C-D7C6-43E7-AECA-030E2C23A8B8}']
{Methods}
function charAt(index: Integer): Char; cdecl;
function length: Integer; cdecl;
function subSequence(start: Integer; end_: Integer): JCharSequence; cdecl;
function toString: JString; cdecl;
end;
TJCharSequence = class(TJavaGenericImport<JCharSequenceClass, JCharSequence>) end;
JGregorianCalendarClass = interface(JCalendarClass)
['{69F4EF00-93DA-4249-8A30-3A3E4A71DA03}']
{Property Methods}
function _GetAD: Integer;
function _GetBC: Integer;
{Methods}
function init: JGregorianCalendar; cdecl; overload;
function init(year: Integer; month: Integer; day: Integer): JGregorianCalendar; cdecl; overload;
function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer): JGregorianCalendar; cdecl; overload;
function init(year: Integer; month: Integer; day: Integer; hour: Integer; minute: Integer; second: Integer): JGregorianCalendar; cdecl; overload;
function init(locale: JLocale): JGregorianCalendar; cdecl; overload;
function init(timezone: JTimeZone): JGregorianCalendar; cdecl; overload;
function init(timezone: JTimeZone; locale: JLocale): JGregorianCalendar; cdecl; overload;
{Properties}
property AD: Integer read _GetAD;
property BC: Integer read _GetBC;
end;
[JavaSignature('java/util/GregorianCalendar')]
JGregorianCalendar = interface(JCalendar)
['{CB851885-16EA-49E7-8AAF-DBFE900DA328}']
{Methods}
procedure add(field: Integer; value: Integer); cdecl;
function clone: JObject; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function getActualMaximum(field: Integer): Integer; cdecl;
function getActualMinimum(field: Integer): Integer; cdecl;
function getGreatestMinimum(field: Integer): Integer; cdecl;
function getGregorianChange: JDate; cdecl;
function getLeastMaximum(field: Integer): Integer; cdecl;
function getMaximum(field: Integer): Integer; cdecl;
function getMinimum(field: Integer): Integer; cdecl;
function hashCode: Integer; cdecl;
function isLeapYear(year: Integer): Boolean; cdecl;
procedure roll(field: Integer; value: Integer); cdecl; overload;
procedure roll(field: Integer; increment: Boolean); cdecl; overload;
procedure setFirstDayOfWeek(value: Integer); cdecl;
procedure setGregorianChange(date: JDate); cdecl;
procedure setMinimalDaysInFirstWeek(value: Integer); cdecl;
end;
TJGregorianCalendar = class(TJavaGenericImport<JGregorianCalendarClass, JGregorianCalendar>) end;
JJSONTokenerClass = interface(JObjectClass)
['{CFDB19D3-6222-4DBF-9012-1EF6EA1D518D}']
{Methods}
function init(in_: JString): JJSONTokener; cdecl;
function dehexchar(hex: Char): Integer; cdecl;
end;
[JavaSignature('org/json/JSONTokener')]
JJSONTokener = interface(JObject)
['{A7330D36-4304-4864-BACD-547E8AF8AAAD}']
{Methods}
procedure back; cdecl;
function more: Boolean; cdecl;
function next: Char; cdecl; overload;
function next(c: Char): Char; cdecl; overload;
function next(length: Integer): JString; cdecl; overload;
function nextClean: Char; cdecl;
function nextString(quote: Char): JString; cdecl;
function nextTo(excluded: JString): JString; cdecl; overload;
function nextTo(excluded: Char): JString; cdecl; overload;
function nextValue: JObject; cdecl;
procedure skipPast(thru: JString); cdecl;
function skipTo(to_: Char): Char; cdecl;
function syntaxError(message: JString): JJSONException; cdecl;
function toString: JString; cdecl;
end;
TJJSONTokener = class(TJavaGenericImport<JJSONTokenerClass, JJSONTokener>) end;
JMapClass = interface(IJavaClass)
['{2A7CE403-063B-45CA-9F4D-EA1E64304F1C}']
end;
[JavaSignature('java/util/Map')]
JMap = interface(IJavaInstance)
['{BE6A5DBF-B121-4BF2-BC18-EB64729C7811}']
{Methods}
procedure clear; cdecl;
function containsKey(key: JObject): Boolean; cdecl;
function containsValue(value: JObject): Boolean; cdecl;
function entrySet: JSet; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function &get(key: JObject): JObject; cdecl;
function hashCode: Integer; cdecl;
function isEmpty: Boolean; cdecl;
function keySet: JSet; cdecl;
function put(key: JObject; value: JObject): JObject; cdecl;
procedure putAll(map: JMap); cdecl;
function remove(key: JObject): JObject; cdecl;
function size: Integer; cdecl;
function values: JCollection; cdecl;
end;
TJMap = class(TJavaGenericImport<JMapClass, JMap>) end;
JLocaleClass = interface(JObjectClass)
['{0A5D70AA-C01B-437F-97C8-FEE25C595AE7}']
{Property Methods}
function _GetCANADA: JLocale;
function _GetCANADA_FRENCH: JLocale;
function _GetCHINA: JLocale;
function _GetCHINESE: JLocale;
function _GetENGLISH: JLocale;
function _GetFRANCE: JLocale;
function _GetFRENCH: JLocale;
function _GetGERMAN: JLocale;
function _GetGERMANY: JLocale;
function _GetITALIAN: JLocale;
function _GetITALY: JLocale;
function _GetJAPAN: JLocale;
function _GetJAPANESE: JLocale;
function _GetKOREA: JLocale;
function _GetKOREAN: JLocale;
function _GetPRC: JLocale;
function _GetROOT: JLocale;
function _GetSIMPLIFIED_CHINESE: JLocale;
function _GetTAIWAN: JLocale;
function _GetTRADITIONAL_CHINESE: JLocale;
function _GetUK: JLocale;
function _GetUS: JLocale;
{Methods}
function init(language: JString): JLocale; cdecl; overload;
function init(language: JString; country: JString): JLocale; cdecl; overload;
function init(language: JString; country: JString; variant: JString): JLocale; cdecl; overload;
function getAvailableLocales: TJavaObjectArray<JLocale>; cdecl;
function getDefault: JLocale; cdecl;
function getISOCountries: TJavaObjectArray<JString>; cdecl;
function getISOLanguages: TJavaObjectArray<JString>; cdecl;
procedure setDefault(locale: JLocale); cdecl;
{Properties}
property CANADA: JLocale read _GetCANADA;
property CANADA_FRENCH: JLocale read _GetCANADA_FRENCH;
property CHINA: JLocale read _GetCHINA;
property CHINESE: JLocale read _GetCHINESE;
property ENGLISH: JLocale read _GetENGLISH;
property FRANCE: JLocale read _GetFRANCE;
property FRENCH: JLocale read _GetFRENCH;
property GERMAN: JLocale read _GetGERMAN;
property GERMANY: JLocale read _GetGERMANY;
property ITALIAN: JLocale read _GetITALIAN;
property ITALY: JLocale read _GetITALY;
property JAPAN: JLocale read _GetJAPAN;
property JAPANESE: JLocale read _GetJAPANESE;
property KOREA: JLocale read _GetKOREA;
property KOREAN: JLocale read _GetKOREAN;
property PRC: JLocale read _GetPRC;
property ROOT: JLocale read _GetROOT;
property SIMPLIFIED_CHINESE: JLocale read _GetSIMPLIFIED_CHINESE;
property TAIWAN: JLocale read _GetTAIWAN;
property TRADITIONAL_CHINESE: JLocale read _GetTRADITIONAL_CHINESE;
property UK: JLocale read _GetUK;
property US: JLocale read _GetUS;
end;
[JavaSignature('java/util/Locale')]
JLocale = interface(JObject)
['{877ADE25-1D13-4963-9A17-17EE17B3A0A8}']
{Methods}
function clone: JObject; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function getCountry: JString; cdecl;
function getDisplayCountry: JString; cdecl; overload;
function getDisplayCountry(locale: JLocale): JString; cdecl; overload;
function getDisplayLanguage: JString; cdecl; overload;
function getDisplayLanguage(locale: JLocale): JString; cdecl; overload;
function getDisplayName: JString; cdecl; overload;
function getDisplayName(locale: JLocale): JString; cdecl; overload;
function getDisplayVariant: JString; cdecl; overload;
function getDisplayVariant(locale: JLocale): JString; cdecl; overload;
function getISO3Country: JString; cdecl;
function getISO3Language: JString; cdecl;
function getLanguage: JString; cdecl;
function getVariant: JString; cdecl;
function hashCode: Integer; cdecl;
function toString: JString; cdecl;
end;
TJLocale = class(TJavaGenericImport<JLocaleClass, JLocale>) end;
JTimeZoneClass = interface(JObjectClass)
['{8F823620-CE10-44D5-82BA-24BFD63DCF80}']
{Property Methods}
function _GetLONG: Integer;
function _GetSHORT: Integer;
{Methods}
function init: JTimeZone; cdecl;
function getAvailableIDs: TJavaObjectArray<JString>; cdecl; overload;
function getAvailableIDs(offsetMillis: Integer): TJavaObjectArray<JString>; cdecl; overload;
function getDefault: JTimeZone; cdecl;
function getTimeZone(id: JString): JTimeZone; cdecl;
procedure setDefault(timeZone: JTimeZone); cdecl;
{Properties}
property LONG: Integer read _GetLONG;
property SHORT: Integer read _GetSHORT;
end;
[JavaSignature('java/util/TimeZone')]
JTimeZone = interface(JObject)
['{9D5215F4-A1B5-4B24-8B0B-EB3B88A0328D}']
{Methods}
function clone: JObject; cdecl;
function getDSTSavings: Integer; cdecl;
function getDisplayName: JString; cdecl; overload;
function getDisplayName(locale: JLocale): JString; cdecl; overload;
function getDisplayName(daylightTime: Boolean; style: Integer): JString; cdecl; overload;
function getDisplayName(daylightTime: Boolean; style: Integer; locale: JLocale): JString; cdecl; overload;
function getID: JString; cdecl;
function getOffset(time: Int64): Integer; cdecl; overload;
function getOffset(era: Integer; year: Integer; month: Integer; day: Integer; dayOfWeek: Integer; timeOfDayMillis: Integer): Integer; cdecl; overload;
function getRawOffset: Integer; cdecl;
function hasSameRules(timeZone: JTimeZone): Boolean; cdecl;
function inDaylightTime(time: JDate): Boolean; cdecl;
procedure setID(id: JString); cdecl;
procedure setRawOffset(offsetMillis: Integer); cdecl;
function useDaylightTime: Boolean; cdecl;
end;
TJTimeZone = class(TJavaGenericImport<JTimeZoneClass, JTimeZone>) end;
JFileFilterClass = interface(IJavaClass)
['{74779212-F9FA-40FE-A5C2-41FBC7919220}']
end;
[JavaSignature('java/io/FileFilter')]
JFileFilter = interface(IJavaInstance)
['{5A5564B5-D25E-4D6A-AF92-F0725E9011DE}']
{Methods}
function accept(pathname: JFile): Boolean; cdecl;
end;
TJFileFilter = class(TJavaGenericImport<JFileFilterClass, JFileFilter>) end;
JEnumSetClass = interface(JAbstractSetClass)
['{67EF0287-D91B-44E0-9574-4CA9974FBC38}']
{Methods}
function allOf(elementType: Jlang_Class): JEnumSet; cdecl;
function complementOf(s: JEnumSet): JEnumSet; cdecl;
function copyOf(s: JEnumSet): JEnumSet; cdecl; overload;
function copyOf(c: JCollection): JEnumSet; cdecl; overload;
function noneOf(elementType: Jlang_Class): JEnumSet; cdecl;
function &of(e: JEnum): JEnumSet; cdecl; overload;
function &of(e1: JEnum; e2: JEnum): JEnumSet; cdecl; overload;
function &of(e1: JEnum; e2: JEnum; e3: JEnum): JEnumSet; cdecl; overload;
function &of(e1: JEnum; e2: JEnum; e3: JEnum; e4: JEnum): JEnumSet; cdecl; overload;
function &of(e1: JEnum; e2: JEnum; e3: JEnum; e4: JEnum; e5: JEnum): JEnumSet; cdecl; overload;
function range(start: JEnum; end_: JEnum): JEnumSet; cdecl;
end;
[JavaSignature('java/util/EnumSet')]
JEnumSet = interface(JAbstractSet)
['{C8A6B028-B797-406A-9EE4-B65671555D97}']
{Methods}
function clone: JEnumSet; cdecl;
end;
TJEnumSet = class(TJavaGenericImport<JEnumSetClass, JEnumSet>) end;
Jutil_ObservableClass = interface(JObjectClass)
['{2BD8C696-02FF-4378-A514-ACD431BEE106}']
{Methods}
function init: Jutil_Observable; cdecl;
end;
[JavaSignature('java/util/Observable')]
Jutil_Observable = interface(JObject)
['{B8443F0E-B41C-4475-934B-1C917FCF617B}']
{Methods}
procedure addObserver(observer: JObserver); cdecl;
function countObservers: Integer; cdecl;
procedure deleteObserver(observer: JObserver); cdecl;
procedure deleteObservers; cdecl;
function hasChanged: Boolean; cdecl;
procedure notifyObservers; cdecl; overload;
procedure notifyObservers(data: JObject); cdecl; overload;
end;
TJutil_Observable = class(TJavaGenericImport<Jutil_ObservableClass, Jutil_Observable>) end;
JFilenameFilterClass = interface(IJavaClass)
['{E466E540-E65D-43EC-8913-E8F8AEEA354F}']
end;
[JavaSignature('java/io/FilenameFilter')]
JFilenameFilter = interface(IJavaInstance)
['{B55A4F67-1AE9-41F5-BCF8-305D3902A782}']
{Methods}
function accept(dir: JFile; filename: JString): Boolean; cdecl;
end;
TJFilenameFilter = class(TJavaGenericImport<JFilenameFilterClass, JFilenameFilter>) end;
JJSONObjectClass = interface(JObjectClass)
['{32FBF926-19C3-45AF-A29E-C312D95B34CC}']
{Property Methods}
function _GetNULL: JObject;
{Methods}
function init: JJSONObject; cdecl; overload;
function init(copyFrom: JMap): JJSONObject; cdecl; overload;
function init(readFrom: JJSONTokener): JJSONObject; cdecl; overload;
function init(json: JString): JJSONObject; cdecl; overload;
function init(copyFrom: JJSONObject; names: TJavaObjectArray<JString>): JJSONObject; cdecl; overload;
function numberToString(number: JNumber): JString; cdecl;
function quote(data: JString): JString; cdecl;
{Properties}
property NULL: JObject read _GetNULL;
end;
[JavaSignature('org/json/JSONObject')]
JJSONObject = interface(JObject)
['{7B4F68E8-ADFC-40EC-A119-37FA9778A11C}']
{Methods}
function accumulate(name: JString; value: JObject): JJSONObject; cdecl;
function &get(name: JString): JObject; cdecl;
function getBoolean(name: JString): Boolean; cdecl;
function getDouble(name: JString): Double; cdecl;
function getInt(name: JString): Integer; cdecl;
function getJSONArray(name: JString): JJSONArray; cdecl;
function getJSONObject(name: JString): JJSONObject; cdecl;
function getLong(name: JString): Int64; cdecl;
function getString(name: JString): JString; cdecl;
function has(name: JString): Boolean; cdecl;
function isNull(name: JString): Boolean; cdecl;
function keys: JIterator; cdecl;
function length: Integer; cdecl;
function names: JJSONArray; cdecl;
function opt(name: JString): JObject; cdecl;
function optBoolean(name: JString): Boolean; cdecl; overload;
function optBoolean(name: JString; fallback: Boolean): Boolean; cdecl; overload;
function optDouble(name: JString): Double; cdecl; overload;
function optDouble(name: JString; fallback: Double): Double; cdecl; overload;
function optInt(name: JString): Integer; cdecl; overload;
function optInt(name: JString; fallback: Integer): Integer; cdecl; overload;
function optJSONArray(name: JString): JJSONArray; cdecl;
function optJSONObject(name: JString): JJSONObject; cdecl;
function optLong(name: JString): Int64; cdecl; overload;
function optLong(name: JString; fallback: Int64): Int64; cdecl; overload;
function optString(name: JString): JString; cdecl; overload;
function optString(name: JString; fallback: JString): JString; cdecl; overload;
function put(name: JString; value: Boolean): JJSONObject; cdecl; overload;
function put(name: JString; value: Double): JJSONObject; cdecl; overload;
function put(name: JString; value: Integer): JJSONObject; cdecl; overload;
function put(name: JString; value: Int64): JJSONObject; cdecl; overload;
function put(name: JString; value: JObject): JJSONObject; cdecl; overload;
function putOpt(name: JString; value: JObject): JJSONObject; cdecl;
function remove(name: JString): JObject; cdecl;
function toJSONArray(names: JJSONArray): JJSONArray; cdecl;
function toString: JString; cdecl; overload;
function toString(indentSpaces: Integer): JString; cdecl; overload;
end;
TJJSONObject = class(TJavaGenericImport<JJSONObjectClass, JJSONObject>) end;
JStringClass = interface(JObjectClass)
['{E61829D1-1FD3-49B2-BAC6-FB0FFDB1A495}']
{Property Methods}
function _GetCASE_INSENSITIVE_ORDER: JComparator;
{Methods}
function init: JString; cdecl; overload;
function init(data: TJavaArray<Byte>): JString; cdecl; overload;
function init(data: TJavaArray<Byte>; high: Integer): JString; cdecl; overload;//Deprecated
function init(data: TJavaArray<Byte>; offset: Integer; byteCount: Integer): JString; cdecl; overload;
function init(data: TJavaArray<Byte>; high: Integer; offset: Integer; byteCount: Integer): JString; cdecl; overload;//Deprecated
function init(data: TJavaArray<Byte>; offset: Integer; byteCount: Integer; charsetName: JString): JString; cdecl; overload;
function init(data: TJavaArray<Byte>; charsetName: JString): JString; cdecl; overload;
function init(data: TJavaArray<Char>): JString; cdecl; overload;
function init(data: TJavaArray<Char>; offset: Integer; charCount: Integer): JString; cdecl; overload;
function init(toCopy: JString): JString; cdecl; overload;
function init(stringBuffer: JStringBuffer): JString; cdecl; overload;
function init(codePoints: TJavaArray<Integer>; offset: Integer; count: Integer): JString; cdecl; overload;
function init(stringBuilder: JStringBuilder): JString; cdecl; overload;
function copyValueOf(data: TJavaArray<Char>): JString; cdecl; overload;
function copyValueOf(data: TJavaArray<Char>; start: Integer; length: Integer): JString; cdecl; overload;
function valueOf(data: TJavaArray<Char>): JString; cdecl; overload;
function valueOf(data: TJavaArray<Char>; start: Integer; length: Integer): JString; cdecl; overload;
function valueOf(value: Char): JString; cdecl; overload;
function valueOf(value: Double): JString; cdecl; overload;
function valueOf(value: Single): JString; cdecl; overload;
function valueOf(value: Integer): JString; cdecl; overload;
function valueOf(value: Int64): JString; cdecl; overload;
function valueOf(value: JObject): JString; cdecl; overload;
function valueOf(value: Boolean): JString; cdecl; overload;
{Properties}
property CASE_INSENSITIVE_ORDER: JComparator read _GetCASE_INSENSITIVE_ORDER;
end;
[JavaSignature('java/lang/String')]
JString = interface(JObject)
['{8579B374-1E68-4729-AE3C-C8DA0A6D6F9F}']
{Methods}
function charAt(index: Integer): Char; cdecl;
function codePointAt(index: Integer): Integer; cdecl;
function codePointBefore(index: Integer): Integer; cdecl;
function codePointCount(start: Integer; end_: Integer): Integer; cdecl;
function compareTo(string_: JString): Integer; cdecl;
function compareToIgnoreCase(string_: JString): Integer; cdecl;
function concat(string_: JString): JString; cdecl;
function &contains(cs: JCharSequence): Boolean; cdecl;
function contentEquals(strbuf: JStringBuffer): Boolean; cdecl; overload;
function contentEquals(cs: JCharSequence): Boolean; cdecl; overload;
function endsWith(suffix: JString): Boolean; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function equalsIgnoreCase(string_: JString): Boolean; cdecl;
procedure getBytes(start: Integer; end_: Integer; data: TJavaArray<Byte>; index: Integer); cdecl; overload;//Deprecated
function getBytes: TJavaArray<Byte>; cdecl; overload;
function getBytes(charsetName: JString): TJavaArray<Byte>; cdecl; overload;
procedure getChars(start: Integer; end_: Integer; buffer: TJavaArray<Char>; index: Integer); cdecl;
function hashCode: Integer; cdecl;
function indexOf(c: Integer): Integer; cdecl; overload;
function indexOf(c: Integer; start: Integer): Integer; cdecl; overload;
function indexOf(string_: JString): Integer; cdecl; overload;
function indexOf(subString: JString; start: Integer): Integer; cdecl; overload;
function intern: JString; cdecl;
function isEmpty: Boolean; cdecl;
function lastIndexOf(c: Integer): Integer; cdecl; overload;
function lastIndexOf(c: Integer; start: Integer): Integer; cdecl; overload;
function lastIndexOf(string_: JString): Integer; cdecl; overload;
function lastIndexOf(subString: JString; start: Integer): Integer; cdecl; overload;
function length: Integer; cdecl;
function matches(regularExpression: JString): Boolean; cdecl;
function offsetByCodePoints(index: Integer; codePointOffset: Integer): Integer; cdecl;
function regionMatches(thisStart: Integer; string_: JString; start: Integer; length: Integer): Boolean; cdecl; overload;
function regionMatches(ignoreCase: Boolean; thisStart: Integer; string_: JString; start: Integer; length: Integer): Boolean; cdecl; overload;
function replace(oldChar: Char; newChar: Char): JString; cdecl; overload;
function replace(target: JCharSequence; replacement: JCharSequence): JString; cdecl; overload;
function replaceAll(regularExpression: JString; replacement: JString): JString; cdecl;
function replaceFirst(regularExpression: JString; replacement: JString): JString; cdecl;
function split(regularExpression: JString): TJavaObjectArray<JString>; cdecl; overload;
function split(regularExpression: JString; limit: Integer): TJavaObjectArray<JString>; cdecl; overload;
function startsWith(prefix: JString): Boolean; cdecl; overload;
function startsWith(prefix: JString; start: Integer): Boolean; cdecl; overload;
function subSequence(start: Integer; end_: Integer): JCharSequence; cdecl;
function substring(start: Integer): JString; cdecl; overload;
function substring(start: Integer; end_: Integer): JString; cdecl; overload;
function toCharArray: TJavaArray<Char>; cdecl;
function toLowerCase: JString; cdecl; overload;
function toLowerCase(locale: JLocale): JString; cdecl; overload;
function toString: JString; cdecl;
function toUpperCase: JString; cdecl; overload;
function toUpperCase(locale: JLocale): JString; cdecl; overload;
function trim: JString; cdecl;
end;
TJString = class(TJavaGenericImport<JStringClass, JString>) end;
JSetClass = interface(JCollectionClass)
['{A3E290FD-FD46-4DA8-B728-07B04920F5DE}']
end;
[JavaSignature('java/util/Set')]
JSet = interface(JCollection)
['{07BF19A2-0C1C-4ABF-9028-1F99DD0E0A79}']
{Methods}
function add(object_: JObject): Boolean; cdecl;
function addAll(collection: JCollection): Boolean; cdecl;
procedure clear; cdecl;
function &contains(object_: JObject): Boolean; cdecl;
function containsAll(collection: JCollection): Boolean; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function hashCode: Integer; cdecl;
function isEmpty: Boolean; cdecl;
function iterator: JIterator; cdecl;
function remove(object_: JObject): Boolean; cdecl;
function removeAll(collection: JCollection): Boolean; cdecl;
function retainAll(collection: JCollection): Boolean; cdecl;
function size: Integer; cdecl;
function toArray: TJavaObjectArray<JObject>; cdecl; overload;
function toArray(array_: TJavaObjectArray<JObject>): TJavaObjectArray<JObject>; cdecl; overload;
end;
TJSet = class(TJavaGenericImport<JSetClass, JSet>) end;
JShortClass = interface(JNumberClass)
['{FAD495F3-40B7-46DB-B3B6-8DBBD38D8E16}']
{Property Methods}
function _GetMAX_VALUE: SmallInt;
function _GetMIN_VALUE: SmallInt;
function _GetSIZE: Integer;
function _GetTYPE: Jlang_Class;
{Methods}
function init(string_: JString): JShort; cdecl; overload;
function init(value: SmallInt): JShort; cdecl; overload;
function decode(string_: JString): JShort; cdecl;
function parseShort(string_: JString): SmallInt; cdecl; overload;
function parseShort(string_: JString; radix: Integer): SmallInt; cdecl; overload;
function reverseBytes(s: SmallInt): SmallInt; cdecl;
function toString(value: SmallInt): JString; cdecl; overload;
function valueOf(string_: JString): JShort; cdecl; overload;
function valueOf(string_: JString; radix: Integer): JShort; cdecl; overload;
function valueOf(s: SmallInt): JShort; cdecl; overload;
{Properties}
property MAX_VALUE: SmallInt read _GetMAX_VALUE;
property MIN_VALUE: SmallInt read _GetMIN_VALUE;
property SIZE: Integer read _GetSIZE;
property &TYPE: Jlang_Class read _GetTYPE;
end;
[JavaSignature('java/lang/Short')]
JShort = interface(JNumber)
['{48D3B355-1222-4BD6-94BF-F40B5EE8EF02}']
{Methods}
function byteValue: Byte; cdecl;
function compareTo(object_: JShort): Integer; cdecl;
function doubleValue: Double; cdecl;
function equals(object_: JObject): Boolean; cdecl;
function floatValue: Single; cdecl;
function hashCode: Integer; cdecl;
function intValue: Integer; cdecl;
function longValue: Int64; cdecl;
function shortValue: SmallInt; cdecl;
function toString: JString; cdecl; overload;
end;
TJShort = class(TJavaGenericImport<JShortClass, JShort>) end;
JThreadGroupClass = interface(JObjectClass)
['{D7D65FE0-0CB7-4C72-9129-C344705D0F4C}']
{Methods}
function init(name: JString): JThreadGroup; cdecl; overload;
function init(parent: JThreadGroup; name: JString): JThreadGroup; cdecl; overload;
end;
[JavaSignature('java/lang/ThreadGroup')]
JThreadGroup = interface(JObject)
['{5BF3F856-7BFB-444A-8059-341CBC2A10B2}']
{Methods}
function activeCount: Integer; cdecl;
function activeGroupCount: Integer; cdecl;
function allowThreadSuspension(b: Boolean): Boolean; cdecl;//Deprecated
procedure checkAccess; cdecl;
procedure destroy; cdecl;
function enumerate(threads: TJavaObjectArray<JThread>): Integer; cdecl; overload;
function enumerate(threads: TJavaObjectArray<JThread>; recurse: Boolean): Integer; cdecl; overload;
function enumerate(groups: TJavaObjectArray<JThreadGroup>): Integer; cdecl; overload;
function enumerate(groups: TJavaObjectArray<JThreadGroup>; recurse: Boolean): Integer; cdecl; overload;
function getMaxPriority: Integer; cdecl;
function getName: JString; cdecl;
function getParent: JThreadGroup; cdecl;
procedure interrupt; cdecl;
function isDaemon: Boolean; cdecl;
function isDestroyed: Boolean; cdecl;
procedure list; cdecl;
function parentOf(g: JThreadGroup): Boolean; cdecl;
procedure resume; cdecl;//Deprecated
procedure setDaemon(isDaemon: Boolean); cdecl;
procedure setMaxPriority(newMax: Integer); cdecl;
procedure stop; cdecl;//Deprecated
procedure suspend; cdecl;//Deprecated
function toString: JString; cdecl;
procedure uncaughtException(t: JThread; e: JThrowable); cdecl;
end;
TJThreadGroup = class(TJavaGenericImport<JThreadGroupClass, JThreadGroup>) end;
JComparatorClass = interface(IJavaClass)
['{BFB6395F-2694-4292-A1B5-87CC1138FB77}']
end;
[JavaSignature('java/util/Comparator')]
JComparator = interface(IJavaInstance)
['{0754C41C-92B8-483B-88F0-B48BFE216D46}']
{Methods}
function compare(lhs: JObject; rhs: JObject): Integer; cdecl;
function equals(object_: JObject): Boolean; cdecl;
end;
TJComparator = class(TJavaGenericImport<JComparatorClass, JComparator>) end;
JJSONArrayClass = interface(JObjectClass)
['{34FBA399-2B13-49B4-BD53-5BDFE4653285}']
{Methods}
function init: JJSONArray; cdecl; overload;
function init(copyFrom: JCollection): JJSONArray; cdecl; overload;
function init(readFrom: JJSONTokener): JJSONArray; cdecl; overload;
function init(json: JString): JJSONArray; cdecl; overload;
end;
[JavaSignature('org/json/JSONArray')]
JJSONArray = interface(JObject)
['{34738D80-ED10-413D-9467-36A3785DBFF4}']
{Methods}
function equals(o: JObject): Boolean; cdecl;
function &get(index: Integer): JObject; cdecl;
function getBoolean(index: Integer): Boolean; cdecl;
function getDouble(index: Integer): Double; cdecl;
function getInt(index: Integer): Integer; cdecl;
function getJSONArray(index: Integer): JJSONArray; cdecl;
function getJSONObject(index: Integer): JJSONObject; cdecl;
function getLong(index: Integer): Int64; cdecl;
function getString(index: Integer): JString; cdecl;
function hashCode: Integer; cdecl;
function isNull(index: Integer): Boolean; cdecl;
function join(separator: JString): JString; cdecl;
function length: Integer; cdecl;
function opt(index: Integer): JObject; cdecl;
function optBoolean(index: Integer): Boolean; cdecl; overload;
function optBoolean(index: Integer; fallback: Boolean): Boolean; cdecl; overload;
function optDouble(index: Integer): Double; cdecl; overload;
function optDouble(index: Integer; fallback: Double): Double; cdecl; overload;
function optInt(index: Integer): Integer; cdecl; overload;
function optInt(index: Integer; fallback: Integer): Integer; cdecl; overload;
function optJSONArray(index: Integer): JJSONArray; cdecl;
function optJSONObject(index: Integer): JJSONObject; cdecl;
function optLong(index: Integer): Int64; cdecl; overload;
function optLong(index: Integer; fallback: Int64): Int64; cdecl; overload;
function optString(index: Integer): JString; cdecl; overload;
function optString(index: Integer; fallback: JString): JString; cdecl; overload;
function put(value: Boolean): JJSONArray; cdecl; overload;
function put(value: Double): JJSONArray; cdecl; overload;
function put(value: Integer): JJSONArray; cdecl; overload;
function put(value: Int64): JJSONArray; cdecl; overload;
function put(value: JObject): JJSONArray; cdecl; overload;
function put(index: Integer; value: Boolean): JJSONArray; cdecl; overload;
function put(index: Integer; value: Double): JJSONArray; cdecl; overload;
function put(index: Integer; value: Integer): JJSONArray; cdecl; overload;
function put(index: Integer; value: Int64): JJSONArray; cdecl; overload;
function put(index: Integer; value: JObject): JJSONArray; cdecl; overload;
function toJSONObject(names: JJSONArray): JJSONObject; cdecl;
function toString: JString; cdecl; overload;
function toString(indentSpaces: Integer): JString; cdecl; overload;
end;
TJJSONArray = class(TJavaGenericImport<JJSONArrayClass, JJSONArray>) end;
JLongClass = interface(JNumberClass)
['{BA567CF5-58F3-41A7-BAA4-538606294DE9}']
{Property Methods}
function _GetMAX_VALUE: Int64;
function _GetMIN_VALUE: Int64;
function _GetSIZE: Integer;
function _GetTYPE: Jlang_Class;
{Methods}
function init(value: Int64): JLong; cdecl; overload;
function init(string_: JString): JLong; cdecl; overload;
function bitCount(v: Int64): Integer; cdecl;
function decode(string_: JString): JLong; cdecl;
function getLong(string_: JString): JLong; cdecl; overload;
function getLong(string_: JString; defaultValue: Int64): JLong; cdecl; overload;
function getLong(string_: JString; defaultValue: JLong): JLong; cdecl; overload;
function highestOneBit(v: Int64): Int64; cdecl;
function lowestOneBit(v: Int64): Int64; cdecl;
function numberOfLeadingZeros(v: Int64): Integer; cdecl;
function numberOfTrailingZeros(v: Int64): Integer; cdecl;
function parseLong(string_: JString): Int64; cdecl; overload;
function parseLong(string_: JString; radix: Integer): Int64; cdecl; overload;
function reverse(v: Int64): Int64; cdecl;
function reverseBytes(v: Int64): Int64; cdecl;
function rotateLeft(v: Int64; distance: Integer): Int64; cdecl;
function rotateRight(v: Int64; distance: Integer): Int64; cdecl;
function signum(v: Int64): Integer; cdecl;
function toBinaryString(v: Int64): JString; cdecl;
function toHexString(v: Int64): JString; cdecl;
function toOctalString(v: Int64): JString; cdecl;
function toString(n: Int64): JString; cdecl; overload;
function toString(v: Int64; radix: Integer): JString; cdecl; overload;
function valueOf(string_: JString): JLong; cdecl; overload;
function valueOf(string_: JString; radix: Integer): JLong; cdecl; overload;
function valueOf(v: Int64): JLong; cdecl; overload;
{Properties}
property MAX_VALUE: Int64 read _GetMAX_VALUE;
property MIN_VALUE: Int64 read _GetMIN_VALUE;
property SIZE: Integer read _GetSIZE;
property &TYPE: Jlang_Class read _GetTYPE;
end;
[JavaSignature('java/lang/Long')]
JLong = interface(JNumber)
['{F2E23531-34CC-4607-94D6-F85B4F95FB43}']
{Methods}
function byteValue: Byte; cdecl;
function compareTo(object_: JLong): Integer; cdecl;
function doubleValue: Double; cdecl;
function equals(o: JObject): Boolean; cdecl;
function floatValue: Single; cdecl;
function hashCode: Integer; cdecl;
function intValue: Integer; cdecl;
function longValue: Int64; cdecl;
function shortValue: SmallInt; cdecl;
function toString: JString; cdecl; overload;
end;
TJLong = class(TJavaGenericImport<JLongClass, JLong>) end;
JFileInputStreamClass = interface(JInputStreamClass)
['{A1EB6AE5-8562-4E38-8182-61F57E51733A}']
{Methods}
function init(file_: JFile): JFileInputStream; cdecl; overload;
function init(fd: JFileDescriptor): JFileInputStream; cdecl; overload;
function init(path: JString): JFileInputStream; cdecl; overload;
end;
[JavaSignature('java/io/FileInputStream')]
JFileInputStream = interface(JInputStream)
['{55CBCA4D-B04C-442A-BD74-ADFFD715A1A5}']
{Methods}
function available: Integer; cdecl;
procedure close; cdecl;
function getFD: JFileDescriptor; cdecl;
function read: Integer; cdecl; overload;
function read(buffer: TJavaArray<Byte>; byteOffset: Integer; byteCount: Integer): Integer; cdecl; overload;
function skip(byteCount: Int64): Int64; cdecl;
end;
TJFileInputStream = class(TJavaGenericImport<JFileInputStreamClass, JFileInputStream>) end;
JStringBufferClass = interface(JAbstractStringBuilderClass)
['{F6BF4ECD-EA63-4AF3-A901-99D4221796D7}']
{Methods}
function init: JStringBuffer; cdecl; overload;
function init(capacity: Integer): JStringBuffer; cdecl; overload;
function init(string_: JString): JStringBuffer; cdecl; overload;
function init(cs: JCharSequence): JStringBuffer; cdecl; overload;
end;
[JavaSignature('java/lang/StringBuffer')]
JStringBuffer = interface(JAbstractStringBuilder)
['{3CECFBBE-9C21-4D67-9F6F-52BB1DB2C638}']
{Methods}
function append(b: Boolean): JStringBuffer; cdecl; overload;
function append(ch: Char): JStringBuffer; cdecl; overload;
function append(d: Double): JStringBuffer; cdecl; overload;
function append(f: Single): JStringBuffer; cdecl; overload;
function append(i: Integer): JStringBuffer; cdecl; overload;
function append(l: Int64): JStringBuffer; cdecl; overload;
function append(obj: JObject): JStringBuffer; cdecl; overload;
function append(string_: JString): JStringBuffer; cdecl; overload;
function append(sb: JStringBuffer): JStringBuffer; cdecl; overload;
function append(chars: TJavaArray<Char>): JStringBuffer; cdecl; overload;
function append(chars: TJavaArray<Char>; start: Integer; length: Integer): JStringBuffer; cdecl; overload;
function append(s: JCharSequence): JStringBuffer; cdecl; overload;
function append(s: JCharSequence; start: Integer; end_: Integer): JStringBuffer; cdecl; overload;
function appendCodePoint(codePoint: Integer): JStringBuffer; cdecl;
function charAt(index: Integer): Char; cdecl;
function codePointAt(index: Integer): Integer; cdecl;
function codePointBefore(index: Integer): Integer; cdecl;
function codePointCount(beginIndex: Integer; endIndex: Integer): Integer; cdecl;
function delete(start: Integer; end_: Integer): JStringBuffer; cdecl;
function deleteCharAt(location: Integer): JStringBuffer; cdecl;
procedure ensureCapacity(min: Integer); cdecl;
procedure getChars(start: Integer; end_: Integer; buffer: TJavaArray<Char>; idx: Integer); cdecl;
function indexOf(subString: JString; start: Integer): Integer; cdecl;
function insert(index: Integer; ch: Char): JStringBuffer; cdecl; overload;
function insert(index: Integer; b: Boolean): JStringBuffer; cdecl; overload;
function insert(index: Integer; i: Integer): JStringBuffer; cdecl; overload;
function insert(index: Integer; l: Int64): JStringBuffer; cdecl; overload;
function insert(index: Integer; d: Double): JStringBuffer; cdecl; overload;
function insert(index: Integer; f: Single): JStringBuffer; cdecl; overload;
function insert(index: Integer; obj: JObject): JStringBuffer; cdecl; overload;
function insert(index: Integer; string_: JString): JStringBuffer; cdecl; overload;
function insert(index: Integer; chars: TJavaArray<Char>): JStringBuffer; cdecl; overload;
function insert(index: Integer; chars: TJavaArray<Char>; start: Integer; length: Integer): JStringBuffer; cdecl; overload;
function insert(index: Integer; s: JCharSequence): JStringBuffer; cdecl; overload;
function insert(index: Integer; s: JCharSequence; start: Integer; end_: Integer): JStringBuffer; cdecl; overload;
function lastIndexOf(subString: JString; start: Integer): Integer; cdecl;
function offsetByCodePoints(index: Integer; codePointOffset: Integer): Integer; cdecl;
function replace(start: Integer; end_: Integer; string_: JString): JStringBuffer; cdecl;
function reverse: JStringBuffer; cdecl;
procedure setCharAt(index: Integer; ch: Char); cdecl;
procedure setLength(length: Integer); cdecl;
function subSequence(start: Integer; end_: Integer): JCharSequence; cdecl;
function substring(start: Integer): JString; cdecl; overload;
function substring(start: Integer; end_: Integer): JString; cdecl; overload;
function toString: JString; cdecl;
procedure trimToSize; cdecl;
end;
TJStringBuffer = class(TJavaGenericImport<JStringBufferClass, JStringBuffer>) end;
function JStringToString(const JStr: JString): string;
function StringToJString(const Str: string): JString;
implementation
function JStringToString(const JStr: JString): string;
begin
if JStr = nil then
Result := ''
else
Result:= JNIStringToString(TJNIResolver.GetJNIEnv, JNIString((JStr as ILocalObject).GetObjectID));
end;
function StringToJString(const Str: string): JString;
var
LocalRef: JNIObject;
begin
LocalRef := StringToJNIString(TJNIResolver.GetJNIEnv, Str);
Result := TJString.Wrap(LocalRef);
TJNIResolver.DeleteLocalRef(LocalRef);
end;
end.
|
{*******************************************************}
{ }
{ Это дополнение для класса THTTPSend из либы }
{ synapse для работы с сетью и оно реализует }
{ правильную обработку http редиректов 301 и 302, }
{ ну и пару функций для удобной работы с }
{ HTTP-хедерами HTTP-запросов }
{ }
{ Copyright (C) 2018-2019 Witcher }
{ }
{*******************************************************}
unit httpsend_helper;
interface
uses
SysUtils, Classes, httpsend;
type
THttpSend_ = class helper for THTTPSend
function HeaderNameByIndex(index:integer):string;
function HeaderByName(const HeaderName:string):string;
function HTTPMethod2(const Method, URL: string): Boolean;
end;
implementation
{ THttpSend_ }
function THttpSend_.HeaderByName(const HeaderName: string): string;
var
i : integer;
begin
for i:=0 to Headers.Count-1 do
begin
if LowerCase(HeaderNameByIndex(i)) = lowercase(HeaderName) then
begin
Result:=copy(Headers[i],pos(':',
LowerCase(Headers[i]))+2,
Length(Headers[i])-length(HeaderName));
break;
end;
end;
end;
function THttpSend_.HeaderNameByIndex(index: integer): string;
begin
if (index > (Headers.Count-1)) or (index < 0) then Exit;
Result := copy(Headers[index],0, pos(':',Headers[index])-1);
end;
function THttpSend_.HTTPMethod2(const Method, URL: string): Boolean;
var
Heads: TStringList;
Cooks: TStringList;
Redirect: string;
Doc:TMemoryStream;
begin
try
Heads:=TStringList.Create;
Cooks:=TStringList.Create;
Doc:=TMemoryStream.Create;
Doc.LoadFromStream(Document);
Cooks.Assign(Cookies);
Heads.Assign(Headers);
Result := HTTPMethod(Method,URL);
if (ResultCode=301) or (ResultCode=302) then
begin
Redirect:=HeaderByName('location');
Headers.Assign(Heads);
Document.Clear;
Document.LoadFromStream(Doc);
Cookies.Assign(Cooks);
Result := HTTPMethod(Method,Redirect);
end;
finally
FreeAndNil(Heads);
FreeAndNil(Cooks);
FreeAndNil(Doc)
end;
end;
end.
|
unit ClienteServidor;
interface
uses
Threads,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Datasnap.DBClient, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, System.Threading, TratarExcecao;
type
TServidor = class
private
FPath: String;
public
constructor Create;
//Tipo do parâmetro não pode ser alterado
function SalvarArquivos(AData: OleVariant): Boolean; overload;
function SalvarArquivos(cds: TClientDataSet): Boolean; overload;
end;
TfClienteServidor = class(TForm)
ProgressBar: TProgressBar;
btEnviarSemErros: TButton;
btEnviarComErros: TButton;
btEnviarParalelo: TButton;
procedure FormCreate(Sender: TObject);
procedure btEnviarSemErrosClick(Sender: TObject);
procedure btEnviarComErrosClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btEnviarParaleloClick(Sender: TObject);
private
FPath: String;
FServidor: TServidor;
FCDSParalelo: TClientDataSet;
function InitDataset: TClientDataset;
procedure Inicializar_ProgressBar;
procedure Carregar_ProgressBar(Posicao: Integer);
procedure EnviarSemErros(Qtde_Enviar: Integer);
procedure GravarCds(Cds: TClientDataSet; contador: Integer);
public
end;
var
fClienteServidor: TfClienteServidor;
const
QTD_ARQUIVOS_ENVIAR = 100;
implementation
uses
IOUtils;
{$R *.dfm}
procedure TfClienteServidor.btEnviarComErrosClick(Sender: TObject);
var
cds: TClientDataset;
i: Integer;
begin
cds := InitDataset;
Inicializar_ProgressBar;
for i := 1 to QTD_ARQUIVOS_ENVIAR do
begin
try
GravarCds(cds, I);
Carregar_ProgressBar(i);
{$REGION Simulação de erro, não alterar}
if i = (QTD_ARQUIVOS_ENVIAR/2) then
FServidor.SalvarArquivos(NULL);
{$ENDREGION}
except on e: EDBClient do
begin
ShowMessage('aqui');
end;
end;
end;
FServidor.SalvarArquivos(cds.Data);
end;
procedure TfClienteServidor.btEnviarParaleloClick(Sender: TObject);
begin
if not Assigned(FCDSParalelo) then
FCDSParalelo := InitDataset;
TParallel.For(1, QTD_ARQUIVOS_ENVIAR,
procedure(i: Integer)
begin
TThread.Queue(TThread.CurrentThread,
procedure
begin
GravarCds(FCDSParalelo, I);
Carregar_ProgressBar(I);
if I mod 10 = 0 then
begin
FServidor.SalvarArquivos(FCDSParalelo);
FCDSParalelo.EmptyDataSet;
end;
end);
end);
end;
procedure TfClienteServidor.btEnviarSemErrosClick(Sender: TObject);
begin
EnviarSemErros(QTD_ARQUIVOS_ENVIAR);
end;
procedure TfClienteServidor.Carregar_ProgressBar(Posicao: Integer);
begin
ProgressBar.Position := Posicao;
end;
procedure TfClienteServidor.EnviarSemErros(Qtde_Enviar: Integer);
var
cds: TClientDataset;
I: Integer;
begin
try
cds := InitDataset;
Inicializar_ProgressBar;
for I := 1 to Qtde_Enviar do
begin
GravarCds(cds, I);
Carregar_ProgressBar(I);
if I mod 10 = 0 then
begin
FServidor.SalvarArquivos(cds);
cds.EmptyDataSet;
Application.ProcessMessages;
end;
end;
finally
FreeAndNil(cds);
ShowMessage('Finalizado!');
Inicializar_ProgressBar;
end;
end;
procedure TfClienteServidor.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
FServidor.Free;
FCDSParalelo.Free;
end;
procedure TfClienteServidor.FormCreate(Sender: TObject);
begin
inherited;
FPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'pdf.pdf';
FServidor := TServidor.Create;
end;
procedure TfClienteServidor.GravarCds(Cds: TClientDataSet; contador: Integer);
begin
cds.Append;
TBlobField(cds.FieldByName('Arquivo')).LoadFromFile(FPath);
cds.FieldByName('Nome').AsString := contador.ToString;
cds.Post;
end;
procedure TfClienteServidor.Inicializar_ProgressBar;
begin
ProgressBar.Max := QTD_ARQUIVOS_ENVIAR;
ProgressBar.Position := 0;
end;
function TfClienteServidor.InitDataset: TClientDataset;
begin
Result := TClientDataset.Create(nil);
Result.FieldDefs.Add('Arquivo', ftBlob);
Result.FieldDefs.Add('Nome', ftString, 20);
Result.CreateDataSet;
end;
{ TServidor }
constructor TServidor.Create;
begin
FPath := ExtractFilePath(ParamStr(0)) + 'Servidor\';
end;
function TServidor.SalvarArquivos(AData: OleVariant): Boolean;
var
cds: TClientDataSet;
FileName: string;
begin
try
Result := False;
cds := TClientDataset.Create(nil);
cds.Data := AData;
{$REGION Simulação de erro, não alterar}
if cds.RecordCount = 0 then
Exit;
{$ENDREGION}
cds.First;
while not cds.Eof do
begin
FileName := FPath + cds.FieldByName('Nome').AsString+'.pdf';//cds.RecNo.ToString + '.pdf';
if TFile.Exists(FileName) then
TFile.Delete(FileName);
TBlobField(cds.FieldByName('Arquivo')).SaveToFile(FileName);
cds.Next;
end;
Result := True;
except
raise;
end;
end;
function TServidor.SalvarArquivos(cds: TClientDataSet): Boolean;
var
FileName: string;
begin
try
Result := False;
{$REGION Simulação de erro, não alterar}
if cds.RecordCount = 0 then
Exit;
{$ENDREGION}
cds.First;
while not cds.Eof do
begin
FileName := FPath + cds.FieldByName('Nome').AsString+'.pdf';//cds.RecNo.ToString + '.pdf';
if TFile.Exists(FileName) then
TFile.Delete(FileName);
TBlobField(cds.FieldByName('Arquivo')).SaveToFile(FileName);
cds.Next;
end;
Result := True;
except
raise;
end;
end;
end.
|
unit ContentKeeper;
interface
uses
FMX.Layouts, FMX.Objects, System.Classes, REST.Json,
System.JSON, System.SysUtils, FMX.Dialogs, TypInfo,
GameObject, PlayerPanzer, CollisionBlock, BotPanzer,
Panzer, MainFr, Helper;
type
TContentKeeper = class
public
procedure SaveContent(Frame: TMainForm);
procedure LoadContent(Frame: TMainForm);
end;
implementation
procedure SaveToFile(Str: String);
var
SaveFile: Text;
begin
AssignFile(SaveFile, GetCurrentDir + '\Save.js');
Rewrite(SaveFile);
WriteLn(SaveFile, Str);
CloseFile(SaveFile);
end;
procedure TContentKeeper.SaveContent;
var
JsMainObject: TJSONObject;
JsArray: TJSONArray;
JsObject: TJSONObject;
i: Integer;
begin
JsArray := TJSONArray.Create;
for i := 0 to Frame.recGameContentBg.ComponentCount - 1 do
begin
JsObject := TJSONObject.Create;
with (Frame.recGameContentBg.Components[i] as TGameObject) do
begin
JsObject.AddPair(TJSONPair.Create.Create('ClassName', ClassName));
JsObject.AddPair(TJSONPair.Create.Create('PositionX', Position.X.ToString));
JsObject.AddPair(TJSONPair.Create.Create('PositionY', Position.Y.ToString));
JsObject.AddPair(TJSONPair.Create.Create('BlockType', GetEnumName(TypeInfo(TGameObjectType), Ord(BlockType))));
if ClassType = TPlayerPanzer then
with Frame.recGameContentBg.Components[i] as TPlayerPanzer do
JsObject.AddPair(TJSONPair.Create.Create('Side', GetEnumName(TypeInfo(TSide), Ord(Side))));
end;
JsArray.AddElement(JsObject);
end;
JsMainObject := TJSONObject.Create;
JsMainObject.AddPair('Data', JsArray);
SaveToFile(JsMainObject.ToString);
end;
function LoadFromFile: string;
var
LoadFile: Text;
tmpStr: string;
begin
Result := '';
if FileExists(GetCurrentDir + '\Save.js') then
begin
AssignFile(LoadFile, GetCurrentDir + '\Save.js');
Reset(LoadFile);
while not Eof(LoadFile) do
begin
ReadLn(LoadFile, tmpStr);
Result := Result + tmpStr;
end;
CloseFile(LoadFile);
end;
end;
procedure TContentKeeper.LoadContent(Frame: TMainForm);
var
JsMainObject: TJSONObject;
JsArray: TJSONArray;
i: Integer;
begin
JsMainObject := TJSonObject.ParseJSONValue(TEncoding.ASCII.GetBytes(LoadFromFile), 0) as TJSONObject;
if Assigned(JsMainObject) then
begin
JsArray := (JsMainObject.GetValue('Data') as TJSONArray);
for i := 0 to JsArray.Count - 1 do
begin
with (JsArray.Items[i] as TJSONObject) do
begin
if GetValue('ClassName').Value = 'TCollisionBlock' then
Frame.DrawCollisionBlock(
GetValue('PositionX').Value.ToInteger,
GetValue('PositionY').Value.ToInteger,
//GetValue('BlockType').Value.ToInteger,
TGameObjectType.SteelWall
);
if GetValue('ClassName').Value = 'TPlayerPanzer' then
Frame.DrawPlayerPanzer(
GetValue('PositionX').Value.ToInteger,
GetValue('PositionY').Value.ToInteger,
TSide.Top
);
//GetPropValue(TSide, GetValue('Side').Value.ToInteger, True);
end;
end;
end;
JsMainObject.Free;
end;
end.
|
unit LayoutManager;
interface
uses
Windows,
LayoutItem,
Controls,
SysUtils,
Classes;
type
TLayoutItemVisualSettingsHolder = class
protected
FLayoutItem: TLayoutItem;
public
destructor Destroy; override;
constructor Create;
published
property LayoutItem: TLayoutItem read FLayoutItem write FLayoutItem;
end;
TLayoutItemVisualSettingsHolders = class;
TLayoutItemVisualSettingsHoldersEnumerator = class (TListEnumerator)
protected
function GetCurrentLayoutItemVisualSettingsHolder:
TLayoutItemVisualSettingsHolder;
public
constructor Create(
LayoutItemVisualSettingsHolders: TLayoutItemVisualSettingsHolders
);
property Current: TLayoutItemVisualSettingsHolder
read GetCurrentLayoutItemVisualSettingsHolder;
end;
TLayoutItemVisualSettingsHolders = class (TList)
protected
function GetLayoutItemVisualSettingsHolderByIndex(
Index: Integer
): TLayoutItemVisualSettingsHolder;
procedure SetLayoutItemVisualSettingsHolderByIndex(
Index: Integer;
Value: TLayoutItemVisualSettingsHolder
);
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
function IndexOfByLayoutItem(LayoutItem: TLayoutItem): Integer;
function FindByLayoutItem(LayoutItem: TLayoutItem): TLayoutItemVisualSettingsHolder;
procedure RemoveByLayoutItem(LayoutItem: TLayoutItem);
procedure RemoveByLayoutItemForControl(Control: TControl);
function GetEnumerator: TLayoutItemVisualSettingsHoldersEnumerator;
property Items[Index: Integer]: TLayoutItemVisualSettingsHolder
read GetLayoutItemVisualSettingsHolderByIndex
write SetLayoutItemVisualSettingsHolderByIndex; default;
end;
TLayoutManager = class abstract (TLayoutItem)
protected
FLayoutItemVisualSettingsHolders: TLayoutItemVisualSettingsHolders;
function CreateLayoutItemVisualSettingsHolder(
LayoutItem: TLayoutItem
): TLayoutItemVisualSettingsHolder; virtual; abstract;
function CreateLayoutItemVisualSettingsHolderList:
TLayoutItemVisualSettingsHolders; virtual;
procedure ApplyVisualSettingsForLayoutItem(
LayoutItemVisualSettingsHolder: TLayoutItemVisualSettingsHolder
); virtual; abstract;
function CreateAndAddVisualSettingsHolderFor(LayoutItem: TLayoutItem): TLayoutItemVisualSettingsHolder; overload;
function CreateAndAddVisualSettingsHolderFor(Control: TControl): TLayoutItemVisualSettingsHolder; overload;
function CreateAndAddVisualSettingsHolderFor(LayoutManager: TLayoutManager): TLayoutItemVisualSettingsHolder; overload;
function GetIndexOfLayoutItemVisualSettingsHolder(
LayoutItemVisualSettingsHolder: TLayoutItemVisualSettingsHolder
): Integer;
function CreateLayoutItemFor(Control: TControl): TLayoutItem;
function GetLayoutItemCount: Integer;
procedure Initialize;
public
destructor Destroy; override;
constructor Create;
function AddLayoutItem(LayoutItem: TLayoutItem): Integer;
function AddControl(Control: TControl): Integer;
function AddLayoutManager(LayoutManager: TLayoutManager): Integer;
procedure RemoveLayoutItem(LayoutItem: TLayoutItem);
procedure RemoveLayoutItemByIndex(const Index: Integer);
procedure RemoveControl(Control: TControl);
procedure RemoveLayoutManager(LayoutManager: TLayoutManager);
function GetLayoutItemByIndex(Index: Integer): TLayoutItem;
function FindVisualSettingsHolderFor(LayoutItem: TLayoutItem): TLayoutItemVisualSettingsHolder;
procedure ApplyLayout; virtual;
property LayoutItemCount: Integer read GetLayoutItemCount;
property LayoutItems[Index: Integer]: TLayoutItem
read GetLayoutItemByIndex; default;
end;
TLayoutManagerBuilder = class abstract
protected
FLayoutManager: TLayoutManager;
function CreateLayoutManager: TLayoutManager; virtual; abstract;
public
constructor Create; virtual;
destructor Destroy; override;
function AddControl(Control: TControl): TLayoutManagerBuilder; overload;
function AddControls(Controls: array of TControl): TLayoutManagerBuilder; overload;
function AddLayoutManager(LayoutManager: TLayoutManager): TLayoutManagerBuilder; overload;
function AddLayoutManagers(LayoutManagers: array of TLayoutManager): TLayoutManagerBuilder; overload;
function Build: TLayoutManager;
function BuildAndDestroy: TLayoutManager;
end;
implementation
uses
ControlLayoutItem;
{ TLayoutItemVisualSettingsHolder }
constructor TLayoutItemVisualSettingsHolder.Create;
begin
inherited;
end;
destructor TLayoutItemVisualSettingsHolder.Destroy;
begin
FreeAndNil(FLayoutItem);
inherited;
end;
{ TLayoutItemVisualSettingsHoldersEnumerator }
constructor TLayoutItemVisualSettingsHoldersEnumerator.Create(
LayoutItemVisualSettingsHolders: TLayoutItemVisualSettingsHolders);
begin
inherited Create(LayoutItemVisualSettingsHolders);
end;
function TLayoutItemVisualSettingsHoldersEnumerator.GetCurrentLayoutItemVisualSettingsHolder: TLayoutItemVisualSettingsHolder;
begin
Result := TLayoutItemVisualSettingsHolder(GetCurrent);
end;
{ TLayoutItemVisualSettingsHolders }
function TLayoutItemVisualSettingsHolders.FindByLayoutItem(
LayoutItem: TLayoutItem
): TLayoutItemVisualSettingsHolder;
var SearchLayoutItemVisualSettingsHolderIndex: Integer;
begin
SearchLayoutItemVisualSettingsHolderIndex := IndexOfByLayoutItem(LayoutItem);
if SearchLayoutItemVisualSettingsHolderIndex >= 0 then
Result := Self[SearchLayoutItemVisualSettingsHolderIndex]
else Result := nil;
end;
function TLayoutItemVisualSettingsHolders.GetEnumerator: TLayoutItemVisualSettingsHoldersEnumerator;
begin
Result := TLayoutItemVisualSettingsHoldersEnumerator.Create(Self);
end;
function TLayoutItemVisualSettingsHolders.
GetLayoutItemVisualSettingsHolderByIndex(
Index: Integer
): TLayoutItemVisualSettingsHolder;
begin
Result := TLayoutItemVisualSettingsHolder(Get(Index));
end;
function TLayoutItemVisualSettingsHolders.IndexOfByLayoutItem(
LayoutItem: TLayoutItem): Integer;
begin
for Result := 0 to Count - 1 do
if Self[Result].LayoutItem = LayoutItem then
Exit;
Result := -1;
end;
procedure TLayoutItemVisualSettingsHolders.Notify(Ptr: Pointer;
Action: TListNotification);
begin
if (Action = lnDeleted) and Assigned(Ptr) then
TLayoutItemVisualSettingsHolder(Ptr).Free;
end;
procedure TLayoutItemVisualSettingsHolders.RemoveByLayoutItem(
LayoutItem: TLayoutItem
);
var I: Integer;
begin
for I := 0 to Count - 1 do
if Self[I].LayoutItem = LayoutItem then begin
Delete(I);
Exit;
end;
end;
procedure TLayoutItemVisualSettingsHolders.RemoveByLayoutItemForControl(
Control: TControl
);
var I: Integer;
begin
for I := 0 to Count - 1 do
if
(Self[I].LayoutItem is TControlLayoutItem) and
((Self[I].LayoutItem as TControlLayoutItem).Control = Control)
then begin
Delete(I);
Exit;
end;
end;
procedure TLayoutItemVisualSettingsHolders.
SetLayoutItemVisualSettingsHolderByIndex(
Index: Integer;
Value: TLayoutItemVisualSettingsHolder
);
begin
Put(Index, Value);
end;
{ TLayoutManager }
function TLayoutManager.AddControl(Control: TControl): Integer;
begin
Result := AddLayoutItem(CreateLayoutItemFor(Control));
end;
function TLayoutManager.AddLayoutItem(LayoutItem: TLayoutItem): Integer;
begin
Result :=
GetIndexOfLayoutItemVisualSettingsHolder(
CreateAndAddVisualSettingsHolderFor(LayoutItem)
);
end;
function TLayoutManager.AddLayoutManager(
LayoutManager: TLayoutManager): Integer;
begin
Result := AddLayoutItem(LayoutManager as TLayoutItem);
end;
procedure TLayoutManager.ApplyLayout;
var LayoutItemVisualSettingsHolder: TLayoutItemVisualSettingsHolder;
begin
for
LayoutItemVisualSettingsHolder in
FLayoutItemVisualSettingsHolders
do begin
if LayoutItemVisualSettingsHolder.LayoutItem is TLayoutManager then
TLayoutManager(LayoutItemVisualSettingsHolder.LayoutItem).ApplyLayout;
ApplyVisualSettingsForLayoutItem(LayoutItemVisualSettingsHolder);
end;
end;
constructor TLayoutManager.Create;
begin
inherited;
Initialize;
end;
function TLayoutManager.CreateAndAddVisualSettingsHolderFor(
LayoutItem: TLayoutItem
): TLayoutItemVisualSettingsHolder;
begin
Result := CreateLayoutItemVisualSettingsHolder(LayoutItem);
Result.LayoutItem := LayoutItem;
FLayoutItemVisualSettingsHolders.Add(Result);
end;
function TLayoutManager.CreateAndAddVisualSettingsHolderFor(
Control: TControl): TLayoutItemVisualSettingsHolder;
begin
Result := CreateAndAddVisualSettingsHolderFor(TControlLayoutItem.Create(Control));
end;
function TLayoutManager.CreateAndAddVisualSettingsHolderFor(
LayoutManager: TLayoutManager): TLayoutItemVisualSettingsHolder;
begin
Result := CreateAndAddVisualSettingsHolderFor(LayoutManager as TLayoutItem);
end;
function TLayoutManager.CreateLayoutItemFor(Control: TControl): TLayoutItem;
begin
Result := TControlLayoutItem.Create(Control);
end;
function TLayoutManager.CreateLayoutItemVisualSettingsHolderList: TLayoutItemVisualSettingsHolders;
begin
Result := TLayoutItemVisualSettingsHolders.Create;
end;
destructor TLayoutManager.Destroy;
begin
FreeAndNil(FLayoutItemVisualSettingsHolders);
inherited;
end;
function TLayoutManager.FindVisualSettingsHolderFor(
LayoutItem: TLayoutItem
): TLayoutItemVisualSettingsHolder;
begin
Result := FLayoutItemVisualSettingsHolders.FindByLayoutItem(LayoutItem);
end;
function TLayoutManager.GetLayoutItemByIndex(
Index: Integer
): TLayoutItem;
begin
if (Index < 0) or (Index >= FLayoutItemVisualSettingsHolders.Count) then
Result := nil
else Result := FLayoutItemVisualSettingsHolders[Index].LayoutItem;
end;
function TLayoutManager.GetLayoutItemCount: Integer;
begin
Result := FLayoutItemVisualSettingsHolders.Count;
end;
function TLayoutManager.GetIndexOfLayoutItemVisualSettingsHolder(
LayoutItemVisualSettingsHolder: TLayoutItemVisualSettingsHolder
): Integer;
begin
Result :=
FLayoutItemVisualSettingsHolders.IndexOf(
LayoutItemVisualSettingsHolder
);
end;
procedure TLayoutManager.Initialize;
begin
FLayoutItemVisualSettingsHolders :=
CreateLayoutItemVisualSettingsHolderList;
end;
procedure TLayoutManager.RemoveControl(Control: TControl);
begin
FLayoutItemVisualSettingsHolders.RemoveByLayoutItemForControl(Control);
end;
procedure TLayoutManager.RemoveLayoutItem(LayoutItem: TLayoutItem);
begin
FLayoutItemVisualSettingsHolders.RemoveByLayoutItem(LayoutItem);
end;
procedure TLayoutManager.RemoveLayoutItemByIndex(const Index: Integer);
begin
FLayoutItemVisualSettingsHolders.Delete(Index);
end;
procedure TLayoutManager.RemoveLayoutManager(LayoutManager: TLayoutManager);
begin
FLayoutItemVisualSettingsHolders.RemoveByLayoutItem(LayoutManager);
end;
{ TLayoutManagerBuilder }
function TLayoutManagerBuilder.AddControls(
Controls: array of TControl
): TLayoutManagerBuilder;
var Control: TControl;
begin
for Control in Controls do
FLayoutManager.AddControl(Control);
Result := Self;
end;
function TLayoutManagerBuilder.AddControl(Control: TControl): TLayoutManagerBuilder;
begin
FLayoutManager.AddControl(Control);
Result := Self;
end;
function TLayoutManagerBuilder.AddLayoutManagers(
LayoutManagers: array of TLayoutManager
): TLayoutManagerBuilder;
var LayoutManager: TLayoutManager;
begin
for LayoutManager in LayoutManagers do
FLayoutManager.AddLayoutManager(LayoutManager);
Result := Self;
end;
function TLayoutManagerBuilder.AddLayoutManager(
LayoutManager: TLayoutManager
): TLayoutManagerBuilder;
begin
FLayoutManager.AddLayoutManager(LayoutManager);
Result := Self;
end;
function TLayoutManagerBuilder.Build: TLayoutManager;
begin
Result := FLayoutManager;
end;
function TLayoutManagerBuilder.BuildAndDestroy: TLayoutManager;
begin
Result := Build;
FLayoutManager := nil;
Destroy;
end;
constructor TLayoutManagerBuilder.Create;
begin
inherited;
FLayoutManager := CreateLayoutManager;
end;
destructor TLayoutManagerBuilder.Destroy;
begin
inherited;
end;
end.
|
unit RepositorioCaixa;
interface
uses DB, Auditoria, Repositorio;
type
TRepositorioCaixa = class(TRepositorio)
protected
function Get (Dataset :TDataSet) :TObject; overload; override;
function GetNomeDaTabela :String; override;
function GetIdentificador(Objeto :TObject) :Variant; override;
function GetRepositorio :TRepositorio; override;
protected
function SQLGet :String; override;
function SQLSalvar :String; override;
function SQLGetAll :String; override;
function SQLRemover :String; override;
function SQLGetExiste(campo: String): String; override;
protected
function IsInsercao(Objeto :TObject) :Boolean; override;
protected
procedure SetParametros (Objeto :TObject ); override;
procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override;
protected
procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); override;
procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); override;
procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); override;
end;
implementation
uses SysUtils, Caixa;
{ TRepositorioCaixa }
function TRepositorioCaixa.Get(Dataset: TDataSet): TObject;
var
Caixa :TCaixa;
begin
Caixa:= TCaixa.Create;
Caixa.codigo := self.FQuery.FieldByName('codigo').AsInteger;
Caixa.data_abertura := self.FQuery.FieldByName('data_abertura').AsDateTime;
Caixa.valor_abertura := self.FQuery.FieldByName('valor_abertura').AsFloat;
Caixa.data_fechamento := self.FQuery.FieldByName('data_fechamento').AsDateTime;
Caixa.valor_fechamento := self.FQuery.FieldByName('valor_fechamento').AsFloat;
result := Caixa;
end;
function TRepositorioCaixa.GetIdentificador(Objeto: TObject): Variant;
begin
result := TCaixa(Objeto).Codigo;
end;
function TRepositorioCaixa.GetNomeDaTabela: String;
begin
result := 'CAIXA';
end;
function TRepositorioCaixa.GetRepositorio: TRepositorio;
begin
result := TRepositorioCaixa.Create;
end;
function TRepositorioCaixa.IsInsercao(Objeto: TObject): Boolean;
begin
result := (TCaixa(Objeto).Codigo <= 0);
end;
procedure TRepositorioCaixa.SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject);
var
CaixaAntigo :TCaixa;
CaixaNovo :TCaixa;
begin
CaixaAntigo := (AntigoObjeto as TCaixa);
CaixaNovo := (Objeto as TCaixa);
if (CaixaAntigo.data_abertura <> CaixaNovo.data_abertura) then
Auditoria.AdicionaCampoAlterado('data_abertura', DateTimeToStr(CaixaAntigo.data_abertura), DateTimeToStr(CaixaNovo.data_abertura));
if (CaixaAntigo.valor_abertura <> CaixaNovo.valor_abertura) then
Auditoria.AdicionaCampoAlterado('valor_abertura', FloatToStr(CaixaAntigo.valor_abertura), FloatToStr(CaixaNovo.valor_abertura));
if (CaixaAntigo.data_fechamento <> CaixaNovo.data_fechamento) then
Auditoria.AdicionaCampoAlterado('data_fechamento', DateTimeToStr(CaixaAntigo.data_fechamento), DateTimeToStr(CaixaNovo.data_fechamento));
if (CaixaAntigo.valor_fechamento <> CaixaNovo.valor_fechamento) then
Auditoria.AdicionaCampoAlterado('valor_fechamento', FloatToStr(CaixaAntigo.valor_fechamento), FloatToStr(CaixaNovo.valor_fechamento));
end;
procedure TRepositorioCaixa.SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject);
var
Caixa :TCaixa;
begin
Caixa := (Objeto as TCaixa);
Auditoria.AdicionaCampoExcluido('codigo' , IntToStr(Caixa.codigo));
Auditoria.AdicionaCampoExcluido('data_abertura' , DateTimeToStr(Caixa.data_abertura));
Auditoria.AdicionaCampoExcluido('valor_abertura' , FloatToStr(Caixa.valor_abertura));
Auditoria.AdicionaCampoExcluido('data_fechamento' , DateTimeToStr(Caixa.data_fechamento));
Auditoria.AdicionaCampoExcluido('valor_fechamento', FloatToStr(Caixa.valor_fechamento));
end;
procedure TRepositorioCaixa.SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject);
var
Caixa :TCaixa;
begin
Caixa := (Objeto as TCaixa);
Auditoria.AdicionaCampoIncluido('codigo' , IntToStr(Caixa.codigo));
Auditoria.AdicionaCampoIncluido('data_abertura' , DateTimeToStr(Caixa.data_abertura));
Auditoria.AdicionaCampoIncluido('valor_abertura' , FloatToStr(Caixa.valor_abertura));
Auditoria.AdicionaCampoIncluido('data_fechamento' , DateTimeToStr(Caixa.data_fechamento));
Auditoria.AdicionaCampoIncluido('valor_fechamento', FloatToStr(Caixa.valor_fechamento));
end;
procedure TRepositorioCaixa.SetIdentificador(Objeto: TObject; Identificador: Variant);
begin
TCaixa(Objeto).Codigo := Integer(Identificador);
end;
procedure TRepositorioCaixa.SetParametros(Objeto: TObject);
var
Caixa :TCaixa;
begin
Caixa := (Objeto as TCaixa);
self.FQuery.ParamByName('codigo').AsInteger := Caixa.codigo;
self.FQuery.ParamByName('data_abertura').AsDateTime := Caixa.data_abertura;
self.FQuery.ParamByName('valor_abertura').AsFloat := Caixa.valor_abertura;
self.FQuery.ParamByName('data_fechamento').AsDateTime := Caixa.data_fechamento;
self.FQuery.ParamByName('valor_fechamento').AsFloat := Caixa.valor_fechamento;
end;
function TRepositorioCaixa.SQLGet: String;
begin
result := 'select * from CAIXA where codigo = :ncod';
end;
function TRepositorioCaixa.SQLGetAll: String;
begin
result := 'select * from CAIXA';
end;
function TRepositorioCaixa.SQLGetExiste(campo: String): String;
begin
result := 'select'+ campo +' from CAIXA where '+ campo +' = :ncampo';
end;
function TRepositorioCaixa.SQLRemover: String;
begin
result := ' delete from CAIXA where codigo = :codigo ';
end;
function TRepositorioCaixa.SQLSalvar: String;
begin
result := 'update or insert into CAIXA (CODIGO ,DATA_ABERTURA ,VALOR_ABERTURA ,DATA_FECHAMENTO ,VALOR_FECHAMENTO) '+
' values ( :CODIGO , :DATA_ABERTURA , :VALOR_ABERTURA , :DATA_FECHAMENTO , :VALOR_FECHAMENTO) ';
end;
end.
|
unit OAuth2.Intuit;
interface
uses
REST.Client
, REST.Authenticator.OAuth
;
type
TIntuitOAuth2 = class(TOAuth2Authenticator)
private
FRefreshExpiry: TDateTime;
public
procedure ChangeAuthCodeToAccesToken;
procedure ChangeRefreshTokenToAccesToken;
published
property RefreshExpiry: TDateTime read FRefreshExpiry write FRefreshExpiry;
property AccessToken;
property AccessTokenEndpoint;
property AccessTokenExpiry;
property AuthCode;
property AuthorizationEndpoint;
property ClientID;
property ClientSecret;
property LocalState;
property RedirectionEndpoint;
property RefreshToken;
property ResponseType;
property Scope;
property TokenType;
end;
implementation
uses
REST.Consts,
REST.Types,
System.NetEncoding,
System.SysUtils,
System.DateUtils;
{ TIntuitOAuth2 }
procedure TIntuitOAuth2.ChangeRefreshTokenToAccesToken;
var
LClient: TRestClient;
LRequest: TRESTRequest;
LToken: string;
LIntValue: int64;
AuthData : String;
begin
// we do need an authorization-code here, because we want
// to send it to the servce and exchange the code into an
// access-token.
// if AuthCode = '' then
// raise EOAuth2Exception.Create(SAuthorizationCodeNeeded);
LClient := TRestClient.Create(AccessTokenEndpoint);
try
// LClient.ProxyServer := 'localhost';
// LClient.ProxyPort := 5555;
LRequest := TRESTRequest.Create(LClient); // The LClient now "owns" the Request and will free it.
LRequest.Method := TRESTRequestMethod.rmPOST;
LRequest.AddAuthParameter('refresh_token', RefreshToken, TRESTRequestParameterKind.pkGETorPOST);
LRequest.AddAuthParameter('grant_type', 'refresh_token', TRESTRequestParameterKind.pkGETorPOST);
AuthData := 'Basic ' +TNetEncoding.Base64.Encode(ClientID+':'+ClientSecret);
AuthData := AuthData.Replace(#10,'').Replace(#13,''); // remove crlf
LRequest.AddAuthParameter('Authorization', AuthData, TRESTRequestParameterKind.pkHTTPHEADER,[TRESTRequestParameterOption.poDoNotEncode]);
LRequest.Execute;
if LRequest.Response.GetSimpleValue('access_token', LToken) then
AccessToken := LToken;
if LRequest.Response.GetSimpleValue('refresh_token', LToken) then
RefreshToken := LToken;
// detect token-type. this is important for how using it later
if LRequest.Response.GetSimpleValue('token_type', LToken) then
TokenType := OAuth2TokenTypeFromString(LToken);
// if provided by the service, the field "expires_in" contains
// the number of seconds an access-token will be valid
if LRequest.Response.GetSimpleValue('expires_in', LToken) then
begin
LIntValue := StrToIntdef(LToken, -1);
if (LIntValue > -1) then
AccessTokenExpiry := IncSecond(Now, LIntValue)
else
AccessTokenExpiry := 0.0;
end;
if LRequest.Response.GetSimpleValue('x_refresh_token_expires_in', LToken) then
begin
LIntValue := StrToIntdef(LToken, -1);
if (LIntValue > -1) then
FRefreshExpiry := IncSecond(Now, LIntValue)
else
FRefreshExpiry := 0.0;
end;
// an authentication-code may only be used once.
// if we succeeded here and got an access-token, then
// we do clear the auth-code as is is not valid anymore
// and also not needed anymore.
if (AccessToken <> '') then
AuthCode := '';
finally
LClient.DisposeOf;
end;
end;
procedure TIntuitOAuth2.ChangeAuthCodeToAccesToken;
var
LClient: TRestClient;
LRequest: TRESTRequest;
LToken: string;
LIntValue: int64;
AuthData : String;
begin
// we do need an authorization-code here, because we want
// to send it to the servce and exchange the code into an
// access-token.
if AuthCode = '' then
raise EOAuth2Exception.Create(SAuthorizationCodeNeeded);
LClient := TRestClient.Create(AccessTokenEndpoint);
try
// LClient.ProxyServer := 'localhost';
// LClient.ProxyPort := 5555;
LRequest := TRESTRequest.Create(LClient); // The LClient now "owns" the Request and will free it.
LRequest.Method := TRESTRequestMethod.rmPOST;
LRequest.AddAuthParameter('code', AuthCode, TRESTRequestParameterKind.pkGETorPOST);
LRequest.AddAuthParameter('redirect_uri', RedirectionEndpoint, TRESTRequestParameterKind.pkGETorPOST,[TRESTRequestParameterOption.poDoNotEncode]);
LRequest.AddAuthParameter('grant_type', 'authorization_code', TRESTRequestParameterKind.pkGETorPOST);
AuthData := 'Basic ' +TNetEncoding.Base64.Encode(ClientID+':'+ClientSecret);
AuthData := AuthData.Replace(#10,'').Replace(#13,''); // remove crlf
LRequest.AddAuthParameter('Authorization', AuthData, TRESTRequestParameterKind.pkHTTPHEADER,[TRESTRequestParameterOption.poDoNotEncode]);
LRequest.Execute;
if LRequest.Response.GetSimpleValue('access_token', LToken) then
AccessToken := LToken;
if LRequest.Response.GetSimpleValue('refresh_token', LToken) then
RefreshToken := LToken;
// detect token-type. this is important for how using it later
if LRequest.Response.GetSimpleValue('token_type', LToken) then
TokenType := OAuth2TokenTypeFromString(LToken);
// if provided by the service, the field "expires_in" contains
// the number of seconds an access-token will be valid
if LRequest.Response.GetSimpleValue('expires_in', LToken) then
begin
LIntValue := StrToIntdef(LToken, -1);
if (LIntValue > -1) then
AccessTokenExpiry := IncSecond(Now, LIntValue)
else
AccessTokenExpiry := 0.0;
end;
if LRequest.Response.GetSimpleValue('x_refresh_token_expires_in', LToken) then
begin
LIntValue := StrToIntdef(LToken, -1);
if (LIntValue > -1) then
FRefreshExpiry := IncSecond(Now, LIntValue)
else
FRefreshExpiry := 0.0;
end;
// an authentication-code may only be used once.
// if we succeeded here and got an access-token, then
// we do clear the auth-code as is is not valid anymore
// and also not needed anymore.
if (AccessToken <> '') then
AuthCode := '';
finally
LClient.DisposeOf;
end;
end;
end.
|
unit Ugame;
interface
uses
Classes, SysUtils, UDeck, UCard, UPlayer;
type
{ TGame }
TGame = class abstract
private
var
FgameDeck: TDeck;
FplayerArray: array of TPLayer;
FnumPlayers: integer;
FhandSize: integer;
function getNumPlayers: integer;
public
constructor Create(AnumPlayers:integer; AcardsPerPlayer:integer);
procedure SortAllHandsBySuit(); //sorts cards for all players
function PlayerHandToStr(playerNumber:integer):string;
function DeckToStr(): string;
procedure DealAllCards();
function GetPlayerCardsInHand(playerNumber:integer):integer; //get number of cards in hand
function GetPlayerCard(playerNumber:integer; cardIndex:integer):TCard; // get the ith card
end;
implementation
constructor TGame.Create(AnumPlayers:integer; AcardsPerPlayer:integer);
var
playerIndex:integer;
begin
FhandSize:= AcardsPerPlayer;
FnumPlayers:= AnumPlayers;
SetLength(FplayerArray, AnumPlayers);
FgameDeck:=TDeck.Create();
FgameDeck.ShuffleDeck();
//Create the TPlayer objects
for playerIndex:= 0 to FnumPlayers-1 do
FplayerArray[playerIndex]:= TPlayer.create();
end;
procedure TGame.SortAllHandsBySuit();
var
i: integer;
begin
for i:= 0 to FnumPlayers-1 do
begin
TPlayer(FplayerArray[i]).SortSuits();
end;
end;
procedure TGame.DealAllCards();
var
cardsDealtPerHand:integer;
playerIndex:integer;
begin
for cardsDealtPerHand:= 0 to FhandSize-1 do
begin
for playerIndex:=0 to FnumPlayers-1 do
begin
TPlayer(FplayerArray[playerIndex]).AddCard(FgameDeck.DealTopCard());
end;
end;
end;
function TGame.getNumPlayers(): integer;
begin
result:=FnumPlayers;
end;
function TGame.GetPlayerCard(playerNumber, cardIndex: integer): TCard;
begin
result:= FplayerArray[playerNumber].getCard(cardIndex);
end;
function TGame.getPlayerCardsInHand(playerNumber: integer): integer;
begin
result:= Tplayer(FplayerArray[playerNumber]).numCards;
end;
function TGame.PlayerHandToStr(playerNumber:integer):string;
begin
result:= Tplayer(FplayerArray[playerNumber]).HandToStr();
end;
function TGame.DeckToStr(): string;
begin
if FgameDeck.GetCardsLeft() <> 0 then
result:= FgameDeck.DeckToStr
else
result:= 'deck is empty';
end;
end.
|
unit uLibrary;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fgl;
{$REGION ERRORS}
const
ERROR_DUPLICATE_KEY = 1;
ERROR_ARGUMENT_ISEMPTY = 2;
ERROR_SAX_PARSER = 3;
resourcestring
sERROR_DUPLICATE_KEY = 'Дубликат ключа';
sERROR_ARGUMENT_ISEMPTY = 'Не указано значение аргумента';
sERROR_EMPTY_TAG_NAME = 'Найден пустой тег';
sERROR_EMPTY_ATTR_NAME = 'Найден пустой аттрибут';
{$ENDREGION ERRORS}
{$REGION Types, Declarations etc.}
resourcestring
// Строковое представление типов переменных
sUINT8L = 'UINT8L';
sUINT8H = 'UINT8H';
sUINT16 = 'UINT16';
sSINT16 = 'SINT16';
sUINT32 = 'UINT32';
sSINT32 = 'SINT32';
sUINTIP = 'UINTIP';
sFLOAT = 'FLOAT';
sBITMAP16 = 'BITMAP16';
sBITMAP32 = 'BITMAP32';
sBOOL = 'BOOL';
sBOOL_EXT = 'BOOL_EXT';
sIO_DATA = 'IO_DATA';
sID_DATA = 'ID_DATA';
sID_VERSION = 'ID_VERSION';
sID_SN = 'ID_SN';
sID_HARD = 'ID_HARD';
sID_SOFT = 'ID_SOFT';
sID_PROJECT = 'ID_PROJECT';
sID_BOX = 'ID_BOX';
sID_PLANT = 'ID_PLANT';
sID_TYPEFIRMWARE = 'ID_TYPEFIRMWARE';
sPROC = 'PROC';
sUNKNOWN = 'UNKNOWN';
// Строковое представление уровня доступа
sUSER = 'Пользователь';
sDEVELOPER = 'Разработчик';
sSERVICE = 'Сервис';
// Строковое представление разновидности переменной
sNormal = 'Обычная';
sGauge = 'Калибровочная';
// Строковое представление разновидности регистров
sHolding = 'HOLDING';
sInput = 'INPUT';
// Строковое представление синхронизации: 0 Двунаправленный, 1 Принудительный, 2 Только запись
sBedirectional = 'Двунаправленный';
sForce = 'Принудительный';
sReadOnly = 'Только запись';
type
// Разделы бибилиотеки: разработчика, пользователя
TTypeSublibrary = (slDeveloper, slUser);
// Типы сигнатур: автоопределение, RCCU, автоопределение недоступно (старые)
TTypeSignature = (sgNone = 0, sgAuto, sgRccu);
// Типы bootloader'а: 1 - без записи в 120-124 смещение, 2 - с записью, 3 - с шифрованием
TTypeBootloader = (bl1 = 1, bl2, bl3);
// Тип регистра: Holding, Input
TTypeRegister = (trHolding, trInput);
TTypeRegisters = array[TTypeRegister] of String;
// Уровень доступа: пользователь, производитель, сервис
TAccess = (acUser, acDeveloper, acService);
TAccesses = array[TAccess] of String;
// Разновидность переменной: обычный, калибровочный
TKind = (kdNormal, kdGauge);
TKinds = array[TKind] of String;
// Режимы синхронизации: 0 Двунаправленный, 1 Принудительный, 2 Только запись
TSynchronization = (syBedirectional, syForce, syReadOnly);
TSynchronizations = array[TSynchronization] of String;
// Тип переменной
TVarType = (
vtUINT8L, // младший 8-битная беззнаковая целочисленная 0 .. 255 byte
vtUINT8H, // старшая 8-битная беззнаковая целочисленная 0 .. 255 byte
vtUINT16, // 16-разрядная беззнаковая целочисленная 0 .. 65535 word
vtSINT16, // 16-разрядная знаковая целочисленная -32768 .. -32767 smallint
vtUINT32, // 32-разрядная беззнаковая целочисленная 0 .. -2147483647 dword
vtSINT32, // 32-разрядная знаковая целочисленная -2147483648 .. -2147483647 longint
vtFLOAT, // 32 бита с плавающей запятой single
vtBITMAP16, // 16-разрядная беззнаковая целочисленная 0 .. 65535 word
vtBITMAP32, // 32-разрядная беззнаковая целочисленная 0 .. -2147483647 dword
vtBOOL, // 16-битная
vtBOOL_EXT, // 16-битная
vtUINTIP, // 32-разрядная беззнаковая целочисленная 0 .. -2147483647 dword
vtIO_DATA,
vtID_DATA,
vtID_VERSION,
vtID_SN,
vtID_HARD,
vtID_SOFT,
vtID_TYPEFIRMWARE,
vtID_PROJECT,
vtID_BOX,
vtID_PLANT,
vtPROC,
vtUNKNOWN);
TVarTypes = specialize TFPGMap<String, TVarType>;
{$ENDREGION Types, Declarations etc.}
type
{$REGION BASE}
//////////////////////////////////////////////////////////////////////////////
// BASE
// Базовый интерфейс библиотеки
IBase = interface
['{C55FE7E5-2B4B-4ECA-9E9B-39B823A1627D}']
// Возвращает код ошибки, одновременно сбрасывая его в памяти
function GetLastError: dword;
// Возвращает описание ошибки, в т.ч. системной
function GetErrorDesc(const aError: dword): String;
end;
IDescEnumerator = interface
['{E72BAA4A-E3F3-4C6E-88E3-332B78845ED1}']
function GetCurrent: String;
function MoveNext: Boolean;
property Current: String read GetCurrent;
end;
// Используется для многострочного текста
IDescription = interface(IBase)
['{8D02C3E0-A7D9-49D5-ADBC-6078601AA1B7}']
function GetCount: Integer;
function Add(const S: String): Integer;
procedure Delete(Index: Integer);
procedure Clear;
function GetTextStr: String;
procedure SetTextStr(const Value: String);
function Get(Index: Integer): String;
function GetEnumerator: IDescEnumerator;
property Text: String read GetTextStr write SetTextStr;
property Strings[Index: Integer]: String read Get; default;
property Count: Integer read GetCount;
end;
IMapEnumerator = interface
['{E0F17492-F0E2-4D48-A1E3-8ED9CA6BD25F}']
function GetCurrent: Pointer;
function MoveNext: Boolean;
property Current: Pointer read GetCurrent;
end;
// Используется для переменных, пиклиста, карты битов, когда требуется
// быстрый поиск
generic IMap<TKey, TData> = interface(IBase)
['{834C7C3A-B130-4B4A-9468-B0C02AFDF179}']
function Add(const aKey: TKey): Integer;
function Remove(const aKey: TKey): Integer;
function Find(const aKey: TKey; out Index: Integer): Boolean;
function IndexOf(const aKey: TKey): Integer;
function IndexOfData(const aData: TData): Integer;
function ExtractData(const Item: Pointer): TData;
function ExtractKey(const Item: Pointer): TKey;
function GetDuplicates: TDuplicates;
procedure SetDuplicates(const aDuplicates: TDuplicates);
function GetSorted: Boolean;
procedure SetSorted(aSorted: Boolean);
function GetKey(Index: Integer): TKey;
function GetKeyData(const AKey: TKey): TData;
function GetData(Index: Integer): TData;
function GetCount: Integer;
function GetEnumerator: IMapEnumerator;
property Duplicates: TDuplicates read GetDuplicates write SetDuplicates;
property Keys[Index: Integer]: TKey read GetKey;
property Data[Index: Integer]: TData read GetData;
property Count: Integer read GetCount;
property Sorted: Boolean read GetSorted write SetSorted;
end;
generic IListEnumerator<T> = interface
['{3A2EEF74-2DE4-4B7E-A981-8247DF10708E}']
function GetCurrent: T;
function MoveNext: Boolean;
property Current: T read GetCurrent;
end;
// Используется для неупорядочного списка данных
generic IList<T> = interface(IBase)
['{834C7C3A-B130-4B4A-9468-B0C02AFDF179}']
function Get(Index: Integer): T;
function GetLast: T;
function GetFirst: T;
function Extract(const Item: T): T;
function IndexOf(const Item: T): Integer;
function Remove(const Item: T): Integer;
function GetCount: Integer;
procedure Insert(Index: Integer; const Item: T);
function Add(const Item: T): Integer;
property First: T read GetFirst;
property Last: T read GetLast;
property Count: Integer read GetCount;
property Items[Index: Integer]: T read Get; default;
end;
{$ENDREGION BASE}
//////////////////////////////////////////////////////////////////////////////
// LIBRARY
{
Интерфейсы библиотеки
}
ILibrary = interface;
ISublibrary = interface;
IModule = interface;
IModuleDefine = interface;
IBaseDescription = interface;
IRegisters = interface;
IVars = interface;
IVarDefine = interface;
IBits = interface;
IBitDefine = interface;
IPickList = interface;
IPickItem = interface;
IGroups = interface;
IGroupsList = interface;
IGroup = interface;
IGroupItem = interface;
IPreSets = interface;
IPickLists = interface;
IBitsSet = interface;
{
Главный класс библиотеки
}
ILibrarySpec = specialize IMap<TTypeSublibrary, ISublibrary>;
ILibrary = interface(ILibrarySpec)
['{3080B5EE-8E6E-4113-9AE7-49FDA49CD430}']
property SubLibrary[aTypeModule: TTypeSublibrary]: TData read GetKeyData; default;
end;
{
Библиотека разработчика или пользователя, является разделами библиотеки
}
ISublibrarySpec = specialize IMap<Word, IModule>;
ISublibrary = interface(ISublibrarySpec)
['{060A6576-A6DA-400F-B418-B0D41C5C2640}']
property Module[aUid: Word]: TData read GetKeyData; default;
end;
{
Модуль, относящийся к одному из разделов библиотеки
}
IModule = interface(IBase)
['{A050DFAF-E18A-4272-ACB8-47414201541F}']
function GetUid: Word;
procedure SetUid(const aUid: Word);
function GetName: String;
procedure SetName(const aName: String);
function GetTypeSignature: TTypeSignature;
procedure SetTypeSignature(const aTypeSignature: TTypeSignature);
function GetTypeBootloader: TTypeBootloader;
procedure SetTypeBootloader(const aTypeBootloader: TTypeBootloader);
function GetModuleDefine: IModuleDefine;
property Name: String read GetName write SetName;
property Uid: Word read GetUid write SetUid;
property TypeSignature: TTypeSignature read GetTypeSignature write SetTypeSignature;
property TypeBootloader: TTypeBootloader
read GetTypeBootloader write SetTypeBootloader;
property ModuleDefine: IModuleDefine read GetModuleDefine;
end;
{
Детальное описание модуля
}
IModuleDefine = interface(IBase)
['{4A44E843-C50D-419E-AD6B-55EC62CDC0B6}']
function GetBaseDescription: IBaseDescription;
function GetPreSets: IPreSets;
function GetRegisters: IRegisters;
function GetConfiguration: IGroups;
property BaseDescription: IBaseDescription read GetBaseDescription;
property PreSets: IPreSets read GetPreSets;
property Registers: IRegisters read GetRegisters;
property Configuration: IGroups read GetConfiguration;
end;
{
Назначение модуля и его графическое представление
}
IBaseDescription = interface(IBase)
['{FAA522EF-E8DC-4329-9DB8-11DE590004E3}']
function GetDescription: IDescription;
function GetImage: String;
procedure SetImage(const aImage: String);
property Description: IDescription read GetDescription;
property Image: String read GetImage write SetImage;
end;
{
Предустановленные значения
}
IPreSets = interface(IBase)
['{7D6AA590-3951-46C6-91C5-AF1C42483146}']
function GetPickLists: IPickLists;
function GetBitsSet: IBitsSet;
property PickLists: IPickLists read GetPickLists;
property BitsSet: IBitsSet read GetBitsSet;
end;
{
Предустановленный список значений
}
IPickListsSpec = specialize IMap<string, IPickList>;
IPickLists = interface(IPickListsSpec)
['{1F3FA130-6B3E-444B-A1F9-96AF4AD14FCC}']
property PickLists[aName: string]: TData read GetKeyData; default;
end;
{
Предустановленный список наборов битов
}
IBitsSetSpec = specialize IMap<string, IBits>;
IBitsSet = interface(IBitsSetSpec)
['{86EB0665-CC7B-4A61-9201-37B685FAF1B1}']
property BitsSet[aName: string]: TData read GetKeyData; default;
end;
{
Коллекция регистров
}
IRegistersSpec = specialize IMap<TTypeRegister, IVars>;
IRegisters = interface(IRegistersSpec)
['{060A6576-A6DA-400F-B418-B0D41C5C2640}']
property VarSet[aTypeRegister: TTypeRegister]: TData read GetKeyData; default;
function FindByUid(const aUid: string): IVarDefine;
end;
{
Коллекция переменных одного типа регистра
}
IVarsSpec = specialize IMap<string, IVarDefine>;
IVars = interface(IVarsSpec)
['{04008726-DCE7-41BA-BF4A-25874965B827}']
property VarDefine[aUid: string]: TData read GetKeyData; default;
end;
{
Описание переменной
}
{ IVarDefine }
IVarDefine = interface(IBase)
['{6096EA10-C9C1-4238-92E5-2E379537E3D9}']
function GetAccess: TAccess;
procedure SetAccess(const aAccess: TAccess);
function GetVarType: TVarType;
procedure SetVarType(const aVarType: TVarType);
function GetKind: TKind;
procedure SetKind(const aKind: TKind);
function GetReadAlways: Boolean;
procedure SetReadAlways(const aReadAlways: Boolean);
function GetDescription: IDescription;
function GetMultipler: DWord;
procedure SetMultipler(const aMultipler: DWord);
function GetIndex: Word;
procedure SetIndex(const aIndex: Word);
function GetName: String;
procedure SetName(const aName: String);
function GetTypeRegister: TTypeRegister;
function GetShortDescription: String;
procedure SetShortDescription(const aShortDescription: String);
function GetSingleRequest: Boolean;
procedure SetSingleRequest(const aSingleRequest: Boolean);
function GetUid: String;
function GetVer: String;
procedure SetVer(const aVer: String);
function GetSynchronization: TSynchronization;
procedure SetSynchronization(const aSynchronization: TSynchronization);
procedure SetMeasure(const aMeasure: string);
function GetMeasure: string;
function GetBits: IBits;
procedure SetBits(const aBits: IBits);
function GetPickList: IPickList;
procedure SetPickList(const aPickList: IPickList);
procedure Copy(const aVar: IVarDefine);
property Access: TAccess read GetAccess write SetAccess;
property Description: IDescription read GetDescription;
property Index: Word read GetIndex write SetIndex;
property Kind: TKind read GetKind write SetKind;
property Multipler: DWord read GetMultipler write SetMultipler;
property Name: String read GetName write SetName;
property TypeRegister: TTypeRegister read GetTypeRegister;
property ReadAlways: Boolean read GetReadAlways write SetReadAlways;
property ShortDescription: String read GetShortDescription write SetShortDescription;
property SingleRequest: Boolean read GetSingleRequest write SetSingleRequest;
property Synchronization: TSynchronization
read GetSynchronization write SetSynchronization;
property Uid: String read GetUid;
property VarType: TVarType read GetVarType write SetVarType;
property Ver: String read GetVer write SetVer;
property Bits: IBits read GetBits write SetBits;
property Picklist: IPickList read GetPickList write SetPickList;
property Measure: string read GetMeasure write SetMeasure;
end;
{
Коллекция битов
}
IBitsSpec = specialize IMap<byte, IBitDefine>;
IBits = interface(IBitsSpec)
['{04008726-DCE7-41BA-BF4A-25874965B827}']
function GetName: string;
procedure SetName(const aName: string);
function GetShortDescription: String;
procedure SetShortDescription(const aShortDescription: String);
procedure Clear;
property BitDefine[aBit: byte]: TData read GetKeyData; default;
property Name: string read GetName write SetName;
property ShortDescription: String read GetShortDescription write SetShortDescription;
end;
{
Описание отдельных битов
}
IBitDefine = interface(IBase)
['{2661A677-5958-48CE-ADBE-1E7957F11B56}']
function GetIndex: byte;
procedure SetIndex(const aIndex: byte);
function GetName: string;
procedure SetName(const aName: string);
function GetShortDescription: string;
procedure SetShortDescription(const aShortDescription: string);
function GetDescription: IDescription;
function GetVer: string;
procedure SetVer(const aVer: string);
procedure Copy(const aBit: IBitDefine);
property Index: byte read GetIndex write SetIndex;
property Name: string read GetName write SetName;
property ShortDescription: string read GetShortDescription write SetShortDescription;
property Description: IDescription read GetDescription;
property Ver: string read GetVer write SetVer;
end;
{
Список
}
IPickListSpec = specialize IMap<byte, IPickItem>;
IPickList = interface(IPickListSpec)
['{22C21F01-1341-42AE-BEFE-2B6A219F4BD6}']
function GetName: string;
procedure SetName(const aName: string);
function GetShortDescription: string;
procedure SetShortDescription(const aShortDescription: string);
procedure Clear;
property PickItem[aItem: byte]: TData read GetKeyData; default;
property Name: string read GetName write SetName;
property ShortDescription: string read GetShortDescription write SetShortDescription;
end;
{
Элемент списка
}
IPickItem = interface(IBase)
['{2661A677-5958-48CE-ADBE-1E7957F11B56}']
function GetValue: word;
procedure SetValue(const aValue: word);
function GetName: string;
procedure SetName(const aName: string);
function GetShortDescription: string;
procedure SetShortDescription(const aShortDescription: string);
function GetVer: string;
procedure SetVer(const aVer: string);
function GetDescription: IDescription;
procedure Copy(const aPickItem: IPickItem);
property Value: word read GetValue write SetValue;
property Name: string read GetName write SetName;
property ShortDescription: string read GetShortDescription write SetShortDescription;
property Description: IDescription read GetDescription;
property Ver: String read GetVer write SetVer;
end;
{
Коллекция групп переменных конфигурации
}
IGroups = interface(IBase)
['{4A426538-0847-433E-AA2C-C55E32CD3DB8}']
function GetGroupsList: IGroupsList;
function GetGroup: IGroup;
function GetImageIndex: Integer;
function GetShortDescription: string;
procedure SetImageIndex(const aImageIndex: Integer);
procedure SetShortDescription(const aShortDescription: string);
property GroupsList: IGroupsList read GetGroupsList;
property Group: IGroup read GetGroup;
property ShortDescription: string read GetShortDescription write SetShortDescription;
property ImageIndex: Integer read GetImageIndex write SetImageIndex;
end;
{
Список коллекций групп конфигурации
}
IGroupsListSpec = specialize IList<IGroups>;
IGroupsListEnumeratorSpec = specialize IListEnumerator<IGroups>;
IGroupsList = interface(IGroupsListSpec)
['{0C1A424D-6E27-413F-8C21-2CCF742D5B65}']
function GetEnumerator: IGroupsListEnumeratorSpec;
function AddGroups(const aShortDescription: string = ''): Integer;
function Find(const aShortDescription: string): Integer;
end;
{
Список групп
}
IGroupSpec = specialize IList<IGroupItem>;
IGroupEnumeratorSpec = specialize IListEnumerator<IGroupItem>;
IGroup = interface(IGroupSpec)
['{43255234-E361-4C44-A2BD-CD0D2E43B366}']
function GetEnumerator: IGroupEnumeratorSpec;
function AddGroupItem(const aVarDefine: IVarDefine): Integer;
end;
{
Элемент группы = описание переменной и ее интерфейсное представление
}
IGroupItem = interface(IBase)
['{F18BB969-B619-44EB-AC12-E080BEF43087}']
function GetVarDefine: IVarDefine;
property VarDefine: IVarDefine read GetVarDefine;
end;
{$REGION EXTERNAL}
function GetLibrary(const aFileNames: array of string): ILibrary; external 'library.dll';
procedure CloseLibrary; external 'library.dll';
function GetNewGuid: String; external 'library.dll';
procedure SaveLibrary(const aLibrary: ILibrary); external 'library.dll';
{$ENDREGION EXTERNAL}
var
VarTypes: TVarTypes;
Accesses: TAccesses;
Kinds: TKinds;
TypeRegisters: TTypeRegisters;
Synchronizations: TSynchronizations;
DWordTypes: set of TVarType;
implementation
procedure PopulateVarTypes();
begin
with VarTypes do
begin
Add(sUINT8L, vtUINT8L);
Add(sUINT8H, vtUINT8H);
Add(sUINT16, vtUINT16);
Add(sSINT16, vtSINT16);
Add(sUINT32, vtUINT32);
Add(sSINT32, vtSINT32);
Add(sFLOAT, vtFLOAT);
Add(sBITMAP16, vtBITMAP16);
Add(sBITMAP32, vtBITMAP32);
Add(sBOOL, vtBOOL);
Add(sBOOL_EXT, vtBOOL_EXT);
Add(sIO_DATA, vtIO_DATA);
Add(sID_DATA, vtID_DATA);
Add(sID_VERSION, vtID_VERSION);
Add(sID_SN, vtID_SN);
Add(sID_HARD, vtID_Hard);
Add(sID_SOFT, vtID_SOFT);
Add(sID_TYPEFIRMWARE, vtID_TYPEFIRMWARE);
Add(sID_PROJECT, vtID_PROJECT);
Add(sID_BOX, vtID_BOX);
Add(sID_PLANT, vtID_PLANT);
Add(sPROC, vtPROC);
Add(sUNKNOWN, vtUNKNOWN);
end;
end;
procedure PopulateAccesses;
begin
Accesses[acUser] := sUSER;
Accesses[acDeveloper] := sDeveloper;
Accesses[acService] := sService;
end;
procedure PopulateKinds;
begin
Kinds[kdNormal] := sNormal;
Kinds[kdGauge] := sGauge;
end;
procedure PopulateRegisters;
begin
TypeRegisters[trHolding] := sHolding;
TypeRegisters[trInput] := sInput;
end;
procedure PopulateSynchronization;
begin
Synchronizations[syBedirectional] := sBedirectional;
Synchronizations[syForce] := sForce;
Synchronizations[syReadOnly] := sReadOnly;
end;
initialization
begin
DWordTypes := [vtUINT32, vtSINT32, vtFLOAT, vtBITMAP32, vtBOOL_EXT, vtUINTIP, vtIO_DATA];
VarTypes := TVarTypes.Create;
PopulateVarTypes();
PopulateAccesses();
PopulateKinds();
PopulateRegisters();
PopulateSynchronization();
end;
finalization
begin
FreeAndNil(VarTypes);
end;
end.
|
unit Helper.Message;
interface
uses
System.Classes,
System.UITypes,
System.UIConsts,
System.SysUtils,
FMX.Controls,
FMX.Objects,
FMX.Graphics,
FMX.Layouts,
FMX.Types,
FMX.StdCtrls,
FMX.Effects,
FMX.Dialogs,
FMX.Forms,
Helper.CommonTypes,
FMX.Ani;
type
TMessage = class
private
class var
FLytBackground: TLayout;
FLytButtons: TLayout;
FRctBackground: TRectangle;
FRctMessage: TRectangle;
FRectSbtOk: TRectangle;
FRectSbtYes: TRectangle;
FRectSbtNo: TRectangle;
FBtnOk: TButton;
FBtnYes: TButton;
FBtnNo: TButton;
FSdwMessage: TShadowEffect;
FLblHeader: TLabel;
FLblMessage: TLabel;
FTextColor: string;
FTextFont: string;
FBtnColor: string;
FBackgroundColor: string;
FProcToastFloatAnimationFinish: TProc;
FStyleBook: TStyleBook;
FParent: TControl;
FCloseDialogProc: TInputCloseDialogProc;
class procedure PrepareBackground();
class procedure FRctBackgroundClick(Sender: TObject);
class procedure ButtonClick(Sender: TObject);
class procedure Resize();
class procedure AddButtons(const aMsgTypeButton: TMsgTypeButton = mtbOk);
class procedure ShowMessage();
class procedure ToastFloatAnimationFinish(Sender: TObject);
public
class procedure Hide();
class procedure Show(const ATextColor: string; const ATextFont: string;
const ABtnColor: string; const ABackgroundColor: string;
const aMsg: String = ''; const aTitle: String = '';
const aMsgTypeButton: TMsgTypeButton = mtbOk;
const aMsgType: TMsgType = mtInformation;
const ACloseDialogProc: TInputCloseDialogProc = nil);
class procedure Toast(const aMsg, AFontName: string; const ADelay: Single;
const AProc: TProc = nil);
end;
implementation
{ TMessage }
class procedure TMessage.AddButtons(const aMsgTypeButton: TMsgTypeButton);
procedure ConfiguraRectangle(var aRec: TRectangle; const aAlign: TAlignLayout;
aColor: String);
begin
if not(Assigned(aRec)) then
aRec := TRectangle.Create(Application.MainForm);
aRec.Parent := FLytButtons;
aRec.Visible := True;
aRec.Align := aAlign;
aRec.Stroke.Kind := TBrushKind.None;
aRec.Fill.Color := StringToAlphaColor(aColor);
aRec.Width := aRec.Height;
aRec.ClipChildren := True;
aRec.XRadius := 8;
aRec.YRadius := 8;
end;
procedure ConfiguraBotao(var aBtn: TButton; const aParant: TControl;
const aTexto: String; const aModalResult: TModalResult);
begin
if not(Assigned(aBtn)) then
aBtn := TButton.Create(Application.MainForm);
aBtn.Parent := aParant;
aBtn.StyleLookup := 'btnTransparent';
aBtn.Align := TAlignLayout.Contents;
aBtn.Text := aTexto;
aBtn.StyledSettings := [];
aBtn.Font.Style := [TFontStyle.fsBold];
aBtn.TextSettings.Font.Family := FTextFont;
aBtn.TextSettings.Font.Size := 16;
aBtn.TextSettings.FontColor := StringToAlphaColor('White');
aBtn.CanFocus := False;
aBtn.ModalResult := aModalResult;
aBtn.OnClick := ButtonClick;
end;
begin
if (Assigned(FRectSbtOk)) then
FRectSbtOk.Visible := False;
if (Assigned(FRectSbtYes)) then
FRectSbtYes.Visible := False;
if (Assigned(FRectSbtNo)) then
FRectSbtNo.Visible := False;
case aMsgTypeButton of
mtbOk:
begin
ConfiguraRectangle(FRectSbtOk, TAlignLayout.HorzCenter, FBtnColor);
ConfiguraBotao(FBtnOk, FRectSbtOk, 'OK', idOK);
end;
mtbYesNo:
begin
ConfiguraRectangle(FRectSbtYes, TAlignLayout.Left, FBtnColor);
ConfiguraBotao(FBtnYes, FRectSbtYes, 'Sim', idYes);
ConfiguraRectangle(FRectSbtNo, TAlignLayout.Right, FBtnColor);
ConfiguraBotao(FBtnNo, FRectSbtNo, 'Não', idNo);
FLytButtons.Margins.Left := { FRctMessage.Width - } FRectSbtYes.
Width * 1.2;
FLytButtons.Margins.Right := { FRctMessage.Width - } FRectSbtYes.
Width * 1.2;
end;
mtbLoading:
;
mtbNone:
;
end;
end;
class procedure TMessage.ButtonClick(Sender: TObject);
begin
Hide;
if (TInputCloseDialogProc(FCloseDialogProc) <> nil) then
FCloseDialogProc(TButton(Sender).ModalResult);
Application.ProcessMessages;
end;
class procedure TMessage.FRctBackgroundClick(Sender: TObject);
begin
Hide();
end;
class procedure TMessage.Hide;
begin
FLytBackground.Visible := False;
FParent.SetFocus;
end;
class procedure TMessage.PrepareBackground();
begin
FParent := TControl(Application.MainForm); // FormMain.tbcMain;
if not(Assigned(FLytBackground)) then
FLytBackground := TLayout.Create(Application.MainForm);
FLytBackground.Visible := False;
FLytBackground.Align := TAlignLayout.Contents;
//
{$REGION 'FRctBackground'}
if not(Assigned(FRctBackground)) then
FRctBackground := TRectangle.Create(Application.MainForm);
FRctBackground.Stroke.Kind := TBrushKind.None;
FRctBackground.Fill.Color := StringToAlphaColor('Black');
FRctBackground.Align := TAlignLayout.Contents;
FRctBackground.Parent := FLytBackground;
FRctBackground.OnClick := FRctBackgroundClick;
{$ENDREGION}
//
{$REGION 'FRctMessage'}
if not(Assigned(FRctMessage)) then
FRctMessage := TRectangle.Create(Application.MainForm);
FRctMessage.Stroke.Kind := TBrushKind.None;
FRctMessage.Fill.Color := StringToAlphaColor(FBackgroundColor);
FRctMessage.Align := TAlignLayout.VertCenter;
FRctMessage.Parent := FLytBackground;
FRctMessage.Margins.Left := 20;
FRctMessage.Margins.Right := 20;
FRctMessage.XRadius := 8;
FRctMessage.YRadius := 8;
FRctMessage.BringToFront;
FRctMessage.Height := 100;
FSdwMessage := TShadowEffect.Create(Application.MainForm);
FSdwMessage.Parent := FRctMessage;
{$ENDREGION}
//
{$REGION 'FLytButtons'}
if not(Assigned(FLytButtons)) then
FLytButtons := TLayout.Create(Application.MainForm);
FLytButtons.Align := TAlignLayout.Bottom;
FLytButtons.Parent := FRctMessage;
FLytButtons.Margins.Bottom := 10;
FLytButtons.Margins.Left := 4;
FLytButtons.Margins.Right := 4;
FLytButtons.Margins.Top := 5;
FLytButtons.Height := 50;
FLytButtons.BringToFront;
{$ENDREGION}
//
{$REGION 'FLblHeader'}
if not(Assigned(FLblHeader)) then
FLblHeader := TLabel.Create(Application.MainForm);
FLblHeader.Parent := FRctMessage;
FLblHeader.Align := TAlignLayout.MostTop;
FLblHeader.Margins.Bottom := 5;
FLblHeader.Margins.Left := 4;
FLblHeader.Margins.Right := 4;
FLblHeader.Margins.Top := 5;
FLblHeader.StyledSettings := [];
FLblHeader.AutoSize := True;
FLblHeader.Font.Style := [];
FLblHeader.TextSettings.Font.Family := FTextFont;
FLblHeader.TextSettings.Font.Size := 16;
FLblHeader.TextSettings.FontColor := StringToAlphaColor(FTextColor);
FLblHeader.TextSettings.HorzAlign := TTextAlign.Center;
{$ENDREGION}
//
{$REGION 'FLblMessage'}
if not(Assigned(FLblMessage)) then
FLblMessage := TLabel.Create(Application.MainForm);
FLblMessage.Parent := FRctMessage;
FLblMessage.Align := TAlignLayout.Top;
FLblMessage.Margins.Bottom := 5;
FLblMessage.Margins.Left := 4;
FLblMessage.Margins.Right := 4;
FLblMessage.Margins.Top := 5;
FLblMessage.StyledSettings := [];
FLblMessage.AutoSize := True;
FLblMessage.Font.Style := [];
FLblMessage.TextSettings.Font.Family := FTextFont;
FLblMessage.TextSettings.Font.Size := 16;
FLblMessage.TextSettings.FontColor := StringToAlphaColor(FTextColor);
FLblMessage.TextSettings.HorzAlign := TTextAlign.Center;
{$ENDREGION}
//
FLytBackground.Parent := Application.MainForm;
end;
class procedure TMessage.Resize();
var
vTam: Single;
begin
FRctMessage.Height := FLytButtons.Height + FLytButtons.Margins.Bottom +
FLytButtons.Margins.Top + FLblHeader.Height + FLblHeader.Margins.Bottom +
FLblHeader.Margins.Top + FLblMessage.Height + FLblMessage.Margins.Bottom +
FLblMessage.Margins.Top;
// para nao permitir que ele suma com os botoes
if (FRctMessage.Height > Application.MainForm.ClientHeight) then
FRctMessage.Height := Application.MainForm.ClientHeight - 20;
end;
class procedure TMessage.Show(const ATextColor: string; const ATextFont: string;
const ABtnColor: string; const ABackgroundColor: string; const aMsg: String;
const aTitle: String; const aMsgTypeButton: TMsgTypeButton;
const aMsgType: TMsgType; const ACloseDialogProc: TInputCloseDialogProc);
begin
FTextColor := ATextColor;
FTextFont := ATextFont;
FBtnColor := ABtnColor;
FBackgroundColor := ABackgroundColor;
PrepareBackground();
FLblHeader.Visible := (Trim(aTitle) <> '');
FLblHeader.Text := aTitle;
FLblMessage.Text := aMsg;
AddButtons(aMsgTypeButton);
FCloseDialogProc := ACloseDialogProc;
ShowMessage;
end;
class procedure TMessage.ShowMessage;
begin
FLytBackground.Visible := True;
FLytBackground.Opacity := 0;
FRctBackground.Opacity := 0;
FLytBackground.Visible := True;
FRctBackground.Visible := True;
Resize();
FRctBackground.AnimateFloat('opacity', 0.5);
FLytBackground.AnimateFloat('opacity', 1);
FLytBackground.BringToFront;
FLytBackground.SetFocus;
end;
class procedure TMessage.Toast(const aMsg, AFontName: string;
const ADelay: Single; const AProc: TProc = nil);
var
LLytToastBackground: TLayout;
LLytToast: TLayout;
LRctToastBackground: TRectangle;
LLblMsg: TLabel;
LFloatAnimation: TFloatAnimation;
LRandomNumber: Integer;
begin
FProcToastFloatAnimationFinish := AProc;
LRandomNumber := 1 + Random(1000);
LLytToastBackground :=
TLayout(Application.MainForm.FindComponent('lytToastBackground'));
if (LLytToastBackground = nil) then
LLytToastBackground := TLayout.Create(Application.MainForm);
LLytToastBackground.Align := TAlignLayout.Contents;
LLytToastBackground.Visible := False;
LLytToastBackground.Name := 'lytToastBackground';
{$REGION 'LLytToast'}
LLytToast := TLayout.Create(LLytToastBackground);
LLytToast.Align := TAlignLayout.Bottom;
LLytToast.Parent := LLytToastBackground;
LLytToast.Height := 50;
if (LLytToastBackground.ChildrenCount = 1) then
LLytToast.Margins.Bottom := 40
else
LLytToast.Margins.Bottom := 10;
LLytToast.Margins.Left := 40;
LLytToast.Margins.Right := 40;
LLytToast.Opacity := 0;
LLytToast.HitTest := True;
LLytToast.Name := 'lytToast' + LRandomNumber.ToString;
{$ENDREGION}
//
{$REGION 'LRctToastBackground'}
LRctToastBackground := TRectangle.Create(LLytToast);
LRctToastBackground.Parent := LLytToast;
LRctToastBackground.Align := TAlignLayout.Contents;
LRctToastBackground.XRadius := 5;
LRctToastBackground.YRadius := 5;
LRctToastBackground.Stroke.Kind := TBrushKind.None;
LRctToastBackground.Stroke.Color := StringToAlphaColor('Null');
LRctToastBackground.Fill.Color := StringToAlphaColor('Black');
LRctToastBackground.Opacity := 0;
{$ENDREGION}
//
{$REGION 'LLblMsg'}
LLblMsg := TLabel.Create(LLytToast);
LLblMsg.Parent := LLytToast;
LLblMsg.Align := TAlignLayout.Top;
LLblMsg.Margins.Left := 10;
LLblMsg.Margins.Right := 10;
LLblMsg.StyledSettings := [TStyledSetting.Size, TStyledSetting.Style];
LLblMsg.TextSettings.HorzAlign := TTextAlign.Center;
LLblMsg.TextSettings.Font.Family := AFontName;
LLblMsg.TextSettings.FontColor := StringToAlphaColor('White');
LLblMsg.TextSettings.WordWrap := True;
LLblMsg.AutoSize := True;
LLblMsg.Text := aMsg;
{$ENDREGION}
//
{$REGION 'FloatAnimation'}
LFloatAnimation := TFloatAnimation.Create(LLytToast);
LFloatAnimation.Delay := ADelay;
LFloatAnimation.Duration := 0.2;
LFloatAnimation.PropertyName := 'Opacity';
LFloatAnimation.StartValue := 1;
LFloatAnimation.StopValue := 0;
LFloatAnimation.Tag := LRandomNumber;
LFloatAnimation.OnFinish := ToastFloatAnimationFinish;
LFloatAnimation.Parent := LLytToast;
{$ENDREGION}
//
LLytToastBackground.Parent := Application.MainForm;
LLytToastBackground.Visible := True;
//
{$REGION 'Resize'}
LLblMsg.RecalcSize;
if (LLblMsg.Height > LLytToast.Height) then
LLytToast.Height := LLblMsg.Height + 10;
LLblMsg.Align := TAlignLayout.Client;
{$ENDREGION}
//
LLytToastBackground.BringToFront;
LRctToastBackground.AnimateFloat('opacity', 0.7);
LLytToast.AnimateFloat('opacity', 1);
LLytToastBackground.SetFocus;
LFloatAnimation.Enabled := True;
end;
class procedure TMessage.ToastFloatAnimationFinish(Sender: TObject);
var
LLytBackground: TLayout;
LLyt: TLayout;
begin
TFloatAnimation(Sender).Enabled := False;
LLyt := TLayout(TFloatAnimation(Sender).Parent);
if (LLyt = nil) then
Exit;
TFloatAnimation(Sender).Parent := nil;
LLyt.Parent := nil;
FreeAndNil(LLyt);
LLytBackground := TLayout(Application.MainForm.FindComponent
('lytToastBackground'));
if (LLytBackground = nil) then
Exit;
if (LLytBackground.ChildrenCount = 0) then
begin
LLytBackground.Parent := nil;
FreeAndNil(LLytBackground);
end;
if(Assigned(FProcToastFloatAnimationFinish))then
FProcToastFloatAnimationFinish;
end;
end.
|
unit NewUser;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ParentForm, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxControls,
cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, ChoicePeriod,
dsdGuides, cxDropDownEdit, cxCalendar, cxTextEdit, cxMaskEdit, cxButtonEdit,
cxPropertiesStore, dsdAddOn, dsdDB, cxLabel, dxSkinsCore,
dxSkinsDefaultPainters, cxCheckBox, dsdAction, Vcl.ActnList, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven,
dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver,
dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld,
dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue;
type
TNewUserForm = class(TParentForm)
dsdUserSettingsStorageAddOn: TdsdUserSettingsStorageAddOn;
cxPropertiesStore: TcxPropertiesStore;
FormParams: TdsdFormParams;
cxLabel2: TcxLabel;
edPhone: TcxTextEdit;
cxLabel1: TcxLabel;
edName: TcxTextEdit;
ceUnit: TcxButtonEdit;
cxLabel12: TcxLabel;
cePosition: TcxButtonEdit;
cxLabel11: TcxLabel;
edLogin: TcxTextEdit;
cxLabel3: TcxLabel;
edPassword: TcxTextEdit;
cxLabel4: TcxLabel;
UnitGuides: TdsdGuides;
PositionGuides: TdsdGuides;
ActionList: TActionList;
dsdDataSetRefresh: TdsdDataSetRefresh;
dsdFormClose: TdsdFormClose;
dsdInsertUpdateGuides: TdsdInsertUpdateGuides;
cxButton2: TcxButton;
cxButton1: TcxButton;
spGet: TdsdStoredProc;
HeaderExitName: THeaderExit;
actExitName: TdsdExecStoredProc;
spGet_ExitName: TdsdStoredProc;
spInsertUpdate: TdsdStoredProc;
actShowPUSHMessageInfo: TdsdShowPUSHMessage;
spPUSHInfo: TdsdStoredProc;
ceInternshipCompleted: TcxCheckBox;
ceisSite: TcxCheckBox;
edNameUkr: TcxTextEdit;
cxLabel5: TcxLabel;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TNewUserForm);
end.
|
{*************************************************************************
An Object to query MySql Server Version 5 and get the Result In Xml Stream
http://dev.mysql.com/doc/refman/5.0/en/
http://dev.mysql.com/doc/refman/5.0/en/string-syntax.html
*************************************************************************}
unit Alcinoe.MySql.Client;
interface
uses
Winapi.Windows,
System.Contnrs,
System.SyncObjs,
Alcinoe.Common,
Alcinoe.XMLDoc,
Alcinoe.StringList,
Alcinoe.StringUtils,
Alcinoe.MySql.Wrapper;
Type
{-------------------------------------------------------------}
TalMySqlClientSelectDataOnNewRowFunct = reference to Procedure(
XMLRowData: TalXmlNode;
const ViewTag: AnsiString;
ExtData: Pointer;
Var Continue: Boolean);
{---------------------------------}
EALMySqlError = class(EALException)
private
FErrorCode: Integer;
FSQLstate: AnsiString;
public
constructor Create(
const aErrorMsg: AnsiString;
const aErrorCode: Integer;
const aSqlState: AnsiString); overload;
property ErrorCode: Integer read FErrorCode;
property SQLState: AnsiString read FSQLState;
end;
{---------------------}
TALMySQLOption = record
Option: TMySqlOption;
Value: PANSIChar;
end;
TALMySQLOptions = array of TALMySQLOption;
{-----------------------------}
TalMySqlClient = Class(Tobject)
Private
fLibrary: TALMySqlLibrary;
FownLibrary: Boolean;
fMySql: PMySql;
fNullString: AnsiString;
finTransaction: Boolean;
function GetConnected: Boolean;
function GetInTransaction: Boolean;
Protected
function loadCachedData(
const Key: AnsiString;
var DataStr: AnsiString): Boolean; virtual;
Procedure SaveDataToCache(
const Key: ansiString;
const CacheThreshold: integer;
const DataStr: ansiString); virtual;
procedure CheckAPIError(Error: Boolean);
Function GetFieldValue(
aFieldValue: PAnsiChar;
aFieldType: TMysqlFieldTypes;
aFieldLength: integer;
const aFormatSettings: TALFormatSettingsA): AnsiString;
procedure initObject; virtual;
procedure OnSelectDataDone(
const SQL: AnsiString;
const RowTag: AnsiString;
const ViewTag: AnsiString;
Skip: integer;
First: Integer;
CacheThreshold: Integer;
TimeTaken: double); virtual;
procedure OnUpdateDataDone(
const SQL: AnsiString;
TimeTaken: double); virtual;
Public
Constructor Create(
ApiVer: TALMySqlVersion_API;
const lib: AnsiString = 'libmysql.dll'); overload; virtual;
Constructor Create(lib: TALMySqlLibrary); overload; virtual;
Destructor Destroy; Override;
Procedure Connect(
const Host: AnsiString;
Port: integer;
const DataBaseName,
Login,
Password,
CharSet: AnsiString;
Const ClientFlag: Cardinal = 0;
Const Options: TALMySQLOptions = nil); virtual;
Procedure Disconnect;
Procedure TransactionStart;
Procedure TransactionCommit;
Procedure TransactionRollback;
Procedure SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
const ViewTag: AnsiString;
Skip: integer; // used only if value is > 0
First: Integer; // used only if value is > 0
CacheThreshold: Integer; // The threshold value (in ms) determine whether we will use
// cache or not. Values <= 0 deactivate the cache
XMLDATA: TalXMLNode;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA); overload; virtual;
Procedure SelectData(
const SQL: AnsiString;
Skip: integer;
First: Integer;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA); overload; virtual;
Procedure SelectData(
const SQL: AnsiString;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA); overload; virtual;
Procedure SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
Skip: integer;
First: Integer;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA); overload; virtual;
Procedure SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA); overload; virtual;
Procedure SelectData(
const SQL: AnsiString;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA); overload; virtual;
procedure UpdateData(SQLs: TALStringsA); overload; virtual;
procedure UpdateData(const SQL: AnsiString); overload; virtual;
procedure UpdateData(const SQLs: array of AnsiString); overload; virtual;
function insert_id(const SQL: AnsiString): ULongLong;
Property Connected: Boolean Read GetConnected;
Property InTransaction: Boolean read GetInTransaction;
Property NullString: AnsiString Read fNullString Write fNullString;
property Lib: TALMySqlLibrary read FLibrary;
end;
{--------------------------------------}
TalMySqlConnectionPoolContainer = record
ConnectionHandle: PMySql;
LastAccessDate: int64;
End;
TalMySqlConnectionPool = array of TalMySqlConnectionPoolContainer;
{-------------------------------------------}
TalMySqlConnectionPoolClient = Class(Tobject)
Private
FLibrary: TALMySqlLibrary;
FownLibrary: Boolean;
FConnectionPool: TalMySqlConnectionPool;
FConnectionPoolCount: integer;
FConnectionPoolCapacity: integer;
FConnectionPoolCS: TCriticalSection;
FWorkingConnectionCount: Integer;
FReleasingAllconnections: Boolean;
FLastConnectionGarbage: Int64;
FConnectionMaxIdleTime: integer;
FHost: AnsiString;
FPort: Integer;
FDataBaseName: AnsiString;
fLogin: AnsiString;
fPassword: AnsiString;
fCharset: AnsiString;
fOpenConnectionClientFlag: cardinal;
FOpenConnectionOptions: TALMySQLOptions;
FNullString: AnsiString;
Protected
function loadCachedData(
const Key: AnsiString;
var DataStr: AnsiString): Boolean; virtual;
Procedure SaveDataToCache(
const Key: ansiString;
const CacheThreshold: integer;
const DataStr: ansiString); virtual;
procedure CheckAPIError(ConnectionHandle: PMySql; Error: Boolean);
function GetDataBaseName: AnsiString; virtual;
function GetHost: AnsiString; virtual;
function GetPort: integer; virtual;
Function GetFieldValue(
aFieldValue: PAnsiChar;
aFieldType: TMysqlFieldTypes;
aFieldLength: integer;
const aFormatSettings: TALFormatSettingsA): AnsiString;
Function AcquireConnection: PMySql; virtual;
Procedure ReleaseConnection(var ConnectionHandle: PMySql; const CloseConnection: Boolean = False); virtual;
procedure initObject(
const aHost: AnsiString;
aPort: integer;
const aDataBaseName,
aLogin,
aPassword,
aCharSet: AnsiString;
Const aOpenConnectionClientFlag: Cardinal = 0;
Const aOpenConnectionOptions: TALMySQLOptions = nil); virtual;
procedure OnSelectDataDone(
const SQL: AnsiString;
const RowTag: AnsiString;
const ViewTag: AnsiString;
Skip: integer;
First: Integer;
CacheThreshold: Integer;
TimeTaken: double); virtual;
procedure OnUpdateDataDone(
const SQL: AnsiString;
TimeTaken: double); virtual;
Public
Constructor Create(
const aHost: AnsiString;
aPort: integer;
const aDataBaseName,
aLogin,
aPassword,
aCharSet: AnsiString;
aApiVer: TALMySqlVersion_API;
Const alib: AnsiString = 'libmysql.dll';
Const aOpenConnectionClientFlag: Cardinal = 0;
Const aOpenConnectionOptions: TALMySQLOptions = nil); overload; virtual;
Constructor Create(
const aHost: AnsiString;
aPort: integer;
const aDataBaseName,
aLogin,
aPassword,
aCharSet: AnsiString;
alib: TALMySqlLibrary;
Const aOpenConnectionClientFlag: Cardinal = 0;
Const aOpenConnectionOptions: TALMySQLOptions = nil); overload; virtual;
Destructor Destroy; Override;
Procedure ReleaseAllConnections(Const WaitWorkingConnections: Boolean = True); virtual;
Procedure TransactionStart(Var ConnectionHandle: PMySql); virtual;
Procedure TransactionCommit(var ConnectionHandle: PMySql; const CloseConnection: Boolean = False); virtual;
Procedure TransactionRollback(var ConnectionHandle: PMySql; const CloseConnection: Boolean = False); virtual;
Procedure SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
const ViewTag: AnsiString;
Skip: integer; // used only if value is > 0
First: Integer; // used only if value is > 0
CacheThreshold: Integer; // The threshold value (in ms) determine whether we will use
// cache or not. Values <= 0 deactivate the cache
XMLDATA: TalXMLNode;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil); overload; virtual;
Procedure SelectData(
const SQL: AnsiString;
Skip: integer;
First: Integer;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil); overload; virtual;
Procedure SelectData(
const SQL: AnsiString;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil); overload; virtual;
Procedure SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
Skip: integer;
First: Integer;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil); overload; virtual;
Procedure SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil); overload; virtual;
Procedure SelectData(
const SQL: AnsiString;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil); overload; virtual;
procedure UpdateData(SQLs: TALStringsA; const ConnectionHandle: PMySql = nil); overload; virtual;
procedure UpdateData(const SQL: AnsiString; const ConnectionHandle: PMySql = nil); overload; virtual;
procedure UpdateData(const SQLs: array of AnsiString; const ConnectionHandle: PMySql = nil); overload; virtual;
Function insert_id(const SQL: AnsiString; const ConnectionHandle: PMySql = nil): UlongLong; virtual;
Function ConnectionCount: Integer;
Function WorkingConnectionCount: Integer;
property DataBaseName: AnsiString read GetDataBaseName;
property Host: AnsiString read GetHost;
property Port: integer read GetPort;
property ConnectionMaxIdleTime: integer read FConnectionMaxIdleTime write fConnectionMaxIdleTime;
Property NullString: AnsiString Read fNullString Write fNullString;
property Lib: TALMySqlLibrary read FLibrary;
end;
Function AlMySqlClientSlashedStr(Const Str: AnsiString): AnsiString;
var
ALMySqlFormatSettings: TALFormatSettingsA;
implementation
uses
System.Classes,
System.SysUtils,
System.Diagnostics,
System.AnsiStrings,
Alcinoe.Cipher,
Alcinoe.WinApi.Common;
{******************************************************************}
Function AlMySqlClientSlashedStr(Const Str: AnsiString): AnsiString;
var I: Integer;
begin
Result := Str;
for I := Length(Result) downto 1 do
if Result[I] in ['''','"','\',#0] then Insert('\', Result, I);
Result := '''' + Result + '''';
end;
{*******************************}
constructor EALMySqlError.Create(
const aErrorMsg: AnsiString;
const aErrorCode: Integer;
const aSqlState: AnsiString);
begin
fErrorCode := aErrorCode;
FSQLstate := aSqlState;
inherited create(aErrorMsg);
end;
{********************************************}
function TalMySqlClient.GetConnected: Boolean;
begin
result := assigned(fMySql);
end;
{************************************************}
function TalMySqlClient.GetInTransaction: Boolean;
begin
result := finTransaction;
end;
{*************************************}
function TalMySqlClient.loadCachedData(
const Key: AnsiString;
var DataStr: AnsiString): Boolean;
begin
result := false; //virtual need to be overriden
end;
{***************************************}
Procedure TalMySqlClient.SaveDataToCache(
const Key: ansiString;
const CacheThreshold: integer;
const DataStr: ansiString);
begin
//virtual need to be overriden
end;
{*****************************************************}
procedure TalMySqlClient.CheckAPIError(Error: Boolean);
Begin
if Error then begin
if assigned(FMySql) then raise EALMySqlError.Create(
fLibrary.mysql_error(fMySQL),
fLibrary.mysql_errno(fMySQL),
fLibrary.mysql_SqlState(fMySQL))
else raise EALMySqlError.Create(
'MySql error',
-1,
'HY000'); // The value 'HY000' (general error) is used for unmapped error numbers.
end;
end;
{************************************}
function TalMySqlClient.GetFieldValue(
aFieldValue: PAnsiChar;
aFieldType: TMysqlFieldTypes;
aFieldLength: integer;
const aFormatSettings: TALFormatSettingsA): AnsiString;
begin
//The lengths of the field values in the row may be obtained by calling mysql_fetch_lengths().
//Empty fields and fields containing NULL both have length 0; you can distinguish these
//by checking the pointer for the field value. If the pointer is NULL, the field
//is NULL; otherwise, the field is empty.
IF aFieldValue = nil then result := fNullString
else begin
Case aFieldType of
FIELD_TYPE_DECIMAL,
FIELD_TYPE_NEWDECIMAL,
FIELD_TYPE_FLOAT,
FIELD_TYPE_DOUBLE: result := ALFloatToStrA(ALStrToFloat(aFieldValue,ALMySqlFormatSettings),aformatSettings);
FIELD_TYPE_DATETIME: Result := ALDateTimeToStrA(ALStrToDateTime(aFieldValue,ALMySqlFormatSettings),aformatSettings);
FIELD_TYPE_DATE,
FIELD_TYPE_NEWDATE: Result := ALDateToStrA(ALStrToDate(aFieldValue,ALMySqlFormatSettings),aformatSettings);
FIELD_TYPE_TIME: Result := ALTimeToStrA(ALStrToTime(aFieldValue,ALMySqlFormatSettings),aformatSettings);
FIELD_TYPE_TIMESTAMP: Result := ALDateTimeToStrA(ALStrToDateTime(aFieldValue,ALMySqlFormatSettings),aformatSettings);
FIELD_TYPE_NULL: result := fNullString; // Example: SELECT NULL FROM DUAL
Else SetString(Result, aFieldValue, aFieldLength);
end;
end;
end;
{**********************************}
procedure TalMySqlClient.initObject;
begin
fMySql := nil;
finTransaction := False;
fNullString := '';
end;
{********************************}
constructor TalMySqlClient.Create(
ApiVer: TALMySqlVersion_API;
const lib: AnsiString = 'libmysql.dll');
begin
fLibrary := TALMySqlLibrary.Create(ApiVer);
try
fLibrary.Load(lib);
FownLibrary := True;
initObject;
Except
fLibrary.free;
raise;
end;
end;
{******************************************************}
constructor TalMySqlClient.Create(lib: TALMySqlLibrary);
begin
fLibrary := lib;
FownLibrary := False;
initObject;
end;
{********************************}
destructor TalMySqlClient.Destroy;
begin
If Connected then disconnect;
if FownLibrary then fLibrary.Free;
inherited;
end;
{*************************************************************
http://dev.mysql.com/doc/refman/5.1/en/mysql-real-connect.html}
procedure TalMySqlClient.connect(
const Host: AnsiString;
Port: integer;
const DataBaseName,
Login,
Password,
CharSet: AnsiString;
Const ClientFlag: Cardinal = 0;
const Options: TALMySQLOptions = nil);
var I: integer;
begin
if connected then raise Exception.Create('Already connected');
// This function must be called early within each
// created thread to initialize thread-specific variables
// this look very important because if we comment this and
// the mysql_thread_end then the Flibrary.unload can take several seconds
// you can see this in the ALSQLBenchmark.exe project with the loop update button
CheckAPIError(FLibrary.mysql_thread_init <> 0);
Try
//Allocates or initializes a MYSQL object suitable for mysql_real_connect()
fMySQL := fLibrary.mysql_init(nil);
CheckAPIError(fMySQL = nil);
//set the The name of the character set to use as the default character set.
If (CharSet <> '') then CheckAPIError(fLibrary.mysql_options(fMySQL, MYSQL_SET_CHARSET_NAME, PAnsiChar(CharSet)) <> 0);
// set the options if they are existing
for I := 0 to length(Options) - 1 do
CheckAPIError(
FLibrary.mysql_options(
FMySQL,
Options[I].Option,
Options[I].Value) <> 0);
//attempts to establish a connection to a MySQL database engine running on host
CheckAPIError(
fLibrary.mysql_real_connect(
fMySQL,
PAnsiChar(Host),
PAnsiChar(Login),
PAnsiChar(Password),
PAnsiChar(DatabaseName),
Port,
nil,
ClientFlag) = nil);
Except
//close the FMySql and free memory allocated by mysql_thread_init().
if assigned(FMySql) then fLibrary.MySql_close(FMySql);
FLibrary.mysql_thread_end;
FMySql := nil;
Raise;
End;
end;
{**********************************}
procedure TalMySqlClient.Disconnect;
begin
If not connected then exit;
if InTransaction then TransactionRollback;
try
//close the FMySql and free memory allocated by mysql_thread_init().
FLibrary.MySql_close(FMySql);
FLibrary.mysql_thread_end;
Except
//Disconnect must be a "safe" procedure because it's mostly called in
//finalization part of the code that it is not protected
End;
FMySql := Nil;
end;
{****************************************}
procedure TalMySqlClient.TransactionStart;
begin
//Error if we are not connected
If not connected then raise Exception.Create('Not connected');
if InTransaction then raise Exception.Create('Another transaction is active');
//execute the query
UpdateData('START TRANSACTION');
finTransaction := True;
end;
{*****************************************}
procedure TalMySqlClient.TransactionCommit;
begin
//Error if we are not connected
if not InTransaction then raise Exception.Create('No active transaction to commit');
//Execute the Query
UpdateData('COMMIT');
finTransaction := False;
end;
{*******************************************}
procedure TalMySqlClient.TransactionRollback;
begin
//Error if we are not connected
if not InTransaction then raise Exception.Create('No active transaction to rollback');
//Execute the Query
Try
UpdateData('ROLLBACK');
Except
//some error can happen if the network go down for exemple
//i don't really know what to do in this case of error
//but what else we can do ? commit => exept => rollback => except ???
End;
finTransaction := False;
end;
{****************************************}
procedure TalMySqlClient.OnSelectDataDone(
const SQL: AnsiString;
const RowTag: AnsiString;
const ViewTag: AnsiString;
Skip: integer;
First: Integer;
CacheThreshold: Integer;
TimeTaken: Double);
begin
// virtual
end;
{****************************************}
procedure TalMySqlClient.OnUpdateDataDone(
const SQL: AnsiString;
TimeTaken: double);
begin
// virtual
end;
{**********************************}
procedure TalMySqlClient.SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
const ViewTag: AnsiString;
Skip: integer; // used only if value is > 0
First: Integer; // used only if value is > 0
CacheThreshold: Integer; // The threshold value (in ms) determine whether we will use
// cache or not. Values <= 0 deactivate the cache
XMLDATA: TalXMLNode;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA);
Var LMySqlRes: PMYSQL_RES;
LMySqlRow: PMYSQL_ROW;
LMySqlFields: array of PMYSQL_FIELD;
LMySqlFieldLengths: PMYSQL_LENGTHS;
LColumnCount: Integer;
LColumnIndex: integer;
LNewRec: TalXmlNode;
LValueRec: TalXmlNode;
LViewRec: TalXmlNode;
LRecIndex: integer;
LRecAdded: integer;
LContinue: Boolean;
LXmlDocument: TalXmlDocument;
LUpdateRowTagByFieldValue: Boolean;
LStopWatch: TStopWatch;
LCacheKey: ansiString;
LCacheStr: ansiString;
LTmpRowTag: ansiString;
begin
//Error if we are not connected
If not connected then raise Exception.Create('Not connected');
//only OnNewRowFunct / XMLDATA can be used
if assigned(OnNewRowFunct) then XMLDATA := nil;
//clear the XMLDATA
if assigned(XMLDATA) then LXmlDocument := Nil
else begin
LXmlDocument := TALXmlDocument.create('root');
XMLDATA := LXmlDocument.DocumentElement;
end;
Try
//init the TstopWatch
LStopWatch := TstopWatch.Create;
//Handle the CacheThreshold
LCacheKey := '';
If (CacheThreshold > 0) and
(not assigned(LXmlDocument)) and
((XMLdata.ChildNodes.Count = 0) or // else the save will not work
(ViewTag <> '')) then begin
//try to load from from cache
LCacheKey := ALStringHashSHA1(
RowTag + '#' +
ALIntToStrA(Skip) + '#' +
ALIntToStrA(First) + '#' +
ALGetFormatSettingsID(FormatSettings) + '#' +
SQL);
if loadcachedData(LCacheKey, LCacheStr) then begin
//init the aViewRec
if (ViewTag <> '') then LViewRec := XMLdata.AddChild(ViewTag)
else LViewRec := XMLdata;
//assign the tmp data to the XMLData
LViewRec.LoadFromXML(LCacheStr, true{XmlContainOnlyChildNodes}, false{ClearChildNodes});
//exit
exit;
end;
end;
//start the TstopWatch
LStopWatch.Reset;
LStopWatch.Start;
//prepare the query
CheckAPIError(fLibrary.mysql_real_query(fMySQL, PAnsiChar(SQL), length(SQL)) <> 0);
LMySqlRes := fLibrary.mysql_use_result(fMySQL);
CheckAPIError(LMySqlRes = nil);
Try
//Returns the number of columns in a result set.
LColumnCount := fLibrary.mysql_num_fields(LMySqlRes);
//init the aMySqlFields array
//this not work anymore in MYSQL5.5, i don't know why so i use mysql_fetch_field instead
//aMySqlFields := fLibrary.mysql_fetch_fields(aMySqlRes);
setlength(LMySqlFields,LColumnCount);
for LColumnIndex := 0 to LColumnCount - 1 do
LMySqlFields[LColumnIndex] := fLibrary.mysql_fetch_field(LMySqlRes);
//init the aViewRec
if (ViewTag <> '') and (not assigned(LXmlDocument)) then LViewRec := XMLdata.AddChild(ViewTag)
else LViewRec := XMLdata;
//init aUpdateRowTagByFieldValue
if ALPosA('&>',RowTag) = 1 then begin
LTmpRowTag := ALcopyStr(RowTag,3,maxint);
LUpdateRowTagByFieldValue := LTmpRowTag <> '';
end
else begin
LTmpRowTag := RowTag;
LUpdateRowTagByFieldValue := False;
end;
//loop throught all row
LRecIndex := 0;
LRecAdded := 0;
while True do begin
//retrieve the next row. return A MYSQL_ROW structure for the next row.
//NULL if there are no more rows to retrieve or if an error occurred.
LMySqlRow := fLibrary.mysql_fetch_row(LMySqlRes);
//break if no more row
if LMySqlRow = nil then begin
CheckAPIerror(Flibrary.mysql_errno(fMySQL) <> 0);
break;
end
//download the row
else begin
//process if > Skip
inc(LRecIndex);
If LRecIndex > Skip then begin
//init NewRec
if (LTmpRowTag <> '') and (not assigned(LXmlDocument)) then LNewRec := LViewRec.AddChild(LTmpRowTag)
Else LNewRec := LViewRec;
//init aMySqlFieldLengths
LMySqlFieldLengths := fLibrary.mysql_fetch_lengths(LMySqlRes);
CheckAPIerror(LMySqlFieldLengths = nil);
//loop throught all column
For LColumnIndex := 0 to LColumnCount - 1 do begin
LValueRec := LNewRec.AddChild(ALlowercase(LMySqlFields[LColumnIndex].name));
if (LMySqlFields[LColumnIndex]._type in [FIELD_TYPE_TINY_BLOB,
FIELD_TYPE_MEDIUM_BLOB,
FIELD_TYPE_LONG_BLOB,
FIELD_TYPE_BLOB]) then LValueRec.ChildNodes.Add(
LValueRec.OwnerDocument.CreateNode(
GetFieldValue(
LMySqlRow[LColumnIndex],
LMySqlFields[LColumnIndex]._type,
LMySqlFieldLengths[LColumnIndex],
FormatSettings),
ntCData))
else LValueRec.Text := GetFieldValue(
LMySqlRow[LColumnIndex],
LMySqlFields[LColumnIndex]._type,
LMySqlFieldLengths[LColumnIndex],
FormatSettings);
if LUpdateRowTagByFieldValue and (LValueRec.NodeName=LNewRec.NodeName) then LNewRec.NodeName := ALLowerCase(LValueRec.Text);
end;
//handle OnNewRowFunct
if assigned(OnNewRowFunct) then begin
LContinue := True;
OnNewRowFunct(LNewRec, ViewTag, ExtData, LContinue);
if Not LContinue then Break;
end;
//free the node if aXmlDocument
if assigned(LXmlDocument) then LXmlDocument.DocumentElement.ChildNodes.Clear;
//handle the First
inc(LRecAdded);
If (First > 0) and (LRecAdded >= First) then Break;
end;
end;
end;
Finally
//Frees the memory allocated to aMySqlRes
fLibrary.mysql_free_result(LMySqlRes);
End;
//do the OnSelectDataDone
LStopWatch.Stop;
OnSelectDataDone(
SQL,
RowTag,
ViewTag,
Skip,
First,
CacheThreshold,
LStopWatch.Elapsed.TotalMilliseconds);
//save to the cache
If LCacheKey <> '' then begin
//save the data
LViewRec.SaveToXML(LCacheStr, true{SaveOnlyChildNodes});
SaveDataToCache(
LCacheKey,
CacheThreshold,
LCacheStr);
end;
Finally
if assigned(LXmlDocument) then LXmlDocument.free;
End;
end;
{**********************************}
procedure TalMySqlClient.SelectData(
const SQL: AnsiString;
Skip: Integer;
First: Integer;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA);
begin
SelectData(
SQL,
'', // RowTag,
'', //ViewTag,
Skip,
First,
-1, // CacheThreshold,
nil, // XMLDATA,
OnNewRowFunct,
ExtData,
FormatSettings);
end;
{**********************************}
procedure TalMySqlClient.SelectData(
const SQL: AnsiString;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA);
begin
SelectData(
SQL,
'', // RowTag,
'', // ViewTag,
-1, // Skip,
-1, // First,
-1, // CacheThreshold,
nil, // XMLDATA,
OnNewRowFunct,
ExtData,
FormatSettings);
end;
{**********************************}
procedure TalMySqlClient.SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
Skip: Integer;
First: Integer;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA);
begin
SelectData(
SQL,
RowTag,
'', // ViewTag,
Skip,
First,
-1, // CacheThreshold,
XMLDATA,
nil, // OnNewRowFunct,
nil, // ExtData,
FormatSettings);
end;
{**********************************}
procedure TalMySqlClient.SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA);
begin
SelectData(
SQL,
RowTag,
'', // ViewTag,
-1, // Skip,
-1, // First,
-1, // CacheThreshold,
XMLDATA,
nil, // OnNewRowFunct,
nil, // ExtData,
FormatSettings);
end;
{**********************************}
procedure TalMySqlClient.SelectData(
const SQL: AnsiString;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA);
begin
SelectData(
SQL,
'', // RowTag,
'', // ViewTag,
-1, // Skip,
-1, // First,
-1, // CacheThreshold,
XMLDATA,
nil, // OnNewRowFunct,
nil, // ExtData,
FormatSettings);
end;
{*********************************************************}
procedure TalMySqlClient.UpdateData(const SQL: AnsiString);
Var LStopWatch: TStopWatch;
begin
//Error if we are not connected
If not connected then raise Exception.Create('Not connected');
//init the TstopWatch
LStopWatch := TstopWatch.Create;
//start the TstopWatch
LStopWatch.Reset;
LStopWatch.Start;
//do the query
CheckAPIError(fLibrary.mysql_real_query(fMySQL, PAnsiChar(SQL), length(SQL)) <> 0);
//do the OnUpdateDataDone
LStopWatch.Stop;
OnUpdateDataDone(
SQL,
LStopWatch.Elapsed.TotalMilliseconds);
end;
{*******************************************************************}
procedure TalMySqlClient.UpdateData(const SQLs: array of AnsiString);
var I: integer;
begin
for I := Low(SQLs) to High(SQLs) do
UpdateData(SQLs[I]);
end;
{*****************************************************}
procedure TalMySqlClient.UpdateData(SQLs: TALStringsA);
var I: integer;
begin
for I := 0 to sqls.Count - 1 do
UpdateData(SQLs[I]);
end;
{******************************************************************}
function TalMySqlClient.insert_id(const SQL: AnsiString): ULongLong;
begin
//if the SQL is not empty
if SQL <> '' then begin
//Execute the Query
UpdateData(SQL);
//Returns the value generated for an AUTO_INCREMENT column
//by the previous INSERT or UPDATE statement
Result := fLibrary.mysql_insert_id(fMySQL);
end
//else simply gave an 0 result
else result := 0;
end;
{***************************************************}
function TalMySqlConnectionPoolClient.loadCachedData(
const Key: AnsiString;
var DataStr: AnsiString): Boolean;
begin
result := false; //virtual need to be overriden
end;
{*****************************************************}
Procedure TalMySqlConnectionPoolClient.SaveDataToCache(
const Key: ansiString;
const CacheThreshold: integer;
const DataStr: ansiString);
begin
//virtual need to be overriden
end;
{*********************************************************************************************}
procedure TalMySqlConnectionPoolClient.CheckAPIError(ConnectionHandle: PMySql; Error: Boolean);
begin
if Error then begin
if assigned(ConnectionHandle) then raise EALMySqlError.Create(
fLibrary.mysql_error(ConnectionHandle),
fLibrary.mysql_errno(ConnectionHandle),
fLibrary.mysql_SqlState(ConnectionHandle))
else raise EALMySqlError.Create(
'MySql error',
-1,
'HY000'); // The value 'HY000' (general error) is used for unmapped error numbers.
end;
end;
{****************************************************************}
function TalMySqlConnectionPoolClient.GetDataBaseName: AnsiString;
begin
result := FdatabaseName;
end;
{********************************************************}
function TalMySqlConnectionPoolClient.GetHost: AnsiString;
begin
result := fHost;
end;
{*****************************************************}
function TalMySqlConnectionPoolClient.GetPort: integer;
begin
result := fPort;
end;
{**************************************************}
function TalMySqlConnectionPoolClient.GetFieldValue(
aFieldValue: PAnsiChar;
aFieldType: TMysqlFieldTypes;
aFieldLength: integer;
const aFormatSettings: TALFormatSettingsA): AnsiString;
begin
//The lengths of the field values in the row may be obtained by calling mysql_fetch_lengths().
//Empty fields and fields containing NULL both have length 0; you can distinguish these
//by checking the pointer for the field value. If the pointer is NULL, the field
//is NULL; otherwise, the field is empty.
IF aFieldValue = nil then result := fNullString
else begin
Case aFieldType of
FIELD_TYPE_DECIMAL,
FIELD_TYPE_NEWDECIMAL,
FIELD_TYPE_FLOAT,
FIELD_TYPE_DOUBLE: result := ALFloatToStrA(ALStrToFloat(aFieldValue,ALMySqlFormatSettings),aformatSettings);
FIELD_TYPE_DATETIME: Result := ALDateTimeToStrA(ALStrToDateTime(aFieldValue,ALMySqlFormatSettings),aformatSettings);
FIELD_TYPE_DATE,
FIELD_TYPE_NEWDATE: Result := ALDateToStrA(ALStrToDate(aFieldValue,ALMySqlFormatSettings),aformatSettings);
FIELD_TYPE_TIME: Result := ALTimeToStrA(ALStrToTime(aFieldValue,ALMySqlFormatSettings),aformatSettings);
FIELD_TYPE_TIMESTAMP: Result := ALDateTimeToStrA(ALStrToDateTime(aFieldValue,ALMySqlFormatSettings),aformatSettings);
FIELD_TYPE_NULL: result := fNullString; // Example: SELECT NULL FROM DUAL
Else SetString(Result, aFieldValue, aFieldLength);
end;
end;
end;
{************************************************}
procedure TalMySqlConnectionPoolClient.initObject(
const aHost: AnsiString;
aPort: integer;
const aDataBaseName,
aLogin,
aPassword,
aCharSet: AnsiString;
Const aOpenConnectionClientFlag: Cardinal = 0;
Const aOpenConnectionOptions: TALMySQLOptions = nil);
begin
fHost := aHost;
fPort := aPort;
FDataBaseName:= aDataBaseName;
fLogin := aLogin;
fPassword := aPassword;
fCharset := aCharset;
fOpenConnectionClientFlag := aOpenConnectionClientFlag;
FOpenConnectionOptions := aOpenConnectionOptions;
setlength(FConnectionPool,0);
FConnectionPoolCount := 0;
FConnectionPoolCapacity := 0;
FConnectionPoolCS:= TCriticalSection.create;
FWorkingConnectionCount:= 0;
FReleasingAllconnections := False;
FLastConnectionGarbage := GettickCount64;
FConnectionMaxIdleTime := 1200000; // 1000 * 60 * 20 = 20 min
FNullString := '';
end;
{**********************************************}
constructor TalMySqlConnectionPoolClient.Create(
const aHost: AnsiString;
aPort: integer;
const aDataBaseName,
aLogin,
aPassword,
aCharSet: AnsiString;
aApiVer: TALMySqlVersion_API;
Const alib: AnsiString = 'libmysql.dll';
Const aOpenConnectionClientFlag: Cardinal = 0;
Const aOpenConnectionOptions: TALMySQLOptions = nil);
begin
fLibrary := TALMySqlLibrary.Create(aApiVer);
Try
fLibrary.Load(alib);
FownLibrary := True;
initObject(
aHost,
aPort,
aDataBaseName,
aLogin,
aPassword,
aCharSet,
aOpenConnectionClientFlag,
aOpenConnectionOptions);
except
FreeandNil(fLibrary);
raise;
End;
end;
{**********************************************}
constructor TalMySqlConnectionPoolClient.Create(
const aHost: AnsiString;
aPort: integer;
const aDataBaseName,
aLogin,
aPassword,
aCharSet: AnsiString;
alib: TALMySqlLibrary;
Const aOpenConnectionClientFlag: Cardinal = 0;
Const aOpenConnectionOptions: TALMySQLOptions = nil);
begin
fLibrary := alib;
FownLibrary := False;
initObject(
aHost,
aPort,
aDataBaseName,
aLogin,
aPassword,
aCharSet,
aOpenConnectionClientFlag,
aOpenConnectionOptions);
end;
{**********************************************}
destructor TalMySqlConnectionPoolClient.Destroy;
begin
//Release all connections
if assigned(fLibrary) then ReleaseAllConnections;
//free object
FConnectionPoolCS.free;
if FownLibrary and assigned(fLibrary) then fLibrary.Free;
//inherite
inherited;
end;
{*******}
ThreadVar
_ThreadInitRefCount: Integer;
{**************************************************************}
function TalMySqlConnectionPoolClient.AcquireConnection: PMySql;
Var LTickCount: int64;
i: integer;
Begin
//synchronize the code
FConnectionPoolCS.Acquire;
Try
//MYSQL IT's A SHEET
//http://bugs.mysql.com/bug.php?id=66740
//https://bugzilla.redhat.com/show_bug.cgi?id=846602
//MySQL requires that each thread that uses the MySQL API first call
//mysql_thread_init() and at the end call mysql_thread_end(). If the thread
//fails to call mysql_thread_end(), then MySQL will block the main thread at
//program termination and wait for this threads to call mysql_thread_end().
//If that doesn't happen, then it prints an error message to STDERR.
//Not a very user-friendly behavior.
//
// This function must be called early within each
// created thread to initialize thread-specific variables
// this look very important because if we comment this and
// the mysql_thread_end then the Flibrary.unload can take several seconds
// you can see this in the ALSQLBenchmark.exe project with the loop update button
// http://dev.mysql.com/doc/refman/5.6/en/threaded-clients.html
CheckAPIError(Nil, FLibrary.mysql_thread_init <> 0);
inc(_ThreadInitRefCount);
Try
//raise an exception if currently realeasing all connection
if FReleasingAllconnections then raise Exception.Create('Can not acquire connection: currently releasing all connections');
//delete the old unused connection
LTickCount := GettickCount64;
if LTickCount - fLastConnectionGarbage > (60000 {every minutes}) then begin
while FConnectionPoolCount > 0 do begin
if LTickCount - FConnectionPool[0].Lastaccessdate > FConnectionMaxIdleTime then begin
Try
FLibrary.MySql_close(FConnectionPool[0].ConnectionHandle);
Except
//Disconnect must be a "safe" procedure because it's mostly called in
//finalization part of the code that it is not protected
//that the bulsheet of MySql to answer SQLITE_BUSY instead of free
//everything
End;
Dec(FConnectionPoolCount);
if FConnectionPoolCount > 0 then
begin
ALMove(
FConnectionPool[1],
FConnectionPool[0],
(FConnectionPoolCount) * SizeOf(TalMySqlConnectionPoolContainer));
end;
end
else break;
end;
FLastConnectionGarbage := LTickCount;
end;
//acquire the new connection from the pool
If FConnectionPoolCount > 0 then begin
Result := FConnectionPool[FConnectionPoolCount - 1].ConnectionHandle;
Dec(FConnectionPoolCount);
end
//create a new connection
else begin
result := nil;
Try
//Allocates or initializes a MYSQL object suitable for mysql_real_connect()
Result := fLibrary.mysql_init(nil);
CheckAPIError(nil, result = nil);
//set the The name of the character set to use as the default character set.
If (fCharSet <> '') then CheckAPIError(Result, fLibrary.mysql_options(Result, MYSQL_SET_CHARSET_NAME, PAnsiChar(fCharSet)) <> 0);
// set the options if they are existing
for i := 0 to length(FOpenConnectionOptions) - 1 do
CheckAPIError(
Result,
FLibrary.mysql_options(
Result,
FOpenConnectionOptions[i].Option,
FOpenConnectionOptions[i].Value) <> 0);
//attempts to establish a connection to a MySQL database engine running on host
CheckAPIError(
Result,
fLibrary.mysql_real_connect(
Result,
PAnsiChar(Host),
PAnsiChar(fLogin),
PAnsiChar(fPassword),
PAnsiChar(fDatabaseName),
Port,
nil,
fOpenConnectionClientFlag) = nil);
Except
//close the FMySql
if assigned(Result) then fLibrary.MySql_close(Result);
Raise;
End;
end;
//increase the connection count
inc(FWorkingConnectionCount);
Except
// free memory allocated by mysql_thread_init().
dec(_ThreadInitRefCount);
if _ThreadInitRefCount = 0 then FLibrary.mysql_thread_end;
Raise;
End;
//get out of the synchronization
finally
FConnectionPoolCS.Release;
end;
End;
{***************************************************************************************}
{Applications must finalize all prepared statements and close all BLOB handles associated
with the MySql object prior to attempting to close the object. If MySql_close() is
called on a database connection that still has outstanding prepared statements or
BLOB handles, then it returns SQLITE_BUSY.
If MySql_close() is invoked while a transaction is open, the transaction is
automatically rolled back.}
procedure TalMySqlConnectionPoolClient.ReleaseConnection(var ConnectionHandle: PMySql; const CloseConnection: Boolean = False);
begin
//security check
if not assigned(ConnectionHandle) then raise Exception.Create('Connection handle can not be null');
//release the connection
FConnectionPoolCS.Acquire;
Try
//add the connection to the pool
If (not CloseConnection) and (not FReleasingAllconnections) then begin
if FConnectionPoolCount = FConnectionPoolCapacity then begin
if FConnectionPoolCapacity > 64 then FConnectionPoolCapacity := FConnectionPoolCapacity + (FConnectionPoolCapacity div 4) else
if FConnectionPoolCapacity > 8 then FConnectionPoolCapacity := FConnectionPoolCapacity + 16 else
FConnectionPoolCapacity := FConnectionPoolCapacity + 4;
SetLength(FConnectionPool, FConnectionPoolCapacity);
end;
FConnectionPool[FConnectionPoolCount].ConnectionHandle := ConnectionHandle;
FConnectionPool[FConnectionPoolCount].LastAccessDate := GettickCount64;
Inc(FConnectionPoolCount);
end
//close the connection
else begin
try
FLibrary.MySql_close(ConnectionHandle);
Except
//Disconnect must be a "safe" procedure because it's mostly called in
//finalization part of the code that it is not protected
end;
end;
//set the connectionhandle to nil
ConnectionHandle := nil;
//dec the WorkingConnectionCount
Dec(FWorkingConnectionCount);
// free memory allocated by mysql_thread_init().
// http://dev.mysql.com/doc/refman/5.6/en/threaded-clients.html
Try
dec(_ThreadInitRefCount);
if _ThreadInitRefCount = 0 then FLibrary.mysql_thread_end;
Except
//Disconnect must be a "safe" procedure because it's mostly called in
//finalization part of the code that it is not protected
End;
finally
FConnectionPoolCS.Release;
end;
end;
{*********************************************************************************************************}
procedure TalMySqlConnectionPoolClient.ReleaseAllConnections(Const WaitWorkingConnections: Boolean = True);
begin
//i m still not sure if the FLibrary.MySql_close
//need the FLibrary.mysql_thread_init. the mysql doc
//if a very true bullsheet. i think it's cost
//nothing to call it here. but of course this mean that
//releaseconnection could not be call inside a thread
//that still own a connection because at the end of this
//function we call mysql_thread_end
try
FLibrary.mysql_thread_init;
inc(_ThreadInitRefCount);
except
//must be safe
end;
try
{we do this to forbid any new thread to create a new transaction}
FReleasingAllconnections := True;
Try
//wait that all transaction are finished
if WaitWorkingConnections then
while true do begin
FConnectionPoolCS.Acquire;
Try
if FWorkingConnectionCount <= 0 then break;
finally
FConnectionPoolCS.Release;
end;
sleep(1);
end;
{free all database}
FConnectionPoolCS.Acquire;
Try
while FConnectionPoolCount > 0 do begin
Try
FLibrary.MySql_close(FConnectionPool[FConnectionPoolcount - 1].ConnectionHandle);
Except
//Disconnect must be a "safe" procedure because it's mostly called in
//finalization part of the code that it is not protected
End;
Dec(FConnectionPoolCount);
end;
FLastConnectionGarbage := GettickCount64;
finally
FConnectionPoolCS.Release;
end;
finally
//Do not forbid anymore new thread to create a new transaction
FReleasingAllconnections := False;
End;
finally
try
dec(_ThreadInitRefCount);
if _ThreadInitRefCount = 0 then FLibrary.mysql_thread_end;
except
//must be safe
end;
end;
end;
{************************************************************************************}
procedure TalMySqlConnectionPoolClient.TransactionStart(Var ConnectionHandle: PMySql);
begin
//ConnectionHandle must be null
if assigned(ConnectionHandle) then raise Exception.Create('Connection handle must be null');
//init the aConnectionHandle
ConnectionHandle := AcquireConnection;
try
//start the transaction
UpdateData('START TRANSACTION', ConnectionHandle);
except
ReleaseConnection(ConnectionHandle, True);
raise;
end;
end;
{*****************************************************************************************************************************}
procedure TalMySqlConnectionPoolClient.TransactionCommit(var ConnectionHandle: PMySql; const CloseConnection: Boolean = False);
begin
//security check
if not assigned(ConnectionHandle) then raise Exception.Create('Connection handle can not be null');
//commit the transaction
UpdateData('COMMIT', ConnectionHandle);
//release the connection
ReleaseConnection(ConnectionHandle, CloseConnection);
end;
{*******************************************************************************************************************************}
procedure TalMySqlConnectionPoolClient.TransactionRollback(var ConnectionHandle: PMySql; const CloseConnection: Boolean = False);
var LTmpCloseConnection: Boolean;
begin
//security check
if not assigned(ConnectionHandle) then raise Exception.Create('Connection handle can not be null');
//rollback the connection
LTmpCloseConnection := CloseConnection;
Try
Try
UpdateData('ROLLBACK', ConnectionHandle);
except
//to not raise an exception, most of the time TransactionRollback
//are call inside a try ... except
//raising the exception here will hide the first exception message
//it's not a problem to hide the error here because closing the
//connection will normally rollback the data
LTmpCloseConnection := True;
End;
Finally
//release the connection
ReleaseConnection(ConnectionHandle, LTmpCloseConnection);
End;
end;
{******************************************************}
procedure TalMySqlConnectionPoolClient.OnSelectDataDone(
const SQL: AnsiString;
const RowTag: AnsiString;
const ViewTag: AnsiString;
Skip: integer;
First: Integer;
CacheThreshold: Integer;
TimeTaken: double);
begin
// virtual
end;
{******************************************************}
procedure TalMySqlConnectionPoolClient.OnUpdateDataDone(
const SQL: AnsiString;
TimeTaken: double);
begin
// virtual
end;
{************************************************}
procedure TalMySqlConnectionPoolClient.SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
const ViewTag: AnsiString;
Skip: integer; // used only if value is > 0
First: Integer; // used only if value is > 0
CacheThreshold: Integer; // The threshold value (in ms) determine whether we will use
// cache or not. Values <= 0 deactivate the cache
XMLDATA: TalXMLNode;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil);
Var LMySqlRes: PMYSQL_RES;
LMySqlRow: PMYSQL_ROW;
LMySqlFields: array of PMYSQL_FIELD;
LMySqlFieldLengths: PMYSQL_LENGTHS;
LColumnCount: Integer;
LColumnIndex: integer;
LNewRec: TalXmlNode;
LValueRec: TalXmlNode;
LViewRec: TalXmlNode;
LRecIndex: integer;
LRecAdded: integer;
LTmpConnectionHandle: PMySql;
LOwnConnection: Boolean;
LContinue: Boolean;
LXmlDocument: TalXmlDocument;
LUpdateRowTagByFieldValue: Boolean;
LStopWatch: TStopWatch;
LCacheKey: ansiString;
LCacheStr: ansiString;
LTmpRowTag: ansiString;
begin
//only OnNewRowFunct / XMLDATA can be used
if assigned(OnNewRowFunct) then XMLDATA := nil;
//clear the XMLDATA
if assigned(XMLDATA) then LXmlDocument := Nil
else begin
LXmlDocument := TALXmlDocument.create('root');
XMLDATA := LXmlDocument.DocumentElement;
end;
try
//init the TstopWatch
LStopWatch := TstopWatch.Create;
//Handle the CacheThreshold
LCacheKey := '';
If (CacheThreshold > 0) and
(not assigned(LXmlDocument)) and
((XMLdata.ChildNodes.Count = 0) or // else the save will not work
(ViewTag <> '')) then begin
//try to load from from cache
LCacheKey := ALStringHashSHA1(
RowTag + '#' +
ALIntToStrA(Skip) + '#' +
ALIntToStrA(First) + '#' +
ALGetFormatSettingsID(FormatSettings) + '#' +
SQL);
if loadcachedData(LCacheKey, LCacheStr) then begin
//init the aViewRec
if (ViewTag <> '') then LViewRec := XMLdata.AddChild(ViewTag)
else LViewRec := XMLdata;
//assign the tmp data to the XMLData
LViewRec.LoadFromXML(LCacheStr, true{XmlContainOnlyChildNodes}, false{ClearChildNodes});
//exit
exit;
end;
end;
//acquire a connection and start the transaction if necessary
LTmpConnectionHandle := ConnectionHandle;
LOwnConnection := (not assigned(ConnectionHandle));
if LOwnConnection then TransactionStart(LTmpConnectionHandle);
Try
//start the TstopWatch
LStopWatch.Reset;
LStopWatch.Start;
//prepare the query
CheckAPIError(LTmpConnectionHandle, fLibrary.mysql_real_query(LTmpConnectionHandle, PAnsiChar(SQL), length(SQL)) <> 0);
LMySqlRes := fLibrary.mysql_use_result(LTmpConnectionHandle);
CheckAPIError(LTmpConnectionHandle, LTmpConnectionHandle = nil);
Try
//Returns the number of columns in a result set.
LColumnCount := fLibrary.mysql_num_fields(LMySqlRes);
//init the aMySqlFields array
//this not work anymore in MYSQL5.5, i don't know why so i use mysql_fetch_field instead
//aMySqlFields := fLibrary.mysql_fetch_fields(aMySqlRes);
setlength(LMySqlFields,LColumnCount);
for LColumnIndex := 0 to LColumnCount - 1 do
LMySqlFields[LColumnIndex] := fLibrary.mysql_fetch_field(LMySqlRes);
//init the aViewRec
if (ViewTag <> '') and (not assigned(LXmlDocument)) then LViewRec := XMLdata.AddChild(ViewTag)
else LViewRec := XMLdata;
//init aUpdateRowTagByFieldValue
if ALPosA('&>',RowTag) = 1 then begin
LTmpRowTag := ALcopyStr(RowTag,3,maxint);
LUpdateRowTagByFieldValue := LTmpRowTag <> '';
end
else begin
LTmpRowTag := RowTag;
LUpdateRowTagByFieldValue := False;
end;
//loop throught all row
LRecIndex := 0;
LRecAdded := 0;
while True do begin
//retrieve the next row. return A MYSQL_ROW structure for the next row.
//NULL if there are no more rows to retrieve or if an error occurred.
LMySqlRow := fLibrary.mysql_fetch_row(LMySqlRes);
//break if no more row
if LMySqlRow = nil then begin
CheckAPIerror(LTmpConnectionHandle, Flibrary.mysql_errno(LTmpConnectionHandle) <> 0);
break;
end
//download the row
else begin
//process if > Skip
inc(LRecIndex);
If LRecIndex > Skip then begin
//init NewRec
if (LTmpRowTag <> '') and (not assigned(LXmlDocument)) then LNewRec := LViewRec.AddChild(LTmpRowTag)
Else LNewRec := LViewRec;
//init aMySqlFieldLengths
LMySqlFieldLengths := fLibrary.mysql_fetch_lengths(LMySqlRes);
CheckAPIerror(LTmpConnectionHandle, LMySqlFieldLengths = nil);
//loop throught all column
For LColumnIndex := 0 to LColumnCount - 1 do begin
LValueRec := LNewRec.AddChild(ALlowercase(LMySqlFields[LColumnIndex].name));
if (LMySqlFields[LColumnIndex]._type in [FIELD_TYPE_TINY_BLOB,
FIELD_TYPE_MEDIUM_BLOB,
FIELD_TYPE_LONG_BLOB,
FIELD_TYPE_BLOB]) then LValueRec.ChildNodes.Add(
LValueRec.OwnerDocument.CreateNode(
GetFieldValue(
LMySqlRow[LColumnIndex],
LMySqlFields[LColumnIndex]._type,
LMySqlFieldLengths[LColumnIndex],
FormatSettings),
ntCData))
else LValueRec.Text := GetFieldValue(
LMySqlRow[LColumnIndex],
LMySqlFields[LColumnIndex]._type,
LMySqlFieldLengths[LColumnIndex],
FormatSettings);
if LUpdateRowTagByFieldValue and (LValueRec.NodeName=LNewRec.NodeName) then LNewRec.NodeName := ALLowerCase(LValueRec.Text);
end;
//handle OnNewRowFunct
if assigned(OnNewRowFunct) then begin
LContinue := True;
OnNewRowFunct(LNewRec, ViewTag, ExtData, LContinue);
if Not LContinue then Break;
end;
//free the node if aXmlDocument
if assigned(LXmlDocument) then LXmlDocument.DocumentElement.ChildNodes.Clear;
//handle the First
inc(LRecAdded);
If (First > 0) and (LRecAdded >= First) then Break;
end;
end;
end;
Finally
//Frees the memory allocated to aMySqlRes
fLibrary.mysql_free_result(LMySqlRes);
End;
//do the OnSelectDataDone
LStopWatch.Stop;
OnSelectDataDone(
SQL,
RowTag,
ViewTag,
Skip,
First,
CacheThreshold,
LStopWatch.Elapsed.TotalMilliseconds);
//save to the cache
If LCacheKey <> '' then begin
//save the data
LViewRec.SaveToXML(LCacheStr, true{SaveOnlyChildNodes});
SaveDataToCache(
LCacheKey,
CacheThreshold,
LCacheStr);
end;
//commit the transaction and release the connection if owned
if LOwnConnection then TransactionCommit(LTmpConnectionHandle);
except
on E: Exception do begin
// rollback the transaction and release the connection if owned
// TODO
// instead of closing the connection, it's could be better to know
// if the error is related to the connection, or related to the
// SQL (like we do in Alcinoe.FBX.Client with GetCloseConnectionByErrCode
if LOwnConnection then TransactionRollback(LTmpConnectionHandle, true);
//raise the error
raise;
end;
end;
finally
if assigned(LXmlDocument) then LXmlDocument.free;
end;
end;
{************************************************}
procedure TalMySqlConnectionPoolClient.SelectData(
const SQL: AnsiString;
Skip: Integer;
First: Integer;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil);
begin
SelectData(
SQL,
'', // RowTag,
'', // ViewTag,
Skip,
First,
-1, // CacheThreshold,
nil, // XMLDATA,
OnNewRowFunct,
ExtData,
FormatSettings,
ConnectionHandle);
end;
{************************************************}
procedure TalMySqlConnectionPoolClient.SelectData(
const SQL: AnsiString;
OnNewRowFunct: TalMySqlClientSelectDataOnNewRowFunct;
ExtData: Pointer;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil);
begin
SelectData(
SQL,
'', // RowTag,
'', // ViewTag,
-1, // Skip,
-1, // First,
-1, // CacheThreshold,
nil, // XMLDATA,
OnNewRowFunct,
ExtData,
FormatSettings,
ConnectionHandle);
end;
{************************************************}
procedure TalMySqlConnectionPoolClient.SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
Skip: Integer;
First: Integer;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil);
begin
SelectData(
SQL,
RowTag,
'', // ViewTag,
Skip,
First,
-1, // CacheThreshold,
XMLDATA,
nil, // OnNewRowFunct,
nil, // ExtData,
FormatSettings,
ConnectionHandle);
end;
{************************************************}
procedure TalMySqlConnectionPoolClient.SelectData(
const SQL: AnsiString;
const RowTag: AnsiString;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil);
begin
SelectData(
SQL,
RowTag,
'', // ViewTag,
-1, // Skip,
-1, // First,
-1, // CacheThreshold,
XMLDATA,
nil, // OnNewRowFunct,
nil, // ExtData,
FormatSettings,
ConnectionHandle);
end;
{************************************************}
procedure TalMySqlConnectionPoolClient.SelectData(
const SQL: AnsiString;
XMLDATA: TalXMLNode;
const FormatSettings: TALFormatSettingsA;
const ConnectionHandle: PMySql = nil);
begin
SelectData(
SQL,
'', // RowTag,
'', // ViewTag,
-1, // Skip,
-1, // First,
-1, // CacheThreshold,
XMLDATA,
nil, // OnNewRowFunct,
nil, // ExtData,
FormatSettings,
ConnectionHandle);
end;
{*************************************************************************************************************}
procedure TalMySqlConnectionPoolClient.UpdateData(const SQL: AnsiString; const ConnectionHandle: PMySql = nil);
Var LTmpConnectionHandle: PMySql;
LOwnConnection: Boolean;
LStopWatch: TStopWatch;
begin
//acquire a connection and start the transaction if necessary
LTmpConnectionHandle := ConnectionHandle;
LOwnConnection := (not assigned(ConnectionHandle));
if LOwnConnection then TransactionStart(LTmpConnectionHandle);
Try
//init the TstopWatch
LStopWatch := TstopWatch.Create;
//start the TstopWatch
LStopWatch.Reset;
LStopWatch.Start;
//do the query
CheckAPIError(LTmpConnectionHandle, fLibrary.mysql_real_query(LTmpConnectionHandle, PAnsiChar(SQL), length(SQL)) <> 0);
//do the OnUpdateDataDone
LStopWatch.Stop;
OnUpdateDataDone(
SQL,
LStopWatch.Elapsed.TotalMilliseconds);
//commit the transaction and release the connection if owned
if LOwnConnection then TransactionCommit(LTmpConnectionHandle);
except
On E: Exception do begin
// rollback the transaction and release the connection if owned
// TODO
// instead of closing the connection, it's could be better to know
// if the error is related to the connection, or related to the
// SQL (like we do in Alcinoe.FBX.Client with GetCloseConnectionByErrCode
if LOwnConnection then TransactionRollback(LTmpConnectionHandle, true);
//raise the error
raise;
end;
end;
end;
{************************************************}
procedure TalMySqlConnectionPoolClient.UpdateData(
const SQLs: array of AnsiString;
const ConnectionHandle: PMySql = nil);
Var LTmpConnectionHandle: PMySql;
LOwnConnection: Boolean;
I: integer;
begin
//acquire a connection and start the transaction if necessary
LTmpConnectionHandle := ConnectionHandle;
LOwnConnection := (not assigned(ConnectionHandle));
if LOwnConnection then TransactionStart(LTmpConnectionHandle);
Try
//update the data
for I := Low(SQLs) to High(SQLs) do
UpdateData(
SQLs[I],
LTmpConnectionHandle);
//commit the transaction and release the connection if owned
if LOwnConnection then TransactionCommit(LTmpConnectionHandle);
except
On E: Exception do begin
// rollback the transaction and release the connection if owned
// TODO
// instead of closing the connection, it's could be better to know
// if the error is related to the connection, or related to the
// SQL (like we do in Alcinoe.FBX.Client with GetCloseConnectionByErrCode
if LOwnConnection then TransactionRollback(LTmpConnectionHandle, true);
//raise the error
raise;
end;
end;
end;
{************************************************}
procedure TalMySqlConnectionPoolClient.UpdateData(
SQLs: TALStringsA;
const ConnectionHandle: PMySql = nil);
Var LTmpConnectionHandle: PMySql;
LOwnConnection: Boolean;
I: integer;
begin
//acquire a connection and start the transaction if necessary
LTmpConnectionHandle := ConnectionHandle;
LOwnConnection := (not assigned(ConnectionHandle));
if LOwnConnection then TransactionStart(LTmpConnectionHandle);
Try
//update the data
for I := 0 to SQLs.Count - 1 do
UpdateData(
SQLs[I],
LTmpConnectionHandle);
//commit the transaction and release the connection if owned
if LOwnConnection then TransactionCommit(LTmpConnectionHandle);
except
On E: Exception do begin
// rollback the transaction and release the connection if owned
// TODO
// instead of closing the connection, it's could be better to know
// if the error is related to the connection, or related to the
// SQL (like we do in Alcinoe.FBX.Client with GetCloseConnectionByErrCode
if LOwnConnection then TransactionRollback(LTmpConnectionHandle, true);
//raise the error
raise;
end;
end;
end;
{**********************************************************************************************************************}
function TalMySqlConnectionPoolClient.insert_id(const SQL: AnsiString; const ConnectionHandle: PMySql = nil): ULongLong;
Var LTmpConnectionHandle: PMySql;
LOwnConnection: Boolean;
begin
//acquire a connection and start the transaction if necessary
LTmpConnectionHandle := ConnectionHandle;
LOwnConnection := (not assigned(ConnectionHandle));
if LOwnConnection then TransactionStart(LTmpConnectionHandle);
Try
//if the SQL is not empty
if SQL <> '' then begin
//do the query
UpdateData(SQL, LTmpConnectionHandle);
//Returns the value generated for an AUTO_INCREMENT column
//by the previous INSERT or UPDATE statement
Result := fLibrary.mysql_insert_id(LTmpConnectionHandle);
end
//if the SQL is empty, simply gave an 0 result
else result := 0;
//commit the transaction and release the connection if owned
if LOwnConnection then TransactionCommit(LTmpConnectionHandle);
except
On E: Exception do begin
// rollback the transaction and release the connection if owned
// TODO
// instead of closing the connection, it's could be better to know
// if the error is related to the connection, or related to the
// SQL (like we do in Alcinoe.FBX.Client with GetCloseConnectionByErrCode
if LOwnConnection then TransactionRollback(LTmpConnectionHandle, true);
//raise the error
raise;
end;
end;
end;
{*************************************************************}
function TalMySqlConnectionPoolClient.ConnectionCount: Integer;
begin
FConnectionPoolCS.Acquire;
Try
Result := FConnectionPoolCount + FWorkingConnectionCount;
finally
FConnectionPoolCS.Release;
end;
end;
{********************************************************************}
function TalMySqlConnectionPoolClient.WorkingConnectionCount: Integer;
begin
FConnectionPoolCS.Acquire;
Try
Result := FWorkingConnectionCount;
finally
FConnectionPoolCS.Release;
end;
end;
initialization
ALMySQLFormatSettings := TALFormatSettingsA.Create('en-US'); // 1033 {en-US}
ALMySQLFormatSettings.DecimalSeparator := '.';
ALMySQLFormatSettings.ThousandSeparator := ',';
ALMySQLFormatSettings.DateSeparator := '-';
ALMySQLFormatSettings.TimeSeparator := ':';
ALMySQLFormatSettings.ShortDateFormat := 'yyyy/mm/dd';
ALMySQLFormatSettings.ShortTimeFormat := 'hh:nn:ss';
end.
|
unit Threads;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls;
type
TThreads = class(TThread)
FTempoMaximo: Integer;
FNumeroThreads: Integer;
procedure SetTempoMaximo(const Value: integer);
procedure SetNumeroThreads(const Value: integer);
procedure IncrementProgressBar;
{ Private declarations }
protected
procedure TMemoThreadInicio;
procedure TMemoThreadFim;
procedure Execute; override;
private
FForm: TForm;
procedure DecNumeroThreads;
public
constructor Create(CreateSuspended: Boolean; AForm: TForm);
property TempoMaximo: integer read FTempoMaximo write SetTempoMaximo;
property NumeroThreads: integer read FNumeroThreads write SetNumeroThreads;
end;
TfThreads = class(TForm)
EDNumeroThreads: TEdit;
EDTempMax: TEdit;
Button1: TButton;
ProgressBar1: TProgressBar;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
private
FNumeroDeThreads: Integer;
{ Private declarations }
public
{ Public declarations }
end;
var
fThreads: TfThreads;
implementation
{$R *.dfm}
procedure TfThreads.Button1Click(Sender: TObject);
var
I: Integer;
LThread: TThreads;
begin
ProgressBar1.Min := 0;
ProgressBar1.Max := (StrToInt(EDNumeroThreads.Text) * 101) + StrToInt(EDNumeroThreads.Text);
ProgressBar1.Position := 0;
for I := 0 to StrToInt(EDNumeroThreads.Text) do
begin
LThread := TThreads.Create(True, Self);
LThread.FreeOnTerminate := True;
FNumeroDeThreads := FNumeroDeThreads + 1;
LThread.TempoMaximo := StrToInt(EDTempMax.Text);
LThread.Start;
end;
end;
{ TThreads }
procedure TThreads.DecNumeroThreads;
var
LFormAux : TfThreads;
begin
inherited;
LFormAux := FForm as TfThreads;
LFormAux.FNumeroDeThreads := LFormAux.FNumeroDeThreads - 1;
end;
procedure TThreads.Execute;
var
I: Integer;
LTime : Integer;
begin
inherited;
Synchronize(TMemoThreadInicio);
while not(Terminated) do
begin
for I := 0 to (100) do
begin
LTime := Random(Self.TempoMaximo);
Sleep(LTime);
Synchronize(IncrementProgressBar);
end;
Synchronize(DecNumeroThreads);
Synchronize(IncrementProgressBar);
Synchronize(TMemoThreadFim);
end;
end;
procedure TThreads.IncrementProgressBar;
var
LFormAux : TfThreads;
begin
LFormAux := FForm as TfThreads;
LFormAux.ProgressBar1.Position := LFormAux.ProgressBar1.Position + 1;
end;
procedure TThreads.SetNumeroThreads(const Value: integer);
begin
FNumeroThreads := Value;
end;
procedure TThreads.SetTempoMaximo(const Value: integer);
begin
FTempoMaximo := Value;
end;
procedure TThreads.TMemoThreadFim;
var
LFormAux : TfThreads;
begin
LFormAux := FForm as TfThreads;
LFormAux.Memo1.Lines.Add(Self.ThreadID.ToString+' – Processo finalizado');
end;
procedure TThreads.TMemoThreadInicio;
var
LFormAux : TfThreads;
begin
LFormAux := FForm as TfThreads;
LFormAux.Memo1.Lines.Add(Self.ThreadID.ToString+' – Iniciando processamento');
end;
constructor TThreads.Create(CreateSuspended: Boolean; AForm: TForm);
begin
inherited Create (CreateSuspended);
FForm := AForm;
FreeOnTerminate := True;
end;
procedure TfThreads.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := True;
if FNumeroDeThreads > 0 then
begin
Application.MessageBox('Existem threads em execução. Aguardo o fim do processo',
'Atenção',MB_OK);
CanClose := false;
end;
end;
procedure TfThreads.FormCreate(Sender: TObject);
begin
FNumeroDeThreads := 0;
end;
end.
|
unit PropMapEditController;
interface
uses
Classes, SysUtils, tiObject, mapper, mvc_base, widget_controllers, AppModel,
PropMapEditViewFrm, BaseOkCancelDialogController, BaseDialogViewFrm;
type
// -----------------------------------------------------------------
// Class Objects
// -----------------------------------------------------------------
{: Main application controller. }
TPropMapEditController = class(TBaseOkCancelDialogController)
private
FPropertyTypes: TMapPropertyTypeList;
FClassProps: TMapClassPropList;
protected
procedure DoCreateMediators; override;
procedure HandleOKClick(Sender: TObject); override;
public
constructor Create; override;
destructor Destroy; override;
procedure Init; override;
function Model: TPropMapping; reintroduce;
function View: TPropMapEditView; reintroduce;
end;
implementation
uses
vcl_controllers, StdCtrls, Controls, Dialogs;
{ TClassPropEditController }
constructor TPropMapEditController.Create;
begin
inherited;
FClassProps := TMapClassPropList.Create;
FClassProps.OwnsObjects := false;
FPropertyTypes := TMapPropertyTypeList.Create;
FPropertyTypes.OwnsObjects := false;
end;
destructor TPropMapEditController.Destroy;
begin
FClassProps.Free;
FPropertyTypes.Free;
inherited;
end;
procedure TPropMapEditController.DoCreateMediators;
var
lCboCtrl: TComboBoxController;
begin
inherited;
lCboCtrl := TComboBoxController.Create(Model, View.cboPropName, 'PropName');
lCboCtrl.ListData := FClassProps;
lCboCtrl.ListDisplayProp := 'Name';
lCboCtrl.ListValueProp := 'Name';
AddController(lCboCtrl);
lCboCtrl := TComboBoxController.Create(Model, View.cboPropType, 'PropertyType');
lCboCtrl.ListData := FPropertyTypes;
lCboCtrl.ListDisplayProp := 'TypeName';
lCboCtrl.ListValueProp := 'TypeName';
AddController(lCboCtrl);
AddController(TEditController.Create(Model, View.eFieldName, 'FieldName'));
end;
procedure TPropMapEditController.HandleOKClick(Sender: TObject);
var
lMsg: string;
begin
if not Model.IsValid(lMsg) then
begin
MessageDlg('Error(s): ' + sLineBreak + lMsg, mtError, [mbOK], 0);
exit;
end;
inherited;
end;
procedure TPropMapEditController.Init;
var
lMapClass: TMapClassDef;
begin
lMapClass := TMapClassDef(ParentController.Model);
FClassProps.Assign(lMapClass.ClassProps);
FClassProps.SortByProps(['Name']);
FPropertyTypes.Assign(TAppModel.Instance.CurrentPropertyTypes);
FPropertyTypes.SortByProps(['TypeName']);
inherited;
end;
function TPropMapEditController.Model: TPropMapping;
begin
result := inherited Model as TPropMapping;
end;
function TPropMapEditController.View: TPropMapEditView;
begin
result := inherited View as TPropMapEditView;
end;
end.
|
unit u.graph;
interface
uses
FMX.Graphics // for TCanvas
, System.UITypes // for TAlphaColorRec + others
, System.Math.Vectors // for TPolygon + others
, FMX.Objects;
Function GetColor(Const nColor: Integer): TAlphaColor;
procedure DrawText(var Region: Trectangle; const sText: String; Y1, X1: Single; Const Color, background: TAlphaColor);
procedure Cls(var Region: Trectangle; Color: TAlphaColor = TAlphaColorRec.Black);
procedure MakePNG(Var aImage: TBitmap; Const filename: string);
Procedure DrawSprite(var Region: Trectangle; const oBmp: TBitmap; Y1, X1: Single; Const Color, background: TAlphaColor; lOver:Boolean = true);
implementation
uses
System.Types, FMX.Types, System.Classes, FMX.Surfaces, System.SysUtils;
Function GetColor(Const nColor: Integer): TAlphaColor;
begin
case nColor of
0: Result := TAlphaColorRec.Black;
1: Result := TAlphaColorRec.Blue;
2: Result := TAlphaColorRec.Green;
3: Result := TAlphaColorRec.Cyan;
4: Result := TAlphaColorRec.Red;
5: Result := TAlphaColorRec.Magenta;
6: Result := TAlphaColorRec.Brown;
7: Result := TAlphaColorRec.White;
8: Result := TAlphaColorRec.Grey;
9: Result := TAlphaColorRec.Lightblue;
10: Result := TAlphaColorRec.Lightgreen;
11: Result := TAlphaColorRec.Lightcyan;
12: Result := TAlphaColorRec.Red;
13: Result := TAlphaColorRec.Lightcoral;
14: Result := TAlphaColorRec.Yellow;
15: Result := TAlphaColorRec.White;
else
Result := TAlphaColorRec.Black;
end;
end;
Procedure DrawSprite(var Region: Trectangle; const oBmp: TBitmap; Y1, X1: Single; Const Color, background: TAlphaColor; lOver:Boolean = true);
var mRect, mRectSource: TRectF;
sWidth: Single;
sHeight: Single;
FB: TBrush;
bitdata1: TBitmapData;
y: Integer;
x: Integer;
oLocalBMP: TBitmap;
begin
if assigned(Region.Fill.Bitmap.Bitmap.Canvas) then
begin
Region.Fill.Bitmap.Bitmap.Canvas.BeginScene();
oLocalBMP := TBitmap.Create;
try
oLocalBMP.Assign(oBmp);
if (oBmp.Map(TMapAccess.ReadWrite, bitdata1)) then
try
for y := 0 to 7 do
for x := 0 to 7 do
if bitdata1.GetPixel(x, y) <> 0 then
bitdata1.SetPixel(x, y, Color)
else
begin
if background <> 0 then
bitdata1.SetPixel(x, y, background);
end;
finally
oBmp.Unmap(bitdata1);
end;
Region.Fill.Bitmap.Bitmap.canvas.Stroke.Kind := TBrushKind.None;
Region.Fill.Bitmap.Bitmap.canvas.StrokeThickness := 0;
sWidth := 8;
sHeight := 8;
X1 := (X1 * sWidth);
Y1 := (Y1 * sHeight);
mRect.Create(X1, Y1, X1 + sWidth, Y1 + sHeight);
mRectSource.Create(0, 0, oBmp.Width, oBmp.Height);
if not lOver then
begin
FB := TBrush.Create(TBrushKind.bkSolid, Background);
Region.Fill.Bitmap.Bitmap.Canvas.FillRect(mrect,0,0,[],1,FB);
FreeAndNil(FB);
end;
Region.Fill.Bitmap.bitmap.Canvas.DrawBitmap(oBmp, mRectSource, mRect, 1.0);
finally
Region.Fill.Bitmap.Bitmap.Canvas.EndScene;
oBmp.Assign(oLocalBMP);
oLocalBMP.Free;
oLocalBMP := Nil;
end;
end;
end;
procedure DrawText(var Region:Trectangle;const sText: String; Y1, X1: Single; Const Color, Background: TAlphaColor );
var mRect: TRectF;
sWidth: Single;
sHeight: Single;
FB: TBrush;
begin
if assigned(Region.Fill.Bitmap.Bitmap.Canvas) then begin
Region.Fill.Bitmap.Bitmap.Canvas.BeginScene();
try
Region.Fill.Bitmap.bitmap.Canvas.Font.Family := 'Courier New';
Region.Fill.Bitmap.bitmap.Canvas.Font.size := 8;
Region.Fill.Bitmap.Bitmap.canvas.Stroke.Kind := TBrushKind.None;
Region.Fill.Bitmap.Bitmap.canvas.StrokeThickness := 0;
Region.Fill.Bitmap.bitmap.Canvas.Fill.Color := Color;
sWidth := 8;//Region.Fill.Bitmap.bitmap.Canvas.TextWidth('X');
sHeight := 8;//Region.Fill.Bitmap.bitmap.Canvas.TextHeight('X');
X1 := (X1 * sWidth);
Y1 := (Y1 * sHeight);
sWidth := 8 * Length(sText);//Region.Fill.Bitmap.bitmap.Canvas.TextWidth(sText);
sHeight := Region.Fill.Bitmap.bitmap.Canvas.TextHeight(sText);
mRect.Create(X1, Y1, X1 + sWidth, Y1 + sHeight);
FB := TBrush.Create(TBrushKind.bkSolid, Background);
Region.Fill.Bitmap.Bitmap.Canvas.FillRect(mrect,0,0,[],1,FB);
FreeAndNil(FB);
Region.Fill.Bitmap.bitmap.Canvas.FillText(mRect, sText, false, 1.0, [], TTextAlign.Leading, TTextAlign.Center);
finally
Region.Fill.Bitmap.Bitmap.Canvas.EndScene;
end;
end;
end;
procedure Cls(var Region:Trectangle; Color: TAlphaColor = TAlphaColorRec.Black);
Var X1, Y1: Integer;
mRect: TRectF;
FB: TBrush;
begin
if assigned(Region.Fill.Bitmap.Bitmap.Canvas) then begin
Region.Fill.Bitmap.Bitmap.Canvas.BeginScene();
try
X1 := 0;
Y1 := 0;
mRect.Create(X1, Y1, X1 + Region.Width, Y1 + Region.Height);
FB := TBrush.Create(TBrushKind.bkSolid, Color);
Region.Fill.Bitmap.Bitmap.Canvas.FillRect(mrect,0,0,[],1,FB);
FreeAndNil(FB);
finally
Region.Fill.Bitmap.Bitmap.Canvas.EndScene;
end;
end;
end;
procedure MakePNG(Var aImage: TBitmap; Const filename: string);
var
Stream: TMemoryStream;
Surf: TBitmapSurface;
aFile : string;
begin
Stream := TMemoryStream.Create;
aImage.SaveToStream(Stream);
try
Stream.Position := 0;
Surf := TBitmapSurface.Create;
try
Surf.Assign(aImage);
if not TBitmapCodecManager.SaveToStream(
Stream,
Surf,
'.png') then
raise EBitmapSavingFailed.Create(
'Error saving Bitmap to png');
finally
Surf.Free;
end;
Stream.Position := 0;
aImage.LoadFromStream(Stream);
Stream.Position := 0;
Stream.SaveToFile(filename);
finally
Stream.Free;
end;
end;
end.
|
unit Trees;
interface
uses
Classes, Tokens;
type
TTree = class
private
FChildren: TList;
FParent: TTree; //if null it is root
FToken: IToken;
fDesc: AnsiString;
public
constructor Create(token: IToken); overload;
constructor Create(desc: AnsiString); overload;
destructor Destroy; override;
function getChild(n: integer): TTree;
function getChildCount(): integer;
function getParent(): TTree;
procedure addChild(t: TTree);
procedure addToken(token: IToken);
procedure setMainToken(token: IToken);
procedure deleteChild(n: integer);
procedure print(depth: integer);
end;
implementation
{ TTree }
procedure TTree.addToken(token: IToken);
begin
addChild(TTree.Create(token));
end;
procedure TTree.setMainToken(token: IToken);
begin
FToken := token;
end;
procedure TTree.addChild(t: TTree);
begin
if FChildren=nil then
FChildren:=TList.Create;
FChildren.Add(t);
t.FParent := self;
end;
constructor TTree.Create(token: IToken);
begin
FToken := token;
end;
constructor TTree.Create(desc: AnsiString);
begin
FDesc := desc;
end;
procedure TTree.deleteChild(n: integer);
begin
FChildren.Delete(n);
end;
destructor TTree.Destroy;
var
i: integer;
begin
if FChildren<>nil then
for i:=0 to FChildren.Count-1 do
TObject(FChildren[i]).Free;
FChildren.Free;
inherited;
end;
function TTree.getChild(n: integer): TTree;
begin
result:=FChildren[n];
end;
function TTree.getChildCount: integer;
begin
if FChildren=nil then
result:=0
else
result:=FChildren.Count;
end;
function TTree.getParent: TTree;
begin
result := FParent;
end;
procedure TTree.print(depth: integer);
var
i:integer;
begin
for i:=0 to depth-1 do write(' ');
if FToken=nil then
writeln(fDesc)
else
writeln(FToken.getValue);
if FChildren<>nil then
for i:=0 to FChildren.Count-1 do
TTree(FChildren[i]).print(depth+1);
end;
end.
|
unit AbstractApplicationServiceRegistry;
interface
uses
ApplicationService,
ApplicationServiceRegistry,
SysUtils,
Classes;
type
TAbstractApplicationServiceRegistry =
class abstract (TInterfacedObject, IApplicationServiceRegistry)
protected
function GetServiceTypeName(ServiceTypeInfo: Pointer): String;
public
procedure Clear; virtual; abstract;
procedure RegisterApplicationService(
ApplicationServiceTypeInfo: Pointer;
ApplicationService: IApplicationService
); virtual; abstract;
procedure RegisterOrUpdateApplicationService(
ApplicationServiceTypeInfo: Pointer;
ApplicationService: IApplicationService
); virtual; abstract;
function GetApplicationService(
ApplicationServiceTypeInfo: Pointer
): IApplicationService; virtual; abstract;
end;
implementation
uses
TypInfo;
{ TAbstractApplicationServiceRegistry }
function TAbstractApplicationServiceRegistry.GetServiceTypeName(
ServiceTypeInfo: Pointer): String;
begin
Result := PTypeInfo(ServiceTypeInfo)^.Name;
end;
end.
|
unit SMBlueprint;
interface
uses
System.SysUtils,
System.Classes,
DateUtils,
System.zlib,
SMBlueprintTypes
// ,DynaArray3D
;
// =============================================================================
// =============================================================================
type
TSMBlueprint = class
private
fChilds:array of TSMBlueprint;
fParent:TSMBlueprint;
fDataFiles:array of TSMDataFile;
fBlockInfos:TBlockInfoArray;
fBluePrintPath:string;
fDataName:string;
// fBlocks:TDynaArray3D;
fHeadFile:THead;
procedure LoadConfig(BlockConfigPath, BlockTypesPath:string);
procedure BlockDecode(var rawBlock:TBlockRaw; var block:TBlock);
procedure BlockEncode(var rawBlock:TBlockRaw; var block:TBlock);
procedure DataLoad(DataFolder:string);
procedure DataSave(DataFolder:string);
procedure DataFileLoad(DataFile:string;var data:TSMDataCompressed);
procedure DataFileSave(DataFile:string;var data:TSMDataCompressed);
procedure DataChunkZipUn(var ChunkZip:TChunkDataCompressed;var ChunkUnZip:TChunkDataUncompressed);
procedure DataChunkZip (var ChunkZip:TChunkDataCompressed;var ChunkUnZip:TChunkDataUncompressed;var sizeOut:integer);
procedure DataChunkDecode(var chunkRaw:TChunkDataCompressed;var chunkDecomp:TChunkDataDecoded);
procedure DataChunkEncode(var chunkRaw:TChunkDataCompressed;
var chunkDecomp:TChunkDataDecoded;
var ChunkZipSize:integer);
procedure DataDecode(var dataRaw:TSMDataCompressed;var dataDecod:TSMDataDecoded);
procedure DataEncode(var dataRaw:TSMDataCompressed;var dataDecod:TSMDataDecoded);
procedure HeadLoad(HeadFile:string;var head:THead);
procedure HeadRecalc;
procedure HeadSave(HeadFile:string;var head:THead);
function DataHeaderCreate:TDataHeader;
function DataChunkHeaderCreate(x,y,z:Integer):TChunkHeader;
function DataBlockCreate(ID:Word):TBlock;
procedure DataOptimize;
procedure CoordinatesDataToWorld(fi,ci,bi:integer;var ar:integer);
procedure CoordinatesWorldToData(var fi,ci,cci,bi:integer;ar:integer);
// procedure DataToArray;
// procedure ArrayToData;
procedure BlueprintLoad(Path:string);
procedure BlueprintSave(Path:string);
function BlockRawToBin(var blockRaw:TBlockRaw):string;
function BlockRawGetId(var blockRaw:TBlockRaw):Word;
procedure SwapBytes(p:Pointer;size:Byte);
procedure PrintHead(var head:THead;var blockInfo:TBlockInfoArray);
procedure PrintDataHead(var head:TDataHeader);
procedure PrintDataChunkHead(var head:TChunkHeader);
procedure PrintDataChunkBody(var chunk:TChunkDataDecoded;var blockInfo:TBlockInfoArray);
procedure PrintDataChunks(var chunks:TChunkArrayDecoded; var blockInfo:TBlockInfoArray);
procedure SetBlock(x,y,z:Integer;Value:TBlock);
function GetBlock(x,y,z:Integer):TBlock;
function GetBlockInfo(Id:word):TBlockInfo;
function GetBounds:THeadBoundBox;
public
procedure Load(pathDir: string);
procedure Save(pathDir: string);
procedure test;
function GetBlockNew(ID:Word):TBlock;
procedure GetStatistics(var stats:THeadElements);
property Blocks[x,y,z:Integer]:TBlock read GetBlock write SetBlock;
property BlockInfo[Id:Word]:TBlockInfo read GetBlockInfo;
property Bounds:THeadBoundBox read GetBounds;
constructor Create(BlockConfigPath, BlockTypesPath:string);
destructor Destroy;
end;
implementation
{ TSMBlueprint }
{
procedure TSMBlueprint.ArrayToData;
var
f,fx,fy,fz,c,cx,cy,cz,ccx,ccy,ccz,bx,by,bz,wx,wy,wz:Integer;
fbx,fby,fbz:Integer;
block:PBlock;
bounds:TDynaArray3DBounds;
i,j,k:integer;
chunkDecoded:TChunkDataDecoded;
fsize,csize:integer;
flag:Boolean;
begin
SetLength(fDataFiles,0);
fsize:=0;
fBlocks.Recalculate;
fBlocks.BoundsUpdate;
bounds:=fBlocks.Bounds;
fbx:=bounds.minX-1;
fby:=bounds.minY-1;
fbz:=bounds.minZ-1;
for wx := bounds.minX to bounds.maxX do
for wy := bounds.minY to bounds.maxY do
for wz := bounds.minZ to bounds.maxZ do
begin
CoordinatesArrayToData(fz,cx,ccx,bx,wx);//file X,Z is actually innner Z,X
CoordinatesArrayToData(fy,cy,ccy,by,wy);
CoordinatesArrayToData(fx,cz,ccz,bz,wz);
//find file with given coordinates
flag:=false;
if fsize>0 then
for i := 0 to fsize-1 do
with fDataFiles[i] do
begin
if (position.x=fx)AND(position.y=fy)AND(position.z=fz) then
begin
f:=i;
flag:=true;
Break;
end;
end;
if not flag then //create new file if can not find position
begin
fsize:= fsize+1;
SetLength(fDataFiles,fsize);
f:= fsize-1;
fDataFiles[f].position.x:=fx;
fDataFiles[f].position.y:=fy;
fDataFiles[f].position.z:=fz;
fDataFiles[f].data.header:= DataHeaderCreate;
SetLength(fDataFiles[f].data.chunks,0);
end;
c:= fDataFiles[f].data.header.index[cx,cy,cz].ID;
if c=-1 then //add new chunk
begin
csize:=Length(fDataFiles[f].data.chunks);
csize:=csize+1;
SetLength(fDataFiles[f].data.chunks, csize);
c:=csize-1;
fDataFiles[f].data.header.index[cx,cy,cz].ID:=c;
fDataFiles[f].data.header.time[cx,cy,cz]:= DateTimeToUnix(Now)*1000;
fDataFiles[f].data.chunks[c].header:= DataChunkHeaderCreate(ccx,ccy,ccz);
fDataFiles[f].data.chunks[c].header.time:= DateTimeToUnix(Now)*1000;
end;
//finally write block data
block:=fBlocks.Voxels[wx,wy,wz];
if block = nil then
fDataFiles[f].data.chunks[c].data[bx,by,bz]:= DataBlockCreate //empty block
else
fDataFiles[f].data.chunks[c].data[bx,by,bz]:= block^;
end;
DataOptimize; //remove empty chunks
end; }
procedure TSMBlueprint.BlockDecode(var rawBlock:TBlockRaw; var block: TBlock);
var flag:byte;
begin
{
Type1
10-0 ID
19-11 HP
23 22 21 The block facing
Type2
10-0 ID
19-11 HP
23 22 The axis of rotation.
00 : +Y
01 : -Y
10 : -Z
11 : +Z
21 20 The amount of clockwise rotation around the axis of rotation, in 90-degree steps
Type3
10-0 ID
18-11 HP
19 23 22 The axis of rotation.
000 : +Y
001 : -Y
010 : -Z
011 : +Z
100 : -X
101 : +X
21 20 The amount of clockwise rotation around the axis of rotation, in 90-degree steps
}
{
bits from 24 to 1
11 to 1 is block ID, 2047 blocks types
18 to 12 is block HP, 255 HP max
24 to 19 is block specific status, like active and/or facing and rotation
}
with block do begin
//get ID
flag:=$7; //111 bin 9-11(1-3) bits
ID:= (rawBlock[1] and flag) shl 8;
ID:= ID + rawBlock[2]; // 1-8 bits
//if ID = 0 then nothing to do here
if ID = 0 then
Exit;
//get HP
flag:=$7;// 111 bin 19-17 bits
HP:= (rawBlock[0] and flag) shl 5;
flag:=$F8; // 1111 1000 bin 16-12(8-4) bits
HP:= HP + ((rawBlock[1] and flag) shr 3);
//get Active status. Default 0 = active
if fBlockInfos[ID].canACtivate then begin
flag:=$8; //1000 bin 20(4) bits
active:= (rawBlock[0] and flag) shr 3;
end;
//whatever we do - store first 5 bits
//to remember orientation data to replace not implemented code
orientation:=(rawBlock[0] and $f8) shr 3; // 1111 1000 bin to 1 1111 bin
//init facing info
rX:=0;
rY:=0;
rZ:=0;
tX:=0;
tY:=0;
tZ:=0;
flag:=$F0; //1111 0000 bin 24-21(8-5) bits
//ration
flag:=(rawBlock[0] and flag);
flag:= flag shr 4; // 11110000 bin to 1111 bin
//find facing sides
// +x (f)orward
// -x (b)ackward
// +y (u)p
// -y (d)own
// -z (r)ight
// +z (l)eft
bGeom:= fBlockInfos[ID].blockGeometry;
case bGeom of
//Cube have one primary rectangle face what define ration
bgCube:begin
{Cube
0000 +x
0001 -x
0010 +y
0011 -y
0100 -z
0101 +z}
case flag of
0:rX:=1;
1:rX:=-1;
2:rY:=1;
3:rY:=-1;
4:rZ:=-1;
5:rZ:=1;
end;
end;
bgWedge:begin
//Wedge have two primary rectangle faces what define ration
//also have 2 triangle faces what not important and defined by rectangles
{Wedge
0000 df
0001 dl
0010 db
0011 dr
}
case flag of
0:begin
rX:=1;
rY:=-1;
end;
1:begin
rY:=-1;
rZ:=1
end;
2:begin
rX:=-1;
rY:=-1;
end;
3:begin
rY:=-1;
rZ:=-1
end;
{Wedge
0100 uf
0101 ur
0110 ub
0111 ul
}
4:begin
rX:=1;
rY:=1;
end;
5:begin
rY:=1;
rZ:=-1
end;
6:begin
rX:=-1;
rY:=1
end;
7:begin
rY:=1;
rZ:=1;
end;
{Wedge
1000 rf
1001 rb
1010 lf
1011 lb}
8:begin
rX:=1;
rZ:=-1
end;
9:begin
rX:=-1;
rZ:=-1
end;
10:begin
rX:=1;
rZ:=1
end;
11:begin
rX:=-1;
rZ:=1
end;
end;
end;
bgCorner:begin
//Corner have primary 1 rectangle and 2 triangle faces
// what define ration
//Flag is about 1111 bin
//plus used additional bit for rotation for Corner block
//I will place this bit to begin the of "flag"
//but reference is not changed, so rightest bit in ref is leftest bit in "flag"
//1000 bin to 1 000 bin and OR with flag 1111 bin
flag:=flag or ((rawBlock[2] and $8)shl 1);
{Corner
00000 dfr
00010 dbr
00100 dbl
00110 dfl
01000 ufr
01010 ubr
01100 ubl
01110 ufl
10000 bur
10010 bul
10100 bdl
10110 bdr
11000 fdr
11010 fur
11100 ful
11110 fdl
00001 rbd
00011 rbu
00101 rfu
00111 rfd
01001 lbd
01011 lbu
01101 lfu
01111 lfd
}
{Wedge
00000 dfr
00010 dbr
00100 dbl
00110 dfl}
case flag of
0:begin
rY:=-1;
tX:=1;
tZ:=-1;
end;
1:begin
rY:=-1;
tX:=-1;
tZ:=-1;
end;
2:begin
rY:=-1;
tX:=-1;
tZ:=1;
end;
3:begin
rY:=-1;
tX:=1;
tZ:=1;
end;
{Wedge
01000 ufr
01010 ubr
01100 ubl
01110 ufl}
4:begin
rY:=1;
tX:=1;
tZ:=-1;
end;
5:begin
rY:=1;
tX:=-1;
tZ:=-1;
end;
6:begin
rY:=1;
tX:=-1;
tZ:=1;
end;
7:begin
rY:=1;
tX:=1;
tZ:=1;
end;
{Wedge
10000 bur
10010 bul
10100 bdl
10110 bdr}
8:begin
rX:=-1;
tY:=1;
tZ:=-1;
end;
9:begin
rX:=-1;
tY:=1;
tZ:=1;
end;
10:begin
rX:=-1;
tY:=-1;
tZ:=1;
end;
11:begin
rX:=-1;
tY:=-1;
tZ:=-1;
end;
{Wedge
11000 fdr
11010 fur
11100 ful
11110 fdl}
12:begin
rX:=1;
tY:=-1;
tZ:=-1;
end;
13:begin
rX:=1;
tY:=1;
tZ:=-1;
end;
14:begin
rX:=1;
tY:=1;
tZ:=1;
end;
15:begin
rX:=1;
tY:=-1;
tZ:=1;
end;
{Wedge
00001 rbd
00011 rbu
00101 rfu
00111 rfd}
16:begin
rZ:=-1;
tX:=-1;
tY:=-1;
end;
17:begin
rZ:=-1;
tX:=-1;
tY:=1;
end;
18:begin
rZ:=-1;
tX:=1;
tY:=1;
end;
19:begin
rZ:=-1;
tX:=1;
tY:=-1;
end;
{Wedge
01001 lbd
01011 lbu
01101 lfu
01111 lfd}
20:begin
rZ:=1;
tX:=-1;
tY:=-1;
end;
21:begin
rZ:=1;
tX:=-1;
tY:=1;
end;
22:begin
rZ:=1;
tX:=1;
tY:=1;
end;
23:begin
rZ:=1;
tX:=1;
tY:=-1;
end;
end;
end;
//not implemented yet
bgXShape:begin
end;
bgTetra:begin
//Tetra ration defined by 3 trianle faces
{TETRA
0000 dfr
0001 dbr
0010 dbl
0011 dfl
0100 ufr
0101 urb
0110 ulb
0111 ulf}
{TETRA
0000 dfr
0001 dbr
0010 dbl
0011 dfl}
case flag of
0:begin
tX:=1;
tY:=-1;
tZ:=-1;
end;
1:begin
tX:=-1;
tY:=-1;
tZ:=-1;
end;
2:begin
tX:=-1;
tY:=-1;
tZ:=1;
end;
3:begin
tX:=1;
tY:=-1;
tZ:=1;
end;
{TETRA
0100 ufr
0101 urb
0110 ulb
0111 ulf}
4:begin
tX:=1;
tY:=1;
tZ:=-1;
end;
5:begin
tX:=-1;
tY:=1;
tZ:=-1;
end;
6:begin
tX:=-1;
tY:=1;
tZ:=1;
end;
7:begin
tX:=1;
tY:=1;
tZ:=1;
end;
end;
end;
bgPenta: begin
//Penta have 3 rectangle faces what define ration
//and 3 triangle faces, what not impotant and defined by rectangles
{TETRA
0000 dfr
0001 dbr
0010 dbl
0011 dfl
0100 ufr
0101 urb
0110 ulb
0111 ulf}
{TETRA
0000 dfr
0001 dbr
0010 dbl
0011 dfl}
case flag of
0:begin
rX:=1;
rY:=-1;
rZ:=-1;
end;
1:begin
rX:=-1;
rY:=-1;
rZ:=-1;
end;
2:begin
rX:=-1;
rY:=-1;
rZ:=1;
end;
3:begin
rX:=1;
rY:=-1;
rZ:=1;
end;
{TETRA
0100 ufr
0101 urb
0110 ulb
0111 ulf}
4:begin
rX:=1;
rY:=1;
rZ:=-1;
end;
5:begin
rX:=-1;
rY:=1;
rZ:=-1;
end;
6:begin
rX:=-1;
rY:=1;
rZ:=1;
end;
7:begin
rX:=1;
rY:=1;
rZ:=1;
end;
end;
end;
//not implemented yet
bgRail:begin
end;
end;//primary case end
end; // with 'block' end
end;
procedure TSMBlueprint.BlockEncode(var rawBlock: TBlockRaw; var block: TBlock);
var
flag:Integer;
orient:Byte;
begin
rawBlock[0]:= 0; //zero fill initiation
rawBlock[1]:= 0;
rawBlock[2]:= 0;
with block do begin
// if ID = 0 then nothing to do here
if ID = 0 then
Exit;
//get ID 2047 max
rawBlock[2]:= ID and $ff; // 000 1111 1111 bin; 1-8 bits
rawBlock[1]:= rawBlock[1] or ((ID shr 8) and $7); // 111 bin 9-11(1-3) bits
//get HP 255 max
rawBlock[1]:= rawBlock[1] or ((HP and $1F) shl $3);// 1 1111 bin to 1111 1000 bin 12-16(4-8) bits
rawBlock[0]:= rawBlock[0] or ((HP shr 5) and $7); // 1110 0000 bin to 111 bin 17-19(1-3) bits
//get Active status. Default 0 = active
if fBlockInfos[ID].canACtivate then
rawBlock[0]:= rawBlock[0] or (active shl 3); // 1 bin to 1000 bin 20(4) bits
//flag is XYZxyz
flag:=0;
flag:=flag+rX+1;
flag:=flag*10;
flag:=flag+rY+1;
flag:=flag*10;
flag:=flag+rZ+1;
flag:=flag*10;
flag:=flag+tX+1;
flag:=flag*10;
flag:=flag+tY+1;
flag:=flag*10;
flag:=flag+tZ+1;
//look at decode comments for information about next
orient:=0;
case fBlockInfos[ID].blockGeometry of
bgCube:
case flag of
211111: orient:=0;
011111: orient:=1;
121111: orient:=2;
101111: orient:=3;
110111: orient:=4;
112111: orient:=5;
end;
bgWedge:
case flag of
201111:orient:=0;
102111:orient:=1;
001111:orient:=2;
100111:orient:=3;
221111:orient:=4;
120111:orient:=5;
021111:orient:=6;
122111:orient:=7;
210111:orient:=8;
010111:orient:=9;
212111:orient:=10;
012111:orient:=11;
end;
bgCorner:
case flag of
{00000 dfr
00010 dbr
00100 dbl
00110 dfl}
101210:orient:=0;
101010:orient:=1;
101012:orient:=2;
101212:orient:=3;
{01000 ufr
01010 ubr
01100 ubl
01110 ufl}
121210:orient:=4;
121010:orient:=5;
121012:orient:=6;
121212:orient:=7;
{10000 bur
10010 bul
10100 bdl
10110 bdr}
011120:orient:=8;
011122:orient:=9;
011102:orient:=10;
011100:orient:=11;
{11000 fdr
11010 fur
11100 ful
11110 fdl}
211100:orient:=12;
211120:orient:=13;
211122:orient:=14;
211102:orient:=15;
{00001 rbd
00011 rbu
00101 rfu
00111 rfd}
110001:orient:=16;
110021:orient:=17;
110221:orient:=18;
110201:orient:=19;
{01001 lbd
01011 lbu
01101 lfu
01111 lfd}
112001:orient:=20;
112021:orient:=21;
112221:orient:=22;
112201:orient:=23;
end;
//not inplemented
bgXShape:orient:=(orientation shr 4)+((orientation and $f) shl 1);
bgTetra:
case flag of
{TETRA
0000 dfr
0001 dbr
0010 dbl
0011 dfl}
111200:orient:=0;
111000:orient:=1;
111002:orient:=2;
111202:orient:=3;
{TETRA
0100 ufr
0101 urb
0110 ulb
0111 ulf}
111220:orient:=4;
111020:orient:=5;
111022:orient:=6;
111222:orient:=7;
end;
bgPenta:
case flag of
{0000 dfr
0001 dbr
0010 dbl
0011 dfl}
200111:orient:=0;
000111:orient:=1;
002111:orient:=2;
202111:orient:=3;
{0100 ufr
0101 urb
0110 ulb
0111 ulf}
220111:orient:=4;
020111:orient:=5;
022111:orient:=6;
222111:orient:=7;
end;
//not inplemented
bgRail:orient:=(orientation shr 4)+((orientation and $f) shl 1);
end;// case 'blockStyle' end
end;//with 'block' end
orient:=(orient shr 4) +((orient and $f) shl 1);
orient:=orient shl 3;
rawBlock[0]:= rawBlock[0] or orient;
end;
function TSMBlueprint.BlockRawGetId(var blockRaw: TBlockRaw): Word;
begin
Result:= blockRaw[2] +( ( blockRaw[1] and $7 ) shl 8);
end;
function TSMBlueprint.BlockRawToBin(var blockRaw:TBlockRaw): string;
var
flag:byte;
p:PByte;
i:byte;
s:string;
begin
s:='';
for i := 0 to 2 do begin
p:=PByte(Cardinal(@blockRaw)+i);
flag:=$80; // bin 1000 0000
while flag > 0 do begin
if (p^ and flag)>0 then
s:=s+'1'
else
s:=s+'0';
flag:=flag shr 1;
end;
s:=s+' ';
end;
Result:=s;
end;
procedure TSMBlueprint.BlueprintLoad(Path: string);
var
i:integer;
begin
Path:=Trim(Path);
i:=Length(Path);
if Path[i]='\' then
SetLength(Path,i-1);
// HeadLoad(Path+'\'+smFileHead,);
fBluePrintPath:=Path;
DataLoad(Path+'\DATA');
HeadLoad(Path+'\'+smFileHead,fHeadFile);
// DataToArray;
end;
procedure TSMBlueprint.BlueprintSave(Path: string);
var
i:Integer;
begin
Path:=Trim(Path);
i:=Length(Path);
if Path[i]='\' then
SetLength(Path,i-1);
if not DirectoryExists(Path) then
if not CreateDir(Path) then
raise Exception.Create('Can not create dir to save files: '+path);
// ArrayToData;
DataSave(Path+'\DATA');
HeadRecalc;
HeadSave(Path+'\'+smFileHead,fHeadFile);
end;
procedure TSMBlueprint.CoordinatesWorldToData(var fi, ci, cci, bi: integer;
ar: integer);//file, chunk, chunk center, block, array
var
wi,k:integer;
begin
wi:= ar + 8 + 128;
bi:= ((wi mod 16)+16)mod 16; //real math (x mod 16) !
k:=-1;
if wi < 0 then
begin
wi:= wi - 16 - 256 + 1;
k:=1;
end;
cci:= k*128+(wi div 16)*16;
ci:= abs(((wi div 16))mod 16);
fi:= (wi div 16)div 16;
end;
procedure TSMBlueprint.CoordinatesDataToWorld(fi, ci, bi: integer;
var ar: integer); //file, chunk, block, array
var
wi,k:integer;
begin
wi:=fi*16*16;
k:=1;
if fi < 0 then
k:=-1;
wi:=wi+k*ci*16;
wi:=wi+bi;
wi:=wi-8-128+((1-k)div 2)*256;
ar:=wi;
end;
constructor TSMBlueprint.Create(BlockConfigPath,
BlockTypesPath: string);
begin
fDataName:='';
SetLength(fDataFiles,0);
//fBlocks:=TDynaArray3D.Create;
LoadConfig(BlockConfigPath,BlockTypesPath);
end;
function TSMBlueprint.DataBlockCreate(ID:Word): TBlock;
var
block:TBlock;
begin
block.bGeom:=fBlockInfos[ID].blockGeometry;
block.rX:=0;
block.rY:=0;
block.rZ:=0;
block.tX:=0;
block.tY:=0;
block.tZ:=0;
if fBlockInfos[ID].canACtivate then
block.active:=0 //set as turned off (equals 1)
else
block.active:=smBlockPropUseless;
block.rotation:=smBlockPropUseless;
block.orientation:=0;
block.HP:=fBlockInfos[ID].maxHP;
block.ID:=ID;
Result:=block;
end;
procedure TSMBlueprint.DataChunkDecode(var chunkRaw: TChunkDataCompressed;
var chunkDecomp: TChunkDataDecoded);
var
chunkUnZip:TChunkDataUncompressed;
i,j,k:integer;
begin
DataChunkZipUn(chunkRaw,chunkUnZip);
//decode block data
for i := 0 to 15 do
for j := 0 to 15 do
for k := 0 to 15 do
BlockDecode(chunkUnZip[i,j,k], chunkDecomp[i,j,k]);
end;
procedure TSMBlueprint.DataChunkEncode(var chunkRaw: TChunkDataCompressed;
var chunkDecomp: TChunkDataDecoded; var ChunkZipSize: integer);
var
chunkUnZip:TChunkDataUncompressed;
chunkUnzipSize:Integer;
i,j,k:byte;
pzip,puzip:pointer;
begin
puzip:=@chunkUnZip;
//encode block data
for i := 0 to 15 do
for j := 0 to 15 do
for k := 0 to 15 do begin
BlockEncode(chunkUnZip[i,j,k], chunkDecomp[i,j,k]);
end;
DataChunkZip(chunkRaw,chunkUnZip,ChunkZipSize);
end;
function TSMBlueprint.DataChunkHeaderCreate(x,y,z:Integer): TChunkHeader;
var
chunkHeader:TChunkHeader;
begin
chunkHeader.ver:= smDataChunkHeaderVersion;;
chunkHeader.time:= DateTimeToUnix(Now)*1000;
chunkHeader.pos.x:= x;
chunkHeader.pos.y:= y;
chunkHeader.pos.z:= z;
chunkHeader.dataByte:= smDataChunkHeaderDataByte;
chunkHeader.zipedSize:=0;
Result:= chunkHeader;
end;
procedure TSMBlueprint.DataChunkZip(var ChunkZip: TChunkDataCompressed;
var ChunkUnZip: TChunkDataUncompressed; var sizeOut: integer);
var
pin,pout:Pointer;
begin
FillChar(ChunkZip,smDataChunkDataSize,0); //first fill chunk with zeroes
pin:=@ChunkUnZip;
ZCompress(pin,SizeOf(TChunkDataUncompressed),pout,sizeOut,zcMax);
if sizeOut > smDataChunkDataSize then //check size
raise Exception.Create('Ziped chunk have too big size');
Move(pout^,ChunkZip,sizeOut);
end;
procedure TSMBlueprint.DataChunkZipUn(var ChunkZip: TChunkDataCompressed;
var ChunkUnZip: TChunkDataUncompressed);
var
pin,pout:Pointer;
sizeOut:integer;
begin
pin:=@ChunkZip;
ZDecompress(pin,smDataChunkDataSize,pout,sizeOut);
if sizeOut <> SizeOf(TChunkDataUncompressed) then //check size
raise Exception.Create('Unziped chunk have wrone size');
Move(pout^,ChunkUnZip,sizeOut);
end;
procedure TSMBlueprint.DataDecode(var dataRaw: TSMDataCompressed;
var dataDecod: TSMDataDecoded);
var
i:word;
begin
{ if Length(dataRaw.chunks)< 1 then
raise Exception.Create('No chunks to decode or chunk count error');}
//copy data header
Move(dataRaw.header,dataDecod.header,SizeOf(TDataHeader));
SetLength( dataDecod.chunks, Length( dataRaw.chunks ) );
//extract chunks
if Length(dataRaw.chunks)>0 then
for i := 0 to length(dataRaw.chunks)-1 do begin
Move(dataRaw.chunks[i].header,
dataDecod.chunks[i].header,
SizeOf(TChunkHeader)); //copy chunk header
DataChunkDecode(dataRaw.chunks[i].data, dataDecod.chunks[i].data); //decode chunk data
end;
end;
procedure TSMBlueprint.DataEncode(var dataRaw: TSMDataCompressed;
var dataDecod: TSMDataDecoded);
var
i:word;
chunkZipSize:integer;
begin
{if Length(dataDecod.chunks)< 1 then
raise Exception.Create('No chunks to encode or chunk count error');}
//copy header
Move(dataDecod.header,dataRaw.header,SizeOf(TDataHeader));
SetLength( dataRaw.chunks, Length( dataDecod.chunks ) );
//extract chunks
if Length(dataDecod.chunks)>0 then
for i := 0 to length(dataDecod.chunks)-1 do begin
Move(dataDecod.chunks[i].header,
dataRaw.chunks[i].header,
SizeOf(TChunkHeader));//copy chunk header
DataChunkEncode(dataRaw.chunks[i].data,
dataDecod.chunks[i].data,
chunkZipSize); //encode chunk data
dataRaw.chunks[i].header.zipedSize:=chunkZipSize;
dataDecod.chunks[i].header.zipedSize:=chunkZipSize;
end;
end;
procedure TSMBlueprint.DataFileLoad(DataFile: string;
var data: TSMDataCompressed);
var
f:file;
i,j,k:integer;
chunkCount:word;
c:word;
begin
AssignFile(f,DataFile);
Reset(f,1);
//get number of chunks in file;
chunkCount:=(FileSize(f) - SizeOf(TDataHeader)) div smDataChunkSize;
// File size must be equal to SizeOf(TDataHeader) + N*ChunkSize
if (FileSize(f) <> (SizeOf(TDataHeader) + (chunkCount * smDataChunkSize) ) ) then
raise Exception.Create('File size of '+DataFile+' not fit to expected size');
i:=FilePos(f);
i:=FileSize(f);
//load file header
BlockRead(f,data.header,SizeOf(TDataHeader));
//load chunks data
SetLength(data.chunks, chunkCount);
if chunkCount > 0 then
for c := 0 to chunkCount-1 do begin
BlockRead(f,data.chunks[c],SizeOf(TChunkCompressed));
end;
CloseFile(f);
//due to file consist of big-endian byte order variables
//and Delphi use little-endian byte order variables
//need to invert byte order for every variable
with data.header do begin
swapbytes(@ver,SizeOf(LongWord));
for i := 0 to 15 do
for j := 0 to 15 do
for k := 0 to 15 do begin
swapbytes(@(Index[i,j,k].ID),sizeof(LongWord));
swapbytes(@(Index[i,j,k].len),sizeof(LongWord));
swapbytes(@(time[i,j,k]),sizeof(UInt64));
end;
end;
// data.chunks[c].header.
if chunkCount > 0 then
for c := 0 to chunkCount-1 do
with data.chunks[c].header do begin
//do nothing with version
swapbytes(@time,SizeOf(time));
swapbytes(@pos,SizeOf(pos));//swap position as solid variable
//do nothing with dataByte
swapbytes(@zipedSize,SizeOf(zipedSize));
//also do nothing with data.chunks[].data
end;
end;
procedure TSMBlueprint.DataFileSave(DataFile: string;
var data: TSMDataCompressed);
var
f:file;
i,j,k:byte;
chunkCount:word;
c:word;
begin
AssignFile(f,DataFile);
Rewrite(f,1);
//due to file consist of big-endian byte order variables
//and Delphi use little-endian byte order variables
//need to invert byte order for every variable
with data.header do begin
swapbytes(@ver,SizeOf(LongWord));
for i := 0 to 15 do
for j := 0 to 15 do
for k := 0 to 15 do begin
swapbytes(@(Index[i,j,k].ID),sizeof(LongWord));
swapbytes(@(Index[i,j,k].len),sizeof(LongWord));
swapbytes(@(time[i,j,k]),sizeof(UInt64));
end;
end;
//get count of chunks in file;
chunkCount:=Length(data.chunks);
if chunkCount > 0 then
for c := 0 to chunkCount-1 do
with data.chunks[c].header do begin
//do nothing with version
swapbytes(@time,SizeOf(time));
swapbytes(@pos,SizeOf(pos));//swap position as solid variable
//do nothing with dataByte
swapbytes(@zipedSize,SizeOf(zipedSize));
//also do nothing with data.chunks[].dataw
end;
//write file header
BlockWrite(f,data.header,SizeOf(TDataHeader));
//write chunks data
if chunkCount > 0 then
for c := 0 to chunkCount-1 do
BlockWrite(f,data.chunks[c],SizeOf(TChunkCompressed));
CloseFile(f);
end;
function TSMBlueprint.DataHeaderCreate: TDataHeader;
var
dataHeader:TDataHeader;
i,j,k:byte;
begin
with dataHeader do
begin
ver:=smDataHeaderVersion;
for i := 0 to 15 do
for j := 0 to 15 do
for k := 0 to 15 do begin
index[i,j,k].ID:=-1;
index[i,j,k].len:=0;
time[i,j,k]:=0;
end;
end;
Result:=dataHeader;
end;
procedure TSMBlueprint.DataLoad(DataFolder: string);
var
f:file;
i,j,k:byte;
filesCount:integer;
chunkCount:word;
c:word;
Search:TSearchRec;
FindRec:Integer;
x,y,z:integer;
s,buf:string;
name:string;
DataCompressed:TSMDataCompressed;
dataDecoded:TSMDataDecoded;
begin
filesCount:=0;
SetLength(fDataFiles,filesCount);
name:='';
FindRec:= FindFirst(DataFolder+'\*.smd2',faAnyFile - faDirectory,Search);
while FindRec = 0 do begin
// get data from file name
s:=Search.Name;
{ i:=Length(s)-Length('.smd2');
j:=3;
while j>0 do begin
if s[i] = '.' then
j:=j-1;
i:=i-1;
end;
name:=Copy(s,1,i);
i:=i+1;
for k := 1 to 3 do begin
i:=i+1;
j:=pos(s,'.',i);
case k of
1:x:=inttostr(copy(s,i,j-i+1));
2:y:=inttostr(copy(s,i,j-i+1));
3:z:=inttostr(copy(s,i,j-i+1));
end;
i:=j+1;
end; }
// get data from file name
i:=Length(s)-Length('.smd2');
for k:=1 to 3 do begin
buf:='';
While true do begin
if not(s[i] in ['0'..'9','-']) then
begin
i:=i-1;
break;
end else
begin
buf:=s[i]+buf;
i:=i-1;
end;
end;
case k of
1:z:=strtoint(buf);
2:y:=strtoint(buf);
3:x:=strtoint(buf);
end;
end;
name:=copy(s,1,i);
if fDataName='' then
fDataName:=name
else
if fDataName<>name then
raise Exception.Create('Name of DATA files must be same! Error with name: '+name);
Inc(filesCount);
SetLength(fDataFiles,filesCount);
fDataFiles[filesCount-1].position.x:= x;
fDataFiles[filesCount-1].position.y:= y;
fDataFiles[filesCount-1].position.z:= z;
DataFileLoad(DataFolder+'\'+Search.Name,DataCompressed);
DataDecode(DataCompressed,fDataFiles[filesCount-1].data);
FindRec:=FindNext(Search);
end;
FindClose(Search);
end;
//Remove zero chunks and remap indexes of chunks
//after that deletion
procedure TSMBlueprint.DataOptimize;
var
f,c,bx,by,bz,i,j,k:Integer;
fsize,csize,count:Integer;
map,remap:array of Integer;
flag:Boolean;
begin
fsize:= Length(fDataFiles);
if fsize>0 then
begin
for f:= 0 to fsize-1 do
begin
csize:=Length(fDataFiles[f].data.chunks);
if csize>0 then
begin
SetLength(map,csize);
SetLength(remap,csize);
count:=0;//count of not zero chunks
for c := 0 to csize-1 do //check if chunks is usefull
begin
flag:=false;
for bx := 0 to 15 do
for by := 0 to 15 do
for bz := 0 to 15 do
if fDataFiles[f].data.chunks[c].data[bx,by,bz].ID > 0 then
begin
flag:=true;
Break;
end;
if flag then begin
map[c]:= c;
count:= count+1;
end
else
map[i]:= -1;
end;
for i:=0 to csize-1 do //reset index info
remap[i]:=-1;
i:=0;
j:=0;
while j<count do //calculare remapping array
begin
if map[j]<> -1 then
begin
remap[j]:=i;
i:=i+1;
end;
j:=j+1;
end;
if count>0 then //move chunks
for i := 0 to csize-1 do
begin
if remap[i]<>-1 then
if remap[i]<>i then
begin
fDataFiles[f].data.chunks[remap[i]].header:= fDataFiles[f].data.chunks[i].header;
Move(fDataFiles[f].data.chunks[i].data,
fDataFiles[f].data.chunks[remap[i]].data,
SizeOf(TChunkDataDecoded)
);
end;
end;
SetLength(fDataFiles[f].data.chunks,count); //update array size
//remap indexes
for i := 0 to 15 do
for j := 0 to 15 do
for k := 0 to 15 do
begin
c:=fDataFiles[f].data.header.index[i,j,k].ID;
if c<>-1 then
begin
fDataFiles[f].data.header.index[i,j,k].ID:=remap[c];
fDataFiles[f].data.header.time[i,j,k]:=0;
end;
end;
end;
end;
end;
end;
procedure TSMBlueprint.DataSave(DataFolder: string);
var
i:Integer;
s:string;
x,y,z,id:integer;
DataCompressed:TSMDataCompressed;
begin
if not DirectoryExists(DataFolder) then
if not CreateDir(DataFolder) then
raise Exception.Create('Can not create dir to save files: '+DataFolder);
if Length(fDataFiles) = 0 then
raise Exception.Create('No DATA files to write');
for i := Low(fDataFiles) to High(fDataFiles) do begin
with fDataFiles[i].position do
s:=DataFolder+'\'+fDataName+'.'+IntToStr(x)+'.'+IntToStr(y)+'.'+IntToStr(z)+'.smd2';
DataEncode(DataCompressed,fDataFiles[i].data);
//update chunk size in data header
for x := 0 to 15 do
for y := 0 to 15 do
for z := 0 to 15 do
begin
{ id:= fDataFiles[i].data.header.index[x,y,z].ID;
if id > -1 then
fDataFiles[i].data.header.index[x,y,z].len :=
fDataFiles[i].data.chunks[id].header.zipedSize + SizeOf(TChunkHeader);}
id:= DataCompressed.header.index[x,y,z].ID;
if id > -1 then
DataCompressed.header.index[x,y,z].len:=
DataCompressed.chunks[id].header.zipedSize + SizeOf(TChunkHeader);
end;
DataFileSave(s,DataCompressed);
end;
end;
{
procedure TSMBlueprint.DataToArray;
var
cx,cy,cz,f,ñ,bx,by,bz,cID,size:Integer;
wx,wy,wz:Integer;
fpos,cpos:TVector3i;
// dataDec:TChunkDataDecoded;
block:PBlock;
begin
fBlocks.Destroy;
fBlocks:=TDynaArray3D.Create;
size:= Length(fDataFiles);
if size > 0 then
for f := 0 to size-1 do
begin
fpos:=fDataFiles[f].position;
for cx := 0 to 15 do
for cy := 0 to 15 do
for cz := 0 to 15 do
begin
cID:=fDataFiles[f].data.header.index[cx,cy,cz].ID;
if cID > -1 then
begin
cpos:=fDataFiles[f].data.chunks[cID].header.pos;
// DataChunkDecode(fDataFiles[f].data.chunks[cID].data,dataDec);
for bx := 0 to 15 do
for by := 0 to 15 do
for bz := 0 to 15 do
begin
// files coordinates X,Z is a inner coordinates Z,X
CoordinatesDataToArray(fpos.z,cx,bx,wx);
CoordinatesDataToArray(fpos.y,cy,by,wy);
CoordinatesDataToArray(fpos.x,cz,bz,wz);
if fDataFiles[f].data.chunks[cID].data[bx,by,bz].ID > 0 then
begin
new(block);
block^:=fDataFiles[f].data.chunks[cID].data[bx,by,bz];
fBlocks.Voxels[wx,wy,wz]:=block;
end;
end;
end;
end;
end;
end;
}
destructor TSMBlueprint.Destroy;
var
f,c,fs,cs:Integer;
begin
SetLength(fChilds,0);
fs:=Length(fDataFiles);
if fs>0 then
begin
for f := 0 to fs-1 do
SetLength(fDataFiles[f].data.chunks,0);
SetLength(fDataFiles,0);
end;
end;
function TSMBlueprint.GetBlock(x, y, z: Integer): TBlock;
var
bp:PBlock;
fx,fy,fz,cx,cy,cz,ccx,ccy,ccz,bx,by,bz:integer;//coordinates
block:TBlock;
f,c,b:integer; //loop index
fs,cs,bs:integer; // sizes
blockSet:Boolean;
begin
CoordinatesWorldToData(fz,cx,ccx,bx,x);// file Z,X is world X,Z coordinates
CoordinatesWorldToData(fy,cy,ccy,by,y);
CoordinatesWorldToData(fx,cz,ccz,bz,z);
block:=DataBlockCreate(0); // init, always zero
blockSet:=false;
fs:=Length(fDataFiles);
if fs > 0 then
for f := 0 to fs-1 do
if (fDataFiles[f].position.x = fx) AND
(fDataFiles[f].position.y = fy) AND
(fDataFiles[f].position.z = fz)
then
begin
{ cs:=Length(fDataFiles[f].data.chunks);
if cs > 0 then
for c := 0 to cs-1 do
begin
with fDataFiles[f].data.chunks[c] do
begin
if (header.pos.x = ccx) AND
(header.pos.y = ccy) AND
(header.pos.z = ccz)
then begin
block:=data[bx,by,bz];
blockSet:=true;
Break;
end;
end;
end;
if blockSet then
Break; }
c:= fDataFiles[f].data.header.index[cx,cy,cz].ID;
if c > -1 then
begin
block:= fDataFiles[f].data.chunks[c].data[bx,by,bz];
Break;
end;
end;
Result:=block;
end;
function TSMBlueprint.GetBlockInfo(Id: word): TBlockInfo;
begin
Result:=fBlockInfos[Id];
end;
function TSMBlueprint.GetBlockNew(ID:Word): TBlock;
begin
Result:=DataBlockCreate(ID);
end;
function TSMBlueprint.GetBounds: THeadBoundBox;
begin
Result:=fHeadFile.bounBox;
end;
procedure TSMBlueprint.GetStatistics(var stats: THeadElements);
begin
stats.Count:=fHeadFile.stats.Count;
stats.Elements:=Copy(fHeadFile.stats.Elements,0,fHeadFile.stats.Count);
end;
procedure TSMBlueprint.HeadLoad(HeadFile: string; var head: THead);
var
i,size:integer;
f:file;
b:byte;
begin
// AssignFile(f,fileName);
AssignFile(f,HeadFile);
Reset(f,1);
//get size of header beside array of stats
// BlockRead(f,head.version,SizeOf(head.version));
BlockRead(f,head.ver, SizeOf(head.ver));
BlockRead(f,head.entType, SizeOf(head.ver));
BlockRead(f,head.bounBox.min, SizeOf(head.bounBox.min));
BlockRead(f,head.bounBox.max, SizeOf(head.bounBox.max));
BlockRead(f,head.stats.Count, SizeOf(head.stats.Count));
//swap bytes
swapbytes(@head.ver, SizeOf(head.ver));
swapbytes(@head.entType, SizeOf(head.entType));
swapbytes(@head.bounBox.min, SizeOf(head.bounBox.min));
swapbytes(@head.bounBox.max, SizeOf(head.bounBox.max));
swapbytes(@head.stats.Count, SizeOf(head.stats.Count));
SetLength(head.stats.Elements, head.stats.Count);
//read array and swap bytes
for i := 0 to head.stats.Count - 1 do begin
BlockRead(f,head.stats.Elements[i].ID,
Sizeof(head.stats.Elements[i].ID));
BlockRead(f,head.stats.Elements[i].Count,
Sizeof(head.stats.Elements[i].Count));
swapbytes(@head.stats.Elements[i].ID,
SizeOf(head.stats.Elements[i].ID));
swapbytes(@head.stats.Elements[i].Count,
SizeOf(head.stats.Elements[i].Count));
end;
CloseFile(f);
end;
procedure TSMBlueprint.HeadRecalc;
var
i,j,k,f,c,b,count:Integer;
fs,cs:Integer;
fx,fy,fz,cx,cy,cz,bx,by,bz,wx,wy,wz:integer;//coordinates file/chunk/block/world
blocks:array[1..smBlockMaxId] of integer;
Bounds:record minx,miny,minz,maxx,maxy,maxz:Integer;end;
// blocksBounds:TDynaArray3DBounds;
p:^TBlock;
begin
//init
for i := Low(blocks) to High(blocks) do
blocks[i]:=0;
for i := 0 to 2*3-1 do
PInteger(i+Integer(@Bounds.minx))^:=0;
//Find new bounds and count blocks
fs:=Length(fDataFiles);
if fs>0 then
for f := 0 to fs-1 do
begin
fx:= fDataFiles[f].position.x;
fy:= fDataFiles[f].position.y;
fz:= fDataFiles[f].position.z;
for cx := 0 to 15 do
for cy := 0 to 15 do
for cz := 0 to 15 do
begin
c:=fDataFiles[f].data.header.index[cx,cy,cz].ID;
if c > -1 then
begin
for bx := 0 to 15 do
for by := 0 to 15 do
for bz := 0 to 15 do
begin
b:=fDataFiles[f].data.chunks[c].data[bx,by,bz].ID;
if b>0 then
begin
//update bounds
CoordinatesDataToWorld(fz,cx,bx,wx);//file Z,X is world X,Z
CoordinatesDataToWorld(fy,cy,by,wy);
CoordinatesDataToWorld(fx,cz,bz,wz);
if Bounds.minx > wx then
Bounds.minx:=wx
else
if Bounds.maxx < wx then
Bounds.maxx:=wx;
if Bounds.miny > wy then
Bounds.miny:=wy
else
if Bounds.maxy < wy then
Bounds.maxy:=wy;
if Bounds.minz > wz then
Bounds.minz:=wz
else
if Bounds.maxz < wz then
Bounds.maxz:=wz;
//update blocks statistics
blocks[b]:=blocks[b]+1;
end;
end;
end;
end;
end;
//set bounds
//game related offsets of bounds included
fHeadFile.bounBox.Min.x:= Bounds.minX+smBoundBoxOffeset-2;
fHeadFile.bounBox.Min.y:= Bounds.minY+smBoundBoxOffeset-2;
fHeadFile.bounBox.Min.z:= Bounds.minZ+smBoundBoxOffeset-2;
fHeadFile.bounBox.Max.x:= Bounds.maxX+smBoundBoxOffeset+1;
fHeadFile.bounBox.Max.y:= Bounds.maxY+smBoundBoxOffeset+1;
fHeadFile.bounBox.Max.z:= Bounds.maxZ+smBoundBoxOffeset+1;
//find and set count of block types
count:=0;
for i := 1 to smBlockMaxId do
if blocks[i] > 0 then
count:= count + 1;
fHeadFile.stats.Count:= count;
SetLength(fHeadFile.stats.Elements,count);
//update block stats
i:=0;
j:=1;
while j <= smBlockMaxId do begin
if blocks[j]>0 then begin
fHeadFile.stats.Elements[i].ID:= j;
fHeadFile.stats.Elements[i].Count:= blocks[j];
i:= i+1;
end;
j:= j+1;
end;
end;
procedure TSMBlueprint.HeadSave(HeadFile: string; var head: THead);
var
i,size:integer;
f:file;
begin
AssignFile(f,HeadFile);
rewrite(f,1);
//save size before swapping bytes
size:= head.stats.Count;
//get size of header beside array of stats
swapbytes(@head.ver, SizeOf(head.ver));
swapbytes(@head.entType, SizeOf(head.entType));
swapbytes(@head.bounBox.min, SizeOf(head.bounBox.min));
swapbytes(@head.bounBox.max, SizeOf(head.bounBox.max));
swapbytes(@head.stats.Count, SizeOf(head.stats.Count));
BlockWrite(f,head.ver, SizeOf(head.ver));
BlockWrite(f,head.entType, SizeOf(head.entType));
BlockWrite(f,head.bounBox.min, SizeOf(head.bounBox.min));
BlockWrite(f,head.bounBox.max, SizeOf(head.bounBox.max));
BlockWrite(f,head.stats.Count, SizeOf(head.stats.Count));
//swap bytes
// array - swap bytes and write
for i := 0 to size - 1 do begin
swapbytes(@head.stats.Elements[i].ID,
SizeOf(head.stats.Elements[i].ID));
swapbytes(@head.stats.Elements[i].Count,
SizeOf(head.stats.Elements[i].Count));
BlockWrite(f,head.stats.Elements[i].ID,
Sizeof(head.stats.Elements[i].ID));
BlockWrite(f,head.stats.Elements[i].Count,
Sizeof(head.stats.Elements[i].Count));
end;
CloseFile(f);
end;
procedure TSMBlueprint.Load(pathDir: string);
begin
BlueprintLoad(pathDir);
end;
procedure TSMBlueprint.LoadConfig(BlockConfigPath, BlockTypesPath: string);
var
count,id,p,state,l,r,i:integer;
s,subs,nameID:string;
f:TextFile;
begin
//main initialization
for i := Low(fBlockInfos) to High(fBlockInfos) do begin
fBlockInfos[i].ID:=0;
fBlockInfos[i].nameID:='';
fBlockInfos[i].blockGeometry:=bgUnknown;
fBlockInfos[i].canACtivate:=false;
fBlockInfos[i].invGroup:='';
fBlockInfos[i].maxHP:=0;
end;
//load blocks ID and identificators from BlockTypes file
AssignFile(f,BlockTypesPath);
Reset(f);
while not(Eof(f)) do begin
Readln(f,s);
p:= Pos('=',s);
if p = 0 then //if not found then skip this line
Continue;
subs:= LowerCase(Trim(Copy(s,1,p-1))); // also make it have standart chars
id:= StrToInt( Copy(s, p+1, Length(s) - p ) );
fBlockInfos[id].ID:=id;
fBlockInfos[id].nameID:=subs;
end;
CloseFile(f);
//load another information about blocks from BlockConfig file
//simple text parsing, no need for XML-parsers (?) or no time
// to learn XML-parsers
AssignFile(f,BlockConfigPath);
Reset(f);
state:=0;
while not(Eof(f)) do begin
readln(f,s);
case state of
//if not in <block> section
0:begin
if Pos('<Block ',s)=0 then //need wait for <block> section
Continue;
state:=1; // Is IN <block> section, change CASE option next time
//get NameID
l:=Pos('type="',s)+Length('type="');
r:=Pos('"',s,l);
subs:=LowerCase(Trim(Copy(s,l,r-l)));// also make it have standart chars
//find position of this block name in array
i:=0;//local flag
for p := Low(fBlockInfos) to High(fBlockInfos) do begin
if fBlockInfos[p].nameID = subs then begin
i:=1;//remember what we got break;
break;
end;
end;
//if ID was not found then error
if i = 0 then
raise Exception.Create('nameID "'+subs+'" not found while parsing '+BlockConfigPath)
end;
//if exactly IN <block> section
1:begin
// if end of <block> section found
if Pos('</Block>',s)>0 then begin
state:=0;
Continue;
end;
//if this block is in group
l:=pos('<InventoryGroup>',s);
if l > 0 then begin
l:= l + Length('<InventoryGroup>');
r:=Pos('</',s,l);
subs:=LowerCase(Trim(Copy(s,l,r-l)));
fBlockInfos[p].invGroup:=subs;
Continue;
end;
//if this block is can be activated
l:=pos('<CanActivate>',s);
if l > 0 then begin
l:= l + Length('<CanActivate>');
r:=Pos('</',s,l);
subs:=LowerCase(Trim(Copy(s,l,r-l)));
if subs = 'true' then // only check for 'true', else always 'false'
fBlockInfos[p].canACtivate:=True;
Continue;
end;
//if it is line with block style
l:=pos('<BlockStyle>',s);
if l > 0 then begin
l:= l + Length('<BlockStyle>');
r:=Pos('</',s,l);
subs:=Copy(s,l,r-l);
l:=StrToInt(subs);
if l > (bgUnknown-1) then //if block geometry is bigger then known Geometry types
raise Exception.Create('Block geometry value for '+ //then error, and we need to update this code
fBlockInfos[p].nameID +
' is higher then known geomery types');
fBlockInfos[p].blockGeometry:=l; //convert BlockStyle number to ordinal TBlockGeometry
Continue;
end;
l:=pos('<Hitpoints>',s);
if l > 0 then begin
l:= l + Length('<Hitpoints>');
r:=Pos('</',s,l);
subs:=Copy(s,l,r-l);
l:=StrToInt(subs);
if (l <= 0) or (l > smBlockMaxHP) then
raise Exception.Create('Block HP is out of bounds');
fBlockInfos[p].maxHP:= l ;
Continue;
end;
end;
end;
end;
CloseFile(f);
end;
procedure TSMBlueprint.PrintDataChunkBody(var chunk: TChunkDataDecoded;
var blockInfo: TBlockInfoArray);
var
i,j,k:Integer;
begin
Writeln('CHUNK BODY');
for i := 0 to 15 do
for j := 0 to 15 do
for k := 0 to 15 do
if chunk[i,j,k].ID > 0 then
Writeln('(',i:2,',',k:2,',',j:2,') ID: ',
chunk[i,j,k].ID:4,' ',
blockInfo[chunk[i,j,k].ID].nameID);
Writeln('CHUNK BODY end');
Writeln;
end;
procedure TSMBlueprint.PrintDataChunkHead(var head: TChunkHeader);
var
s:string;
begin
Writeln('CHUNK HEADER');
Writeln('Version: ',head.ver);
with head.pos do
Writeln('Position: (',x,', ',y,', ',z,')');
Writeln('Timestamp: ',head.time);
//timestamp includes milliseconds
DateTimeToString(s,'',UnixToDateTime( Head.time div 1000 ));
Writeln('Time: ',s);
Writeln('Some byte: ',head.dataByte);
Writeln('Ziped Size: ',head.zipedSize);
Writeln('CHUNK HEADER end');
Writeln;
end;
procedure TSMBlueprint.PrintDataChunks(var chunks: TChunkArrayDecoded;
var blockInfo: TBlockInfoArray);
var i:Integer;
begin
Writeln('CHUNK LIST');
if Length(chunks)>0 then
for i := Low(chunks) to High(chunks) do begin
Writeln('Chunk #',i);
PrintDataChunkHead(chunks[i].header);
PrintDataChunkBody(chunks[i].data,blockInfo);
end;
Writeln('CHUNK LIST end');
Writeln;
end;
procedure TSMBlueprint.PrintDataHead(var head: TDataHeader);
var
i,j,k:Integer;
s:string;
begin
Writeln('DATA HEADER');
Writeln('Version: ',Head.ver);
Writeln('Chunks:');
for i := 0 to 15 do
for j := 0 to 15 do
for k := 0 to 15 do
if head.index[i,j,k].ID >= 0 then begin
writeln(' Position (',i:2,',',j:2,',',k:2,')');
writeln(' Chunk Index:',Head.index[i,j,k].ID);
writeln(' Chunk Timestamp: ',Head.time[i,j,k]:2);
//timestamp includes milliseconds
DateTimeToString(s,'',UnixToDateTime( Head.time[i,j,k] div 1000 ));
Writeln(' Chunk Time: ',s);
Writeln('DATA HEADER end');
Writeln;
end;
end;
procedure TSMBlueprint.PrintHead(var head: THead;
var blockInfo: TBlockInfoArray);
var s:string;
i:Integer;
begin
writeln('HEAD');
writeln('Version: ',head.ver);
case head.entType of
ord(etShip): s:='Ship';
ord(etShop): s:='Shop';
ord(etSpaceStation): s:='SpaceStation';
ord(etAsteroid): s:='Asteroid';
ord(etPlanet): s:='Planet';
else s:='Unknown';
end;
Writeln('Entity type: ',head.entType,' = ',s);
Writeln('Bounds:');
with head.bounBox do begin
Writeln(' X [',trunc(min.x),',',trunc(max.x),']');
Writeln(' Y [',trunc(min.y),',',trunc(max.y),']');
Writeln(' Z [',trunc(min.z),',',trunc(max.z),']');
end;
Writeln('Elements:');
with head.stats do
for i := 0 to Count-1 do
Writeln(' ID: ',elements[i].ID:4,' Count: ',elements[i].Count:4,
' Name: ',blockInfo[ elements[i].ID ].nameID);
Writeln('HEAD end');
Writeln;
end;
procedure TSMBlueprint.Save(pathDir: string);
begin
BlueprintSave(pathDir);
end;
procedure TSMBlueprint.SetBlock(x, y, z: Integer; Value: TBlock);
var
fx,fy,fz,cx,cy,cz,ccx,ccy,ccz,bx,by,bz,wx,wy,wz:Integer;//file,chunk,chunk center,block,world
f,fs,c,cs:Integer;
blockIsSet:Boolean;
begin
wx:=x;
wy:=y;
wz:=z;
CoordinatesWorldToData(fz,cx,ccx,bx,wx);//file Z,X is world X,Z
CoordinatesWorldToData(fy,cy,ccy,by,wy);
CoordinatesWorldToData(fx,cz,ccz,bz,wz);
fs:=Length(fDataFiles);
blockIsSet:=false;
if fs > 0 then
for f := 0 to fs do
begin
if (fDataFiles[f].position.x = fx) AND
(fDataFiles[f].position.y = fy) AND
(fDataFiles[f].position.z = fz)
then
begin
cs:=Length(fDataFiles[f].data.chunks);
if cs > 0 then
for c := 0 to cs-1 do
begin
if (fDataFiles[f].data.chunks[c].header.pos.x = ccx) AND
(fDataFiles[f].data.chunks[c].header.pos.y = ccy) AND
(fDataFiles[f].data.chunks[c].header.pos.z = ccz)
then
begin
fDataFiles[f].data.chunks[c].data[bx,by,bz]:=Value;
blockIsSet:=true;
end;
end;
//add chunk if not found place to set block
if not blockIsSet then
begin
cs:=cs+1;
SetLength(fDataFiles[f].data.chunks,cs);
c:=cs-1;
fDataFiles[f].data.chunks[c].header:= DataChunkHeaderCreate(ccx,ccy,ccz);
fDataFiles[f].data.header.index[cx,cy,cz].ID:=c;
fDataFiles[f].data.header.time[cx,cy,cx]:= fDataFiles[f].data.chunks[c].header.time;
fDataFiles[f].data.chunks[c].data[bx,by,bz]:=Value;
blockIsSet:= true;
end;
end;
end;
if not blockIsSet then //create file and chunk
begin
fs:= fs+1;
cs:= 0;
SetLength(fDataFiles,fs);
SetLength(fDataFiles[fs].data.chunks,cs);
f:= fs-1;
fDataFiles[f].position.x:= fx;
fDataFiles[f].position.y:= fy;
fDataFiles[f].position.z:= fz;
fDataFiles[f].data.header:= DataHeaderCreate;
cs:= cs+1;
SetLength(fDataFiles[fs].data.chunks,cs);
c:= cs-1;
fDataFiles[f].data.header.index[cx,cy,cz].ID:= c;
fDataFiles[f].data.chunks[c].header:= DataChunkHeaderCreate(ccx,ccy,ccz);
fDataFiles[f].data.header.time[cx,cy,cz]:= fDataFiles[f].data.chunks[c].header.time;
fDataFiles[f].data.chunks[c].data[bx,by,bz]:= Value;
end;
end;
procedure TSMBlueprint.SwapBytes(p: Pointer; size: Byte);
var
i:Byte;
temp:Byte;
pl,pr:PByte;
begin
if size <= 1 then
Exit;
pl:=pbyte(p);
pr:=pl;
inc(pr,size-1);
while LongWord(pl) < LongWord(pr) do
begin
temp:=pl^;
pl^:=pr^;
pr^:=temp;
dec(pr);
inc(pl);
end;
end;
procedure TSMBlueprint.test;
var
f,fs,c,cs,bx,by,bz:integer;
begin
fs:=Length(fDataFiles);
if fs > 0 then
for f := 0 to fs-1 do
begin
cs:=Length(fDataFiles[f].data.chunks);
if cs > 0 then
for c:= 0 to cs-1 do
for bx := 0 to 15 do
for by := 0 to 15 do
for bz := 0 to 15 do
begin
if ((by mod 4 )=0)AND
(fDataFiles[f].data.chunks[c].data[bx,by,bz].ID>1)
then
begin
fDataFiles[f].data.chunks[c].data[bx,by,bz]:= DataBlockCreate(2);
end;
end;
end;
end;
end.
|
{ $HDR$}
{**********************************************************************}
{ Unit archived using Team Coherence }
{ Team Coherence is Copyright 2002 by Quality Software Components }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.TeamCoherence.com }
{**********************************************************************}
{}
{ $Log: 12899: utilsDateTime.pas
{
{ Rev 1.0 2003-03-19 17:37:56 peter
}
unit utilsDateTime;
{**
Date and time utilities
Copyright © 1997 by EQ Soft AB; all rights reserved
@author P3 (peter.thornqvist@eq-soft.se)
URL: http://www.eq-soft.se/delphistuff
@version 1.0
}
interface
uses
SysUtils;
{$I VER.INC }
const
daySun = 1;
dayMon = 2;
dayTue = 3;
dayWed = 4;
dayThu = 5;
dayFri = 6;
daySat = 7;
mJan = 1;
mFeb = 2;
mMar = 3;
mApr = 4;
mMay = 5;
mJun = 6;
mJul = 7;
mAug = 8;
mSep = 9;
mOct = 10;
mNov = 11;
mDec = 12;
{** converts a Delphi 1 date to a TDateTime compatible with later versions of Delphi }
function dateFromDelphi1(aDate:TDateTime):TDateTime;
{** converts a TDateTime to a delphi 1 compatible TDateTime }
function dateToDelphi1(aDate:TDateTime):TDateTime;
{** returns first day of year }
function dateFirstDayOfYear(D: TDateTime): TDateTime;
{** returns last day of year }
function dateLastDayOfYear(D: TDateTime): TDateTime;
{** returns the first day of prev month }
function dateFirstDayOfPrevMonth(aDate:TDateTime): TDateTime;
{** returns the last day of prev month }
function dateLastDayOfPrevMonth(aDate:TDateTime): TDateTime;
{** returns the first day of next month }
function dateFirstDayOfNextMonth(aDate:TDateTime): TDateTime;
{** returns day part of ADate }
function dateDay(ADate: TDateTime): Word;
{** returns month part of ADate }
function dateMonth(ADate: TDateTime): Word;
{** @return year part of ADate }
function dateYear(ADate: TDateTime): Word;
{** Increment ADate with Days,Months and Years
Decrement by using negative values }
function dateIncDate(ADate: TDateTime; Days, Months, Years: Integer): TDateTime;
{** Increment ADate with Delta days. Use negative values to decrement ADate }
function dateIncDay(ADate: TDateTime; Delta: Integer): TDateTime;
{** Increment ADate with Delta months. Use negative values to decrement ADate }
function dateIncMonth(ADate: TDateTime; Delta: Integer): TDateTime;
{** Increment ADate with Delta years. Use negative values to decrement ADate }
function dateIncYear(ADate: TDateTime; Delta: Integer): TDateTime;
{** returns true if ADate is valid }
function dateValidDate(ADate: TDateTime): Boolean;
{** Returns Difference between Date1 and Date2 in Days, Months and Years
Values are always positive }
procedure dateDiff(Date1, Date2: TDateTime; var Days, Months, Years: Word);
{** returns number of months between Date1 and Date2 }
function dateMonthsBetween(Date1, Date2: TDateTime): Double;
{** returns number of days between Date1 and Date2 }
function dateDayInterval(Date1, Date2: TDateTime): Longint;
{** increment ATime by specified values }
function dateIncTime(ATime: TDateTime; Hours, Minutes, Seconds, MSecs: Integer): TDateTime;
{** increment ATime by specified values }
function dateIncHour(ATime: TDateTime; Delta: Integer): TDateTime;
{** increment ATime by specified values }
function dateIncMinute(ATime: TDateTime; Delta: Integer): TDateTime;
{** increment ATime by specified values }
function dateIncSecond(ATime: TDateTime; Delta: Integer): TDateTime;
{** increment ATime by specified values }
function dateIncMSec(ATime: TDateTime; Delta: Integer): TDateTime;
{** returns Week number that D falls in (US valid only) }
function dateWeekOfYear(D: TDateTime): integer; { Armin Hanisch }
{** Returns date of the first monday of week 1 for passed year.
NOTE: this date can be in the preceeding year }
function dateFirstWeek(aYear:integer):TDateTime;
{** returns Date for Count'th aDay in aYear / aMonth.
Example:
dateForDayOfMonth(2,1999,1,dayMon) returns the date for the second monday
in january 1999 }
function dateForDayOfMonth(aCount,aYear,aMonth,aDay:integer):TDateTime;
{** Decodes aDate into aYear, aWeek and aDay.
aDay is a value in the range 1 - 7: Monday to Sunday
}
procedure DecodeWeek(aDate:TDateTime;var aYear,aWeek,aDay:integer);
{** Encodes aYear, aWeek and aDay into a TDateTime variable
aDay should be in the range 1 - 7: Monday to Sunday }
function EncodeWeek(aYear,aWeek,aDay:integer):TDateTime;
{** returns the day number (1~366) of the year }
function dateDayOfYear(D: TDateTime): integer;
{** returns day of week, 0 is Sunday }
function dateDayOfWeek(D: TDateTime): integer;
function GetFirstDate(Datum : TDateTime; PlusYear : Integer) : TDateTime;
function GetFirstWeekDateInYear(Datum : TDateTime; PlusYear : Integer) : TDateTime;
{** returns date in current year that corresponds to given week and day }
function GetDateFromWeek(WeekNo, Day : Integer) : TDateTime;
{** Calculates calendar week assuming:
- Monday is the 1st day of the week.
- The 1st calendar week is the 1st week
of the year that contains a Thursday (ISO standard).
If result is 53, then previous year is assumed.
}
function dateCalendarWeek(aDate: TDateTime): integer;
{** Calculates the four-digit year from a two-digit year using the
TwoDigitYearCenturyWindow variable:
if TwoDigitYearCenturyWindow is 0, values between 0-99 are placed in the current century,
all others are returned unchanged.
If TwoDigitYearCenturyWindow > 0 then this value is subtracted from the current year and
the resulting value is used as a pivot to determine what century to use:
if (CurrentCentury + aYear) is less than the pivot, it is placed in the next century,
otherwise it is placed in this century
Example:
TwoDigitYearCenturyWindow is 50
CurrentYear is 1999
Pivot becomes (19)99 - (19)50 := (19)49
if aYear is 49 or less, Result = 2049 or less
if aYear is 50 or more, Result = 1950 or more
NOTE:
If you are running Delphi 3 or less, the TwoDigitYearCenturyWindow
variable is declared in this unit and initially set to 0
}
function dateFourDigitYear(const aYear:integer):integer;
{** returns a formatted string that contains the wanted date:
Allowed formats are:
d - today
d + 1 - tomorrow
d - 1 - yesterday
v5 - next weekday 5
v015 - next weekday 5 week 1
v00015 - next year 00 day 5 week 1
v2000015 - day 5 week 1 year 2000
06 - next monthday 6
-06 - prev monthday 6
0606 - next month 6, day 6
-0606 - prev month 6, day 6
990606 - next year 99 month 6 day 6
-990606 - prev year 99 month 6 day 6
Weekdays are in the range 1 to 7: Monday to Sunday
Prefixes (v and d) is case-insensitive
Prefix v can be replaced by w
If any error occurs, Default is returned
Invalid characters are stripped before validation
}
function GetFormattedDate(const Str,Default:string):string;
{$IFDEF D3_AND_DOWN }
var
TwoDigitYearCenturyWindow:word = 0;
{$ENDIF }
implementation
function dateFromDelphi1(aDate:TDateTime):TDateTime;
begin
Result := aDate - 693594;
end;
function dateToDelphi1(aDate:TDateTime):TDateTime;
begin
Result := aDate + 693594;
end;
function dateFirstDayOfYear(D: TDateTime): TDateTime;
var
Year,Month,Day : Word;
begin
DecodeDate(D,Year,Month,Day);
Result:=EncodeDate(Year,1,1);
end;
function dateLastDayOfYear(D: TDateTime): TDateTime;
var
Year,Month,Day : Word;
begin
DecodeDate(D,Year,Month,Day);
Result:=EncodeDate(Year,12,31);
end;
function dateFirstDayOfNextMonth(aDate:TDateTime): TDateTime;
var
Year, Month, Day: Word;
begin
DecodeDate(aDate, Year, Month, Day);
Day := 1;
if Month < 12 then Inc(Month)
else begin
Inc(Year);
Month := 1;
end;
Result := EncodeDate(Year, Month, Day);
end;
function dateFirstDayOfPrevMonth(aDate:TDateTime): TDateTime;
var
Year, Month, Day: Word;
begin
DecodeDate(aDate, Year, Month, Day);
Day := 1;
if Month > 1 then Dec(Month)
else begin
Dec(Year);
Month := 12;
end;
Result := EncodeDate(Year, Month, Day);
end;
function dateLastDayOfPrevMonth(aDate:TDateTime): TDateTime;
var
D: TDateTime;
Year, Month, Day: Word;
begin
D := dateFirstDayOfPrevMonth(aDate);
DecodeDate(D, Year, Month, Day);
Day := MonthDays[IsLeapYear(Year), Month];
Result := EncodeDate(Year, Month, Day);
end;
function dateDay(ADate: TDateTime): Word;
var
M, Y: Word;
begin
DecodeDate(ADate, Y, M, Result);
end;
function dateMonth(ADate: TDateTime): Word;
var
D, Y: Word;
begin
DecodeDate(ADate, Y, Result, D);
end;
function dateYear(ADate: TDateTime): Word;
var
D, M: Word;
begin
DecodeDate(ADate, Result, M, D);
end;
function dateIncDate(ADate: TDateTime; Days, Months, Years: Integer): TDateTime;
var
D, M, Y: Word;
Day, Month, Year, DayCount, Day28Delta: Longint;
begin
DecodeDate(ADate, Y, M, D);
Year := Y; Month := M; Day := D;
Day28Delta := Day - 28;
if Day28Delta < 0 then Day28Delta := 0
else Day := 28;
Inc(Year, Years);
Inc(Year, Months div 12);
Inc(Month, Months mod 12);
if Month < 1 then begin
Inc(Month, 12);
Dec(Year);
end
else if Month > 12 then begin
Dec(Month, 12);
Inc(Year);
end;
DayCount := Day + Days + Day28Delta;
while DayCount < 1 do begin
Dec(Month);
if Month < 1 then begin
Inc(Month, 12);
Dec(Year);
end;
DayCount := MonthDays[IsLeapYear(Year), Month] - Abs(DayCount);
end;
while DayCount > MonthDays[IsLeapYear(Year), Month] do begin
Dec(DayCount, MonthDays[IsLeapYear(Year), Month]);
Inc(Month);
if Month > 12 then begin
Dec(Month, 12);
Inc(Year);
end;
end;
Result := EncodeDate(Year, Month, DayCount);
end;
function dateIncDay(ADate: TDateTime; Delta: Integer): TDateTime;
begin
Result := dateIncDate(ADate, Delta, 0, 0);
end;
function dateIncMonth(ADate: TDateTime; Delta: Integer): TDateTime;
begin
Result := dateIncDate(ADate, 0, Delta, 0);
end;
function dateIncYear(ADate: TDateTime; Delta: Integer): TDateTime;
begin
Result := dateIncDate(ADate, 0, 0, Delta);
end;
procedure DateDiff(Date1, Date2: TDateTime; var Days, Months, Years: Word);
var
DtSwap: TDateTime;
Day1, Day2, Month1, Month2, Year1, Year2: Word;
begin
if Date1 > Date2 then begin
DtSwap := Date1;
Date1 := Date2;
Date2 := DtSwap;
end;
DecodeDate(Date1, Year1, Month1, Day1);
DecodeDate(Date2, Year2, Month2, Day2);
if Day2 < Day1 then begin
Dec(Month2);
if Month2 = 0 then begin
Month2 := 12;
Dec(Year2);
end;
Inc(Day2, MonthDays[IsLeapYear(Year2), Month2]);
end;
Days := Day2 - Day1;
if Month2 < Month1 then begin
Inc(Month2, 12);
Dec(Year2);
end;
Months := Month2 - Month1;
Years := Year2 - Year1;
end;
function dateMonthsBetween(Date1, Date2: TDateTime): Double;
var
D, M, Y: Word;
begin
DateDiff(Date1, Date2, D, M, Y);
Result := 12 * Y + M;
if (D > 1) and (D < 7) then Result := Result + 0.25
else if (D >= 7) and (D < 15) then Result := Result + 0.5
else if (D >= 15) and (D < 21) then Result := Result + 0.75
else if (D >= 21) then Result := Result + 1;
end;
function dateValidDate(ADate: TDateTime): Boolean;
var
Year, Month, Day: Word;
begin
try
DecodeDate(ADate, Year, Month, Day);
Result := Trunc(ADate) > 0;
except
Result := False;
end;
end;
function dateDayInterval(Date1, Date2: TDateTime): Longint;
begin
Result := Abs(Trunc(Date2) - Trunc(Date1));
// if Result < 0 then Result := -1;
end;
function dateIncTime(ATime: TDateTime; Hours, Minutes, Seconds, MSecs: Integer): TDateTime;
function dateSign(Value: Integer): SmallInt;
begin
if Value > 0 then Result := 1
else if Value = 0 then Result := 0
else Result := -1;
end;
var
H, M, S, MS: Word;
begin
DecodeTime(ATime, H, M, S, MS);
MSecs := MS + MSecs;
while (MSecs < 0) or (MSecs >= 1000) do begin
Inc(Seconds, dateSign(MSecs));
MSecs := MSecs - 1000 * dateSign(MSecs);
end;
Seconds := S + Seconds;
while (Seconds < 0) or (Seconds >= 60) do begin
Inc(Minutes, dateSign(Seconds));
Seconds := Seconds - 60 * dateSign(Seconds);
end;
Minutes := M + Minutes;
while (Minutes < 0) or (Minutes >= 60) do begin
Inc(Hours, dateSign(Minutes));
Minutes := Minutes - 60 * dateSign(Minutes);
end;
Hours := H + Hours;
while (Hours < 0) or (Hours >= 24) do
Hours := Hours - 24 * dateSign(Hours);
Result := EncodeTime(Hours, Minutes, Seconds, MSecs);
end;
function dateIncHour(ATime: TDateTime; Delta: Integer): TDateTime;
begin
Result := dateIncTime(ATime, Delta, 0, 0, 0);
end;
function dateIncMinute(ATime: TDateTime; Delta: Integer): TDateTime;
begin
Result := dateIncTime(ATime, 0, Delta, 0, 0);
end;
function dateIncSecond(ATime: TDateTime; Delta: Integer): TDateTime;
begin
Result := dateIncTime(ATime, 0, 0, Delta, 0);
end;
function dateIncMSec(ATime: TDateTime; Delta: Integer): TDateTime;
begin
Result := dateIncTime(ATime, 0, 0, 0, Delta);
end;
function dateDayOfWeek(D: TDateTime): integer;
begin
Result := Pred(DayOfWeek(D));
end;
function dateFirstWeek(aYear:integer):TDateTime;
const
DOWThu = 5;
var
Month1stJan:TDateTime; Day1stJan:integer;
begin
Month1stJan := EncodeDate(aYear,1,1);
Day1stJan := DayOfWeek(Month1stJan);
if Day1stJan <= DOWThu then
Result := DOWThu - Day1stJan + Month1stJan - 3
else
Result := DOWThu - Day1stJan + Month1stJan + 4;
end;
function dateForDayOfMonth(aCount,aYear,aMonth,aDay:integer):TDateTime;
var
Month1st:TDateTime;Day1st:integer;
begin
Month1st := EncodeDate(aYear,aMonth,1);
Day1st := DayOfWeek(Month1st);
if Day1st <= aDay then
Result := aDay - Day1st + ((aCount - 1) * 7) + Month1st
else
Result := aDay - Day1st + (aCount * 7) + Month1st;
if (Result - Month1st + 1) > MonthDays[IsLeapYear(aYear),aMonth] then
Result := 0;
end;
procedure DecodeWeek(aDate:TdateTime;var aYear,aWeek,aDay:integer);
var WeekOne:TDateTime;Year,Month,Day:word;
begin
// aDate := Trunc(aDate);
DecodeDate(aDate,Year,Month,Day);
WeekOne := dateFirstWeek(Year);
if aDate >= WeekOne then
begin
aYear := Year;
aWeek := (Trunc(aDate - WeekOne) div 7) + 1;
aDay := (Trunc(aDate - WeekOne) mod 7) + 1;
if (aDate - WeekOne) >= 364 then
begin
WeekOne := dateFirstWeek(Year + 1);
if aDate >= WeekOne then
begin
aYear := Year + 1;
aWeek := (Trunc(aDate - WeekOne) div 7) + 1;
aDay := (Trunc(aDate - WeekOne) mod 7) + 1;
end;
end;
end
else
begin
aYear := Year - 1;
WeekOne := dateFirstWeek(aYear);
aWeek := (Trunc(aDate - WeekOne) div 7) + 1;
aDay := (Trunc(aDate - WeekOne) mod 7) + 1;
end;
end;
function EncodeWeek(aYear,aWeek,aDay:integer):TDateTime;
begin
Result := dateFirstWeek(aYear) + (aWeek - 1) * 7 + aDay - 1;
end;
function dateDayOfYear(D: TDateTime): Integer;
begin
Result := Trunc(D - dateFirstDayOfYear(D))+1;
end;
function dateWeekOfYear(D: TDateTime): Integer;
const
t1: array[1..7] of ShortInt = ( -1, 0, 1, 2, 3, -3, -2);
t2: array[1..7] of ShortInt = ( -4, 2, 1, 0, -1, -2, -3);
var
doy1,
doy2 : Integer;
NewYear : TDateTime;
begin
NewYear := dateFirstDayOfYear(D);
doy1 := dateDayofYear(D) + t1[dateDayOfWeek(NewYear)];
doy2 := dateDayofYear(D) + t2[dateDayOfWeek(D)];
if doy1 <= 0 then
Result := dateWeekOfYear(NewYear-1)
else if (doy2 >= dateDayofYear(dateLastDayOfYear(NewYear))) then
Result:= 1
else
Result:=((doy1-1) div 7) + 1;
end;
function GetFirstDate(Datum : TDateTime; PlusYear : Integer) : TDateTime;
var year, Month, Day : Word;
begin
DecodeDate(Datum, year, Month, Day);
Result := EncodeDate(Year+PlusYear,1,1);
end;
function GetFirstWeekDateInYear(Datum : TDateTime; PlusYear : Integer) : TDateTime;
Begin
Result := GetFirstDate(Datum,PlusYear);
Case DayOfWeek(Result) of
1 : Result := Result + 1;
2 : Result := Result;
3 : Result := Result - 1;
4 : Result := Result - 2;
5 : Result := Result - 3;
6 : Result := Result + 3;
7 : Result := Result + 2;
end;
end;
function GetWeekNo(aDate: TDateTime): Integer;
var
Y, M, D,
FDay : Word;
JanF : TDateTime;
Days : Integer;
begin
try
DecodeDate(aDate, Y, M, D);
JanF := EncodeDate(Y, 1, 1);
FDay := DayOfWeek(JanF);
Days := Trunc(Int(aDate) - JanF) + 7 - DayOfWeek(aDate - 1);
Inc(Days, 7 * Ord(FDay in [dayMon..dayThu]));
Result := Days div 7;
if Result = 0 then
Begin
if (DayOfWeek(EncodeDate(Y - 1, 1, 1)) > dayThu) or (DayOfWeek(EncodeDate(Y - 1, 12, 31)) < dayThu) then
Result := 52
else
Result := 53;
end
else
if Result = 53 then
if (FDay > dayThu) or (DayOfWeek(EncodeDate(Y, 12, 31)) < 5) then
Result := 1;
except
Result := -1;
end;
end;
function GetDateFromWeek(WeekNo, Day : Integer) : TDateTime;
begin
Result := GetFirstWeekDateInYear(EncodeDate(WeekNo div 100,5,5), 0) + (((WeekNo mod 100)-1)*7) + Day;
end;
function dateCalendarWeek(ADate: TDateTime): integer;
var
day: word;
dayOne: word;
firstOfYear: TDateTime;
month: word;
monthOne: word;
year: word;
begin
DecodeDate(ADate, year, month, day);
case DayOfWeek(EncodeDate(year, 1, 1)) of
daySun: dayOne := 2; // Sunday
dayMon: dayOne := 1; // Monday
dayTue: dayOne := 31; // Tuesday
dayWed: dayOne := 30; // Wednesday
dayThu: dayOne := 29; // Thursday
dayFri: dayOne := 4; // Friday
daySat: dayOne := 3; // Saturday
end;
if dayOne > dayWed then
begin
Dec(year);
monthOne := 12
end
else
monthOne := 1;
firstOfYear := EncodeDate(year, monthOne, dayOne);
if aDate < firstOfYear then
Result := 53
else
Result := (Trunc(aDate - firstOfYear) div 7) + 1;
end;
function dateFourDigitYear(const aYear:integer):integer;
var Y:integer;
begin
if aYear > 99 then // ignore these - just send back
begin
Result := aYear;
Exit;
end;
Y := dateYear(Date);
if TwoDigitYearCenturyWindow <= 0 then
begin
Result := aYear + Y div 100 * 100;
Exit;
end;
Y := Y - TwoDigitYearCenturyWindow;
Result := aYear + (Y div 100) * 100;
if aYear <= (Y mod 100) then // next century
Inc(Result,100);
end;
function LastChar(const S:string):char;
begin
if Length(S) = 0 then
Result := #0
else
Result := S[Length(S)];
end;
{ allowed formats:
d - today
d + 1 - tomorrow
d - 1 - yeaterday
etc
invalid characters are ignored
}
function DoDayFormat(const Str,Default:string):String;
var i:integer;
begin
Result := '';
if Length(Str) = 1 then
begin
Result := DateToStr(Date);
Exit;
end;
{ trim: }
for i := 1 to Length(Str) do
if (Str[i] in ['-','+','0'..'9']) then
Result := Result + Str[i];
if Length(Result) > 1 then
begin
if Result[1] = '-' then
Result := DateToStr(Date - StrToInt(Copy(Result,2,MaxInt)))
else if Result[1] = '+' then
Result := DateToStr(Date + StrToInt(Copy(Result,2,MaxInt)))
else
Result := Default;
end
else
Result := Default;
end;
{
allowed formats:
v5 - next weekday 5
v015 - next week 1, weekday 5
v00015 - nästa år XX00, vecka 01, veckodag 5
v2000015 - vecka 1, veckodag 5, år 2000
invalid characters are ignored
}
function DoWeekFormat(const Str,Default:string):String;
var aYear,aWeek,aDay,dY,dW,dD,i:integer;
Y,M,D:word;
begin
if Str = '' then
begin
Result := Default;
Exit;
end;
{ trim string }
for i := 1 to Length(Str) do
if Str[i] in ['0'..'9'] then
Result := Result + Str[i];
if not (LastChar(Result) in ['1'..'7']) then // Monday to Thursday
begin
Result := Default;
Exit;
end;
DecodeDate(Date,Y,M,D);
case Length(Result) of
1: // 5
begin
DecodeWeek(Date,aYear,aWeek,dD);
aDay := StrToInt(LastChar(Result));
if aDay < dD then
Inc(aWeek);
if aWeek > GetWeekNo(EncodeDate(aYear,12,31)) then
begin
Inc(aYear);
aWeek := 1; // ??? kan kanske vara fel ibland (P3)
end;
end;
3: // 015
begin
DecodeWeek(Date,dY,dW,dD);
aYear := Y;
aWeek := StrToInt(Copy(Result,1,2));
aDay := StrToInt(LastChar(Result));
if (aWeek < dW) or ((aWeek = dW) and (aDay < dD)) then
Inc(aYear);
end;
5: // 00015
begin
aYear := StrToInt(Copy(Result,1,2));
aYear := dateFourDigitYear(aYear);
aWeek := StrToInt(Copy(Result,3,2));
aDay := StrToInt(LastChar(Result));
end;
7: // 19990101
begin
aYear := StrToInt(Copy(Result,1,4));
aWeek := StrToInt(Copy(Result,5,2));
aDay := StrToInt(LastChar(Result));
end;
else
Result := Default;
Exit;
end;
try
Result := DateToStr(EncodeWeek(aYear,aWeek,aDay));
except
Result := Default;
end;
end;
{
Allowed formats:
06 - next monthday 6
-06 - prev monthday 6
0706 - next month 7 day 6
-0706 - previous month 7 day 6
990706 - next year 99 month 7 day 6
-990706 - prev year 99 month 7 day 6
19990706 - year 1999 month 7 day 6
invalid characters are stripped from the input before validation
}
function DoDateFormat(const Str,Default:string):string;
var i,aYear,aMonth,aDay:integer;
Y,M,D:Word;
tmp:string;
tmpDate:TDateTime;
FPrev:boolean;
begin
if Length(Str) = 0 then
begin
Result := Default;
Exit;
end;
FPrev := Str[1] = '-';
for i := 1 to Length(Str) do
if (Str[i] in ['0'..'9']) then
Result := Result + Str[i];
DecodeDate(Date,Y,M,D);
try
case Length(Result) of
2: // 06
begin
aDay := StrToInt(Result);
if aDay >= D then
Result := DateToStr(EncodeDate(Y,M,aDay))
else if not FPrev then
begin
tmpDate := IncMonth(Date,1);
DecodeDate(tmpDate,Y,M,D);
Result := DateToStr(EncodeDate(Y,M,aDay));
end
else
begin
tmpDate := IncMonth(Date,-1);
DecodeDate(tmpDate,Y,M,D);
Result := DateToStr(EncodeDate(Y,M,aDay));
end;
end;
4: // 0706
begin
aMonth := StrToInt(Copy(Result,1,2));
aDay := StrToInt(Copy(Result,3,2));
if (aMonth > M) or ((aMonth = M) and (aDay >= D)) then
//do nothing
else
Inc(Y);
if FPrev then Dec(Y);
Result := DateToStr(EncodeDate(Y,aMonth,aDay))
end;
6: // 990706
begin
aYear := StrToInt(Copy(Result,1,2));
aMonth := StrToInt(Copy(Result,3,2));
aDay := StrToInt(Copy(Result,5,2));
// TwoDigitYearCenturyWindow controls the return value:
aYear := dateFourDigitYear(aYear);
if FPrev then Dec(aYear,100);
// if (aMonth > M) or ((aMonth = M) and (aDay >= D)) then
Result := DateToStr(EncodeDate(aYear,aMonth,aDay))
// else
// Result := DateToStr(EncodeDate(aYear + 1,aMonth,aDay));
end;
8: // 19990706
begin
aYear := StrToInt(Copy(Result,1,4));
aMonth := StrToInt(Copy(Result,5,2));
aDay := StrToInt(Copy(Result,7,2));
Result := DateToStr(EncodeDate(aYear,aMonth,aDay));
end;
else
Result := Default;
end;
except
Result := Default;
end;
end;
function GetFormattedDate(const Str,Default:string):string;
var i:integer;tmp:string;
begin
if Str = '' then
begin
Result := Default;
Exit;
end;
if Str[1] in ['v','w','V','W'] then
begin
Result := DoWeekFormat(Str,Default);
Exit;
end;
if Str[1] in ['d','D'] then
begin
Result := DoDayFormat(Str,Default);
Exit;
end;
Result := DoDateFormat(Str,Default);
end;
end.
|
unit UDrawing;
interface
uses
W3System, W3Graphics,
UMouseInputs, UArrow, UArcher, UPlayer, UEnemy, UGroundUnit, UAirUnit, UGameVariables, UShop, UShopItem, UTextures, UScalingInfo;
procedure ClearScreen(canvas : TW3Canvas);
procedure DrawLoadingScreen(canvas : TW3Canvas);
procedure DrawScenery(canvas : TW3Canvas);
procedure DrawPlayer(player : TPlayer; canvas : TW3Canvas);
procedure DrawArcher(archer : TArcher; canvas : TW3Canvas);
procedure DrawArrow(arrows : array of TArrow; canvas : TW3Canvas); overload;
procedure DrawArrow(arrow : TArrow; canvas : TW3Canvas); overload;
procedure DrawEnemy(enemy : array of TEnemy; canvas : TW3Canvas); overload;
procedure DrawEnemy(enemy : TEnemy; canvas : TW3Canvas); overload;
procedure DrawMouseDragLine(player : TPlayer; canvas : TW3Canvas);
procedure DrawCanShoot(player : TPlayer; canvas : TW3Canvas);
procedure DrawHUD(canvas : TW3Canvas);
procedure DrawPauseScreen(canvas : TW3Canvas);
procedure DrawGameOver(canvas : TW3Canvas);
procedure RotateCanvas(angle, xChange, yChange : float; canvas : TW3Canvas);
implementation
procedure ClearScreen(canvas : TW3Canvas);
begin
// Clear background
canvas.FillStyle := "rgb(255, 255, 255)";
canvas.FillRectF(0, 0, GAMEWIDTH * 2, GAMEHEIGHT * 2);
// Draw border
canvas.StrokeStyle := "rgb(0, 0, 0)";
canvas.LineWidth := 4;
canvas.StrokeRectF(0, 0, GAMEWIDTH, GAMEHEIGHT);
end;
procedure DrawLoadingScreen(canvas : TW3Canvas);
begin
canvas.FillStyle := "blue";
canvas.Font := "24pt verdana";
canvas.TextAlign := "center";
canvas.TextBaseLine := "middle";
canvas.FillTextF("Loading Content...", GAMEWIDTH / 2, GAMEHEIGHT / 2, 275);
end;
procedure DrawScenery(canvas : TW3Canvas);
begin
canvas.DrawImageF(TowerTexture.Handle, 0, GAMEHEIGHT - TowerTexture.Handle.height);
// Draw the shop button
canvas.StrokeStyle := "rgb(0, 0, 0)";
canvas.LineWidth := 4;
canvas.FillStyle := "rgb(130, 120, 140)";
canvas.StrokeRect(PauseButtonRect());
canvas.FillRect(PauseButtonRect());
// Get the correct text
var text := "Shop";
if Paused then
begin
text := "Resume";
end;
// Put the text in the button
canvas.Font := IntToStr(Round(PauseButtonRect().Width() / 4)) + "pt verdana";
canvas.FillStyle := "rgb(0, 0, 0)";
canvas.TextAlign := "center";
canvas.TextBaseLine := "middle";
canvas.FillTextF(text, PauseButtonRect().CenterPoint().X, PauseButtonRect().CenterPoint().Y, PauseButtonRect().Width() - 10);
end;
procedure DrawPlayer(player : TPlayer; canvas : TW3Canvas);
begin
// Draw the player
DrawArcher(player, canvas);
// Draw the extra archers
for var i := 0 to High(player.ExtraArchers) do
begin
DrawArcher(player.ExtraArchers[i], canvas);
end;
end;
procedure DrawArcher(archer : TArcher; canvas : TW3Canvas);
begin
// Draw the body of the archer
canvas.DrawImageF(ArcherTexture.Handle, archer.X, archer.Y);
// Rotate the canvas for the bow
RotateCanvas(archer.Angle(), archer.X + ArcherTexture.Handle.width / 2, archer.Y + ArcherTexture.Handle.height / 3, canvas);
// Draw the bow
canvas.DrawImageF(BowTexture.Handle, archer.X + ArcherTexture.Handle.width / 2, archer.Y + ArcherTexture.Handle.height / 3 - BowTexture.Handle.height / 2);
// Draw the string drawback
canvas.StrokeStyle := "rgb(0, 0, 0)";
canvas.LineWidth := 0.1;
canvas.BeginPath();
canvas.MoveToF(archer.X + ArcherTexture.Handle.width / 2 + BowTexture.Handle.width * 3 / 5, archer.Y + ArcherTexture.Handle.height / 3 - BowTexture.Handle.height / 2);
canvas.LineToF(archer.X + ArcherTexture.Handle.width / 2 + BowTexture.Handle.width * 3 / 5 - archer.Power() / 3, archer.Y + ArcherTexture.Handle.height / 3);
canvas.MoveToF(archer.X + ArcherTexture.Handle.width / 2 + BowTexture.Handle.width * 3 / 5, archer.Y + ArcherTexture.Handle.height / 3 + BowTexture.Handle.height / 2);
canvas.LineToF(archer.X + ArcherTexture.Handle.width / 2 + BowTexture.Handle.width * 3 / 5 - archer.Power() / 3, archer.Y + ArcherTexture.Handle.height / 3);
canvas.ClosePath();
canvas.Stroke();
// Un-rotate the canvas
RotateCanvas(-archer.Angle(), archer.X + ArcherTexture.Handle.width / 2, archer.Y + ArcherTexture.Handle.height / 3, canvas);
end;
procedure DrawArrow(arrows : array of TArrow; canvas : TW3Canvas);
begin
for var i := 0 to High(arrows) do
begin
if arrows[i].Active then
begin
DrawArrow(arrows[i], canvas);
end;
end;
end;
procedure DrawArrow(arrow : TArrow; canvas : TW3Canvas);
begin
// Rotate the canvas
RotateCanvas(arrow.GetAngle(), arrow.X, arrow.Y, canvas);
// Draw the arrow
canvas.DrawImageF(ArrowTexture.Handle, arrow.X, arrow.Y);
// Rotate the canvas back
RotateCanvas(-arrow.GetAngle(), arrow.X, arrow.Y, canvas);
end;
procedure DrawEnemy(enemy : array of TEnemy; canvas : TW3Canvas); overload;
begin
for var i := 0 to High(enemy) do
begin
if not enemy[i].Dead then
begin
DrawEnemy(enemy[i], canvas);
end;
end;
end;
procedure DrawEnemy(enemy : TEnemy; canvas : TW3Canvas); overload;
var
textureWidth : integer;
greenWidth : float;
begin
if (enemy is TGroundUnit) then
begin
// Draw the ground unit if it is one
canvas.DrawImageF(GroundUnitTexture.Handle, enemy.X, enemy.Y);
// Draw it frozen if it's meant to be
if enemy.Frozen then
begin
canvas.DrawImageF(FrozenGroundUnitTexture.Handle, enemy.X, enemy.Y);
end;
// Store the texture's width
textureWidth := GroundUnitTexture.Handle.width;
end
else if (enemy is TAirUnit) then
begin
// Draw the air unit if it is one
canvas.DrawImageF(AirUnitTexture.Handle, enemy.X, enemy.Y);
// Draw it frozen if it's meant to be
if enemy.Frozen then
begin
canvas.DrawImageF(FrozenAirUnitTexture.Handle, enemy.X, enemy.Y);
end;
// Store the texture's width
textureWidth := AirUnitTexture.Handle.width;
end;
// Draw the health bar's red underlay above enemy
canvas.FillStyle := "rgb(200, 0, 0)";
canvas.FillRectF(enemy.X, enemy.Y - 13, textureWidth, 5);
// Draw the health bar's green overlay above the enemy
greenWidth := (enemy.Health / enemy.MaxHealth) * textureWidth; // Get the percentage of health and multiply by the bar's width
canvas.FillStyle := "rgb(0, 200, 0)";
canvas.FillRectF(enemy.X, enemy.Y - 13, greenWidth, 5);
end;
procedure DrawMouseDragLine(player : TPlayer; canvas : TW3Canvas);
begin
if MouseDown and not Paused then
begin
canvas.StrokeStyle := "rgba(0, 0, 0, 0.5)";
canvas.LineWidth := 0.3;
canvas.BeginPath();
canvas.MoveToF(MouseDownX, MouseDownY);
canvas.LineToF(CurrentMouseX, CurrentMouseY);
canvas.ClosePath();
canvas.Stroke();
end;
end;
procedure DrawCanShoot(player : TPlayer; canvas : TW3Canvas);
var
text : string; // Text to go in message for the colour blind
begin
// Get red (can't shoot) or green (can shoot) fillers
if player.CanShoot then
begin
canvas.FillStyle := "rgba(0, 200, 0, 0.5)";
text := "Can shoot";
end
else
begin
canvas.FillStyle := "rgba(200, 0, 0, 0.5)";
text := "Can't shoot";
end;
// Draw a circle around the mouse
canvas.BeginPath();
canvas.Ellipse(CurrentMouseX - 7, CurrentMouseY - 7, CurrentMouseX + 7, CurrentMouseY + 7);
canvas.ClosePath();
canvas.Fill();
// Draw a message saying "can/can't shoot" for the colour blind
canvas.Font := "10pt verdana";
canvas.TextAlign := "center";
canvas.TextBaseLine := "bottom";
canvas.FillTextF(text, CurrentMouseX, CurrentMouseY - 12, MAX_INT);
// Also draw this message again above the player for those on a mobile as they can't see through their thumbs
canvas.FillTextF(text, player.X + ArcherTexture.Handle.width / 2, player.Y - 12, MAX_INT)
end;
procedure DrawPauseScreen(canvas : TW3Canvas);
begin
// Draw shop
Shop.Draw(canvas);
// The x position to place instructions and the side padding
var xPos := Shop.Items[0].X + SHOP_WIDTH + 30;
var sidePadding := 30;
// Draw the title
canvas.FillStyle := "rgb(0, 0, 0)";
canvas.TextAlign := "center";
canvas.TextBaseLine := "top";
canvas.FillTextF("Welcome to TowerOfArcher!", xPos + (GAMEWIDTH - xPos - sidePadding) / 2, 50, GAMEWIDTH - xPos - sidePadding);
// Draw instructions
canvas.Font := "16pt verdana";
canvas.TextAlign := "left";
canvas.TextBaseLine := "top";
canvas.FillTextF("How to play:", xPos, 90, GAMEWIDTH - xPos);
canvas.FillTextF("To aim, hold down the left mouse button and drag backwards.", xPos + 40, 130, GAMEWIDTH - xPos - 40 - sidePadding);
canvas.FillTextF("Release the left mouse button to fire.", xPos + 40, 170, GAMEWIDTH - xPos - 40 - sidePadding);
canvas.FillTextF("You can cancel the shot by right-clicking.", xPos + 40, 210, GAMEWIDTH - xPos - 40 - sidePadding);
canvas.FillTextF("If 10 enemies reach your castle, you lose!", xPos + 40, 250, GAMEWIDTH - xPos - 40 - sidePadding);
canvas.FillTextF("Don't forget to check the shop regularly for upgrades!", xPos + 40, 290, GAMEWIDTH - xPos - 40 - sidePadding);
end;
procedure DrawHUD(canvas : TW3Canvas);
begin
canvas.FillStyle := "rgb(220, 20, 50)";
canvas.Font := "15pt verdana";
canvas.TextAlign := "right";
canvas.TextBaseLine := "top";
canvas.FillTextF("Lives: " + IntToStr(Lives), GAMEWIDTH - 20, 10, MAX_INT);
canvas.FillStyle := "rgb(220, 220, 20)";
canvas.FillTextF("Gold: $" + IntToStr(Money), GAMEWIDTH - 20, 40, MAX_INT);
end;
procedure DrawGameOver(canvas : TW3Canvas);
begin
// Draw the text
canvas.Font := "70pt verdana";
canvas.FillStyle := "rgb(0, 0, 0)";
canvas.TextAlign := "center";
canvas.TextBaseLine := "top";
canvas.FillTextF("Game Over!", GAMEWIDTH / 2, 50, MAX_INT);
// Draw the button
canvas.StrokeStyle := "rgb(0, 0, 0)";
canvas.LineWidth := 4;
canvas.FillStyle := "rgb(130, 120, 140)";
canvas.StrokeRect(RestartButtonRect());
canvas.FillRect(RestartButtonRect());
// Put the text in the button
canvas.Font := IntToStr(Round(RestartButtonRect().Width() / 4)) + "pt verdana";
canvas.FillStyle := "rgb(0, 0, 0)";
canvas.TextAlign := "center";
canvas.TextBaseLine := "middle";
canvas.FillTextF("Restart", RestartButtonRect().CenterPoint().X, RestartButtonRect().CenterPoint().Y, RestartButtonRect().Width() - 10);
end;
procedure RotateCanvas(angle, xChange, yChange : float; canvas : TW3Canvas);
begin
// Trasnlate the canvas so the 0,0 point is the center of the object being rotated
canvas.Translate(xChange, yChange);
// Rotate the canvas
canvas.Rotate(angle);
// Detranslate the canvas so the 0,0 point is the normal one
canvas.Translate(-xChange, -yChange);
end;
end.
|
unit SharedConst;
interface
//
// распределение памяти
// с начала памяти
// +0 sizeof(TRGeneralRecord) структура для раздачи GUID (в единственном экземпляре)
// sizeof(TRGeneralRecord) n * sizeof(TRCommandRecord) список структур для общения с клиентами
// с конца памяти - блоки (окна) для передачи файлов
const
// имя сервера
SERVER_NAME: String = '{95FC2447-9ADA-4931-A393-477A48400336}';
// размер памяти для расшаривания
SERVER_MEM_SIZE: UInt64 = 256 * 1024;
// имя mutex для раздачи GUID
GLOBALRECORD_MUTEX_NAME: String = '{718F3915-E128-4032-852F-AC0B22536351}';
// имя mutex для контроля сервера
SERVERCONTROL_MUTEX_NAME: String = '{F57A659E-F930-4FDC-8686-0F6B90AF85A9}';
type
// структура для раздачи GUID
pTRGeneralRecord = ^TRGeneralRecord;
TRGeneralRecord = record
Operation: Cardinal; // код 0/1 (признак занятости имени Mutex)
CommandOffset: Cardinal; // смещение до данных командной записи
GUID: array [0..38] of WideChar; // имя Mutex (UTF-16)
end;
// типы коменд для обмена между клиентом и сервером
TRCommandCode = (
cNone,
cAny,
cToServerPing, // пинг от клиента к серверу
cFromServerPong, // ответ сервера на пинг
cToClientPing, // пинг от сервера к клиенту
cFromClientPong, // ответ клиента серверу
cToClientExit, // оповещение сервера клиентам, что сервер перестает работать
cToServerSendFile, // уведомление серверу, о необходимости передавать файл
cToClientGetPartFile, // запрос части файла у клиента
cToServerPartFile, // передача части файла серверу
cToClientEndFile, // окончание передачи файла серверу
cToClientCancelFile // прерываение передачи файла
);
// структура для обмена данными между клиентом и сервером
pTRCommandRecord = ^TRCommandRecord;
TRCommandRecord = record
Command: TRCommandCode; // тип команды
Position, Size: UInt64; // данные команды (позиция и размер данных)
DataOffset: UInt64; // смещение до блока данных
FileName: array [0..256] of WideChar; // данные команды (имя файла)
end;
implementation
end.
|
unit uBitEditor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Dialogs, Windows, VirtualTrees,
uLibrary,
uVtBaseEditor,
uPropertyEditorNew,
uAdvancedPropertyEditor;
type
{ TBitData }
TBitData = class(TPropertyData)
protected
fBit: IBitDefine;
public
property Bit: IBitDefine read fBit;
end;
{ TIndexBitData }
TIndexBitData = class(TBitData)
protected
function GetValue: string; override;
procedure SetValue(const aValue: string); override;
function GetEditLink: IVtEditLink; override;
public
constructor Create(const aBit: IBitDefine); reintroduce;
end;
{ TNameBitData }
TNameBitData = class(TBitData)
protected
function GetValue: string; override;
procedure SetValue(const aValue: string); override;
public
constructor Create(const aBit: IBitDefine); reintroduce;
end;
{ TShortDescriptionBitData }
TShortDescriptionBitData = class(TBitData)
protected
function GetValue: string; override;
procedure SetValue(const aValue: string); override;
public
constructor Create(const aBit: IBitDefine); reintroduce;
end;
{ TDescriptionBitData }
TDescriptionBitData = class(TBitData)
protected
function GetValue: string; override;
procedure SetValue(const aValue: string); override;
public
constructor Create(const aBit: IBitDefine); reintroduce;
end;
{ TVerBitData }
TVerBitData = class(TBitData)
protected
function GetValue: string; override;
procedure SetValue(const aValue: string); override;
public
constructor Create(const aBit: IBitDefine); reintroduce;
end;
{ TBitEditor }
TBitEditor = class(TAdvancedPropertyEditor)
private
fBits: IBits;
private
procedure SetBits(const aBits: IBits);
procedure AddBit(const aBit: IBitDefine);
procedure ConstructNewBit(const aClonedBit: IBitDefine = nil);
protected
procedure AddNewItem(Sender: TObject); override;
procedure CloneItem(Sender: TObject); override;
procedure DeleteItem(Sender: TObject); override;
public
property Bits: IBits read fBits write SetBits;
end;
implementation
{ TVerBitData }
constructor TVerBitData.Create(const aBit: IBitDefine);
begin
inherited Create;
Key := 'Версия';
fBit := aBit;
end;
function TVerBitData.GetValue: string;
begin
Result := fBit.Ver;
end;
procedure TVerBitData.SetValue(const aValue: string);
begin
fBit.Ver := aValue;
end;
{ TDescriptionBitData }
constructor TDescriptionBitData.Create(const aBit: IBitDefine);
begin
inherited Create;
Key := 'Описание';
fBit := aBit;
end;
function TDescriptionBitData.GetValue: string;
begin
Result := fBit.Description.Text;
end;
procedure TDescriptionBitData.SetValue(const aValue: string);
begin
fBit.Description.Text := aValue;
end;
{ TShortDescriptionBitData }
constructor TShortDescriptionBitData.Create(const aBit: IBitDefine);
begin
inherited Create;
Key := 'Краткое описание';
fBit := aBit;
end;
function TShortDescriptionBitData.GetValue: string;
begin
Result := fBit.ShortDescription;
end;
procedure TShortDescriptionBitData.SetValue(const aValue: string);
begin
fBit.ShortDescription := aValue;
end;
{ TNameBitData }
constructor TNameBitData.Create(const aBit: IBitDefine);
begin
inherited Create;
Key := 'Имя';
fBit := aBit;
end;
function TNameBitData.GetValue: string;
begin
Result := fBit.Name;
end;
procedure TNameBitData.SetValue(const aValue: string);
begin
fBit.Name := aValue;
end;
{ TIndexBitData }
constructor TIndexBitData.Create(const aBit: IBitDefine);
begin
inherited Create;
Key := 'Индекс';
fBit := aBit;
end;
function TIndexBitData.GetValue: string;
begin
Result := IntToStr(fBit.Index);
end;
procedure TIndexBitData.SetValue(const aValue: string);
begin
try
fBit.Index := StrToIntDef(aValue, 0);
if fBit.GetLastError <> 0 then
raise Exception.Create('Дубликат индекса');
except
on E: Exception do
MessageBox(Application.MainFormHandle, PChar(Utf8ToAnsi(E.Message)),
PChar(Utf8ToAnsi('Ошибка')), MB_ICONERROR + MB_OK);
end;
end;
function TIndexBitData.GetEditLink: IVtEditLink;
begin
Result := TVtIntegerEditLink.Create(0, 32);
end;
{ TBitEditor }
procedure TBitEditor.SetBits(const aBits: IBits);
var
P: Pointer;
Bit: IBitDefine;
begin
if fBits <> aBits then
fBits := aBits;
Clear;
for P in fBits do
begin
Bit := fBits.ExtractData(P);
AddBit(Bit);
end;
end;
procedure TBitEditor.AddBit(const aBit: IBitDefine);
var
Node: PVirtualNode;
begin
Node := AddChild(nil, TIndexBitData.Create(aBit));
AddChild(Node, TNameBitData.Create(aBit));
AddChild(Node, TVerBitData.Create(aBit));
AddChild(Node, TShortDescriptionBitData.Create(aBit));
Node := AddChild(Node, TDescriptionBitData.Create(aBit));
Node^.NodeHeight := 3 * Node^.NodeHeight;
Node^.States := Node^.States + [vsMultiline];
end;
procedure TBitEditor.ConstructNewBit(const aClonedBit: IBitDefine);
var
IndexStr: string;
Index: word;
Bit: IBitDefine;
begin
IndexStr := '';
if not InputQuery('Новый индекс', 'Введите новый индекс бита',
IndexStr) then
Exit;
Index := StrToIntDef(IndexStr, 0);
try
if not ((Index >= 0) and (Index < 32)) then
raise Exception.Create(Format('Индекс ''%d'' вне диапазона допустимых значений: 0-31', [Index]));
fBits.Add(Index);
if fBits.GetLastError <> 0 then
raise Exception.Create('Бит с данным индексом уже существует');
Bit := fBits[Index];
if aClonedBit <> nil then
Bit.Copy(aClonedBit);
AddBit(Bit);
except
on E: Exception do
MessageBox(Application.MainFormHandle, PChar(Utf8ToAnsi(E.Message)),
PChar(Utf8ToAnsi('Ошибка')), MB_ICONERROR + MB_OK);
else
MessageBox(Application.MainFormHandle, PChar(Utf8ToAnsi('Ошибка создания бита')),
PChar(Utf8ToAnsi('Ошибка')), MB_ICONERROR + MB_OK);
end;
end;
procedure TBitEditor.AddNewItem(Sender: TObject);
begin
ConstructNewBit;
end;
procedure TBitEditor.CloneItem(Sender: TObject);
begin
ConstructNewBit(TBitData(GetData(FocusedNode)).Bit);
end;
procedure TBitEditor.DeleteItem(Sender: TObject);
var
Node: PVirtualNode;
begin
Node := FocusedNode;
while GetNodeLevel(Node) > 1 do
Node := Node^.Parent;
if MessageBox(Application.MainFormHandle,
PChar(Utf8ToAnsi(Format('Удалить бит ''%s'' из набора?',
[TBitData(GetData(Node)).Bit.Name]))), PChar(Utf8ToAnsi('Удаление')),
MB_ICONWARNING + MB_OKCANCEL) = idCancel then
Exit;
fBits.Remove(TBitData(GetData(Node)).Bit.Index);
DeleteNode(Node);
end;
end.
|
unit Valores;
interface
uses
SysUtils, Classes, DB, IBCustomDataSet, kbmMemTable, dmValoresLoader;
type
TMercadoIndices = (miTodos, miEuropa, miAsia, miAmerica);
TTipoAgrupacionValores = (tavTodos, tavGrupo, tavMercado, tavIndice,
tavMercadoIndices, tavCarteraPendientes, tavCarteraAbiertas, tavTodosPaises,
tavPais);
TValores = class (TObject)
private
MemTableToPopulate: TkbmMemTable;
FTipoAgrupacionValores: TTipoAgrupacionValores;
FMercadoIndicesActivo: TMercadoIndices;
FOIDAgrupacionActiva: integer;
FPaisActivo: string;
procedure Todos;
procedure Grupo(const OIDGrupo: integer);
procedure Mercado(const OIDMercado: integer);
procedure Indice(const OIDIndice: integer);
procedure MercadoIndices(const mi: TMercadoIndices);
procedure CarteraPendientes(const OIDCartera: integer);
procedure CarteraAbiertas(const OIDCartera: integer);
procedure TodosPaises;
protected
procedure Populate(const ValoresLoader: TValoresLoader); virtual;
public
constructor Create(MemTableToPopulate: TkbmMemTable);
procedure LoadConfiguracion;
procedure SaveConfiguracion;
procedure ActivarMercadoIndices(const mi: TMercadoIndices);
procedure ActivarMercado(OID: integer);
procedure ActivarTodos;
procedure ActivarTodosPaises;
procedure ActivarPais(const pais: string);
procedure ActivarGrupo(OID: integer);
procedure ActivarIndice(OID: integer);
procedure ActivarCartera(OID: integer; pendiente: boolean);
procedure Reload;
property TipoAgrupacionValores: TTipoAgrupacionValores read FTipoAgrupacionValores;
property OIDAgrupacionActiva: integer read FOIDAgrupacionActiva;
property MercadoIndicesActivo: TMercadoIndices read FMercadoIndicesActivo;
property PaisActivo: string read FPaisActivo;
end;
implementation
uses UtilDB, dmDataComun, dmValoresLoaderCarteraAbiertas,
dmValoresLoaderCarteraPendientes, dmValoresLoaderGrupo, dmValoresLoaderIndice,
dmValoresLoaderMercado, dmValoresLoaderMercadoIndices, dmValoresLoaderTodos,
dmValoresLoaderTodosPaises, dmConfiguracion, dmValoresLoaderPais;
{ TValores }
procedure TValores.ActivarCartera(OID: integer; pendiente: boolean);
begin
if pendiente then begin
CarteraPendientes(OID);
FTipoAgrupacionValores := tavCarteraPendientes;
end
else begin
CarteraAbiertas(OID);
FTipoAgrupacionValores := tavCarteraAbiertas;
end;
FOIDAgrupacionActiva := OID;
end;
procedure TValores.ActivarGrupo(OID: integer);
begin
Grupo(OID);
FTipoAgrupacionValores := tavGrupo;
FOIDAgrupacionActiva := OID;
end;
procedure TValores.ActivarIndice(OID: integer);
begin
Indice(OID);
FTipoAgrupacionValores := tavIndice;
FOIDAgrupacionActiva := OID;
end;
procedure TValores.ActivarMercado(OID: integer);
begin
Mercado(OID);
FTipoAgrupacionValores := tavMercado;
FOIDAgrupacionActiva := OID;
end;
procedure TValores.ActivarMercadoIndices(const mi: TMercadoIndices);
begin
MercadoIndices(mi);
FTipoAgrupacionValores := tavMercadoIndices;
FMercadoIndicesActivo := mi;
end;
procedure TValores.ActivarPais(const pais: string);
var loader: TValoresLoaderPais;
begin
FPaisActivo := pais;
FTipoAgrupacionValores := tavPais;
loader := TValoresLoaderPais.Create(pais);
try
Populate(loader);
finally
loader.Free;
end;
end;
procedure TValores.ActivarTodos;
begin
Todos;
FTipoAgrupacionValores := tavTodos;
end;
procedure TValores.ActivarTodosPaises;
begin
TodosPaises;
FTipoAgrupacionValores := tavTodosPaises;
end;
procedure TValores.CarteraAbiertas(const OIDCartera: integer);
var loader: TValoresLoaderCarteraAbiertas;
begin
loader := TValoresLoaderCarteraAbiertas.Create(OIDCartera);
try
Populate(loader);
finally
loader.Free;
end;
end;
procedure TValores.CarteraPendientes(const OIDCartera: integer);
var loader: TValoresLoaderCarteraPendientes;
begin
loader := TValoresLoaderCarteraPendientes.Create(OIDCartera);
try
Populate(loader);
finally
loader.Free;
end;
end;
constructor TValores.Create(MemTableToPopulate: TkbmMemTable);
begin
inherited Create;
Self.MemTableToPopulate := MemTableToPopulate;
end;
procedure TValores.Grupo(const OIDGrupo: integer);
var loader: TValoresLoaderGrupo;
begin
loader := TValoresLoaderGrupo.Create(OIDGrupo);
try
Populate(loader);
finally
loader.Free;
end;
end;
procedure TValores.Indice(const OIDIndice: integer);
var loader: TValoresLoaderIndice;
begin
loader := TValoresLoaderIndice.Create(OIDIndice);
try
Populate(loader);
finally
loader.Free;
end;
end;
procedure TValores.LoadConfiguracion;
var tipo: string;
aux: integer;
auxPais: string;
begin
tipo := Configuracion.ReadString('Grupo', 'Tipo', 'T');
if tipo = 'G' then begin
aux := Configuracion.ReadInteger('Grupo', 'Grupo', -1);
ActivarGrupo(aux);
end
else
if tipo = 'M' then begin
aux := Configuracion.ReadInteger('Grupo', 'Mercado', -1);
ActivarMercado(aux);
end
else begin
if tipo = 'I' then begin
aux := Configuracion.ReadInteger('Grupo', 'Indices', -1);
ActivarIndice(aux);
end
else
if tipo = 'MI' then begin
aux := Configuracion.ReadInteger('Grupo', 'MercadoIndices', -1);
ActivarMercadoIndices(TMercadoIndices(aux));
end
else begin
if tipo = 'P' then begin
auxPais := Configuracion.ReadString('Grupo', 'Pais', '');
ActivarPais(auxPais);
end
else
ActivarTodos;
end;
end;
end;
procedure TValores.Mercado(const OIDMercado: integer);
var loader: TValoresLoaderMercado;
begin
loader := TValoresLoaderMercado.Create(OIDMercado);
try
Populate(loader);
finally
loader.Free;
end;
end;
procedure TValores.MercadoIndices(const mi: TMercadoIndices);
var loader: TValoresLoaderMercadoIndices;
begin
loader := TValoresLoaderMercadoIndices.Create(mi);
try
Populate(loader);
finally
loader.Free;
end;
end;
procedure TValores.Populate(const ValoresLoader: TValoresLoader);
var events: TDataSetEvents;
valor: PDataComunValor;
OIDValor: integer;
MemTableToPopulateOID_VALOR: TSmallintField;
MemTableToPopulateOID_MERCADO: TSmallintField;
MemTableToPopulateNOMBRE: TIBStringField;
MemTableToPopulateSIMBOLO: TIBStringField;
MemTableToPopulateDECIMALES: TSmallintField;
MemTableToPopulateMERCADO: TIBStringField;
begin
ValoresLoader.Load;
events := DisableEventsDataSet(MemTableToPopulate);
try
MemTableToPopulateOID_VALOR := TSmallintField(MemTableToPopulate.FindField('OID_VALOR'));
MemTableToPopulateOID_MERCADO := TSmallintField(MemTableToPopulate.FindField('OID_MERCADO'));
MemTableToPopulateNOMBRE := TIBStringField(MemTableToPopulate.FindField('NOMBRE'));
MemTableToPopulateSIMBOLO := TIBStringField(MemTableToPopulate.FindField('SIMBOLO'));
MemTableToPopulateDECIMALES := TSmallintField(MemTableToPopulate.FindField('DECIMALES'));
MemTableToPopulateMERCADO := TIBStringField(MemTableToPopulate.FindField('MERCADO'));
MemTableToPopulate.Close;
MemTableToPopulate.Open;
ValoresLoader.qValores.First;
while not ValoresLoader.qValores.Eof do begin
OIDValor := ValoresLoader.qValoresOID_VALOR.Value;
MemTableToPopulate.Append;
MemTableToPopulateOID_VALOR.Value := OIDValor;
valor := DataComun.FindValor(OIDValor);
MemTableToPopulateNOMBRE.Value := valor^.Nombre;
MemTableToPopulateOID_MERCADO.Value := valor^.Mercado^.OIDMercado;
MemTableToPopulateSIMBOLO.Value := valor^.Simbolo;
MemTableToPopulateDECIMALES.Value := valor^.Mercado^.Decimales;
MemTableToPopulateMERCADO.Value := valor^.Mercado^.Nombre;
MemTableToPopulate.Post;
ValoresLoader.qValores.Next;
end;
MemTableToPopulate.First;
finally
EnableEventsDataSet(MemTableToPopulate, events, false);
end;
end;
procedure TValores.Reload;
begin
case FTipoAgrupacionValores of
tavTodos: ActivarTodos;
tavGrupo: ActivarGrupo(FOIDAgrupacionActiva);
tavMercado: ActivarMercado(FOIDAgrupacionActiva);
tavIndice: ActivarIndice(FOIDAgrupacionActiva);
tavMercadoIndices: ActivarMercadoIndices(FMercadoIndicesActivo);
tavCarteraPendientes: ActivarCartera(FOIDAgrupacionActiva, true);
tavCarteraAbiertas: ActivarCartera(FOIDAgrupacionActiva, false);
tavTodosPaises: ActivarTodosPaises;
tavPais: ActivarPais(FPaisActivo);
end;
end;
procedure TValores.SaveConfiguracion;
var tipo: string;
begin
case FTipoAgrupacionValores of
tavGrupo: begin
Configuracion.WriteInteger('Grupo', 'Grupo', OIDAgrupacionActiva);
tipo := 'G';
end;
tavMercado: begin
Configuracion.WriteInteger('Grupo', 'Mercado', OIDAgrupacionActiva);
tipo := 'M';
end;
tavIndice: begin
Configuracion.WriteInteger('Grupo', 'Indices', OIDAgrupacionActiva);
tipo := 'I';
end;
tavMercadoIndices: begin
Configuracion.WriteInteger('Grupo', 'MercadoIndices', integer(MercadoIndicesActivo));
tipo := 'MI';
end;
tavPais: begin
Configuracion.WriteString('Grupo', 'Pais', PaisActivo);
tipo := 'P';
end
else tipo := 'T';
end;
Configuracion.WriteString('Grupo', 'Tipo', tipo);
end;
procedure TValores.Todos;
var loader: TValoresLoaderTodos;
begin
loader := TValoresLoaderTodos.Create;
try
Populate(loader);
finally
loader.Free;
end;
end;
procedure TValores.TodosPaises;
var loader: TValoresLoaderTodosPaises;
begin
loader := TValoresLoaderTodosPaises.Create;
try
Populate(loader);
finally
loader.Free;
end;
end;
end.
|
(******************************************************************************
PROYECTO FACTURACION ELECTRONICA
Copyright (C) 2010-2014 - Bambu Code SA de CV - Ing. Luis Carrasco
Metodos para validar los diferentes tipos de datos y como deben de estar
especificados en el archivo XML.
Este archivo pertenece al proyecto de codigo abierto de Bambu Code:
http://bambucode.com/codigoabierto
La licencia de este codigo fuente se encuentra en:
http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA
******************************************************************************)
unit FacturaReglamentacion;
interface
uses Classes;
type
TFEReglamentacion = class
private
class procedure CorregirConfiguracionRegionalLocal;
class procedure ReemplazarComaSiActuaComoPuntoDecimal(var aCadenaCatidad:
String);
class procedure RegresarConfiguracionRegionalLocal;
class function ObtenerCatalogoMetodosPago() : TStringList;
public
/// <summary>Convierte el valor de moneda al formato de dinero requerido por el SAT
/// </summary>
/// <param name="Monto">Monto a convertir al formato aceptado por el SAT</param>
class function ComoMoneda(aMonto: Currency; const aDecimalesDefault: Integer
= 2): String;
class function ComoCadena(sCadena: String) : String;
class function ComoCantidad(dCantidad: Double; const aNumeroDecimales: Integer
= 2): String;
class function ComoFechaHora(dtFecha: TDateTime) : String;
class function DeFechaHoraISO8601(const aFechaISO8601: String) : TDateTime;
class function ComoFechaAduanera(dtFecha: TDateTime) : String;
class function ComoTasaImpuesto(dTasa: Double; const aDecimalesDefault: Integer
= 2): String;
class function ComoDateTime(sFechaISO8601: String): TDateTime;
class function ComoFechaHoraInforme(dtFecha: TDateTime) : String;
/// <summary>
/// Se encarga de convertir una cadena de método de pago al número del
/// catálogo del SAT. Referencia:
/// http://www.sat.gob.mx/fichas_tematicas/buzon_tributario/Documents/catalogo_metodos_pago.pdf
/// </summary>
/// <param name="aCadenaMetodoDePago">
/// Cadena, Ejemplo: Efectivo, Vales de Despensa, etc.
/// </param>
/// <returns>
/// Regresa el numero del catálogo del SAT oficial o cadena vacía si la
/// cadena no fue encontrada dentro del catálogo oficial.
/// </returns>
class function ConvertirCadenaMetodoDePagoANumeroCatalogo(const
aCadenaMetodoDePago: string): String;
class function DeTasaImpuesto(const aCadenaTasa: String) : Double;
class function DeCantidad(aCadenaCatidad: String): Double;
class function DeMoneda(aMoneda: String): Currency;
class function ConvertirNumeroMetodoDePagoACadena(const aNumeroMetodoDePago: string): String;
end;
var
separadorDecimalAnterior: Char;
const
_PUNTO_DECIMAL = '.';
_COMA_DECIMAL = ',';
_CADENA_NO_IDENTIFICADO = 'NO IDENTIFICADO';
implementation
uses DateUtils,
{$IF Compilerversion >= 20}
Soap.XSBuiltIns,
{$ELSE}
XSBuiltIns,
{$IFEND}
SysUtils, Windows;
var
formatSettingsLocal : TFormatSettings;
class procedure TFEReglamentacion.CorregirConfiguracionRegionalLocal;
begin
// Debido a que si el usuario en la PC tiene una configuración regional incorrecta
// los XMLs se generan con montos y cantidades inválidas
separadorDecimalAnterior := formatSettingsLocal.DecimalSeparator;
// Indicamos que el separador Decimal será el punto
formatSettingsLocal.DecimalSeparator := _PUNTO_DECIMAL;
end;
class procedure TFEReglamentacion.RegresarConfiguracionRegionalLocal;
begin
formatSettingsLocal.DecimalSeparator := separadorDecimalAnterior;
end;
// Segun las reglas del SAT:
// "Se expresa en la forma aaaa-mm-ddThh:mm:ss, de acuerdo con la especificación ISO 8601"
class function TFEReglamentacion.ComoFechaHora(dtFecha: TDateTime) : String;
begin
Result := FormatDateTime('yyyy-mm-dd', dtFecha) + 'T' + FormatDateTime('hh:nn:ss', dtFecha);
end;
class function TFEReglamentacion.DeFechaHoraISO8601(const aFechaISO8601: String) : TDateTime;
begin
// Ref: http://stackoverflow.com/questions/6651829/how-do-i-convert-an-iso-8601-string-to-a-delphi-tdate
with TXSDateTime.Create() do
try
XSToNative(aFechaISO8601);
Result := AsUTCDateTime;
finally
Free;
end;
end;
// Regresa la fecha/hora en el formato del Informe Mensual
class function TFEReglamentacion.ComoFechaHoraInforme(dtFecha: TDateTime) : String;
begin
Result := FormatDateTime('dd/mm/yyyy', dtFecha) + ' ' + FormatDateTime('hh:nn:ss', dtFecha);
{$IFDEF DEBUG}
Assert(Length(Result) = 19, 'La longitud de la fecha del informe no fue de 19 caracteres!');
{$ENDIF}
end;
// Convierte una fecha de ISO 8601 (formato del XML) a TDateTime usado en Delphi.
class function TFEReglamentacion.ComoDateTime(sFechaISO8601: String): TDateTime;
var
sAno, sMes, sDia, sHora, sMin, sMs: String;
begin
// Ejemplo: 2009-08-16T16:30:00
sAno := Copy(sFechaISO8601, 1, 4);
sMes := Copy(sFechaISO8601, 6, 2);
sDia := Copy(sFechaISO8601, 9, 2);
sHora := Copy(sFechaISO8601, 12, 2);
sMin := Copy(sFechaISO8601, 15, 2);
sMs := Copy(sFechaISO8601, 18, 2);
Result := EncodeDateTime(StrToInt(sAno), StrToInt(sMes), StrToInt(sDia), StrToInt(sHora),
StrToInt(sMin), StrToInt(sMs), 0);
end;
class function TFEReglamentacion.ComoFechaAduanera(dtFecha: TDateTime) : String;
begin
// Formato sacado del CFDv2.XSD: "Atributo requerido para expresar la fecha de expedición
// del documento aduanero que ampara la importación del bien. Se expresa en el formato aaaa-mm-dd"
Result := FormatDateTime('yyyy-mm-dd', dtFecha);
end;
class function TFEReglamentacion.ComoMoneda(aMonto: Currency; const
aDecimalesDefault: Integer = 2): String;
begin
// Regresamos los montos de monedas con 6 decimales (maximo permitido en el XSD)
// http://www.sat.gob.mx/cfd/3/cfdv32.xsd
// http://www.sat.gob.mx/cfd/2/cfdv22.xsd
try
CorregirConfiguracionRegionalLocal;
Result:=FloatToStrF(aMonto, ffFixed, 10, aDecimalesDefault);
finally
RegresarConfiguracionRegionalLocal;
end;
end;
class function TFEReglamentacion.ComoTasaImpuesto(dTasa: Double; const
aDecimalesDefault: Integer = 2): String;
begin
// Regresamos los montos de monedas con 6 decimales (maximo permitido en el XSD)
// http://www.sat.gob.mx/cfd/3/cfdv32.xsd
// http://www.sat.gob.mx/cfd/2/cfdv22.xsd
try
CorregirConfiguracionRegionalLocal;
Result:=FloatToStrF(dTasa,ffFixed, 10, aDecimalesDefault);
finally
RegresarConfiguracionRegionalLocal;
end;
end;
class function TFEReglamentacion.DeTasaImpuesto(const aCadenaTasa: String) : Double;
begin
Result := TFEReglamentacion.DeCantidad(aCadenaTasa);
end;
class function TFEReglamentacion.DeCantidad(aCadenaCatidad: String): Double;
begin
try
CorregirConfiguracionRegionalLocal;
ReemplazarComaSiActuaComoPuntoDecimal(aCadenaCatidad);
Result:=StrToFloat(aCadenaCatidad);
finally
RegresarConfiguracionRegionalLocal;
end;
end;
class function TFEReglamentacion.DeMoneda(aMoneda: String): Currency;
begin
try
CorregirConfiguracionRegionalLocal;
ReemplazarComaSiActuaComoPuntoDecimal(aMoneda);
Result:=StrToCurr(aMoneda);
finally
RegresarConfiguracionRegionalLocal;
end;
end;
// Las cadenas usadas en el XML deben de escapar caracteres incorrectos
// Ref: http://dof.gob.mx/nota_detalle.php?codigo=5146699&fecha=15/06/2010
class function TFEReglamentacion.ComoCadena(sCadena: String) : String;
var
sCadenaEscapada: String;
begin
sCadenaEscapada:=sCadena;
// Las siguientes validaciones las omitimos ya que las mismas clases
// de Delphi lo hacen por nosotros:
// En el caso del & se deberá usar la secuencia &
// En el caso del “ se deberá usar la secuencia "
// En el caso del < se deberá usar la secuencia <
// En el caso del > se deberá usar la secuencia >
// En el caso del ‘ se deberá usar la secuencia '
// No es permitido el caracter de | en las cadenas (entra en conflicto con la generación de la Cadena Original)
sCadenaEscapada := StringReplace(sCadenaEscapada, '|', '', [rfReplaceAll]);
// Si se presentan nuevas reglas para los Strings en el XML, incluirlas aqui
Result:=sCadenaEscapada;
end;
class function TFEReglamentacion.ComoCantidad(dCantidad: Double; const
aNumeroDecimales: Integer = 2): String;
begin
// Las cantidades cerradas las regresamos sin decimales
// las que tienen fracciones con 6 digitos decimales para respetar la especificacion
// del Anexo 20 respecto al tipo xs:decimal
try
CorregirConfiguracionRegionalLocal;
if Frac(dCantidad) > 0 then
Result:=FloatToStrF(dCantidad,ffFixed, 10, aNumeroDecimales)
else
Result:=IntToStr(Round(dCantidad));
finally
RegresarConfiguracionRegionalLocal;
end;
end;
class function TFEReglamentacion.ObtenerCatalogoMetodosPago() :TStringList;
begin
Result := TStringList.Create;
Result.Values['EFECTIVO'] := '01';
Result.Values['CHEQUE'] := '02';
Result.Values['TRANSFERENCIA'] := '03';
Result.Values['TRANSFERENCIA ELECTRONICA'] := '03';
Result.Values['TARJETA DE CREDITO'] := '04';
Result.Values['MONEDERO'] := '05';
Result.Values['DINERO ELECTRONICO'] := '06';
Result.Values['VALES'] := '08';
Result.Values['TARJETA DE DEBITO'] := '28';
Result.Values['TARJETA DE SERVICIO'] := '29';
Result.Values['OTROS'] := '99';
Result.Values['NO IDENTIFICADO'] := 'NA';
Result.Values['NA'] := 'NA';
Result.Values['NO APLICA'] := 'NA';
end;
class function TFEReglamentacion.ConvertirNumeroMetodoDePagoACadena(const aNumeroMetodoDePago: string): String;
var
catalogoMetodosDePago: TStringList;
I : Integer;
begin
try
catalogoMetodosDePago := TFEReglamentacion.ObtenerCatalogoMetodosPago();
for I := 0 to catalogoMetodosDePago.Count - 1 do
begin
if catalogoMetodosDePago.ValueFromIndex[I] = aNumeroMetodoDePago then
Result := catalogoMetodosDePago.Names[I];
end;
if Result = '' then
Result := _CADENA_NO_IDENTIFICADO;
finally
catalogoMetodosDePago.Free;
end;
end;
class function TFEReglamentacion.ConvertirCadenaMetodoDePagoANumeroCatalogo(
const aCadenaMetodoDePago: string): String;
var
cadenaSinAcentos: string;
catalogoMetodosDePago: TStringList;
begin
Result := '';
cadenaSinAcentos := UpperCase(aCadenaMetodoDePago);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'Á', 'A', [rfReplaceAll]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'É', 'E', [rfReplaceAll]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'Í', 'I', [rfReplaceAll]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'Ó', 'O', [rfReplaceAll]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'Ú', 'U', [rfReplaceAll]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'á', 'A', [rfReplaceAll]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'é', 'E', [rfReplaceAll]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'í', 'I', [rfReplaceAll]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'ó', 'O', [rfReplaceAll]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'ú', 'U', [rfReplaceAll]);
try
catalogoMetodosDePago := TFEReglamentacion.ObtenerCatalogoMetodosPago();
// Reemplazamos nombres en plural/singular por singular
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'TARJETAS', 'TARJETA', [rfReplaceAll, rfIgnoreCase]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'VALE ', 'VALES', [rfReplaceAll, rfIgnoreCase]);
cadenaSinAcentos := StringReplace(cadenaSinAcentos, 'OTRO ', 'OTROS', [rfReplaceAll, rfIgnoreCase]);
// Convertimos la cadena a numero de catalogo
if catalogoMetodosDePago.Values[cadenaSinAcentos] <> '' then
Result := catalogoMetodosDePago.Values[cadenaSinAcentos]
else
Result := '';
finally
catalogoMetodosDePago.Free;
end;
end;
class procedure TFEReglamentacion.ReemplazarComaSiActuaComoPuntoDecimal(var
aCadenaCatidad: String);
begin
// Reemplazamos cualquier coma por el simbolo de punto
aCadenaCatidad := StringReplace(aCadenaCatidad,
_COMA_DECIMAL,
_PUNTO_DECIMAL,
[rfReplaceAll]);
end;
initialization
formatSettingsLocal := TFormatSettings.Create;
end. |
unit ConstructorsDestructorsForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox,
FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
procedure Show(const Msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
DateUtils;
{
Object Pascal allows custom-named constructors, allowing overloading of
constructors
}
type
TDate = class
private
FDate: TDateTime;
public
constructor Create;
constructor CreateFromValues(m, d, y: Integer);
procedure SetValue(m, d, y: Integer);
function LeapYear: Boolean;
function GetText: string;
procedure Increase;
end;
{ TDate }
constructor TDate.Create;
begin
FDate := Today;
end;
constructor TDate.CreateFromValues(m, d, y: Integer);
begin
SetValue(m, d, y);
end;
function TDate.GetText: string;
begin
Result := DateToStr(FDate);
end;
procedure TDate.Increase;
begin
FDate := FDate + 1;
end;
function TDate.LeapYear: Boolean;
begin
// Call IsLeapYear in SysUtils and YearOf in DateUtils
Result := IsLeapYear(YearOf(FDate));
end;
procedure TDate.SetValue(m, d, y: Integer);
begin
FDate := EncodeDate(y, m, d);
end;
// Class demonstrating destructors and resource management
type
TPerson = class
private
FName: string;
FBirthDate: TDate;
public
constructor Create(name: string);
// unlike constructor, destructor is virtual so is overridden
// calling instance.Free will automatically call Destroy too if it exists
destructor Destroy; override;
// Some actual methods
function Info: string;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ADay: TDate;
begin
// Create
ADay := TDate.Create; // today
// use
ADay.Increase;
if ADay.LeapYear then
Show('Leap year: ' + ADay.GetText)
else
Show('Not a leap year: ' + ADay.GetText);
// Free the memory
ADay.Free;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
ADay: TDate;
begin
// Create
ADay := TDate.CreateFromValues(1, 1, 2020);
// Use
ADay.Increase;
if ADay.LeapYear then
Show('Leap year: ' + ADay.GetText);
// Free the memory
ADay.Free;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
Person: TPerson;
begin
Person := TPerson.Create ('Jack');
// use the class and its internal object
Show (Person.Info);
Person.Free;
end;
procedure TForm1.Show(const Msg: string);
begin
Memo1.Lines.Add(Msg);
end;
{ TPerson }
constructor TPerson.Create(name: string);
begin
FName := Name;
FBirthDate := TDate.Create;
end;
destructor TPerson.Destroy;
begin
// destructor must free instance of TDate class too
FBirthDate.Free;
inherited;
end;
function TPerson.Info: string;
begin
Result := FName + ': ' + FBirthDate.GetText;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2013 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
// Implements a TListView appearance
// Install this appearance using a design time package.
// Once installed, the "MultiDetailItem" appearance can be used with a TListView component
unit MultiDetailAppearanceU;
interface
uses FMX.ListView, FMX.ListView.Types, System.Classes, System.SysUtils,
FMX.Types, System.UITypes;
type
TMultiDetailAppearanceNames = class
public const
ListItem = 'MultiDetailItem';
ListItemCheck = ListItem + 'ShowCheck';
ListItemDelete = ListItem + 'Delete';
Detail1 = 'det1'; // Name of MultiDetail object/data
Detail2 = 'det2';
Detail3 = 'det3';
end;
implementation
uses System.Math, System.Rtti;
type
TMultiDetailItemAppearance = class(TPresetItemObjects)
public const
cTextMarginAccessory = 8;
cDefaultImagePlaceOffsetX = -3;
cDefaultImageTextPlaceOffsetX = 4;
cDefaultHeight = 80;
cDefaultImageWidth = 65;
cDefaultImageHeight = 65;
private
FMultiDetail1: TTextObjectAppearance;
FMultiDetail2: TTextObjectAppearance;
FMultiDetail3: TTextObjectAppearance;
procedure SetMultiDetail1(const Value: TTextObjectAppearance);
procedure SetMultiDetail2(const Value: TTextObjectAppearance);
procedure SetMultiDetail3(const Value: TTextObjectAppearance);
protected
function DefaultHeight: Integer; override;
procedure UpdateSizes; override;
function GetGroupClass: TPresetItemObjects.TGroupClass; override;
procedure SetObjectData(const AListViewItem: TListViewItem; const AIndex: string; const AValue: TValue; var AHandled: Boolean); override;
public
constructor Create; override;
destructor Destroy; override;
published
property Image;
property MultiDetail1: TTextObjectAppearance read FMultiDetail1 write SetMultiDetail1;
property MultiDetail2: TTextObjectAppearance read FMultiDetail2 write SetMultiDetail2;
property MultiDetail3: TTextObjectAppearance read FMultiDetail3 write SetMultiDetail3;
property Accessory;
end;
TMultiDetailDeleteAppearance = class(TMultiDetailItemAppearance)
private const
cDefaultGlyph = TGlyphButtonType.Delete;
public
constructor Create; override;
published
property GlyphButton;
end;
TMultiDetailShowCheckAppearance = class(TMultiDetailItemAppearance)
private const
cDefaultGlyph = TGlyphButtonType.Checkbox;
public
constructor Create; override;
published
property GlyphButton;
end;
const
cMultiDetail1Member = 'Detail1';
cMultiDetail2Member = 'Detail2';
cMultiDetail3Member = 'Detail3';
constructor TMultiDetailItemAppearance.Create;
begin
inherited;
Accessory.DefaultValues.AccessoryType := TAccessoryType.More;
Accessory.DefaultValues.Visible := True;
Accessory.RestoreDefaults;
Text.DefaultValues.VertAlign := TListItemAlign.Trailing;
Text.DefaultValues.TextVertAlign := TTextAlign.taLeading;
Text.DefaultValues.Height := 76; // Item will be bottom aligned, with text top aligned
Text.DefaultValues.Visible := True;
Text.RestoreDefaults;
FMultiDetail1 := TTextObjectAppearance.Create;
FMultiDetail1.Name := TMultiDetailAppearanceNames.Detail1;
FMultiDetail1.DefaultValues.Assign(Text.DefaultValues); // Start with same defaults as Text object
FMultiDetail1.DefaultValues.Height := 56; // Move text down
FMultiDetail1.DefaultValues.IsDetailText := True; // Use detail font
FMultiDetail1.RestoreDefaults;
FMultiDetail1.OnChange := Self.ItemPropertyChange;
FMultiDetail1.Owner := Self;
FMultiDetail2 := TTextObjectAppearance.Create;
FMultiDetail2.Name := TMultiDetailAppearanceNames.Detail2;
FMultiDetail2.DefaultValues.Assign(FMultiDetail1.DefaultValues); // Start with same defaults as Text object
FMultiDetail2.DefaultValues.Height := 38; // Move text down
FMultiDetail2.RestoreDefaults;
FMultiDetail2.OnChange := Self.ItemPropertyChange;
FMultiDetail2.Owner := Self;
FMultiDetail3 := TTextObjectAppearance.Create;
FMultiDetail3.Name := TMultiDetailAppearanceNames.Detail3;
FMultiDetail3.DefaultValues.Assign(FMultiDetail2.DefaultValues); // Start with same defaults as Text object
FMultiDetail3.DefaultValues.Height := 20; // Move text down
FMultiDetail3.RestoreDefaults;
FMultiDetail3.OnChange := Self.ItemPropertyChange;
FMultiDetail3.Owner := Self;
// Define livebindings members that make up MultiDetail
FMultiDetail1.DataMembers :=
TObjectAppearance.TDataMembers.Create(
TObjectAppearance.TDataMember.Create(
cMultiDetail1Member, // Displayed by LiveBindings
Format('Data["%s"]', [TMultiDetailAppearanceNames.Detail1]))); // Expression to access value from TListViewItem
FMultiDetail2.DataMembers :=
TObjectAppearance.TDataMembers.Create(
TObjectAppearance.TDataMember.Create(
cMultiDetail2Member, // Displayed by LiveBindings
Format('Data["%s"]', [TMultiDetailAppearanceNames.Detail2]))); // Expression to access value from TListViewItem
FMultiDetail3.DataMembers :=
TObjectAppearance.TDataMembers.Create(
TObjectAppearance.TDataMember.Create(
cMultiDetail3Member, // Displayed by LiveBindings
Format('Data["%s"]', [TMultiDetailAppearanceNames.Detail3]))); // Expression to access value from TListViewItem
Image.DefaultValues.Width := cDefaultImageWidth;
Image.DefaultValues.Height := cDefaultImageHeight;
Image.RestoreDefaults;
GlyphButton.DefaultValues.VertAlign := TListItemAlign.Center;
GlyphButton.RestoreDefaults;
// Define the appearance objects
AddObject(Text, True);
AddObject(MultiDetail1, True);
AddObject(MultiDetail2, True);
AddObject(MultiDetail3, True);
AddObject(Image, True);
AddObject(Accessory, True);
AddObject(GlyphButton, IsItemEdit); // GlyphButton is only visible when in edit mode
end;
constructor TMultiDetailDeleteAppearance.Create;
begin
inherited;
GlyphButton.DefaultValues.ButtonType := cDefaultGlyph;
GlyphButton.DefaultValues.Visible := True;
GlyphButton.RestoreDefaults;
end;
constructor TMultiDetailShowCheckAppearance.Create;
begin
inherited;
GlyphButton.DefaultValues.ButtonType := cDefaultGlyph;
GlyphButton.DefaultValues.Visible := True;
GlyphButton.RestoreDefaults;
end;
function TMultiDetailItemAppearance.DefaultHeight: Integer;
begin
Result := cDefaultHeight;
end;
destructor TMultiDetailItemAppearance.Destroy;
begin
FMultiDetail1.Free;
FMultiDetail2.Free;
FMultiDetail3.Free;
inherited;
end;
procedure TMultiDetailItemAppearance.SetMultiDetail1(
const Value: TTextObjectAppearance);
begin
FMultiDetail1.Assign(Value);
end;
procedure TMultiDetailItemAppearance.SetMultiDetail2(
const Value: TTextObjectAppearance);
begin
FMultiDetail2.Assign(Value);
end;
procedure TMultiDetailItemAppearance.SetMultiDetail3(
const Value: TTextObjectAppearance);
begin
FMultiDetail3.Assign(Value);
end;
procedure TMultiDetailItemAppearance.SetObjectData(
const AListViewItem: TListViewItem; const AIndex: string;
const AValue: TValue; var AHandled: Boolean);
begin
inherited;
end;
function TMultiDetailItemAppearance.GetGroupClass: TPresetItemObjects.TGroupClass;
begin
Result := TMultiDetailItemAppearance;
end;
procedure TMultiDetailItemAppearance.UpdateSizes;
var
LOuterHeight: Single;
LOuterWidth: Single;
LInternalWidth: Single;
LImagePlaceOffset: Single;
LImageTextPlaceOffset: Single;
begin
BeginUpdate;
try
inherited;
// Update the widths and positions of renderening objects within a TListViewItem
LOuterHeight := Height - Owner.ItemSpaces.Top - Owner.ItemSpaces.Bottom;
LOuterWidth := Owner.Width - Owner.ItemSpaces.Left - Owner.ItemSpaces.Right;
if Image.ActualWidth = 0 then
begin
LImagePlaceOffset := 0;
LImageTextPlaceOffset := 0;
end
else
begin
LImagePlaceOffset := cDefaultImagePlaceOffsetX;
LImageTextPlaceOffset := cDefaultImageTextPlaceOffsetX;
end;
Image.InternalPlaceOffset.X := GlyphButton.ActualWidth + LImagePlaceOffset;
if Image.ActualWidth > 0 then
Text.InternalPlaceOffset.X :=
Image.ActualPlaceOffset.X + Image.ActualWidth + LImageTextPlaceOffset
else
Text.InternalPlaceOffset.X :=
0 + GlyphButton.ActualWidth;
MultiDetail1.InternalPlaceOffset.X := Text.InternalPlaceOffset.X;
MultiDetail2.InternalPlaceOffset.X := Text.InternalPlaceOffset.X;
MultiDetail3.InternalPlaceOffset.X := Text.InternalPlaceOffset.X;
LInternalWidth := LOuterWidth - Text.ActualPlaceOffset.X - Accessory.ActualWidth;
if Accessory.ActualWidth > 0 then
LInternalWidth := LInternalWidth - cTextMarginAccessory;
Text.InternalWidth := Max(1, LInternalWidth);
MultiDetail1.InternalWidth := Text.InternalWidth;
MultiDetail2.InternalWidth := Text.InternalWidth;
MultiDetail3.InternalWidth := Text.InternalWidth;
finally
EndUpdate;
end;
end;
type
TOption = TCustomListView.TRegisterAppearanceOption;
const
sThisUnit = 'MultiDetailAppearanceU'; // Will be added to the uses list when appearance is used
initialization
// MultiDetailItem group
TCustomListView.RegisterAppearance(
TMultiDetailItemAppearance, TMultiDetailAppearanceNames.ListItem,
[TOption.Item], sThisUnit);
TCustomListView.RegisterAppearance(
TMultiDetailDeleteAppearance, TMultiDetailAppearanceNames.ListItemDelete,
[TOption.ItemEdit], sThisUnit);
TCustomListView.RegisterAppearance(
TMultiDetailShowCheckAppearance, TMultiDetailAppearanceNames.ListItemCheck,
[TOption.ItemEdit], sThisUnit);
finalization
TCustomListView.UnregisterAppearances(
TArray<TCustomListView.TItemAppearanceObjectsClass>.Create(
TMultiDetailItemAppearance, TMultiDetailDeleteAppearance,
TMultiDetailShowCheckAppearance));
end.
|
unit JuridicalDetailsTest;
interface
uses dbTest, dbObjectTest, SysUtils, Classes;
type
TJuridicalDetailsTest = class (TdbTest)
protected
// подготавливаем данные для тестирования
procedure SetUp; override;
// возвращаем данные для тестирования
// procedure TearDown; override;
published
procedure ProcedureLoad; override;
end;
(* TJuridicalDetails = class(TObjectTest)
private
function InsertDefault: integer; override;
procedure DeleteRecord(Id: Integer); override;
procedure InsertUpdateInList(Id: integer); override;
public
function InsertUpdatePriceListItem(const Id: integer; PriceListId, GoodsId: integer;
OperDate: TDateTime; Price: double): integer;
constructor Create; override;
procedure Delete(Id: Integer); override;
end;
*)
implementation
uses DB, UtilConst, TestFramework, Authentication, CommonData, Storage,
dbMovementItemTest, dbMovementTest;
procedure TJuridicalDetailsTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'OBJECTHistory\JuridicalDetails\';
inherited;
end;
procedure TJuridicalDetailsTest.SetUp;
begin
inherited;
TAuthentication.CheckLogin(TStorageFactory.GetStorage, 'Админ', 'Админ', gc_User);
end;
(*procedure TJuridicalDetailsTest.TearDown;
begin
inherited;
if Assigned(InsertedIdObjectHistoryList) then
with TPriceListItem.Create do
while InsertedIdObjectHistoryList.Count > 0 do
Delete(StrToInt(InsertedIdObjectHistoryList[0]));
if Assigned(InsertedIdMovementItemList) then
with TMovementItemTest.Create do
while InsertedIdMovementItemList.Count > 0 do
Delete(StrToInt(InsertedIdMovementItemList[0]));
if Assigned(InsertedIdMovementList) then
with TMovementTest.Create do
while InsertedIdMovementList.Count > 0 do
Delete(StrToInt(InsertedIdMovementList[0]));
if Assigned(InsertedIdObjectList) then
with TObjectTest.Create do
while InsertedIdObjectList.Count > 0 do
Delete(StrToInt(InsertedIdObjectList[0]));}
end;
procedure TPriceListItemTest.Test;
var GoodsId, PriceListId: Integer;
RecordCount: Integer;
ObjectTest: TPriceListItem;
Id_2012, Id_2013, Id_2011, Id_2011_06_06: Integer;
begin
GoodsId := TGoodsTest.Create.GetDefault;
PriceListId := TPriceListTest.Create.GetDefault;
try
ObjectTest := TPriceListItem.Create;
// Добавляем историю с датой 01.01.2012
Id_2012 := ObjectTest.InsertUpdatePriceListItem(0, PriceListId, GoodsId, StrToDate('01.01.2012'), 2012);
// Добавляем историю с датой 01.01.2013
Id_2013 := ObjectTest.InsertUpdatePriceListItem(0, PriceListId, GoodsId, StrToDate('01.01.2013'), 2013);
ObjectTest.InsertUpdatePriceListItem(0, PriceListId, GoodsId, StrToDate('01.01.2014'), 2014);
// Добавляем историю с датой 01.01.2011
Id_2011 := ObjectTest.InsertUpdatePriceListItem(0, PriceListId, GoodsId, StrToDate('01.01.2011'), 2011);
// Добавляем историю с датой 06.06.2011
Id_2011_06_06 := ObjectTest.InsertUpdatePriceListItem(0, PriceListId, GoodsId, StrToDate('06.06.2011'), 201106);
// Изменяем историю с датой 01.01.2012 на 01.01.2010
ObjectTest.InsertUpdatePriceListItem(Id_2012, PriceListId, GoodsId, StrToDate('01.01.2010'), 2012);
// Изменяем историю с датой 01.01.2010 на 01.01.2020
ObjectTest.InsertUpdatePriceListItem(Id_2012, PriceListId, GoodsId, StrToDate('01.01.2020'), 2012);
// Изменяем историю с датой 01.01.2020 на 01.01.2012
ObjectTest.InsertUpdatePriceListItem(Id_2012, PriceListId, GoodsId, StrToDate('01.01.2012'), 2012);
// Удаляем историю с датой 06.06.2011
ObjectTest.Delete(Id_2011_06_06);
// Удаляем историю с датой 01.01.2011
ObjectTest.Delete(Id_2011);
// Удаляем историю с датой 01.01.2013
ObjectTest.Delete(Id_2013);
// Удаляем историю с датой 01.01.2012
ObjectTest.Delete(Id_2012);
finally
end;
end;
{ TPriceListItemHistoryTest }
constructor TPriceListItem.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_ObjectHistory_PriceListItem';
spSelect := 'gpSelect_ObjectHistory_PriceListItem';
spGet := '';
end;
procedure TPriceListItem.Delete(Id: Integer);
var Index: Integer;
begin
if InsertedIdObjectHistoryList.Find(IntToStr(Id), Index) then begin
// здесь мы разрешаем удалять ТОЛЬКО вставленные в момент теста данные
DeleteRecord(Id);
InsertedIdObjectHistoryList.Delete(Index);
end
else
raise Exception.Create('Попытка удалить запись, вставленную вне теста!!!');
end;
procedure TPriceListItem.DeleteRecord(Id: Integer);
const
pXML =
'<xml Session = "">' +
'<lpDelete_ObjectHistory OutputType="otResult">' +
'<inId DataType="ftInteger" Value="%d"/>' +
'</lpDelete_ObjectHistory>' +
'</xml>';
begin
TStorageFactory.GetStorage.ExecuteProc(Format(pXML, [Id]))
end;
function TPriceListItem.InsertDefault: integer;
begin
end;
procedure TPriceListItem.InsertUpdateInList(Id: integer);
begin
InsertedIdObjectHistoryList.Add(IntToStr(Id));
end;
function TPriceListItem.InsertUpdatePriceListItem(const Id: integer;
PriceListId, GoodsId: integer; OperDate: TDateTime; Price: double): integer;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inPriceListId', ftInteger, ptInput, PriceListId);
FParams.AddParam('inGoodsId', ftInteger, ptInput, GoodsId);
FParams.AddParam('inOperDate', ftDateTime, ptInput, OperDate);
FParams.AddParam('inPrice', ftFloat, ptInput, Price);
result := InsertUpdate(FParams);
end;
*)
initialization
// TestFramework.RegisterTest('Истории', TJuridicalDetailsTest.Suite);
end.
|
unit BuilderPizzaExample.Processors.CalculatePrice;
interface
uses
BuilderPizzaExample.Processors.ICalculatePrice,
BuilderPizzaExample.Domain.Pizza;
type
TCalculatePrice = class(TInterfacedObject, ICalculatePrice)
public
procedure DefinePrice(APizza: TPizza);
class function New : TCalculatePrice;
end;
implementation
uses
BuilderPizzaExample.Domain.ValueObject.PizzaType,
BuilderPizzaExample.Domain.ValueObject.EdgeType;
{ TCalculatePrice }
procedure TCalculatePrice.DefinePrice(APizza: TPizza);
var
unitsIngredients: Integer;
priceOfIngredients: double;
priceOfPizzaSize: double;
priceOfPizzaType: double;
priceOfEdge: double;
begin
priceOfEdge := 0;
unitsIngredients := APizza.IngredientList.Count;
priceOfIngredients := unitsIngredients * 1.70;
priceOfPizzaSize := Ord(APizza.PizzaSize) * 10;
case APizza.PizzaType of
TPizzaType.Sweet:
priceOfPizzaType := 10
else
priceOfPizzaType := 0;
end;
if Assigned(APizza.Edge) then
begin
case APizza.Edge.EdgeType of
TEdgeType.Chocolate:
priceOfEdge := (5 * Ord(APizza.Edge.EdgeSize))
else
priceOfEdge := (2 * Ord(APizza.Edge.EdgeSize))
end;
end;
APizza.Price := priceOfIngredients + priceOfPizzaSize + priceOfPizzaType +
priceOfEdge;
end;
class function TCalculatePrice.New: TCalculatePrice;
begin
Result := Self.Create;
end;
end.
|
unit Frm_Exportar_datos;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, uniGUITypes, uniGUIAbstractClasses,
uniGUIClasses, uniGUIForm, uniRadioGroup, uniToolBar, uniGUIBaseClasses,
uniScreenMask,SQLConnectionC, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, sqlexpr,dbclient,strutils;
type
TFrmExportarDatos = class(TUniForm)
UniToolBar1: TUniToolBar;
UBAceptar: TUniToolButton;
UBSalir: TUniToolButton;
RadioGroup1: TUniRadioGroup;
UniScreenMask1: TUniScreenMask;
FDQuery1: TFDQuery;
FDQuerytablas: TFDQuery;
procedure UBAceptarClick(Sender: TObject);
procedure UniFormAjaxEvent(Sender: TComponent; EventName: string;
Params: TUniStrings);
procedure UBSalirClick(Sender: TObject);
private
FConexion: TFDConnection;
procedure SetConexion(const Value: TFDConnection);
{ Private declarations }
public
property Conexion: TFDConnection read FConexion write SetConexion;
end;
function FrmExportarDatos: TFrmExportarDatos;
implementation
{$R *.dfm}
uses
MainModule, uniGUIApplication, Funciones, ServerModule;
function FrmExportarDatos: TFrmExportarDatos;
begin
Result := TFrmExportarDatos(UniMainModule.GetFormInstance(TFrmExportarDatos));
end;
procedure TFrmExportarDatos.SetConexion(const Value: TFDConnection);
begin
FConexion := Value;
end;
procedure TFrmExportarDatos.UBAceptarClick(Sender: TObject);
var
Ruta: string;
begin
createdir(IncludeTrailingPathDelimiter(UniServerModule.LocalCachePath)+'gdb');
createdir(IncludeTrailingPathDelimiter(UniServerModule.LocalCachePath)+'xml');
try
case RadioGroup1.ItemIndex of
0:
begin
Ruta:=copy(Conexion.Params.Values['DATABASE'],
Pos(':',Conexion.Params.Values['DATABASE'])+1,
Length(Conexion.Params.Values['DATABASE'])-Pos(':',Conexion.Params.Values['DATABASE']));
CopyFile(PChar(Ruta),PChar(IncludeTrailingPathDelimiter(UniServerModule.LocalCachePath)+'gdb\'+ExtractFileName(Ruta)),False);
end;
1:
begin
// Procesa
FDQuery1.Connection:=Conexion;
FDQuerytablas.Connection:=Conexion;
FDQuerytablas.Close;
FDQuerytablas.sql.Text:= 'select rdb$relation_name '+
'from rdb$relations '+
'where rdb$view_blr is null '+
'and (rdb$system_flag is null or rdb$system_flag = 0);';
FDQuerytablas.Open;
while not FDQuerytablas.eof do
begin
FDQuery1.Close;
FDQuery1.sql.Text:='select * from '+FDQuerytablas.Fields.Fields[0].AsString;
FDQuery1.Open;
FDQuery1.SaveToFile(IncludeTrailingPathDelimiter(UniServerModule.LocalCachePath)+'xml\'+trim(FDQuerytablas.Fields.Fields[0].AsString)+'.xml');
FDQuery1.Close;
FDQuerytablas.next;
end;
end;
end;
finally
ShowMessage('Los datos se han exportado correctamente en el formato seleccionado.'+#13+' Pulsa para comprimir los datos y descargar el fichero "datos.zip".',
procedure (Sender: Tcomponent;AResult: Integer)
begin
UniSession.AddJS(Self.Name+'.form.showMask(''Comprimiendo datos...'');'+#13#10+
'ajaxRequest('+Self.Name+'.form,''COMPRIMIR'',[]);');
end);
end;
end;
procedure TFrmExportarDatos.UBSalirClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFrmExportarDatos.UniFormAjaxEvent(Sender: TComponent;
EventName: string; Params: TUniStrings);
begin
if SameText(EventName,'COMPRIMIR') then
begin
Deletefile(IncludeTrailingPathDelimiter(UniServerModule.LocalCachePath)+'datos.zip');
ComprimirCarpeta(IncludeTrailingPathDelimiter(UniServerModule.LocalCachePath)+ifthen(RadioGroup1.ItemIndex=0,'gdb','xml'),IncludeTrailingPathDelimiter(UniServerModule.LocalCachePath)+'datos.zip','');
UniSession.AddJS(self.Name + '.form.hideMask();');
UniSession.SendFile(IncludeTrailingPathDelimiter(UniServerModule.LocalCachePath)+'datos.zip');
ShowMessage('Proceso finalizado.');
end;
end;
end.
|
unit Manager;
{
TITLE: PROGRAMMING II LABS
SUBTITLE: Practical 2
AUTHOR 1: Carlos Torres Paz LOGIN 1: carlos.torres@udc.es
AUTHOR 2: Daniel Sergio Vega Rodriguez LOGIN 2: d.s.vega@udc.es
GROUP: 5.4
DATE: 03/05/2019
}
interface
uses PartyList,CenterList,SharedTypes;
type
tManager = tListC;
(* Manager hace referencia a una multilista ,es decir, una variable tipo tManager*)
procedure createEmptyManager(var Mng: tManager);
(*
Objetivo: inicializa una multilista.
Entrada: una variable tipo multilista.
Salida: la entrada inicializada y vacía.
*)
{ PRECONDICION GENERAL: La variable de tipo tManager debe estar inicializada a la hora de ser usada por las siguientes funciones:}
function insertCenter(cName: tCenterName; numVotes: tNumVotes; var Mng: tManager):boolean;
(*
Objetivo: inserta un nuevo centro en el manager determinado con un numero de votantes determinado y los "partidos" B y N con sus votos a 0.
Entradas: un nombre de centro, un numero de votos y el manager.
Salidas: el manager con el nuevo centro insertado en la posición correspondiente y un booleano que es TRUE solo si la operación se completó.
Postcondición: Las posiciones de los elementos de la lista posteriores al insertado pueden cambiar de valor. Si había un centro idéntico en la lista
no se modifica la lista y la operación devuelve FALSE.
*)
function insertPartyInCenter(cName: tCenterName; pName: tPartyName; var Mng: tManager):boolean;
(*
Objetivo: inserta un partido en la lista de partidos de un centro (en el manager especificado) con sus votos a 0.
Entradas: el nombre del centro en el que se inserta el partido, el nombre del nuevo partido, el manager en el que se opera.
Salidas: el manager modificado y un booleano que es TRUE si la operación ha sido posible.
Precondición: el centro debe ser válido.
Postcondición: las posiciones de los partidos del centro pueden haber cambiado, si el partido a introducir ya existe la función devuelve FALSE.
*)
function deleteCenters(var Mng: tManager):integer;
(*
Objetivo: elimina los centros electorales cuyo número de votos válidos es 0 y sus respectivas listas de partidos.
Entrada: el manager en el que se va a ejecutar la operación.
Salida: el manager modificado y un entero cuyo valor es el número de partidos eliminados.
*)
procedure deleteManager(var Mng: tManager);
(*
Objetivo: elimina todos los elementos de la multilista (manager) y sus respectivas estructuras subordinadas.
Entradas: el manager que va a ser vaciado.
Salidas: el manager vacío.
*)
procedure ShowStats(var Mng : tManager);
(*
Objetivo: muestra una serie de estadísticas de votación y participación (Número, y porcentajes salvo en NULOS) de cada uno de los centros por separado.
Entradas: la multilista (manager).
Salidas: texto por pantalla
(El manager se pasa por referencia por eficiencia de la memoria, no se modifica en ningún momento)).
Poscondición: si la multilista está vacía el procedimiento emitirá un mensaje de error por pantalla.
*)
function voteInCenter(cName: tCenterName; pName: tPartyName; var Mng: tManager):boolean;
(*
Objetivo: incrementa en uno el número de votos del partido especificado en el centro especificado.
Entradas: el nombre del centro, el nombre del partido, la multilista.
Salidas: la multilista modificada y un booleano que informa de la validez del voto.
Postcondición: si el partido no existe en el centro o si el centro no es válido devuelve FALSE.
*)
implementation
procedure createEmptyManager(var Mng: tManager);
begin
createEmptyListC(Mng);
end;
function insertCenter(cName: tCenterName; numVotes: tNumVotes; var Mng: tManager):boolean;
var
newcenter: tItemC;
newparty: tItem;
newpartylist: tList; (* Variables dedicadas a guardar temporalmente las listas y elementos con los que se opera *)
temp: boolean; (* Boolean temporal que controla el comportamiento de la función y su resultado *)
begin
if findItemC(cName,Mng) = NULLC then begin (*Comprueba si el centro ya existe. Si ya existe, no hace nada y devuelve FALSE*)
createEmptyList(newpartylist);
with newparty do begin (* Partido B *)
partyname:= BLANKVOTE;
numvotes:= 0;
end;
temp:= InsertItem(newparty,newpartylist);
newparty.partyname:= NULLVOTE; (* Partido N *)
temp:= temp and InsertItem(newparty,newpartylist);
if temp then (*Si se han insertado correctamente los partidos en la lista*)
with newcenter do begin (* Creacion del centro nuevo *)
centername := cName;
totalvoters := numVotes;
validvotes := 0;
partylist := newpartylist;
end;
temp:= temp and insertItemC(newcenter,Mng);
if not temp then (*Si la lista de centros estaba llena*)
while not isEmptyList(newpartylist) do
deleteAtPosition(first(newpartylist),newpartylist); (*Borra la lista de partidos*)
insertCenter := temp; (* temp es TRUE si y sólo si la operación se completó*)
end else
insertCenter:=false;
end;
function insertPartyInCenter(cName : tCenterName; pName : tPartyName; var Mng : tManager): boolean;
var
posc : tPosC; (* Variable para conservar la posición del centro en el que se va a operar *)
newlist : tList; (* Puntero con el que se trabaja la lista *)
newparty : tItem; (* Nuevo nodo de lista de partidos *)
begin
posc := findItemC(cName,Mng);
if (posc <> NULLC) then (*Comprueba si existe el centro especificado*)
begin
newlist := getItemC(findItemC(cName,Mng),Mng).partylist; (* Se obtiene el puntero al primer elemento de la lista de partidos del centro *)
if findItem(pName, newlist) = NULL then begin (*Comprueba que el partido no exista ya en la lista*)
with newparty do begin (* Construcción del nuevo partido *)
partyname := pName;
numvotes := 0;
end;
if insertItem(newparty,newlist) then begin (*Comprueba que haya memoria dinámica disponible*)
updateListC(newlist, posc, Mng);(* Actualización del puntero para prevenir errores *)
insertPartyInCenter := true;
end else
insertPartyInCenter := false;
end else
insertPartyInCenter:= false;
end
else
insertPartyInCenter:= false;
end;
procedure deletePartyList(cpos: tPosC; var Mng: tManager); (*Función auxiliar para el DeleteCenters*)
var
plist : tPosL;
begin
plist := getItemC(cpos,Mng).partylist;
while not isEmptyList(plist) do (*Eliminación secuencial de los elementos*)
deleteAtPosition(first(plist),plist);
updateListC(plist,cpos,Mng);(* Actualización del puntero para prevenir errores *)
end;
function deleteCenters(var Mng: tManager):integer;
var
temp: integer; (* Variable que guarda el numero de centros eliminados *)
posc,preposc : tPosC; (* Variables posicion para iterar en la multilista*)
tempcenter : tItemC; (* Variable que guarda el centro en el que esta situada la iteracion *)
begin
if isEmptyListC(Mng) then deleteCenters:= 0
else
begin
temp:= 0;
tempcenter:= getItemC(lastC(Mng),Mng);
while (not isEmptyListC(Mng) and (tempcenter.validvotes = 0)) do begin (*Primero se borra el último centro de la lista todas las veces que sea necesario*)
deletePartyList(lastC(Mng),Mng); (*Borra su lista de partidos*)
writeln('* Remove: center ', tempcenter.centername);
deleteAtPositionC(lastC(Mng),Mng); (*Y luego borra el centro*)
temp:= temp+1;
tempcenter:= getItemC(lastC(Mng),Mng)
end;
if not isEmptyListC(Mng) then begin (*Si la lista no se ha quedado vacía a base de eliminar el último elemento repetidas veces, se continúa*)
posc := lastC(Mng);
preposc := previousC(posc,Mng);
end;
while not isEmptyListC(Mng) and (preposc <> NULLC) do begin
(* Eliminacion de los elementos anteriores al ultimo que cumplen con la condicion de eliminacion*)
tempcenter:= getItemC(preposc,Mng);
with tempcenter do begin
if validvotes = 0 then
begin (* Proceso de eliminacion del centro *)
deletePartyList(preposc,Mng);
writeln('* Remove: center ', centername);
deleteAtPositionC(preposc, Mng);
temp:= temp+1;
end
else
posc:= previousC(posc,Mng);
preposc := previousC(posc,Mng);
end;
end;
deleteCenters := temp;
end;
end;
(*Aquí empezamos los borrados por el final por motivos de eficiencia, ya que los centros son una lista estática y las eliminaciones
son más eficientes por el final. Aun así, no se ha entrado dentro del TAD CenterList en ningún momento, por lo que serviría sin problemas
en el caso de que la lista de centros pasase a ser dinámica*)
procedure deleteManager(var Mng: tManager);
begin
while not isEmptyListC(Mng) do begin
deletePartyList(lastC(Mng),Mng);
deleteAtPositionC(lastC(Mng),Mng);
end;
end;
procedure ShowStats(var Mng : tManager);
var
pos : tPosL;
posc : tPosC;
item : tItem; (*Las variables pos se usan para guardar una posiciones de referencia en la multilista y item como valor temporal*)
participation : tNumVotes; (*Guarda la acumulación de votos en un centro*)
tempvalidvotes : tNumVotes; (*Variable necesaria debido a la posibilidad de que los votos válidos sean 0*)
begin
if not isEmptyListC(Mng) then begin
posc := firstC(Mng);
while (posc <> NULLC) do begin (* Bucle hasta final de lista de centros *)
with getItemC(posc,Mng) do begin
writeln('Center ',centername);
if validvotes = 0 then tempvalidvotes := 1 (* Protección de la división en el caso de que validvotes sea 0 *)
else tempvalidvotes := validvotes;
//-/\-Preámbulos-/\------\/-Partidos-del-centro-\/----------------
pos:= first(partylist);
while pos<>NULL do begin (* Bucle hasta final de lista de partidos *)
item:= getItem(pos,partylist);
if (item.partyname <> NULLVOTE) then (*Condicional que detecta NULLVOTES para no mostrar porcentaje en el mismo*)
writeln('Party ',item.partyname, ' numvotes ', item.numvotes:0, ' (',item.numvotes*100/tempvalidvotes:2:2, '%)') (*Prints all parties on the list*)
else begin
writeln('Party ',item.partyname, ' numvotes ', item.numvotes:0);
participation := item.numvotes;
end;
pos:= next(pos,partylist);
end; (*Linea final de participación \/--\/ *)
participation := participation + validvotes; (* El valor previo de participation es el valor de votos nulos *)
writeln('Participation: ', participation:0, ' votes from ',totalvoters:0, ' voters (', (participation*100/totalvoters):2:2 ,'%)');
end;
writeln; (* <-- Por formato \/ Siguiente centro \/ *)
posc := nextC(posc,Mng);
end;
end else writeln('+ Error: ShowStats not possible'); (* En caso de que la lista esté vacía *)
end;
function voteInCenter(cName: tCenterName; pName: tPartyName; var Mng: tManager):boolean;
var
cpos: tPosC;
ppos: tPosL; (* Variables pos para usar como localizadoras en la multilista *)
nvotes: tNumVotes; (* Número para usar temporalmente en calculos *)
begin
cpos := findItemC(cName,Mng);
if (cpos <> NULLC) then (*Cierto si encontró el centro *)
begin
ppos := findItem(pName , getItemC(cpos,Mng).partylist);
if (ppos <> NULL) then (*Cierto si encontró el partido en el centro *)
begin
if pname <> NULLVOTE then updateValidVotesC((getItemC(cpos,Mng).validvotes + 1),cpos,Mng); (*Comprueba si el voto es nulo, en cuyo caso no actualiza los votos válidos*)
nvotes := GetItem(ppos, getItemC(cpos,Mng).partylist).numvotes;
nvotes := nvotes+1;
UpdateVotes(nvotes, ppos, getItemC(cpos,Mng).partylist); (* Adición del voto (Extracción-Suma-Actualización) *)
voteInCenter := true;
end
else
voteInCenter := false;
end
else
begin
voteInCenter:= false;
end;
end;
end.
|
unit ClasseAbastecimento;
interface
uses ClasseBomba;
type
TAbastecimento = class
private
FImpostoValor: double;
FQtd: double;
FValor: double;
FPreco: double;
FIdAbastecimento: integer;
FIdBomba: TBomba;
FImpostoPorcentagem: double;
FData: TdateTime;
procedure setData(const Value: TdateTime);
procedure setIdAbastecimento(const Value: integer);
procedure setIdBomba(const Value: TBomba);
procedure setImpostoPorcentagem(const Value: double);
procedure setImpostoValor(const Value: double);
procedure setPreco(const Value: double);
procedure setQtd(const Value: double);
procedure setValor(const Value: double);
public
constructor create;
destructor Destroy; override;
property idAbastecimento : integer read FIdAbastecimento write setIdAbastecimento;
property idBomba : TBomba read FIdBomba write setIdBomba;
property data : TdateTime read FData write setData;
property preco : double read FPreco write setPreco;
property qtd : double read FQtd write setQtd;
property valor : double read FValor write setValor;
property impostoPorcentagem : double read FImpostoPorcentagem write setImpostoPorcentagem;
property impostoValor : double read FImpostoValor write setImpostoValor;
end;
implementation
uses
System.SysUtils;
{ TAbastecimento }
constructor TAbastecimento.create;
begin
FIdBomba := TBomba.create;
end;
destructor TAbastecimento.destroy;
begin
freeAndNil(FIdBomba);
end;
procedure TAbastecimento.setData(const Value: TdateTime);
begin
FData := Value;
end;
procedure TAbastecimento.setIdAbastecimento(const Value: integer);
begin
FIdAbastecimento := Value;
end;
procedure TAbastecimento.setIdBomba(const Value: TBomba);
begin
FIdBomba := Value;
end;
procedure TAbastecimento.setImpostoPorcentagem(const Value: double);
begin
FImpostoPorcentagem := Value;
end;
procedure TAbastecimento.setImpostoValor(const Value: double);
begin
FImpostoValor := Value;
end;
procedure TAbastecimento.setPreco(const Value: double);
begin
FPreco := Value;
end;
procedure TAbastecimento.setQtd(const Value: double);
begin
FQtd := Value;
end;
procedure TAbastecimento.setValor(const Value: double);
begin
FValor := Value;
end;
end.
|
unit SOLID.ComOCP;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error,
FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async,
FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TCamadaBD = class
protected
function GerarSQLPrimeirosClientes: string; virtual; abstract;
public
procedure SelecionarPrimeirosClientes;
end;
TFirebird = class(TCamadaBD)
protected
function GerarSQLPrimeirosClientes: string; override;
end;
TOracle = class(TCamadaBD)
protected
function GerarSQLPrimeirosClientes: string; override;
end;
TSQLServer = class(TCamadaBD)
protected
function GerarSQLPrimeirosClientes: string; override;
end;
TPostgreSQL = class(TCamadaBD)
protected
function GerarSQLPrimeirosClientes: string; override;
end;
TSGBD = (dbFirebird, dbOracle, dbSQLServer, dbPostgreSQL);
TFormComOCP = class(TForm)
private
function CamadaDBFactory(SGBD: TSGBD): TCamadaBD;
procedure SelecionarPrimeirosClientes;
{ Private declarations }
public
{ Public declarations }
end;
var
FormComOCP: TFormComOCP;
implementation
{$R *.dfm}
{ TCamadaBD }
procedure TCamadaBD.SelecionarPrimeirosClientes;
var
Query: TFDQuery;
begin
Query := TFDQuery.Create(nil);
try
Query.Open(GerarSQLPrimeirosClientes);
{ ... }
finally
Query.Free;
end;
end;
{ TFirebird }
function TFirebird.GerarSQLPrimeirosClientes: string;
begin
result := 'SELECT FIRST 100 * FROM CLIENTES';
end;
{ TOracle }
function TOracle.GerarSQLPrimeirosClientes: string;
begin
result := 'SELECT * FROM Clientes WHERE rownum <= 100';
end;
{ TSQLServer }
function TSQLServer.GerarSQLPrimeirosClientes: string;
begin
result := 'SELECT TOP 100 * FROM CLIENTES';
end;
{ TPostgreSQL }
function TPostgreSQL.GerarSQLPrimeirosClientes: string;
begin
result := 'SELECT * FROM CLIENTES LIMIT 100';
end;
{ TForm1 }
function TFormComOCP.CamadaDBFactory(SGBD: TSGBD): TCamadaBD;
begin
case SGBD of
dbFirebird: result := TFirebird.Create;
dbOracle: result := TOracle.Create;
dbSQLServer: result := TSQLServer.Create;
dbPostgreSQL: result := TPostgreSQL.Create;
end;
end;
procedure TFormComOCP.SelecionarPrimeirosClientes;
var
CamadaBD: TCamadaBD;
begin
CamadaBD := CamadaDBFactory(dbOracle);
CamadaBD.SelecionarPrimeirosClientes;
end;
end.
|
unit uFizzBuzzCore;
interface
type
IFizzBuzzCore = interface
function getSaida(numero, divisor: Integer; saidaAtual, saidaNova: string) : string;
end;
TFizzBuzzCore = class(TInterfacedObject, IFizzBuzzCore)
private
function getSaida(numero, divisor: Integer; saidaAtual, saidaNova: string) : string;
public
class function new(): IFizzBuzzCore;
end;
implementation
uses
System.SysUtils;
class function TFizzBuzzCore.new(): IFizzBuzzCore;
begin
Result := Self.Create();
end;
function TFizzBuzzCore.getSaida(numero, divisor: Integer; saidaAtual, saidaNova: string): string;
begin
Result := saidaAtual;
if (numero mod divisor = 0) Or (POS(IntToStr(divisor), IntToStr(numero)) > 0) then
Result := saidaNova;
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.FixtureResult;
interface
{$I DUnitX.inc}
uses
{$IFDEF USE_NS}
System.Classes,
System.TimeSpan,
System.Diagnostics,
{$ELSE}
Classes,
TimeSpan,
Diagnostics,
{$ENDIF}
DUnitX.Generics,
DUnitX.TestFramework,
DUnitX.InternalInterfaces;
type
TDUnitXFixtureResult = class(TInterfacedObject,IFixtureResult,IFixtureResultBuilder)
private
FChildren : IList<IFixtureResult>;
FTestResults : IList<ITestResult>;
FFixture : ITestFixtureInfo;
FAllPassed : boolean;
FErrorCount : integer;
FFailureCount : integer;
FPassCount : integer;
FIgnoredCount : integer;
FMemoryLeakCount : Integer;
FTotalCount : integer;
FStopWatch : TStopwatch;
FStartTime : TDateTime;
FFinishTime : TDateTime;
FDuration : TTimeSpan;
FName : string;
FNameSpace : string;
FCanReduce : boolean;
protected
procedure Reduce;
function GetChildCount : Integer;
function GetChildren : IList<IFixtureResult>;
function GetErrorCount : Integer;
function GetErrors : IList<ITestError>;
function GetFailureCount : Integer;
function GetFailures : IList<ITestResult>;
function GetFixture : ITestFixtureInfo;
function GetHasFailures : Boolean;
function GetPassCount : Integer;
function GetPasses : IList<ITestResult>;
function GetTestResultCount : Integer;
function GetTestResults : IList<ITestResult>;
function GetIgnoredCount : Integer;
function GetStartTime: TDateTime;
function GetFinishTime: TDateTime;
function GetDuration: TTimeSpan;
function GetName : string;
function GetNamespace : string;
procedure AddChild(const AFixtureResult: IFixtureResult);
procedure AddTestResult(const AResult: ITestResult);
procedure RecordTestResult(const AResult : ITestResult);
procedure RollUpResults;
public
constructor Create(const AParentResult : IFixtureResult; const AFixture : ITestFixtureInfo);
end;
implementation
uses
{$IFDEF USE_NS}
System.DateUtils,
System.SysUtils;
{$ELSE}
DateUtils,
SysUtils;
{$ENDIF}
const
UNDEFINED_DATETIME = 0;
{ TDUnitXFixtureResult }
procedure TDUnitXFixtureResult.AddChild(const AFixtureResult: IFixtureResult);
begin
if FChildren = nil then
FChildren := TDUnitXList<IFixtureResult>.Create;
FChildren.Add(AFixtureResult);
end;
procedure TDUnitXFixtureResult.AddTestResult(const AResult: ITestResult);
begin
if FTestResults = nil then
FTestResults := TDUnitXList<ITestResult>.Create;
FTestResults.Add(AResult);
RecordTestResult(AResult);
end;
constructor TDUnitXFixtureResult.Create(const AParentResult : IFixtureResult;const AFixture: ITestFixtureInfo);
begin
FFixture := AFixture;
FStartTime := Now;
FFinishTime := UNDEFINED_DATETIME;
FStopWatch := TStopwatch.StartNew;
//Don't create collections here.. we'll lazy create;
FChildren := nil;
FTestResults := nil;
FName := AFixture.Name;
FNameSpace := AFixture.NameSpace;
if AParentResult <> nil then
begin
(AParentResult as IFixtureResultBuilder).AddChild(Self);
FCanReduce := True;
end;
end;
function TDUnitXFixtureResult.GetChildCount: Integer;
begin
if FChildren <> nil then
result := FChildren.Count
else
result := 0;
end;
function TDUnitXFixtureResult.GetChildren: IList<IFixtureResult>;
begin
//Don't pass nill back???
if FChildren = nil then
FChildren := TDUnitXList<IFixtureResult>.Create;
result := FChildren;
end;
function TDUnitXFixtureResult.GetDuration: TTimeSpan;
begin
result := FDuration;
end;
function TDUnitXFixtureResult.GetErrorCount: Integer;
begin
result := FErrorCount;
end;
function TDUnitXFixtureResult.GetErrors: IList<ITestError>;
var
test : ITestResult;
error : ITestError;
begin
result := TDUnitXList<ITestError>.Create;
if FTestResults = nil then
exit;
for test in FTestResults do
begin
if Supports(test,ITestError,error) then
result.Add(error);
end;
end;
function TDUnitXFixtureResult.GetFailureCount: Integer;
begin
result := FFailureCount;
end;
function TDUnitXFixtureResult.GetFailures: IList<ITestResult>;
var
test : ITestResult;
begin
result := TDUnitXList<ITestResult>.Create;
if FTestResults = nil then
exit;
for test in FTestResults do
begin
if test.ResultType = TTestResultType.Failure then
result.Add(test);
end;
end;
function TDUnitXFixtureResult.GetFinishTime: TDateTime;
begin
result := FFinishTime;
end;
function TDUnitXFixtureResult.GetFixture: ITestFixtureInfo;
begin
result := FFixture;
end;
function TDUnitXFixtureResult.GetHasFailures: Boolean;
begin
result := FFailureCount > 0;
end;
function TDUnitXFixtureResult.GetIgnoredCount: Integer;
begin
result := FIgnoredCount;
end;
function TDUnitXFixtureResult.GetName: string;
begin
result := FName;
end;
function TDUnitXFixtureResult.GetNamespace: string;
begin
result := FName;
end;
function TDUnitXFixtureResult.GetPassCount: Integer;
begin
result := FPassCount;
end;
function TDUnitXFixtureResult.GetPasses: IList<ITestResult>;
var
test : ITestResult;
begin
result := TDUnitXList<ITestResult>.Create;
if FTestResults = nil then
exit;
for test in FTestResults do
begin
if test.ResultType = TTestResultType.Pass then
result.Add(test);
end;
end;
function TDUnitXFixtureResult.GetStartTime: TDateTime;
begin
Result := FStartTime;
end;
function TDUnitXFixtureResult.GetTestResultCount: Integer;
begin
if FTestResults = nil then
Exit(0);
result := FTestResults.Count;
end;
function TDUnitXFixtureResult.GetTestResults: IList<DUnitX.TestFramework.ITestResult>;
begin
if FTestResults = nil then
FTestResults := TDUnitXList<ITestResult>.Create;
result := FTestResults;
end;
function Max(const a, b : TDateTime) : TDateTime;
begin
if a > b then
result := a
else
result := b;
end;
procedure TDUnitXFixtureResult.RecordTestResult(const AResult: ITestResult);
begin
Inc(FTotalCount);
case AResult.ResultType of
TTestResultType.Pass : Inc(FPassCount);
TTestResultType.Failure : Inc(FFailureCount);
TTestResultType.Error : Inc(FErrorCount);
TTestResultType.Ignored : Inc(FIgnoredCount);
TTestResultType.MemoryLeak : Inc(FMemoryLeakCount);
end;
if AResult.ResultType <> TTestResultType.Pass then
FAllPassed := False;
end;
procedure TDUnitXFixtureResult.Reduce;
var
fixtureRes : IFixtureResult;
begin
if (FChildren <> nil) and (FChildren.Count > 0) then
begin
//Reduce the children first.
for fixtureRes in FChildren do
fixtureRes.Reduce;
//if we have no tests and only one child, then we reduce to that child.
if FCanReduce and (FChildren.Count = 1) and ((FTestResults = nil) or (FTestResults.Count = 0)) then
begin
fixtureRes := FChildren[0];
FNameSpace := FNameSpace + '.' + FName;
FName := fixtureRes.Name;
FFixture := fixtureRes.Fixture;
if FTestResults = nil then
FTestResults := TDUnitXList<ITestResult>.Create;
FTestResults.AddRange(fixtureRes.TestResults);
FChildren.Clear;
if fixtureRes.ChildCount > 0 then
FChildren.AddRange(fixtureRes.Children)
else
FChildren.Clear;
end;
end;
end;
procedure TDUnitXFixtureResult.RollUpResults;
var
fixture : IFixtureResult;
begin
//guard against rolling up multiple times.
if FFinishTime <> UNDEFINED_DATETIME then
exit;
if FChildren <> nil then
begin
FDuration := TTimeSpan.Zero;
FFinishTime := FStartTime;
for fixture in FChildren do
begin
(fixture as IFixtureResultBuilder).RollUpResults;
Inc(FErrorCount,fixture.ErrorCount);
Inc(FFailureCount,fixture.FailureCount);
Inc(FIgnoredCount,fixture.IgnoredCount);
Inc(FPassCount,fixture.PassCount);
FAllPassed := FAllPassed and (not fixture.HasFailures);
FFinishTime := Max(FFinishTime,fixture.FinishTime);
FDuration := FDuration.Add(fixture.Duration);
end;
end
else if (FFinishTime = UNDEFINED_DATETIME) then
begin
FFinishTime := Now;
FStopWatch.Stop;
FDuration := FStopWatch.Elapsed;
end;
end;
end.
|
unit Helper.ItemListSimplePath;
interface
uses
System.Classes,
System.SysUtils,
Helper.ItemListDefault,
FMX.StdCtrls,
FMX.Objects,
FMX.Types,
FMX.Graphics
;
type
TItemListaSimplePath = class(IlTItemListDefault)
private
FPthIcon: FMX.Objects.TPath;
FLblDetail: TLabel;
FLblText: TLabel;
FDetail: string;
FText: string;
procedure SetDetail(const Value: string);
procedure SetText(const Value: string);
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Text: string read FText write SetText;
property Detail: string read FDetail write SetDetail;
procedure SetIconData(const Value: string);
procedure SetIconMargins(const ABottom, ALeft, ARight, ATop: Integer);
published
{ published declarations }
end;
implementation
{ TItemListaSimplePath }
constructor TItemListaSimplePath.Create(AOwner: TComponent);
begin
inherited;
FLblText := GetNewLabel('Verdana');
FLblText.Align := TAlignLayout.Top;
FLblText.Visible := False;
FLblDetail := GetNewLabel('Verdana');
FLblDetail.Visible := False;
FPthIcon := FMX.Objects.TPath.Create(LytClient);
FPthIcon.Parent := LytClient;
FPthIcon.Align := TAlignLayout.MostRight;
FPthIcon.HitTest := False;
FPthIcon.Visible := False;
FPthIcon.Stroke.Kind := TBrushKind.None;
FPthIcon.Fill.Color := StrToAlphaColor('#FF8B8F8B');
end;
destructor TItemListaSimplePath.Destroy;
begin
FreeAndNil(FPthIcon);
FreeAndNil(FLblText);
FreeAndNil(FLblDetail);
inherited;
end;
procedure TItemListaSimplePath.SetDetail(const Value: string);
begin
FDetail := Value;
FLblDetail.Visible := True;
FLblDetail.Text := Value;
end;
procedure TItemListaSimplePath.SetIconData(const Value: string);
begin
FPthIcon.Visible := not(Value.Trim.IsEmpty);
FPthIcon.Width := FPthIcon.Height;
FPthIcon.Data.Data := Value;
end;
procedure TItemListaSimplePath.SetIconMargins(const ABottom, ALeft, ARight,
ATop: Integer);
begin
FPthIcon.Margins.Bottom := ABottom;
FPthIcon.Margins.Left := ALeft;
FPthIcon.Margins.Right := ARight;
FPthIcon.Margins.Top := ATop;
end;
procedure TItemListaSimplePath.SetText(const Value: string);
begin
FText := Value;
FLblText.Visible := True;
FLblText.Text := Value;
end;
end.
|
unit etalon_page;
// Name: etalon_page.pas
// Copyright: SoftWest group.
// Author: Михалюк Максим
// Date: 16.02.06
// Description: шаблон довідника (лише одна вкладка)
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, dxExEdtr, StdCtrls, Buttons, dxDBGrid, dxTL, dxDBCtrl, dxCntner,
DB, IBCustomDataSet, IBQuery, IBDatabase, veles_h, IBHeader,
Placemnt, ComCtrls, ToolWin, uXToolBar, ExtCtrls, uXControlBar, ImgList,
utils_h, Zutils_h, ib_h, IBUpdateSQL, IBSQL, Menus, uXFilter;
type
//тип функції, яка використовується для виклику діалогів додавання та
//редагування записів (див. bt_ins та bt_upd);
//це є стандарт для діалогів додавання/редагування записів;
//a_document_id - id запису, який треба відредагувати; якщо треба додати запис - 0;
//вертає id запису, який був доданий або відредагований;
//якщо якась помилка вбо користувач натиснув Відмінити вертає < 0;
ZDlgFunc = function(a_document_id: Integer; var a_prm: ZVelesInfoRec): Integer;
Tfetalon_page = class(TForm)
g_page: TdxDBGrid;
base: TIBDatabase;
tr_default: TIBTransaction;
q_page: TIBQuery;
tr_page: TIBTransaction;
ds_page: TDataSource;
form_storage: TFormStorage;
img_list_tool_bar: TImageList;
p_top_control_bar: ZControlBar;
p_main_tool_bar: ZToolBar;
bt_ins: TToolButton;
bt_upd: TToolButton;
bt_del: TToolButton;
ToolButton4: TToolButton;
bt_refresh: TToolButton;
bt_fetch: TToolButton;
upd_page: TIBUpdateSQL;
q_R: TIBSQL;
tr_R: TIBTransaction;
q_W: TIBSQL;
tr_W: TIBTransaction;
popup_menu_page: TPopupMenu;
mi_columns: TMenuItem;
filter_page: ZFilter;
procedure g_pageKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure tool_buttonClick(Sender: TObject); virtual;
procedure g_pageKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormDestroy(Sender: TObject);
procedure mi_columnsClick(Sender: TObject);
procedure filter_pageFilterResult(Sender: TObject;
Result: ZFilterResult);
procedure g_pageKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
ctrl_pushed: Boolean;//чи натиснута клавіша Ctrl
lpDlgFunc: ZDlgFunc;//вказівник на функцію, яка показує діалог для додавання/редагування запису
public
{ Public declarations }
prm: ZVelesInfoRec;//в цьому параметрі зберігається важлива інформація (див. veles_h)
//-------------------------------------
//Усі ці змінні заповнюються в процедурі InitInfo
sql_refresh_document: string;//запит використовується для оновлення одного запису
//(див. RefreshRecord); Важливо! Усі поля запиту повинні
//відповідати полям датасета q_page;
//id запису, який треба оновити задається параметром :idocument_id
sql_delete_document: string;
access_to_del_document: Integer;//якщо > 0 - буде здійснюватись перевірка права видалення
dlg_dll_name: string;//ім'я дллки, яка містить діалог для додавання/редагування запису
dlg_func_name: string;//ім'я функції, яка показує діалог для додавання/редагування запису
//-------------------------------------
dic_refresh_enabled: Boolean;
procedure InitInfo; virtual;//тут відбувається ініціалізація
procedure RefreshPage; virtual;//оновлення всього датасета
procedure RefreshRecord; virtual;//оновлення одного записа
function IsRecordNull: Boolean;
end;
implementation
{$R *.dfm}
{ Tfetalon_page }
procedure Tfetalon_page.InitInfo;
begin
base.SetHandle(prm.db_handle); // передача хендла БД
if sql_delete_document = '' then bt_del.Visible := false;
// зчитування з ini-файлів інформації про стовпці таблиці
g_page.LoadFromIniFile(prm.root_way + WAY_INI + self.ClassName + '_page.ini');
// оновлення головного довідника
dic_refresh_enabled:=true;
RefreshPage;
end;
procedure Tfetalon_page.FormDestroy(Sender: TObject);
begin
//збереження настроєк довідників
g_page.SaveToIniFile(prm.root_way + WAY_INI + self.ClassName + '_page.ini');
end;
procedure Tfetalon_page.RefreshPage;
var
document_id: Integer;
old_cursor: TCursor;
begin
if not dic_refresh_enabled then Exit;
try
if base.Connected then
begin
document_id:=q_page.FieldByName(g_page.KeyField).AsInteger;
old_cursor:=Screen.Cursor;
try
Screen.Cursor:=crSQLWait;
if tr_page.InTransaction then tr_page.Commit;
tr_page.StartTransaction;
if q_page.Active then q_page.Close;
if not q_page.Prepared then q_page.Prepare;
q_page.Open;
tr_page.CommitRetaining;
if document_id <> 0 then
q_page.Locate(g_page.KeyField, document_id, []);
// if g_page.Visible and g_page.Enabled then g_page.SetFocus;
finally
Screen.Cursor:=old_cursor;
end;
end;
except
on E: Exception do
begin
if tr_page.InTransaction then tr_page.Rollback;
ErrorDialog(E.Message, 'Tfetalon_page.RefreshPage');
end;
end;
end;
procedure Tfetalon_page.RefreshRecord;
var
i: Integer;
field: string;
begin
q_page.Edit;
if tr_R.InTransaction then tr_R.Commit;
tr_R.StartTransaction;
q_R.SQL.Text:=sql_refresh_document;
q_R.ParamByName('idocument_id').AsInteger:=
q_page.FieldByName(g_page.KeyField).AsInteger;
q_R.ExecQuery;
for i:=0 to q_R.FieldCount-1 do
begin
field:=q_R.Fields[i].Name;
q_page.FieldByName(field).AsVariant:=q_R.FieldByName(field).AsVariant;
end;
if tr_R.InTransaction then tr_R.Commit;
q_page.Post;
end;
function Tfetalon_page.IsRecordNull: Boolean;
begin
Result:=q_page.FieldByName(g_page.KeyField).IsNull;
if Result then
GMessageBox('Не вибрано жодного запису', 'OK');
end;
procedure Tfetalon_page.g_pageKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
ctrl_pushed:=false;
end;
procedure Tfetalon_page.g_pageKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (ssCtrl in Shift) then ctrl_pushed:=true;
if ctrl_pushed and (Key = Ord('E')) then
tool_buttonClick(bt_upd);
if ctrl_pushed and (Key = Ord('N')) then
tool_buttonClick(bt_ins);
if ((ctrl_pushed and (Key = Ord('D'))) or (Key = VK_DELETE)) then
tool_buttonClick(bt_del);
// if Key = VK_ESCAPE then ModalResult:=mrCancel;
end;
procedure Tfetalon_page.filter_pageFilterResult(Sender: TObject;
Result: ZFilterResult);
begin
if Sender = filter_page then
begin
q_page.SQL.Strings[3]:=Result.DefaultFilter;
RefreshPage;
end;
end;
procedure Tfetalon_page.g_pageKeyPress(Sender: TObject; var Key: Char);
begin
if not ctrl_pushed then
begin
if (Sender = g_page) then filter_page.ShowFilter(Key);
end;
end;
procedure Tfetalon_page.tool_buttonClick(Sender: TObject);
var
button: TToolButton;
old_cursor: TCursor;
lib_handle: THandle;
lpDeleteRecord: function(query: PChar; id: integer; for_upd: TIBQuery;
var prm: ZVelesInfoRec): Integer;
document_id: Integer;
begin
button:=TToolButton(Sender);
if (button = bt_ins)or(button = bt_upd) then
begin
//не вказуючи імена дллки або функції можна визначати власну процедуру
//додвання та оновлення запису
if (dlg_dll_name = '')or(dlg_func_name = '') then Exit;
if button = bt_ins then
begin
document_id:=0;
end
else begin
document_id:=q_page.FieldByName(g_page.KeyField).AsInteger;
if IsRecordNull then Exit;
end;
lib_handle:=LoadLibrary(PChar(dlg_dll_name));
if lib_handle > 32 then
begin
@lpDlgFunc:=GetProcAddress(lib_handle, PChar(dlg_func_name));
if @lpDlgFunc <> nil then
begin
document_id:=lpDlgFunc(document_id, prm);
if document_id > 0 then
begin
if button = bt_ins then q_page.Insert else q_page.Edit;
q_page.FieldByName(g_page.KeyField).AsInteger:=document_id;
q_page.Post;
RefreshRecord;
end;
end;
FreeLibrary(lib_handle);
end;
end
else if button = bt_del then
begin
if access_to_del_document > 0 then
begin
if not HasUserAccessEx(prm, access_to_del_document) then
Exit;
end;
if IsRecordNull then Exit;
lib_handle:=LoadLibrary('zutils.dll');
if lib_handle >= 32 then
begin
@lpDeleteRecord:=GetProcAddress(lib_handle, 'GDeleteRecord');
if @lpDeleteRecord <> nil then
begin
lpDeleteRecord(PChar(sql_delete_document),
q_page.FieldByName(g_page.KeyField).AsInteger, q_page, prm);
end;
FreeLibrary(lib_handle);
end;
end
else if button = bt_refresh then
begin
RefreshPage;
end
else if button = bt_fetch then
begin
old_cursor:=Screen.Cursor;
try
Screen.Cursor:=crSQLWait;
g_page.ShowSummaryFooter:=bt_fetch.Down;
if bt_fetch.Down then
begin
g_page.OptionsDB:=g_page.OptionsDB + [edgoLoadAllRecords];
g_page.Filter.Active:=true;
end
else begin
g_page.OptionsDB:=g_page.OptionsDB - [edgoLoadAllRecords];
g_page.Filter.Active:=false;
end;
finally
Screen.Cursor:=old_cursor;
end;
end;
end;//Tfetalon_page.tool_buttonClick
procedure Tfetalon_page.mi_columnsClick(Sender: TObject);
begin
if not (Sender is TMenuItem) then Exit;
if (Sender as TMenuItem) = mi_columns then g_page.ColumnsCustomizing;
end;
end.
|
(*============================================================================
-----BEGIN PGP SIGNED MESSAGE-----
This code (c) 1994, 1997 Graham THE Ollis
GENERAL NOTES
=============
This is 16bit DOS TURBO PASCAL source code. It has been tested using
TURBO PASCAL 7.0. You will need AT LEAST version 5.0 to compile this
source code. You may need 7.0.
This is a generic pascal header for all my old pascal programs. Most of
these programs were written before I really got excited enough about 32bit
operating systems. In general this code dates back to 1994. Some of it
is important enough that I still work on it. For the most part though,
it's not the best code and it's probably the worst example of
documentation in all of computer science. oh well, you've been warned.
PGP NOTES
=========
This PGP signed message is provided in the hopes that it will prove useful
and informative. My name is Graham THE Ollis <ollisg@ns.arizona.edu> and my
public PGP key can be found by fingering my university account:
finger ollisg@u.arizona.edu
LEGAL NOTES
===========
You are free to use, modify and distribute this source code provided these
headers remain in tact. If you do make modifications to these programs,
i'd appreciate it if you documented your changes and leave some contact
information so that others can blame you and me, rather than just me.
If you maintain a anonymous ftp site or bbs feel free to archive this
stuff away. If your pressing CDs for commercial purposes again have fun.
It would be nice if you let me know about it though.
HOWEVER- there is no written or implied warranty. If you don't trust this
code then delete it NOW. I will in no way be held responsible for any
losses incurred by your using this software.
CONTACT INFORMATION
===================
You may contact me for just about anything relating to this code through
e-mail. Please put something in the subject line about the program you
are working with. The source file would be best in this case (e.g.
frag.pas, hexed.pas ... etc)
ollisg@ns.arizona.edu
ollisg@idea-bank.com
ollisg@lanl.gov
The first address is the most likely to work.
all right. that all said... HAVE FUN!
-----BEGIN PGP SIGNATURE-----
Version: 2.6.2
iQCVAwUBMv1UFoazF2irQff1AQFYNgQAhjiY/Dh3gSpk921FQznz4FOwqJtAIG6N
QTBdR/yQWrkwHGfPTw9v8LQHbjzl0jjYUDKR9t5KB7vzFjy9q3Y5lVHJaaUAU4Jh
e1abPhL70D/vfQU3Z0R+02zqhjfsfKkeowJvKNdlqEe1/kSCxme9mhJyaJ0CDdIA
40nefR18NrA=
=IQEZ
-----END PGP SIGNATURE-----
==============================================================================
| search.pas
| search binary file for a particular string or binary array.
| nice and fast from what i recall.
|
| History:
| Date Author Comment
| ---- ------ -------
| -- --- 94 G. Ollis created and developed program
============================================================================*)
{$I-}
Unit Search;
INTERFACE
Uses
Header;
{++PROCEDURES++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
Procedure DoFindSearch(Var D:DataType);
Procedure FindArray(Var D:DataType);
{++FUNCTIONS+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
{++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
IMPLEMENTATION
Uses
CRT,VConvert,ViewU,FUTIL,CFG,Cursor,UModify;
{----------------------------------------------------------------------}
Procedure DisplayArray;
Var I:Integer;
Begin
GotoXY(1,1);
ClrEol;
For I:=1 To NumElement Do
Begin
If (I=CurrentElement) Then
TextAttr:=ICFG.MsgColor;
Write(FArray[I]:4);
If (I=CurrentElement) Then
TextAttr:=ICFG.MsgLolight;
End;
Writeln;
ClrEol;
For I:=1 To NumElement Do
Begin
If (I=CurrentElement) Then
TextAttr:=ICFG.MsgColor;
Write(' ');
Write(Byte2Str(FArray[I]));
If (I=CurrentElement) Then
TextAttr:=ICFG.MsgLolight;
End;
End;
{------------------------------------------------------------------------}
Procedure ModifyByte(Var B:Byte);
Begin
ClrScr;
TextAttr:=ICFG.MsgColor;
Writeln('Enter in new value for byte.');
Write('> ');
B:=StrToInt(StringEdit(IntToStr(B,0),4,NumSet));
End;
{------------------------------------------------------------------------}
Procedure wtCmdLine(S:String);
Var x:Byte;
Begin
TextAttr:=ICFG.MsgLolight;
For x:=1 To Length(S) Do
Begin
If ((S[x]>='A') And (S[x]<='Z')) Or (S[x]='<') Or (S[x]='>') Then
TextAttr:=ICFG.MsgColor;
Write(S[x]);
If ((S[x]>='A') And (S[x]<='Z')) Or (S[x]='<') Or (S[x]='>') Then
TextAttr:=ICFG.MsgLolight;
End;
End;
{------------------------------------------------------------------------}
Function EnterInArray:Boolean;
Var C:Char;
Begin
Repeat
DisplayArray;
Writeln;
WtCmdLine(' < and > change array size LEFT and RIGHT to move current element');
Writeln;
WtCmdLine(' UP to modify byte <ENTER> to search <ESC> to exit');
HideCursor;
C:=Readkey;
ShowCursor;
If (C='<') Or (C=',') Then
NumElement:=NumElement-1;
If (C='>') Or (C='.') Then
NumElement:=NumElement+1;
If (NumElement<1) Then
NumElement:=1;
If (NumElement>ArrayLength) Then
NumElement:=ArrayLength;
If (CurrentElement>NumElement) Then
CurrentElement:=NumElement;
If (C=#0) Then
Begin
C:=Readkey;
If (C=#75) Then
CurrentElement:=CurrentElement-1;
If (C=#77) Then
CurrentElement:=CurrentElement+1;
If (C=#72) Then
ModifyByte(FArray[CurrentElement]);
If (CurrentElement<1) Then
CurrentElement:=1;
If (CurrentElement>NumElement) Then
CurrentElement:=NumElement;
End;
Until (C=#13) Or (C=#27);
If C=#13 Then
EnterInArray:=True
Else
EnterInArray:=False;
CloseWindow;
End;
{------------------------------------------------------------------------}
Function ScanArrays(P1,P2:Pointer; Count:Byte):Boolean;
Var I:LongInt;
Begin
ScanArrays:=True;
For I:=1 To Count Do
If mem[Seg(P1^):Ofs(P1^)+I]<>mem[Seg(P2^):Ofs(P2^)+I] Then
ScanArrays:=False;
End;
{------------------------------------------------------------------------}
Function ScanArrays2(Var D:DataType; P2:Pointer; Count:Byte; i2:LongInt):Boolean;
Var I:LongInt;
Begin
ScanArrays2:=True;
For I:=1 To Count Do
If GetFileByte(D.stream,I2+I)<>mem[Seg(P2^):Ofs(P2^)+I] Then
ScanArrays2:=False;
End;
{------------------------------------------------------------------------}
Procedure DoFindSearchOld(Var D:DataType);
Var I:LongInt;
Begin
IF D.EOF<imagesize-1 Then
Begin
For I:=D.X+D.offset+1 To D.EOF Do
If (D.D^[I]=FArray[1]) And (ScanArrays(@D.D^[I],@FArray,NumElement-1)) Then
Begin
D.X:=I-D.offset;
Exit;
End;
End
Else
Begin
OpenWindow(10,10,70,10,ICFG.MsgColor);
Write(D.EOF:30,' $',Long2Str(D.EOF));
For I:=D.X+D.offset To D.EOF Do
Begin
If (I mod 100=0) Then
Begin
GotoXY(1,1);
Write(I:11,' $',Long2Str(I));
GotoXY(50,1);
Write(((I*100) div D.EOF):3,'%');
End;
If (GetFileByte(D.stream,I)=FArray[1]) And (ScanArrays2(D,@FArray,NumElement-1,I)) Then
Begin
D.X:=I-D.offset+1;
CloseWindow;
Exit;
End;
If (KeyPressed) Then
Begin
CloseWindow;
Exit;
End;
End;
CloseWindow;
End;
End;
{------------------------------------------------------------------------}
Procedure DoFindSearch(Var D:DataType);
Var
Buff:binaryImagePointer;
I:LongInt;
Count,N,Sz,J:Word;
B:Boolean;
Begin
If (D.EOF<imageSize) Or (MaxAvail<700) Then
Begin
DoFindSearchOld(D);
Exit;
End;
Sz:=MaxAvail;
GetMem(Buff,Sz);
Seek(D.Stream,D.X+D.Offset);
I:=D.X+D.Offset;
OpenWindow(10,10,70,10,ICFG.MsgColor);
Write(D.EOF:30,' $',Long2Str(D.EOF),' NEW');
HideCursor;
While NOT EOF(D.stream) And NOT KeyPressed DO
Begin
BlockRead(D.Stream,Buff^,Sz,Count);
GotoXY(1,1);
Write(I:11,' $',Long2Str(I));
GotoXY(50,1);
Write(((I*100) div D.EOF):3,'%');
For N:=1 To Count Do
If Buff^[N]=FArray[1] Then
Begin
B:=True;
For J:=1 To NumElement-1 Do
If Buff^[N+J]<>FArray[J+1] Then
B:=False;
If B Then
Begin
D.X:=(I+N)-D.offset;
FreeMem(Buff,Sz);
ShowCursor;
CloseWindow;
Exit;
End;
End;
Inc(I,count);
End;
ShowCursor;
CloseWindow;
FreeMem(Buff,Sz);
End;
{------------------------------------------------------------------------}
Procedure FindArray(Var D:DataType);
Begin
OpenWindow(2,12,79,15,ICFG.MsgColor);
If EnterInArray Then
DoFindSearch(D);
End;
{======================================================================}
End. |
program httpget;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
prothandler,
ftpprothandler,
httpprothandler,
Classes
{ add your units here },
IdGlobal, //for some helper functions I like
IdURI,
SysUtils;
procedure PrintHelpScreen;
var LExe : String;
begin
LExe := ExtractFileName(ParamStr(0));
WriteLn(LExe);
WriteLn('');
WriteLn('usage: '+LExe+' [-v] URL');
WriteLn('');
WriteLn(' v : Verbose');
end;
var
GURL : TIdURI;
i : Integer;
LP : TProtHandler;
//program defaults
GVerbose : Boolean;
GHelpScreen : Boolean;
GFTPPort : boolean;
const
GCmdOpts : array [0..5] of string=('-h','--help','-v','--verbose','-P','--port');
begin
GFTPPort := False;
GHelpScreen := False;
GVerbose := False;
LP := nil;
GURL := TIdURI.Create;
try
if ParamCount > 0 then
begin
for i := 1 to ParamCount do
begin
if Copy(ParamStr(i),1,1) = '-' then
begin
WriteLn(ParamStr(i));
case PosInStrArray(ParamStr(i),GCmdOpts) of
0, 1 : begin
GHelpScreen := True;
break;
end;
2, 3 : GVerbose := True;
4, 5 : GFTPPort := True;
end;
end
else
begin
GURL.URI := ParamStr(i);
end;
end;
end
else
begin
GHelpScreen := True;
end;
WriteLn(GURL.URI);
if (GURL.URI = '') or GHelpScreen then
begin
GHelpScreen := True;
end
else
begin
try
if THTTPProtHandler.CanHandleURL(GURL) then
begin
LP := THTTPProtHandler.Create;
LP.Verbose := GVerbose;
LP.GetFile(GURL);
end
else
begin
if TFTPProtHandler.CanHandleURL(GURL) then
begin
LP := TFTPProtHandler.Create;
LP.Verbose := GVerbose;
TFTPProtHandler(LP).Port := GFTPPort;
LP.GetFile(GURL);
end;
end;
finally
FreeAndNil(LP);
end;
end;
finally
FreeAndNil(GURL);
end;
if GHelpScreen then
begin
PrintHelpScreen;
end;
end.
|
unit u_EnumDoublePointClosePoly;
interface
uses
t_GeoTypes,
i_DoublePointFilter,
i_EnumDoublePoint;
type
TEnumDoublePointClosePoly = class(TInterfacedObject, IEnumDoublePoint)
private
FSourceEnum: IEnumDoublePoint;
FFirstPoint: TDoublePoint;
FLastPointEqualToFirst: Boolean;
FPointsInPolyCount: Integer;
FFinished: Boolean;
FNeedAddBreak: Boolean;
private
function Next(out APoint: TDoublePoint): Boolean;
public
constructor Create(
const ASourceEnum: IEnumDoublePoint
);
end;
TEnumLonLatPointClosePoly = class(TEnumDoublePointClosePoly, IEnumLonLatPoint)
public
constructor Create(
const ASourceEnum: IEnumLonLatPoint
);
end;
TEnumProjectedPointClosePoly = class(TEnumDoublePointClosePoly, IEnumProjectedPoint)
public
constructor Create(
const ASourceEnum: IEnumProjectedPoint
);
end;
TEnumLocalPointClosePoly = class(TEnumDoublePointClosePoly, IEnumLocalPoint)
public
constructor Create(
const ASourceEnum: IEnumLocalPoint
);
end;
TDoublePointFilterPolygonClose = class(TInterfacedObject, IDoublePointFilter)
private
function CreateFilteredEnum(const ASource: IEnumDoublePoint): IEnumDoublePoint;
end;
TLonLatPointFilterPolygonClose = class(TInterfacedObject, ILonLatPointFilter)
private
function CreateFilteredEnum(const ASource: IEnumLonLatPoint): IEnumLonLatPoint;
end;
TProjectedPointFilterPolygonClose = class(TInterfacedObject, IProjectedPointFilter)
private
function CreateFilteredEnum(const ASource: IEnumProjectedPoint): IEnumProjectedPoint;
end;
TLocalPointFilterPolygonClose = class(TInterfacedObject, ILocalPointFilter)
private
function CreateFilteredEnum(const ASource: IEnumLocalPoint): IEnumLocalPoint;
end;
implementation
uses
u_GeoFun;
{ TEnumDoublePointClosePoly }
constructor TEnumDoublePointClosePoly.Create(const ASourceEnum: IEnumDoublePoint);
begin
inherited Create;
FSourceEnum := ASourceEnum;
FFinished := False;
FPointsInPolyCount := 0;
FNeedAddBreak := False;
end;
function TEnumDoublePointClosePoly.Next(out APoint: TDoublePoint): Boolean;
var
VPoint: TDoublePoint;
begin
if not FFinished then begin
if FNeedAddBreak then begin
FNeedAddBreak := False;
APoint := CEmptyDoublePoint;
Result := True;
end else begin
if FSourceEnum.Next(VPoint) then begin
if PointIsEmpty(VPoint) then begin
if (FPointsInPolyCount > 1) and (not FLastPointEqualToFirst) then begin
APoint := FFirstPoint;
FNeedAddBreak := True;
end else begin
APoint := VPoint;
end;
Result := True;
FPointsInPolyCount := 0;
end else begin
if FPointsInPolyCount = 0 then begin
FFirstPoint := VPoint;
FPointsInPolyCount := 1;
FLastPointEqualToFirst := True;
end else begin
FLastPointEqualToFirst := DoublePointsEqual(VPoint, FFirstPoint);
Inc(FPointsInPolyCount);
end;
APoint := VPoint;
Result := True;
end;
end else begin
FFinished := True;
if (FPointsInPolyCount > 1) and (not FLastPointEqualToFirst) then begin
APoint := FFirstPoint;
Result := True;
end else begin
APoint := CEmptyDoublePoint;
Result := False;
end;
end;
end;
end else begin
Result := False;
APoint := CEmptyDoublePoint;
end;
end;
{ TEnumLonLatPointClosePoly }
constructor TEnumLonLatPointClosePoly.Create(const ASourceEnum: IEnumLonLatPoint);
begin
inherited Create(ASourceEnum);
end;
{ TEnumProjectedPointClosePoly }
constructor TEnumProjectedPointClosePoly.Create(
const ASourceEnum: IEnumProjectedPoint
);
begin
inherited Create(ASourceEnum);
end;
{ TEnumLocalPointClosePoly }
constructor TEnumLocalPointClosePoly.Create(const ASourceEnum: IEnumLocalPoint);
begin
inherited Create(ASourceEnum);
end;
{ TDoublePointFilterPolygonClose }
function TDoublePointFilterPolygonClose.CreateFilteredEnum(
const ASource: IEnumDoublePoint
): IEnumDoublePoint;
begin
Result := TEnumDoublePointClosePoly.Create(ASource);
end;
{ TLonLatPointFilterPolygonClose }
function TLonLatPointFilterPolygonClose.CreateFilteredEnum(
const ASource: IEnumLonLatPoint
): IEnumLonLatPoint;
begin
Result := TEnumLonLatPointClosePoly.Create(ASource);
end;
{ TProjectedPointFilterPolygonClose }
function TProjectedPointFilterPolygonClose.CreateFilteredEnum(
const ASource: IEnumProjectedPoint
): IEnumProjectedPoint;
begin
Result := TEnumProjectedPointClosePoly.Create(ASource);
end;
{ TLocalPointFilterPolygonClose }
function TLocalPointFilterPolygonClose.CreateFilteredEnum(
const ASource: IEnumLocalPoint
): IEnumLocalPoint;
begin
Result := TEnumLocalPointClosePoly.Create(ASource);
end;
end.
|
{Door Game..by Benson Wong}
{Version .01b}
{Notes:
When the game begins the player starts with the following:
$20,000 (DEFAULT, SYSOP DEFINED)
1 building points (DEFAULT, SYSOP DEFINED)
1 research points (DEFAULT, SYSOP DEFINED)
27,426 population (DEFAULT, SYSOP DEFINED)
100 Normal type soldiers (DEFAULT, SYSOP DEFINED)
10 Agricultrial Region (DEFAULT, SYSOP DEFINED)
3 Industrial Regions (DEFAULT, SYSOP DEFINED)
10,000 Food (DEFAULT, SYSOP DEFINED)
ALL OTHER THINGS ARE SET TO ZERO
}
USES crt,ddplus,Dos;
Const
Player_Data_Filename='PLAYERS.DAT'; {Players save file}
Problem_Log_FileName='PROBLEMS.LOG';
Message_Outfile_Name='Messages.dat';
Registered=False;
NewsFileName='GAMENEWS.ANS';
Type
Global_E = Object {These are the variables that control how}
{many turns the player has and what the new}
{players start out with}
Set_Turns:integer; {Sets how many month or turns the player has}
{every day}
{Misc}
Set_Money:longint; {Sysop defined money variable}
Set_MoneyBank:longint; {Sysop defined money in bank variable}
Set_Population:longint; {Sysop defined Population}
Set_Food:longint; {Sysop defined food}
Set_Energy:longint; {Sysop defined energy}
Set_BuildingP:longint;
Set_ResearchP:longint;
{Military}
Set_HumanS:longint; {Sysop defined Human soldiers}
{Regions}
Set_Agricultural:longint; {Sysop defined Agricultural Regions}
Set_Industrial:longint; {Sysop defined Industrial Regions}
Set_Desert:longint; {Sysop defined Desert Regions}
Set_Urban:longint; {Sysop defined Urban Regions}
Set_Volcanic:longint; {Sysop defined Volcanic Regions}
Set_River:longint; {Sysop defined River Regions}
Set_OceanSea:longint; {Sysop defined Ocean And Sea Regions}
Set_WasteLand:longint; {Sysop defined Wasteland Regions}
{Technology}
{Energy Production Technology }
Set_HydroT:boolean; {Sysop defined: Hydro Power Technology }
Set_WindT:boolean; {Sysop Defined: Wind Power technology}
Set_SolarT:boolean; {Sysop Defined: Solar Power Technology}
Set_FossilT:boolean; {Sysop Defined: Fossil Fuel, Default: TRUE}
Set_FissionT:boolean; {Sysop Defined: Fission Power Technology}
Set_FusionT:boolean; {Sysop Defined: Fusion Power Technology}
Set_CFusionT:boolean; {Sysop Defined: Cold Fusion Power Technology}
{---- War Technology ----}
{Soldier Technology}
Set_HumanNT:boolean; {Sysop Defined: Normal Human Technology,Default:True}
Set_GAHumanT:boolean; {Sysop Defined: GAHuman Technology}
Set_SuperHumanT:boolean; {Sysop Defined: SuperHuman Technology}
Set_HyperHumanT:boolean; {Sysop Defined: HyperHuman Technology}
Set_MegaHumanT:boolean; {Sysop Defined: MegaHuman Technology}
{BioBot Upgrade Technology}
Set_BasicBT:boolean; {Sysop Defined: Basic BioBot Technology}
Set_StandardBT:boolean; {Sysop Defined: Standard BioBot Technology}
Set_AdvancedBT:boolean; {Sysop Defined: Advanced BioBot Technology}
Set_Advanced2BT:boolean; {Sysop Defined: Advanced BioBot L2 Technology}
Set_BattleBT:boolean; {Sysop Defined: Battle BioBot Technology}
Set_HeavyAttackBT:boolean; {Sysop Defined: Heavy Attack BioBot Technology}
Set_OmegaBT:boolean; {Sysop Defined: OMega BioBot Technology}
Set_OmegaL2BT:boolean; {Sysop Defined: Omega BioBot L2 Technology}
{Drone Technology}
Set_Recon1T:boolean; {Sysop Defined: Recon Level 1 Droid}
Set_Recon2T:boolean; {Sysop Defined: Recon Level 2 Droid}
Set_Recon3T:boolean; {Sysop Defined: Recon Level 3 Droid}
{War Vehical Technology}
Set_TankT:boolean; {Sysop Defined: Normal Tank Technology}
Set_HoverCT:boolean; {Sysop Defined: HoverCraft Technology}
Set_JetT:boolean; {Sysop Defined: Jet Technology}
{War Ballistic Weapon Technology}
Set_NukeBT:boolean; {Sysop Defined: Nuclear Bomb Technology}
Set_RadiationBT:boolean; {Sysop Defined: Radation Bomb Technology}
{Viral Weapons}
Set_HypnoT:Boolean; {Sysop Defined: Hypnobomb Technology}
Set_PopulationBT:boolean; {Sysop Defined: Population Bomb Technology}
Set_FoodBT:boolean; {Sysop Defined: Food Bomb Technology}
Set_AntimatterT:boolean; {Sysop Defined: AntiMatter Bomb Technology}
{---- Global Defence Technology ----}
{ODS=Orbital Defence Satillite, ODSNS = Oribital Defence Satillte Network Software}
Set_ODST:boolean; {Sysop Defined: ODST Technology}
Set_ODSNST:boolean; {Sysop Defined: ODSNST Technology}
Set_GroundTT:boolean; {Sysop Defined: Ground Turret Technology}
Set_AntiT:boolean; {Sysop Defined: Anti Aircraft Technology}
Set_GSGT:boolean; {Sysop Defined: Global Shield Generator Technology}
Set_DoomsDayT:boolean; {Sysop Defined: DoomsDay Bomb Technology}
{-=-=-=-=-=- Sysop Defined Players Army Startup Status -=-=-=-=-=-=-=-}
{Soldier Storage Variables}
{Human Type Soldiers}
Set_HumanN:longint; {Number of normal human soldiers}
Set_GAHuman:longint; {Number of GAHuman soldiers}
Set_SuperHuman:longint; {Number of Super Human soldiers}
Set_HyperHuman:longint; {Number of HyperHuman soldiers}
Set_MegaHuman:longint; {Number of MegaHuman soldiers}
Set_BasicB_U:longint; {Number of Basic BioBot Upgraded Soldiers}
Set_StandardB_U:longint; {Number of Standard BioBot Upgraded Soldiers}
Set_AdvancedB_U:longint; {Number of Advanced BioBot Upgraded Soldiers}
Set_AdvancedB2_U:longint; {Number of Advanced-2 BioBot Upgraded Soldiers}
Set_BattleB_U:longint; {Number of Battle BioBot Upgraded Soldiers}
Set_HeavyAttackB_U:longint;{Number of Heavy Attack BioBot upgraded Soldiers}
Set_OmegaB_U:longint; {Number of Omega BioBot upgraded soldiers}
Set_OmegaBL2_U:Longint; {Number of Omega L2 BioBot upgraded soldiers}
{Ballistic Attack Weapons}
Set_AntiMatter_Q:longint; {Number of Antimatter Missles The Player Has}
Set_FoodB_Q:longint; {Number of Food Bombs The Player Has}
Set_NukeB_Q:longint; {Number of nuclear missles the player has}
Set_RadiationB_Q:longint; {Number of Radiation Bombs the player has}
Set_PopulationB_Q:longint; {Number Of Population Bombs The Player Has}
Set_HypnoB_Q:longint; {Number Of HypnoBombs the player has}
{Player's Recon Drone}
Set_Recon1_Q:longint; {Player starts out with this technology}
Set_Recon2_Q:longint; {Did the player research Recon-2 Drone Tech.}
Set_Recon3_Q:longint; {Did the player research Recon-3 Drone Tech.}
{Player's War Vehicals}
Set_Tank_Q:longint; {Did the player research tank tech.}
Set_HoverC_T:longint; {Did the player research Hover Craft Tech.}
Set_Jet_T:longint; {Did the player research Jet Tech.}
{Misc / Advanced Buildings...and other variables for them}
Set_Miners_Guild:boolean; {Does the player have the Miners guild?}
Set_NumMiners:longint; {Number of miners that are unassigned to a mine}
Set_Fishing_Guild:boolean; {Does the player has the fishing guild?}
Set_NumFishers:longint; {The amount of fishermen the player has}
Set_FishStock:longint; {The amount of fish remaining}
Set_Construction_B:longint;{Number of construction sites the player has}
Set_Labs_B:longint; {Number of labs the player has}
Set_Intell_B:boolean; {Does the player have the Intelligence building}
Set_Num_Spy:longint; {Number of spies the player has}
Set_Terrorists:longint; {Number of terrorists the player has}
Set_Lottery_B:boolean; {Does the player have the lottery set up}
{---Global Defence Systems---}
Set_ODSnum:longint; {How many defence satillites the player has}
Set_ODSNS:boolean; {Is the player using the ODSNS?}
Set_GSGnum:longint; {How many Global Shield Generators the player has}
Set_GroundTNum:longint; {How many Ground Turrets The Player Has}
Set_AntiANum:longint; {How many Anti-Aircraft Missle launchers Player has}
Set_DoomsDay_B:boolean; {Does the player have DDay weapon Built}
{---- MINES -------}
Set_GOLD:longint; {Sysop Defined Gold Mines}
Set_silver:longint; {player's silver mines}
Set_Iron:longint; {player's iron mines}
Set_nickel:longint; {player's nickel mines}
Set_copper:longint; {player's copper mines}
end;
Message_Type = record {Type used for messages}
Empire:string[20]; {Record # of Reciever}
Message:array[1..15] of string[75]; {The Message}
end;
Region_Type=Record {A Region Record Template to keep track of regions}
Quantity:longint; {Quantity of this type the player has}
Ready_reg:longint; {Cost to Ready Region}
Num_Used:longint; {Number of regions already used}
end;
{-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
Mines=record {Used for the different types of mines}
Num_mines:longint; {Number of this type of mine the player has}
Miners:longint; {Number of miners at the current mine type}
MinLeft:longint; {Amount of mineral left in mines}
end;
{-=-=-=-=-=-=-=The Users Empire..this is gonna be big!-=-=-=-=-=-=-=-=-=}
One_Player=record {One record for each player}
Last_On:integer; {The last date the player was on}
Turns_Left:byte; {The Number Of Turns The Player Has Left}
Players_1stName:string[30]; {The players first name}
Players_LstName:string[30]; {The players last name}
Worlds_Name:string[20]; {The Name Of The Players Planet}
Empire_name:string[20]; {The Name of the players empire}
{Comparison Variables For Player}
Worlds_NameC:string[20]; {Search variable For Player's Worlds Name}
Empires_NameC:string[20]; {Search Variable for Players Empires Name}
{Main Player Variables}
{Researching and Building Points}
Research_P:longint; {Amount of research points the player has}
Building_P:longint; {Amount of building points the player has}
{POPULATION & FOOD}
Population:longint; {Population of Empire}
Food:longint; {Amount of food the player has on hand}
Food_Storage:longint; {Amount of food the player has in storage}
{MONEY}
Money:longint; {Money value the player has for immediate use}
Money_bank:longint; {Money the player has in the bank}
{ENERGY}
Energy:longint; {Energy value the player has for immediate use}
{ Energy_Cores:shortint; {Number of energy cores the player has Max:10}
Energy_bank:array[1..10] of longint;
{^^ amount of Energy the player has in each core}
{Number of Different Types Of Power Generation Buildings}
Hydro_B:longint; {Number of hydro plants player has}
Wind_B:longint; {Number of Wind Turbines the player has}
Solar_B:longint; {Number of Solar panels the player has}
Fossil_B:longint; {Number of Fossil Fuel Plants}
GeoTher_B:longint; {Number of GeoThermic Taps the player has}
{Nuclear Energy}
Fission_B:longint; {Number of fission plants the player has}
Fusion_B:longint; {Number of fusion plants the player has}
CFusion_B:longint; {Number of cold fusion plants the player has}
{Regions -Stores information on players regions}
Agricult:Region_Type; {Agricultural Region}
Desert:Region_Type; {Desert Region}
Industrial:Region_Type; {Industrial Region}
Urban:Region_Type; {Urban Region}
Volcanic:Region_Type; {Volcanic Region}
River:Region_Type; {River Region}
OceanSea:Region_type; {Ocean/Sea region}
Wastelands:longint; {Completely useless region}
{Mines}
Gold:mines; {player's gold mines}
silver:mines; {player's silver mines}
Iron:mines; {player's iron mines}
nickel:mines; {player's nickel mines}
copper:mines; {player's copper mines}
{-=-=-=-=-=-= Players Researched Technology -=-=-=-=-=-=-}
{Energy Production Technology }
Hydro_T:boolean; {Did the player research hydro Tech.}
Wind_T:boolean; {Did the player research Wind Tech.}
Solar_T:boolean; {Did the player research Solar Tech.}
Fossil_T:boolean; {Player gets this when starting out}
Fission_T:boolean; {Did the player research Fission Tech.}
Fusion_T:boolean; {Did the player research Fusion Tech.}
CFusion_T:boolean; {Did the player research Cold Fusion Tech.}
{---- War Technology ----}
{Soldier Technology}
HumanN_T:boolean; {Player gets this when starting out}
GAHuman_T:boolean; {Did the player research GAHuman Tech.}
SuperHuman_T:boolean; {Did the player research SuperHuman Tech.}
HyperHuman_T:boolean; {Did the player research HyperHuman Tech.}
MegaHuman_T:boolean; {Did the player research MegaHuman Tech.}
{BioBot Upgrade Technology}
BasicB_T:boolean; {Did the player research basic BioBot Tech.}
StandardB_T:boolean; {Did the player research standard BioBot Tech.}
AdvancedB_T:boolean; {Did the player research Advanced BioBot Tech}
Advanced2B_T:boolean; {Did the player research Advanced 2 BioBot Tech.}
BattleB_T:boolean; {Did the player research Battle BioBot Tech.}
HeavyAttackB_T:boolean;{Did the player research Heavy Attack BioBot Tech.}
OmegaB_T:boolean; {Did the player research Omega BioBot Tech.}
OmegaL2B_T:boolean; {Did the player research Omega L2 BioBot Tech.}
{Drone Technology}
Recon1_T:boolean; {Player starts out with this technology}
Recon2_T:boolean; {Did the player research Recon-2 Drone Tech.}
Recon3_T:boolean; {Did the player research Recon-3 Drone Tech.}
{War Vehical Technology}
Tank_T:boolean; {Did the player research tank tech.}
HoverC_T:boolean; {Did the player research Hover Craft Tech.}
Jet_T:boolean; {Did the player research Jet Tech.}
{War Ballistic Weapon Technology}
NukeB_T:boolean; {Did the player research Nuclear bomb tech.}
RadiationB_T:boolean; {Did the player research Radiation Bomb tech.}
Antimatter_T:boolean; {Did the player research Antimatter bomb tech.}
{Viral Weapons}
PopulationB_T:boolean; {Did the player research Population Bomb tech.}
HypnoB_T:boolean; {Did the player research HypnoBomb Technology}
FoodB_T:boolean; {Did the player research Food Bomb tech.}
{---- Global Defence Technology ----}
{ODS=Orbital Defence Satillite, ODSNS = Oribital Defence Satillte Network Software}
ODS_T:boolean; {Did the player research ODS tech.}
ODSNS_T:boolean; {Did the player research ODSN tech.}
GroundT_T:boolean; {Does the player have Ground Turret Tech.}
Anti_T:boolean; {Does the player have anti-aircraft tech.}
GSG_T:boolean; {Does the player have Global Shield Generator tech.}
DoomsDay_T:boolean; {Does the player have the DoomsDay Weapon Tech.}
{-=-=-=-=-=- Players Army Status -=-=-=-=-=-=-=-}
{Soldier Storage Variables}
{Human Type Soldiers}
HumanN:longint; {Number of normal human soldiers}
GAHuman:longint; {Number of GAHuman soldiers}
SuperHuman:longint; {Number of Super Human soldiers}
HyperHuman:longint; {Number of HyperHuman soldiers}
MegaHuman:longint; {Number of MegaHuman soldiers}
BasicB_U:longint; {Number of Basic BioBot Upgraded Soldiers}
StandardB_U:longint; {Number of Standard BioBot Upgraded Soldiers}
AdvancedB_U:longint; {Number of Advanced BioBot Upgraded Soldiers}
AdvancedB2_U:longint; {Number of Advanced-2 BioBot Upgraded Soldiers}
BattleB_U:longint; {Number of Battle BioBot Upgraded Soldiers}
HeavyAttackB_U:longint;{Number of Heavy Attack BioBot upgraded Soldiers}
OmegaB_U:longint; {Number of Omega BioBot upgraded soldiers}
OmegaBL2_U:Longint; {Number of Omega L2 BioBot upgraded soldiers}
{Ballistic Attack Weapons}
AntiMatter_Q:longint; {Number of Antimatter Missles The Player Has}
FoodB_Q:longint; {Number of Food Bombs The Player Has}
NukeB_Q:longint; {Number of nuclear missles the player has}
RadiationB_Q:longint; {Number of Radiation Bombs the player has}
PopulationB_Q:longint; {Number Of Population Bombs The Player Has}
HypnoB_Q:longint; {Number Of HypnoBombs the player has}
{Player's Recon Drone}
Recon1_Q:longint; {Player starts out with this technology}
Recon2_Q:longint; {Did the player research Recon-2 Drone Tech.}
Recon3_Q:longint; {Did the player research Recon-3 Drone Tech.}
{Player's War Vehicals}
Tank_Q:longint; {Did the player research tank tech.}
HoverC_Q:longint; {Did the player research Hover Craft Tech.}
Jet_Q:longint; {Did the player research Jet Tech.}
{Misc / Advanced Buildings...and other variables for them}
Miners_Guild:boolean; {Does the player have the Miners guild?}
NumMiners:longint; {Number of miners that are unassigned to a mine}
Fishing_Guild:boolean; {Does the player has the fishing guild?}
NumFishers:longint; {The amount of fishermen the player has}
FishStock:longint; {The amount of fish remaining}
Construction_B:longint;{Amount of construction Sites the player has}
Intell_B:boolean; {Does the player have the Intelligence building}
Num_Spy:longint; {Number of spies the player has}
Terrorists:longint; {Number of terrorist the player has}
Lottery_B:boolean; {Does the player have the lottery set up}
{---Global Defence Systems---}
ODSnum:longint; {How many defence satillites the player has}
ODSNS:boolean; {Is the player using the ODSNS?}
GSGnum:longint; {How many Global Shield Generators the player has}
GroundTNum:longint; {How many Ground Turrets The Player Has}
AntiANum:longint; {How many Anti-Aircraft Missle launchers Player has}
DoomsDay_B:boolean; {Does the player have DDay weapon Built}
END; {End of the One_Player record Type}
{Record Size For 1 One_player record on APRIL 28/96 = 427 bytes}
Var {Global Variables}
Play_F: file of One_Player; {File with all the players}
Problem_file:text;
A: Global_E;
CurrentPlayer: one_player; {The current player}
TempPlayer: One_Player; {Globaly Used To Store A Temporay Record}
NewsFile:text;
{-=-=-=-=-=-=-=-=-=-=-=-=- Forwards For Procedures -=-=-=-=-=-=-=-=-=-=-=}
Procedure ReadSetup;
Procedure Welcome_To_Game; Forward;
Procedure Search_For_Player; Forward;
Procedure Create_New_Player; Forward;
Procedure Play_Game; Forward;
Procedure Write20Empires; Forward;
Procedure ExitGame; Forward;
Function ConvertDate:integer; Forward;
{-=-=-=-=-=-=-=-=-=-=END Of Forwards For Procedures -=-=-=-=-=-=-=-=-=-=-=}
Procedure ReadSetup;
{DOMINION Setup Program}
{this little program is going to get the new player variable values}
{from the text configuration file.}
Var
Infile:text;
A:Global_E;
C:integer;
Function G:longint;
Var
w:string;
S:string;
x:byte;
we:longint;
Begin
w:='';
repeat
readln(infile,s);
until (s[1] <> '''') and (s <> '');
if s[1]='~' then
for x:=2 to length(s) do
if not(s[x]='~') then
w:=w+s[x]
else
break;
val(w,we,c);
g:=we;
end;
Function B:boolean;
Var
w:string;
S:string;
x:byte;
Begin
w:='';
repeat
readln(infile,s);
until (s[1] <> '''') and (s <> '');
if s[1]='~' then
for x:=2 to length(s) do
if not(s[x]='~') then
w:=w+s[x]
else
break;
if (w='F') or (w='f') then
B:=False
else B:=True;
end;
Begin
assign(infile,'CONFIG.DOM');
reset(infile);
A.Set_Turns:=G;
A.Set_Money:=G;
A.Set_MoneyBank:=G;
A.Set_Population:=G;
A.Set_Food:=G;
A.Set_Energy:=G;
A.Set_HumanN:=G;
A.Set_GaHuman:=G;
A.Set_SuperHuman:=G;
A.Set_HyperHuman:=G;
A.Set_MegaHuman:=G;
A.Set_BasicB_U:=G;
A.Set_StandardB_U:=G;
A.Set_AdvancedB_U:=G;
A.Set_AdvancedB2_U:=G;
A.Set_BattleB_U:=G;
A.Set_HeavyAttackB_U:=G;
A.Set_OmegaB_U:=G;
A.Set_OmegaBL2_u:=G;
A.Set_Foodb_Q:=G;
A.Set_NukeB_Q:=G;
A.Set_RadiationB_Q:=G;
A.Set_PopulationB_Q:=G;
A.Set_HypnoB_Q:=G;
A.Set_AntiMatter_Q:=G;
A.Set_Recon1_Q:=G;
A.Set_Recon2_q:=G;
A.Set_Recon3_Q:=G;
A.Set_Tank_Q:=G;
A.Set_HoverC_T:=G;
A.Set_Jet_T:=G;
A.Set_ODSnum:=G;
A.Set_ODSNS:=B;
A.Set_GSGnum:=G;
A.Set_GroundTnum:=G;
A.Set_AntiANum:=G;
A.Set_DoomsDay_B:=B;
A.Set_HydroT:=B;
A.Set_WindT:=B;
A.Set_SolarT:=B;
A.Set_FossilT:=B;
A.Set_FissionT:=B;
A.Set_FusionT:=B;
A.Set_CFusionT:=B;
A.Set_HumanNT:=B;
A.Set_GAhumanT:=b;
A.Set_SuperHumanT:=b;
A.Set_HyperHumanT:=b;
A.Set_MegaHumanT:=b;
A.Set_BasicBT:=b;
A.Set_StandardBT:=b;
A.Set_AdvancedBT:=b;
A.Set_Advanced2BT:=B;
A.Set_BattleBT:=b;
A.Set_HeavyAttackBT:=b;
A.Set_OmegaBT:=b;
A.Set_OmegaL2BT:=B;
A.Set_Recon1T:=B;
A.Set_Recon2T:=B;
A.Set_Recon3T:=B;
A.Set_TankT:=B;
A.SEt_HoverCT:=B;
A.Set_JetT:=B;
A.Set_NukeBT:=b;
A.Set_RadiationBT:=b;
A.set_HypnoT:=B;
A.SEt_PopulationBT:=b;
A.Set_FoodBT:=b;
A.Set_AntiMatterT:=B;
A.Set_ODST:=B;
A.Set_ODSNST:=B;
A.Set_GroundTT:=B;
A.Set_AntiT:=B;
A.Set_GSGT:=B;
A.Set_DoomsDayT:=B;
A.Set_Miners_Guild:=B;
A.Set_NumMiners:=G;
A.Set_Fishing_Guild:=B;
A.Set_NumFishers:=G;
A.Set_FishStock:=G;
A.Set_Construction_B:=G;
A.Set_Labs_B:=G;
A.Set_Intell_B:=B;
A.Set_Num_Spy:=G;
A.Set_Terrorists:=G;
A.Set_Lottery_B:=B;
A.Set_GOLD:=G;
A.Set_Silver:=G;
A.Set_Iron:=G;
A.Set_Copper:=G;
A.Set_Nickel:=G;
A.Set_Agricultural:=G;
A.Set_Industrial:=G;
A.Set_Desert:=G;
A.Set_Urban:=G;
A.Set_River:=G;
A.Set_OceanSea:=G;
A.Set_WasteLand:=G;
A.Set_BuildingP:=G;
A.Set_ResearchP:=G;
Close(infile);
end;
Function CurrentDate:integer;
Var
Yr,Mon,Da,Dow:word;
StorDay:integer;
Begin
getdate(yr,mon,da,dow);
Case Mon of
1: inc(storday,Da); {jan}
2: inc(storday,da+31); {feb}
3: inc(storday,da+31+28); {mar}
4: inc(storday,da+31+28+31); {apr}
5: inc(storday,da+31+28+31+30);{may}
6: inc(storday,da+31+28+31+30+31); {june}
7: inc(storday,da+31+28+31+30+31+30); {july}
8: inc(storday,da+31+28+31+30+31+30+31); {august}
9: inc(storday,da+31+28+31+30+31+30+31+31); {sept}
10: inc(storday,da+31+28+31+30+31+30+31+31+30); {oct}
11: inc(storday,da+31+28+31+30+31+30+31+31+30+31); {nov}
12: inc(storday,da+31+28+31+30+31+30+31+31+30+31+31); {dec}
end;
CurrentDate:=Storday;
end;
Procedure Write20Empires;
Var
DisplayPlayerRecord:longint;
RE:One_Player; {Temp Record To Look For The Message Recieving Empire}
CountLines:byte; {Used To Count 24 Lines and THen write <more> to the
screen}
Chaf:char;
Begin
set_FOREGROUND(11);
Sclrscr;
writeln(soutput,'Empires Number Empire Name');
writeln(soutput,'-------------- -----------');
For DisplayPlayerRecord:= 0 to filesize(play_F) do
Begin
Seek(Play_F,DisplayPlayerREcord);
Read(Play_F,RE);
set_Foreground(13);
sgoto_xy(6,countlines+1);
Set_Foreground(10);
write(SOUTPUT, DisplayPlayerRecord);
Sgoto_xy(48,countlines+1);
inc(CountLines);
if countlines=20 then begin
SRead_Char(Chaf);
CountLines:=0;
end;
end;
end;
Procedure Messages(ControlCode:byte);
{Control Codes
0: Enter New Message
1: Search For Players Messages}
Var
MessageFile:File Of Message_Type;
ONeWord:string;
OnWord:boolean;
Inchar:char;
CurrentMessage:Message_Type;
CountChar:byte;
CountLn:byte;
Begin
assign(MessageFile,Message_Outfile_Name);
{$I-}
Reset(MessageFile);
{$I+}
if ioresult <> 0 then
rewrite(MessageFile);
If ControlCode=0 then
Begin
{Displayfile('COMMSCR.ANS');}
Write20Empires;
end;
end;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-}
Procedure FadeWrite(output:string; locx:byte; locy:byte; d:byte; Color:byte);
Var
x,y:byte;
Begin
output:=output+' ';
for x:= 1 to length(output) do
Begin
Set_Foreground(15);
Swritexy(locx+x,locy,output[x]);
delay(d);
Set_Foreground(Color);
LowVideo;
if x >=2 then
Swritexy(locx+x-1,locy,output[x-1])
else
Swritexy(locx+x,locy,output[x]);
delay(d);
Set_Foreground(Color);
HighVideo;
if x >=3 then
SWRITEXY(locx+x-2,locy,output[x-2])
else
SWRITEXY(locx+x,locy,output[x]);
delay(d);
end;
end;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-}
Procedure Search_For_Player;
Var
CurrentPos:longint; {The current search position}
StatusOkay:boolean;
testchar:char;
Begin
reset(Play_F);
if filesize(Play_F) =0 then
Create_New_Player
else
for CurrentPos:= 0 to filesize(Play_F) do
begin
seek(Play_F,Currentpos);
read(Play_F,CurrentPlayer);
if (Currentplayer.Players_1stName=User_First_Name) and
(Currentplayer.Players_LstName=User_Last_Name) then
break
else
Create_New_Player;
end;
end;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-}
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-}
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-}
Procedure Create_New_Player;
Var
Empire_N:string;
World_N:string;
Temp_Str1:string[20];
Temp_Str2:string[20];
x,y:byte;
okay:boolean;
Search_Records:boolean;
RecordTrac:longint;
begin
SCLRSCR;
okay:=false;
FadeWrite('Welcome To Dominion.',1,1,10,10);
swriteln('');
Set_ForeGround(13);
FadeWrite('Name Your World <?>: ',1,2,10,15);
Set_Foreground(11);
RecordTrac:=0;
Okay:=False;
REPEAT
if World_N[1]=#3 Then {The Chat Thing..Should Implement this somehow}
Begin
SCLRSCR;
okay:=false;
FadeWrite('Welcome To Dominion.',1,1,10,10);
swriteln('');
Set_ForeGround(13);
FadeWrite('Name Your World <?>: ',1,2,10,15);
Set_Foreground(11);
repeat
SGoto_xy(23,2);
sclreol;
Prompt(World_N,20,False);
until World_n<>'';
end
else
repeat
SGoto_xy(23,2);
sclreol;
Prompt(World_N,20,False);
until World_n<>'';
if World_N[1]='?' Then {If the Player Wants Help, run HELP menu code X}
Begin
Okay:=False;
Set_ForeGround(14);
swriteln('Enter The Name You Want For Your World.');
Set_ForeGround(11);
Search_Records:=False;
end
else
Begin
Temp_Str1:=World_n; {Makes Temp_Str1 equal to Worlds_N}
Search_Records:=True;
end;
{--------------------------------}
For x:=0 To Length(temp_Str1) do
Begin
If Temp_Str1[x]=#32 then
begin {This section erases all the spaces}
delete(Temp_Str1,x,1); {and converts Temp_Str1 To Upper Case}
dec(x);
end;
Temp_Str1[x]:=Upcase(Temp_Str1[x]);
end;
{--------------------------------}
Swriteln('Checking For Duplicate World Names. Please Wait...');
Currentplayer.Worlds_NameC:=Temp_Str1; {Sets The Search String For The}
{Player}
if Filesize(Play_F)=0 then {If There Are no other player records then}
break; {break out of REPEAT UNTIL loop get}
{Empire Name}
{-----------BEGINING OF SEARCH ENGINE----------------------------------}
{This part searches the PLAYERS.DAT File for duplicate World Names...}
{This small little search Engine was a total pain in the ass! It better}
{Keep Working.}
if search_Records=true then
For RecordTrac:=0 to Filesize(Play_F) do
Begin
Seek(PLAY_F,RecordTrac);
read(Play_F,TempPlayer);
If TempPlayer.Worlds_NameC=Currentplayer.Worlds_NameC then
Begin
Okay:=False;
Set_ForeGround(10);
Swriteln('Duplicate World Name Found.');
Swriteln('Please Use Different Name.');
Set_ForeGround(11);
Break;
end;
If EOF(play_f) then
Begin
Okay:=True;
Break;
end;
end;
{-----------END OF SEARCH ENGINE---------------------------------------}
UNTIL Okay=True;
Search_Records:=False;
okay:=false;
{This Part Get's the new players Empire Name}
swriteln('');
Currentplayer.Worlds_Name:=World_n;
fadewrite('New World',wherex,6,10,10);
fadewrite(Currentplayer.Worlds_name,wherex,6,10,15);
fadewrite('Discovered.',wherex,6,10,10);
swriteln('');
FadeWrite('Name Your Empire <?>: ',wherex,wherey,10,15);
Set_Foreground(11);
x:=wherex;
y:=wherey;
RecordTrac:=0;
REPEAT
if Empire_N[1]=#3 Then {The Chat Thing..Should Implement this somehow}
Begin
SCLRSCR;
okay:=false;
FadeWrite('Name Your Empire <?>: ',1,10,10,15);
Set_Foreground(11);
repeat
SGoto_xy(x,y);
sclreol;
Prompt(Empire_N,20,False);
until Empire_N<>'';
end
else
repeat
SGoto_xy(x,y);
sclreol;
Prompt(Empire_N,20,False);
until Empire_n<>'';
if Empire_N[1]='?' Then {If the Player Wants Help, run HELP menu code X}
Begin
Okay:=False;
Set_Foreground(14);
swriteln('Enter The Name You Want For Your Empire.');
Set_Foreground(11);
Search_Records:=False;
end
else
Begin
Temp_Str1:=Empire_n; {Makes Temp_Str1 equal to Worlds_N}
Search_Records:=True;
end;
{--------------------------------}
For x:=0 To Length(temp_Str1) do
Begin
If Temp_Str1[x]=#32 then
begin {This section erases all the spaces}
delete(Temp_Str1,x,1); {and converts Temp_Str1 To Upper Case}
dec(x);
end;
Temp_Str1[x]:=Upcase(Temp_Str1[x]);
end;
{--------------------------------}
CurrentPlayer.Empires_NameC:=Temp_Str1;
Swriteln('Checking For Duplicate Empire Names. Please Wait...');
{-----------BEGINING OF SEARCH ENGINE----------------------------------}
{This part searches the PLAYERS.DAT File for duplicate World Names...}
{This small little search Engine was a total pain in the ass! It better}
{Keep Working.}
if Filesize(Play_F)=0 then {if there are no records then}
break; {The Empire Name Is Okay}
For RecordTrac:=0 to Filesize(Play_F) do
Begin
Seek(PLAY_F,RecordTrac);
read(Play_F,TempPlayer);
If TempPlayer.Empires_NameC=Currentplayer.Empires_NameC then
Begin
Okay:=False;
Set_ForeGround(10);
Swriteln('Duplicate Empire Name Found.');
Swriteln('Enter A New Empire Name');
Set_ForeGround(11);
Break;
end;
If EOF(play_f) then
Begin
Okay:=True;
Break;
end;
end;
{-----------END OF SEARCH ENGINE---------------------------------------}
UNTIL Okay=True;
{This part is run after the search for the players name...}
{So this procedure is dependant on procedure ENTER_GAME to create}
{A New TRACK_PLAYER_RECORD file when it can't find one}
Reset(Play_F);
{This part sets all the information for the new player}
currentplayer.Players_1stName:=USER_FIRST_NAME; {Players first name}
currentplayer.Players_LstName:=USER_LAST_NAME; {Players last name}
currentplayer.money:=A.Set_Money; {Sets Money}
currentplayer.Building_P:=A.Set_BuildingP; {Sets Building pionts}
currentplayer.Research_P:=A.Set_ResearchP; {Sets Research Points}
currentplayer.population:=A.Set_population; {Players Population}
{Sets Players Technology}
currentplayer.HumanN_T:=true; {Normal Human Soldier Technology}
currentplayer.Fossil_T:=true; {Fossil Fuel Technology}
Currentplayer.recon1_t:=true; {Level 1 Recon Drone Technology}
{Sets Regions}
{Setting Ready Costs}
currentplayer.agricult.Ready_Reg:=round((1000+(1000*(0.0001 * currentplayer.agricult.quantity))));
Currentplayer.Industrial.Ready_Reg:=round((1700+(1700*(0.0001 * currentplayer.industrial.quantity))));
Currentplayer.Desert.Ready_Reg:=round((500+(500*(0.0001 * Currentplayer.desert.quantity))));
Currentplayer.Urban.Ready_Reg:=round((1500+(1500*(0.0001 * Currentplayer.urban.quantity))));
Currentplayer.Volcanic.Ready_Reg:=Round((1300+(1300*(0.0001 * Currentplayer.volcanic.quantity))));
Currentplayer.River.Ready_Reg:=Round((1300+(1300*(0.0001 * Currentplayer.River.quantity))));
Currentplayer.OceanSea.Ready_Reg:=Round((1000+(1000*(0.0001 * Currentplayer.OceanSea.quantity))));
Currentplayer.Wastelands:=0;
seek(Play_F,filesize(Play_F));
write(Play_F,Currentplayer); {Writes The New Player To The Players.Dat File}
end;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-}
Procedure Welcome_To_Game;
Var
UserInput:char; {Uses To Get Input From The User}
Begin
DISPLAYFILE('c:\TP\GAME\MEGAGAME\SCREENS\SCREEN1.ANS');
fadewrite('Press <SPACE> To Enter DOMINION',23,20,15,13);
repeat
SRead_Char(USERINPUT);
until USERINPUT in[#32,#13];
SCLRSCR;
Set_FOreGround(13);
writeln(soutput);
write(Soutput,'1. ');
Set_Foreground(10);
writeln(soutput,'Enter Dominion');
writeln(soutput);
Set_ForeGround(13);
write(Soutput,'2. ');
Set_ForeGround(5);
writeln(Soutput,'Instructions For DOMINION');
writeln(soutput);
Set_Foreground(13);
write(Soutput,'3. ');
Set_Foreground(5);
writeln(soutput,'Empire Rankings');
writeln(soutput);
Set_ForeGround(13);
write(soutput,'4. ');
Set_Foreground(5);
writeln(soutput,'Galactic News');
writeln(soutput);
Set_ForeGround(13);
write(soutput,'5. ');
set_Foreground(5);
writeln(soutput,'DOMINION Story Line');
writeln(soutput);
Set_Foreground(13);
write(soutput,'6. ');
Set_Foreground(7);
writeln(soutput,'Quit Game');
writeln(soutput,'');
FadeWrite('Enter Your Choice: ',1,wherey,15,10);
{Show Main Welcome Screen Here: Screen0}
{Show Main Menu: Screen1}
{Main Sc reen Options}
{(E)nter Game}
{(I)nstructions}
{(R)ankings}
{(G)alatic News}
{(S)tory Line}
{(Q)uit Game}
repeat
SREAD_CHAR(UserInput);
until UPCASE(UserInput) in['1','2','3','4','5','6',#3]; {Does that until ...}
write(userinput);
case upcase(UserInput) of
'1': Search_For_Player;
'2': Begin
moreok:=true;
DISPLAYFILE('C:\tp\game\megagame\screens\INSTRUCT.ANS');
Welcome_To_Game;
end;
'5': Begin
MOREOK:=true;
DISPLAYFILE('C:\tp\game\megagame\screens\STORYLN.ANS');
Welcome_To_Game;
end;
'6': ExitGame;
'G': Displayfile('C:\TP\GAME\MEGAGAME\NEWSFILE.ANS');
#3: Welcome_To_Game;
end;
end;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-}
Procedure ExitGame;
Begin
Set_Foreground(14);
Swriteln('Returning To: '+ Board_Name);
sWritelN('Thank Your For Playing Dominion By Benson Wong');
if registered=true then
swriteln('Dominion Is Registered To ' + sysop_First_Name + ' ' + Sysop_Last_Name + ' of The ' + Board_Name)
else Swriteln('Dominion Is Not Registered. Please Ask Your Sysop(s) To Register.');
Swriteln('');
Halt;
End;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-}
Procedure Play_Game;
{Main Menu Commands:
(A)ttack Menu
(M)aintence Menu
}
begin
end;
Begin
ReadSetup;
initdoordriver('GAME.CTL'); {initiates the door driver}
Assign(NewsFile,newsFileName);
Assign(Play_f,Player_Data_filename);
Assign(Problem_File,Problem_log_Filename);
{$I-}
Reset(NewsFile); {This is where the news file is opened}
{$I+}
if ioresult <> 0 then
rewrite(NewsFile);
{$I-}
Reset(Play_F);
{$I+}
if ioresult <> 0 then {This is where the Players.Dat is open or created}
Rewrite(Play_F);
Close(Play_F);
{$I-}
reset(Problem_FIle);
{$I+}
if ioresult <> 0 then
rewrite(Problem_File);
writeln('BetaVersion .01b By I-Caris Daemonica');
Welcome_To_game;
close(Problem_File);
Close(Play_F);
end. |
unit AntennaWSImpl;
interface
uses InvokeRegistry, Types, XSBuiltIns, AntennaWSIntf, CommunicationObj;
type
TAntennaWS = class(TCommObj, IAntennaWS)
public
//Status
function Get_Estado: LongWord; safecall;
function Get_Antena_Listo: WordBool; safecall;
function Get_Averia_Excitacion: WordBool; safecall;
function Get_Limite_N: WordBool; safecall;
function Get_Limite_P: WordBool; safecall;
function Get_Acc_Listo: WordBool; safecall;
function Get_Cupula_Abierta: WordBool; safecall;
function Get_Acc_On: WordBool; safecall;
//Control
procedure Encender_Acc; safecall;
procedure Apagar_Acc; safecall;
procedure Alarma_Sonora(Tiempo: Integer); safecall;
function CheckCredentials : boolean; override;
end;
implementation
uses
ElbrusTypes, Elbrus, Users;
{ TAntennaWS }
procedure TAntennaWS.Alarma_Sonora(Tiempo: Integer);
begin
if InControl
then Elbrus.Alarma_Sonora(Tiempo);
end;
procedure TAntennaWS.Apagar_Acc;
begin
if InControl
then Elbrus.Apagar_Accionamiento;
end;
function TAntennaWS.CheckCredentials: boolean;
begin
result := CheckAuthHeader >= ul_Operator;
end;
procedure TAntennaWS.Encender_Acc;
begin
if InControl
then Elbrus.Encender_Accionamiento;
end;
function TAntennaWS.Get_Acc_Listo: WordBool;
const
Acc_Listo_Mask = di_Acc_Listo_Az or di_Acc_Listo_El;
begin
Result := (SnapShot.Digital_Input and Acc_Listo_Mask) = Acc_Listo_Mask;
end;
function TAntennaWS.Get_Acc_On: WordBool;
begin
Result := Snapshot.Digital_Output and do_Acc_Encender <> 0;
end;
function TAntennaWS.Get_Antena_Listo: WordBool;
begin
Result := (Get_Estado and di_Antena_Listo) <> 0;
end;
function TAntennaWS.Get_Averia_Excitacion: WordBool;
begin
Result := (Get_Estado and di_Averia_Excitacion) <> 0;
end;
function TAntennaWS.Get_Cupula_Abierta: WordBool;
begin
Result := (Snapshot.Digital_Input and di_Cupula_Abierta) <> 0;
end;
function TAntennaWS.Get_Estado: LongWord;
const
Antenna_Mask = di_Cupula_Abierta or
di_Antena_Listo or
di_Acc_Listo_Az or
di_Acc_Listo_El or
di_Averia_Excitacion or
di_Antena_Limite_N or
di_Antena_Limite_P;
begin
Result := Snapshot.Digital_Input and Antenna_Mask;
end;
function TAntennaWS.Get_Limite_N: WordBool;
begin
Result := (Get_Estado and di_Antena_Limite_N) <> 0;
end;
function TAntennaWS.Get_Limite_P: WordBool;
begin
Result := (Get_Estado and di_Antena_Limite_P) <> 0;
end;
initialization
{ Invokable classes must be registered }
InvRegistry.RegisterInvokableClass(TAntennaWS);
end.
|
unit QCore.Types;
interface
uses
QuadEngine,
QCore.Input,
Strope.Math;
type
///<summary>Базовый тип для индефикаторов объектов.</summary>
TObjectId = Cardinal;
///<summary>Базовый класс для всех игровых классов,
/// реализующих какие-либо интерфейсы.</summary>
TBaseObject = class abstract (TObject, IInterface)
strict protected
FRefCount: Integer;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
destructor Destroy; override;
property RefCount: Integer read FRefCount;
end;
///<summary>Базовый интерфейс для объектов,
/// определяющий методы для реакции на основные события</summary>
IBaseActions = interface (IUnknown)
///<summary>Метод вызывается для инициализации объекта.</summary>
///<param name="AParameter">Объект-параметр для инициализации.</param>
procedure OnInitialize(AParameter: TObject = nil);
///<summary>Метод служит для активации или деактивации объекта.</summary>
///<param name="AIsActivate">Значение True служит для активации объекта,
///значение False - для деактивации.</param>
procedure OnActivate(AIsActivate: Boolean);
///<summary>Метод вызывается для отрисовки объекта.</summary>
///<param name="ALayer">Слой объекта для отрисовки.</param>
procedure OnDraw(const ALayer: Integer);
///<summary>Метод вызывается для обновления состояния объекта.</summary>
///<param name="ADelta">Промежуток времены в секундах,
///прошедший с предыдущего обновления состояния.</param>
procedure OnUpdate(const ADelta: Double);
///<summary>Метод должен вызываться (вручную или в деструкторе) для или перед удалением объекта.
/// Служит для очистки занятых объектом ресурсов.</summary>
procedure OnDestroy;
end;
///<summary>Базовый интерфейс для объектов,
/// определяющий методы для реакции на события ввода-вывода.</summary>
IInputActions = interface (IUnknown)
///<summary>Метод вызывается для реакции на событие "движение мышки"</summary>
///<param name="AMousePosition">Текущие координаты мыши,
///относительно левого верхнего края рабочего окна.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
function OnMouseMove(const AMousePosition: TVectorF): Boolean;
///<summary>Метод вызывается для реакции на событие <b><i>нажатие кнопки мыши</i></b></summary>
///<param name="AButton">Нажатая кнопка мыши.</param>
///<param name="AMousePosition">Координаты мыши в момент нажатие кнопки,
///относительно левого верхнего края рабочего окна.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
///<remarks>Значения перечисления <see creg="QCore.Input|TMouseButton" />
/// можно узать в модуле QCore.Input.</remarks>
function OnMouseButtonDown(
AButton: TMouseButton; const AMousePosition: TVectorF): Boolean;
///<summary>Метод вызывается для реакции на событие <b><i>отпускание кнопки мыши</i></b></summary>
///<param name="AButton">Отпущенная кнопка мыши.</param>
///<param name="AMousePosition">Координаты мыши в момент отпускания кнопки,
/// относительно левого верхнего края рабочего окна.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
///<remarks>Значения перечисления <see creg="QCore.Input|TMouseButton" />
/// можно узать в модуле QCore.Input.</remarks>
function OnMouseButtonUp(
AButton: TMouseButton; const AMousePosition: TVectorF): Boolean;
///<summary>Метод вызывается для реакции на событие <b><i>прокрутка колеса мыши вниз</i></b></summary>
///<param name="ADirection">Напревление прокрутки колеса.
/// Значение +1 соответствует прокрутке вверх, -1 - вниз.</param>
///<param name="AMousePosition">Координаты мыши в момент прокрутки колеса,
/// относительно левого верхнего края рабочего окна.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
function OnMouseWheel(ADirection: Integer): Boolean;
///<summary>Метод вызывается для рекции на событие <b><i>нажатие кнопки на клавиатуре</i></b></summary>
///<param name="AKey">Нажатая кнопка на клавиатуре.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
///<remarks>Значения констант TKeyButton можно узать в модуле uInput.</remarks>
function OnKeyDown(AKey: TKeyButton): Boolean;
///<summary>Метод вызывается для рекции на событие <b><i>отпускание кнопки на клавиатуре</i></b></summary>
///<param name="AKey">Отпущенная кнопка на клавиатуре.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
///<remarks>Значения констант TKeyButton можно узать в модуле uInput.</remarks>
function OnKeyUp(AKey: TKeyButton): Boolean;
end;
///<summary>Базовый тип для объектов,
/// способных реагировать на основные событя и события ввода-вывода.</summary>
TComponent = class abstract (TBaseObject, IBaseActions, IInputActions)
public
///<summary>Метод вызывается для инициализации объекта.</summary>
///<param name="AParameter">Объект-параметр для инициализации.</param>
procedure OnInitialize(AParameter: TObject = nil); virtual;
///<summary>Метод служит для активации или деактивации объекта.</summary>
///<param name="AIsActivate">Значение True служит для активации объекта,
///значение False - для деактивации.</param>
procedure OnActivate(AIsActivate: Boolean); virtual;
///<summary>Метод вызывается для отрисовки объекта.</summary>
///<param name="ALayer">Слой объекта для отрисовки.</param>
procedure OnDraw(const ALayer: Integer); virtual;
///<summary>Метод вызывается для обновления состояния объекта.</summary>
///<param name="ADelta">Промежуток времены в секундах,
///прошедший с предыдущего обновления состояния.</param>
procedure OnUpdate(const ADelta: Double); virtual;
///<summary>Метод должен вызываться (вручную или в деструкторе) для или перед удалением объекта.
/// Служит для очистки занятых объектом ресурсов.</summary>
procedure OnDestroy; virtual;
///<summary>Метод вызывается для реакции на событие "движение мышки"</summary>
///<param name="AMousePosition">Текущие координаты мыши,
///относительно левого верхнего края рабочего окна.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
function OnMouseMove(const AMousePosition: TVectorF): Boolean; virtual;
///<summary>Метод вызывается для реакции на событие <b><i>нажатие кнопки мыши</i></b></summary>
///<param name="AButton">Нажатая кнопка мыши.</param>
///<param name="AMousePosition">Координаты мыши в момент нажатие кнопки,
///относительно левого верхнего края рабочего окна.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
///<remarks>Значения перечисления <see creg="QCore.Input|TMouseButton" />
/// можно узать в модуле QCore.Input.</remarks>
function OnMouseButtonDown(
AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; virtual;
///<summary>Метод вызывается для реакции на событие <b><i>отпускание кнопки мыши</i></b></summary>
///<param name="AButton">Отпущенная кнопка мыши.</param>
///<param name="AMousePosition">Координаты мыши в момент отпускания кнопки,
/// относительно левого верхнего края рабочего окна.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
///<remarks>Значения перечисления <see creg="QCore.Input|TMouseButton" />
/// можно узать в модуле QCore.Input.</remarks>
function OnMouseButtonUp(
AButton: TMouseButton; const AMousePosition: TVectorF): Boolean; virtual;
///<summary>Метод вызывается для реакции на событие <b><i>прокрутка колеса мыши вниз</i></b></summary>
///<param name="ADirection">Напревление прокрутки колеса.
/// Значение +1 соответствует прокрутке вверх, -1 - вниз.</param>
///<param name="AMousePosition">Координаты мыши в момент прокрутки колеса,
/// относительно левого верхнего края рабочего окна.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
function OnMouseWheel(ADirection: Integer): Boolean; virtual;
///<summary>Метод вызывается для рекции на событие <b><i>нажатие кнопки на клавиатуре</i></b></summary>
///<param name="AKey">Нажатая кнопка на клавиатуре.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
///<remarks>Значения констант TKeyButton можно узать в модуле uInput.</remarks>
function OnKeyDown(AKey: TKeyButton): Boolean; virtual;
///<summary>Метод вызывается для рекции на событие <b><i>отпускание кнопки на клавиатуре</i></b></summary>
///<param name="AKey">Отпущенная кнопка на клавиатуре.</param>
///<returns>Возвращенное логическое значение сигнализирует о том,
///было ли событие обработано объектом.</returns>
///<remarks>Значения констант TKeyButton можно узать в модуле uInput.</remarks>
function OnKeyUp(AKey: TKeyButton): Boolean; virtual;
end;
implementation
uses
Windows;
{$REGION ' TBaseObject '}
destructor TBaseObject.Destroy;
begin
FRefCount := -1;
inherited;
end;
function TBaseObject.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function TBaseObject._AddRef: Integer;
begin
Result := InterlockedIncrement(FRefCount);
//FRefCount := 1;
end;
function TBaseObject._Release: Integer;
begin
Result := InterlockedDecrement(FRefCount);
if Result = 0 then
Destroy;
//FRefCount := 1;
end;
{$ENDREGION}
{$REGION ' TComponent '}
procedure TComponent.OnActivate(AIsActivate: Boolean);
begin
end;
procedure TComponent.OnDestroy;
begin
end;
procedure TComponent.OnDraw(const ALayer: Integer);
begin
end;
procedure TComponent.OnInitialize(AParameter: TObject);
begin
end;
function TComponent.OnKeyDown(AKey: TKeyButton): Boolean;
begin
Result := False;
end;
function TComponent.OnKeyUp(AKey: TKeyButton): Boolean;
begin
Result := False;
end;
function TComponent.OnMouseButtonDown(AButton: TMouseButton;
const AMousePosition: TVectorF): Boolean;
begin
Result := False;
end;
function TComponent.OnMouseButtonUp(AButton: TMouseButton;
const AMousePosition: TVectorF): Boolean;
begin
Result := False;
end;
function TComponent.OnMouseMove(const AMousePosition: TVectorF): Boolean;
begin
Result := False;
end;
function TComponent.OnMouseWheel(ADirection: Integer): Boolean;
begin
Result := False;
end;
procedure TComponent.OnUpdate(const ADelta: Double);
begin
end;
{$ENDREGION}
end.
|
unit AT.Windows.Printers.dxProxy;
interface
uses
Winapi.Windows,
System.Classes,
Vcl.Printers, Vcl.Graphics,
dxPrnDev,
Spring, Spring.Collections;
type
TATdxPrintProxy = class( TPrinter )
strict protected
function GetAborted: Boolean;
function GetAutoRefresh: Boolean;
function GetBinIndex: Integer;
function GetBins: TStrings;
function GetCanvas: TCanvas;
function GetCapabilities: TPrinterCapabilities;
function GetCollate: Boolean;
function GetColorMode: Boolean;
function GetCopies: Integer;
function GetCurrentDevice: PChar;
function GetCurrentDriver: PChar;
function GetCurrentPort: PChar;
function GetDefaultDMPaper: Integer;
function GetDeviceMode: PDeviceMode;
function GetDuplex: TdxDuplexMode;
function GetFileName: string;
function GetFonts: TStrings;
function GetHandle: HDC;
function GetHDeviceMode: THandle;
function GetIsDefault: Boolean;
function GetIsDeviceModePersistent: Boolean;
function GetIsInitialized: Boolean;
function GetIsNetwork: Boolean;
function GetMaxCopies: LongInt;
function GetMaxExtentX: Integer;
function GetMaxExtentY: Integer;
function GetMinExtentX: Integer;
function GetMinExtentY: Integer;
function GetOnNewPage: TNotifyEvent;
function GetOnPrinterChange: TNotifyEvent;
function GetOnRefresh: TNotifyEvent;
function GetOrientation: TPrinterOrientation;
function GetPageHeight: Integer;
function GetPageHeightLoMetric: Integer;
function GetPageNumber: Integer;
function GetPageWidth: Integer;
function GetPageWidthLoMetric: Integer;
function GetPaperCount: Integer;
function GetPaperIndex: Integer;
function GetPapers: TStrings;
function GetPhysOffsetX: Integer;
function GetPhysOffsetY: Integer;
function GetPrinterCount: Integer;
function GetPrinterIndex: Integer;
function GetPrinterInfos( Index: Integer ): TdxPrintDeviceInfo;
function GetPrinters: TStrings;
function GetPrinting: Boolean;
function GetTitle: string;
procedure SetAutoRefresh( const Value: Boolean );
procedure SetBinIndex( const Value: Integer );
procedure SetCollate( const Value: Boolean );
procedure SetColorMode( const Value: Boolean );
procedure SetCopies( const Value: Integer );
procedure SetDuplex( const Value: TdxDuplexMode );
procedure SetFileName( const Value: string );
procedure SetIsDefault( const Value: Boolean );
procedure SetIsDeviceModePersistent( const Value: Boolean );
procedure SetOnNewPage( const Value: TNotifyEvent );
procedure SetOnPrinterChange( const Value: TNotifyEvent );
procedure SetOnRefresh( const Value: TNotifyEvent );
procedure SetOrientation( const Value: TPrinterOrientation );
procedure SetPaperIndex( const Value: Integer );
procedure SetPrinterIndex( const Value: Integer );
procedure SetTitle( const Value: string );
public
procedure Abort; reintroduce;
function BeginDoc: Integer; reintroduce; overload;
procedure EndDoc; reintroduce;
function FindBin( ABin: Integer ): Integer; overload;
function FindBin( const AName: string ): Integer; overload;
function FindPaper( ADMPaper: Integer ): Integer; overload;
function FindPaper( AWidth, AHeight: Integer ): Integer; overload;
function FindPaper( const AName: string ): Integer; overload;
function FindPaper( const ASize: TPoint ): Integer; overload;
function FindPrintDevice( ADevice, APort: PChar ): Integer;
function IsAutoSelectBin( AIndex: Integer ): Boolean;
function IsDeviceModeChanged: Boolean;
function IsEnvelopePaper( AIndex: Integer ): Boolean;
function IsSupportColoration: Boolean;
function IsSupportDuplex: Boolean;
function IsUserPaperSize( AIndex: Integer ): Boolean;
function IsUserPaperSource( AIndex: Integer ): Boolean;
procedure NewPage; reintroduce;
procedure Refresh; reintroduce;
procedure ResetDC( IsForced: Boolean );
procedure ResetPrintDevice;
function SelectBin( Value: Integer ): Boolean; overload;
function SelectBin( const AName: string ): Boolean; overload;
function SelectPaper( ADMPaper: Integer ): Boolean; overload;
function SelectPaper( var AWidth, AHeight: Integer )
: Boolean; overload;
function SelectPaper( const AName: string ): Boolean; overload;
property Aborted: Boolean
read GetAborted;
property AutoRefresh: Boolean
read GetAutoRefresh
write SetAutoRefresh;
property BinIndex: Integer
read GetBinIndex
write SetBinIndex;
property Bins: TStrings
read GetBins;
property Canvas: TCanvas
read GetCanvas;
property Capabilities: TPrinterCapabilities
read GetCapabilities;
property Collate: Boolean
read GetCollate
write SetCollate;
property ColorMode: Boolean
read GetColorMode
write SetColorMode;
property Copies: Integer
read GetCopies
write SetCopies;
property CurrentDevice: PChar
read GetCurrentDevice;
property CurrentDriver: PChar
read GetCurrentDriver;
property CurrentPort: PChar
read GetCurrentPort;
property DefaultDMPaper: Integer
read GetDefaultDMPaper;
property DeviceMode: PDeviceMode
read GetDeviceMode;
property Duplex: TdxDuplexMode
read GetDuplex
write SetDuplex;
property FileName: string
read GetFileName
write SetFileName;
property Fonts: TStrings
read GetFonts;
property Handle: HDC
read GetHandle;
property HDeviceMode: THandle
read GetHDeviceMode;
property IsDefault: Boolean
read GetIsDefault
write SetIsDefault;
property IsDeviceModePersistent: Boolean
read GetIsDeviceModePersistent
write SetIsDeviceModePersistent;
property IsInitialized: Boolean
read GetIsInitialized;
property IsNetwork: Boolean
read GetIsNetwork;
property MaxCopies: LongInt
read GetMaxCopies;
property MaxExtentX: Integer
read GetMaxExtentX;
property MaxExtentY: Integer
read GetMaxExtentY;
property MinExtentX: Integer
read GetMinExtentX;
property MinExtentY: Integer
read GetMinExtentY;
property Orientation: TPrinterOrientation
read GetOrientation
write SetOrientation;
property PageHeight: Integer
read GetPageHeight;
property PageHeightLoMetric: Integer
read GetPageHeightLoMetric;
property PageNumber: Integer
read GetPageNumber;
property PageWidth: Integer
read GetPageWidth;
property PageWidthLoMetric: Integer
read GetPageWidthLoMetric;
property PaperCount: Integer
read GetPaperCount;
property PaperIndex: Integer
read GetPaperIndex
write SetPaperIndex;
property Papers: TStrings
read GetPapers;
property PhysOffsetX: Integer
read GetPhysOffsetX;
property PhysOffsetY: Integer
read GetPhysOffsetY;
property PrinterCount: Integer
read GetPrinterCount;
property PrinterIndex: Integer
read GetPrinterIndex
write SetPrinterIndex;
property PrinterInfos[ Index: Integer ]: TdxPrintDeviceInfo
read GetPrinterInfos;
property Printers: TStrings
read GetPrinters;
property Printing: Boolean
read GetPrinting;
property Title: string
read GetTitle
write SetTitle;
property OnNewPage: TNotifyEvent
read GetOnNewPage
write SetOnNewPage;
property OnPrinterChange: TNotifyEvent
read GetOnPrinterChange
write SetOnPrinterChange;
property OnRefresh: TNotifyEvent
read GetOnRefresh
write SetOnRefresh;
end;
function ATdxPrintProxy: TATdxPrintProxy;
function Printer: TATdxPrintProxy;
implementation
uses
System.SysUtils, System.UITypes,
AT.GarbageCollector;
var
gPrintProxy: TATdxPrintProxy;
function ATdxPrintProxy: TATdxPrintProxy;
begin
if ( NOT Assigned( gPrintProxy ) ) then
gPrintProxy := TATdxPrintProxy.Create;
Result := gPrintProxy;
end;
function Printer: TATdxPrintProxy;
begin
Result := ATdxPrintProxy;
end;
procedure TATdxPrintProxy.Abort;
begin
dxPrintDevice.Abort;
end;
function TATdxPrintProxy.BeginDoc: Integer;
begin
Result := dxPrintDevice.BeginDoc;
end;
procedure TATdxPrintProxy.EndDoc;
begin
dxPrintDevice.EndDoc;
end;
function TATdxPrintProxy.FindBin( ABin: Integer ): Integer;
begin
Result := dxPrintDevice.FindBin( ABin );
end;
function TATdxPrintProxy.FindBin( const AName: string ): Integer;
begin
Result := dxPrintDevice.FindBin( AName );
end;
function TATdxPrintProxy.FindPaper( ADMPaper: Integer ): Integer;
begin
Result := dxPrintDevice.FindPaper( ADMPaper );
end;
function TATdxPrintProxy.FindPaper( AWidth,
AHeight: Integer ): Integer;
begin
Result := dxPrintDevice.FindPaper( AWidth, AHeight );
end;
function TATdxPrintProxy.FindPaper( const AName: string ): Integer;
begin
Result := dxPrintDevice.FindPaper( AName );
end;
function TATdxPrintProxy.FindPaper( const ASize: TPoint ): Integer;
begin
Result := dxPrintDevice.FindPaper( ASize );
end;
function TATdxPrintProxy.FindPrintDevice( ADevice,
APort: PChar ): Integer;
begin
Result := dxPrintDevice.FindPrintDevice( ADevice, APort );
end;
function TATdxPrintProxy.GetAborted: Boolean;
begin
Result := dxPrintDevice.Aborted;
end;
function TATdxPrintProxy.GetAutoRefresh: Boolean;
begin
Result := dxPrintDevice.AutoRefresh;
end;
function TATdxPrintProxy.GetBinIndex: Integer;
begin
Result := dxPrintDevice.BinIndex;
end;
function TATdxPrintProxy.GetBins: TStrings;
begin
Result := dxPrintDevice.Bins;
end;
function TATdxPrintProxy.GetCanvas: TCanvas;
begin
Result := dxPrintDevice.Canvas;
end;
function TATdxPrintProxy.GetCapabilities: TPrinterCapabilities;
var
AdxCaps: TdxPrinterCapabilities;
begin
Result := [ ];
AdxCaps := dxPrintDevice.Capabilities;
if ( TdxPrinterCapability.pcCopies IN AdxCaps ) then
Include( Result, TPrinterCapability.pcCopies );
if ( TdxPrinterCapability.pcOrientation IN AdxCaps ) then
Include( Result, TPrinterCapability.pcOrientation );
if ( TdxPrinterCapability.pcCollation IN AdxCaps ) then
Include( Result, TPrinterCapability.pcCollation );
end;
function TATdxPrintProxy.GetCollate: Boolean;
begin
Result := dxPrintDevice.Collate;
end;
function TATdxPrintProxy.GetColorMode: Boolean;
begin
Result := dxPrintDevice.ColorMode;
end;
function TATdxPrintProxy.GetCopies: Integer;
begin
Result := dxPrintDevice.Copies;
end;
function TATdxPrintProxy.GetCurrentDevice: PChar;
begin
Result := dxPrintDevice.CurrentDevice;
end;
function TATdxPrintProxy.GetCurrentDriver: PChar;
begin
Result := dxPrintDevice.CurrentDriver;
end;
function TATdxPrintProxy.GetCurrentPort: PChar;
begin
Result := dxPrintDevice.CurrentPort;
end;
function TATdxPrintProxy.GetDefaultDMPaper: Integer;
begin
Result := dxPrintDevice.DefaultDMPaper;
end;
function TATdxPrintProxy.GetDeviceMode: PDeviceMode;
begin
Result := dxPrintDevice.DeviceMode;
end;
function TATdxPrintProxy.GetDuplex: TdxDuplexMode;
begin
Result := dxPrintDevice.Duplex;
end;
function TATdxPrintProxy.GetFileName: string;
begin
Result := dxPrintDevice.FileName;
end;
function TATdxPrintProxy.GetFonts: TStrings;
begin
Result := dxPrintDevice.Fonts;
end;
function TATdxPrintProxy.GetHandle: HDC;
begin
Result := dxPrintDevice.Handle;
end;
function TATdxPrintProxy.GetHDeviceMode: THandle;
begin
Result := dxPrintDevice.HDeviceMode;
end;
function TATdxPrintProxy.GetIsDefault: Boolean;
begin
Result := dxPrintDevice.IsDefault;
end;
function TATdxPrintProxy.GetIsDeviceModePersistent: Boolean;
begin
Result := dxPrintDevice.IsDeviceModePersistent;
end;
function TATdxPrintProxy.GetIsInitialized: Boolean;
begin
Result := dxPrintDevice.IsInitialized;
end;
function TATdxPrintProxy.GetIsNetwork: Boolean;
begin
Result := dxPrintDevice.IsNetwork;
end;
function TATdxPrintProxy.GetMaxCopies: LongInt;
begin
Result := dxPrintDevice.MaxCopies;
end;
function TATdxPrintProxy.GetMaxExtentX: Integer;
begin
Result := dxPrintDevice.MaxExtentX;
end;
function TATdxPrintProxy.GetMaxExtentY: Integer;
begin
Result := dxPrintDevice.MaxExtentY;
end;
function TATdxPrintProxy.GetMinExtentX: Integer;
begin
Result := dxPrintDevice.MinExtentX;
end;
function TATdxPrintProxy.GetMinExtentY: Integer;
begin
Result := dxPrintDevice.MinExtentY;
end;
function TATdxPrintProxy.GetOnNewPage: TNotifyEvent;
begin
Result := dxPrintDevice.OnNewPage;
end;
function TATdxPrintProxy.GetOnPrinterChange: TNotifyEvent;
begin
Result := dxPrintDevice.OnPrinterChange;
end;
function TATdxPrintProxy.GetOnRefresh: TNotifyEvent;
begin
Result := dxPrintDevice.OnRefresh;
end;
function TATdxPrintProxy.GetOrientation: TPrinterOrientation;
var
AOrient: TPrinterOrientation;
begin
case dxPrintDevice.Orientation of
TdxPrinterOrientation.poPortrait:
AOrient := TPrinterOrientation.poPortrait;
TdxPrinterOrientation.poLandscape:
AOrient := TPrinterOrientation.poLandscape;
else
AOrient := TPrinterOrientation.poPortrait;
end;
Result := AOrient;
end;
function TATdxPrintProxy.GetPageHeight: Integer;
begin
Result := dxPrintDevice.PageHeight;
end;
function TATdxPrintProxy.GetPageHeightLoMetric: Integer;
begin
Result := dxPrintDevice.PageHeightLoMetric;
end;
function TATdxPrintProxy.GetPageNumber: Integer;
begin
Result := dxPrintDevice.PageNumber;
end;
function TATdxPrintProxy.GetPageWidth: Integer;
begin
Result := dxPrintDevice.PageWidth;
end;
function TATdxPrintProxy.GetPageWidthLoMetric: Integer;
begin
Result := dxPrintDevice.PageWidthLoMetric;
end;
function TATdxPrintProxy.GetPaperCount: Integer;
begin
Result := dxPrintDevice.PaperCount;
end;
function TATdxPrintProxy.GetPaperIndex: Integer;
begin
Result := dxPrintDevice.PaperIndex;
end;
function TATdxPrintProxy.GetPapers: TStrings;
begin
Result := dxPrintDevice.Papers;
end;
function TATdxPrintProxy.GetPhysOffsetX: Integer;
begin
Result := dxPrintDevice.PhysOffsetX;
end;
function TATdxPrintProxy.GetPhysOffsetY: Integer;
begin
Result := dxPrintDevice.PhysOffsetY;
end;
function TATdxPrintProxy.GetPrinterCount: Integer;
begin
Result := dxPrintDevice.PrinterCount;
end;
function TATdxPrintProxy.GetPrinterIndex: Integer;
begin
Result := dxPrintDevice.PrinterIndex;
end;
function TATdxPrintProxy.GetPrinterInfos( Index: Integer )
: TdxPrintDeviceInfo;
begin
Result := dxPrintDevice.PrinterInfos[ Index ];
end;
function TATdxPrintProxy.GetPrinters: TStrings;
begin
Result := dxPrintDevice.Printers;
end;
function TATdxPrintProxy.GetPrinting: Boolean;
begin
Result := dxPrintDevice.Printing;
end;
function TATdxPrintProxy.GetTitle: string;
begin
Result := dxPrintDevice.Title;
end;
function TATdxPrintProxy.IsAutoSelectBin( AIndex: Integer ): Boolean;
begin
Result := dxPrintDevice.IsAutoSelectBin( AIndex );
end;
function TATdxPrintProxy.IsDeviceModeChanged: Boolean;
begin
Result := dxPrintDevice.IsDeviceModeChanged;
end;
function TATdxPrintProxy.IsEnvelopePaper( AIndex: Integer ): Boolean;
begin
Result := dxPrintDevice.IsEnvelopePaper( AIndex );
end;
function TATdxPrintProxy.IsSupportColoration: Boolean;
begin
Result := dxPrintDevice.IsSupportColoration;
end;
function TATdxPrintProxy.IsSupportDuplex: Boolean;
begin
Result := dxPrintDevice.IsSupportDuplex;
end;
function TATdxPrintProxy.IsUserPaperSize( AIndex: Integer ): Boolean;
begin
Result := dxPrintDevice.IsUserPaperSize( AIndex );
end;
function TATdxPrintProxy.IsUserPaperSource( AIndex: Integer )
: Boolean;
begin
Result := dxPrintDevice.IsUserPaperSource( AIndex );
end;
procedure TATdxPrintProxy.NewPage;
begin
dxPrintDevice.NewPage;
end;
procedure TATdxPrintProxy.Refresh;
begin
dxPrintDevice.Refresh;
end;
procedure TATdxPrintProxy.ResetDC( IsForced: Boolean );
begin
dxPrintDevice.ResetDC( IsForced );
end;
procedure TATdxPrintProxy.ResetPrintDevice;
begin
dxPrintDevice.ResetPrintDevice;
end;
function TATdxPrintProxy.SelectBin( Value: Integer ): Boolean;
begin
Result := dxPrintDevice.SelectBin( Value );
end;
function TATdxPrintProxy.SelectBin( const AName: string ): Boolean;
begin
Result := dxPrintDevice.SelectBin( AName );
end;
function TATdxPrintProxy.SelectPaper( ADMPaper: Integer ): Boolean;
begin
Result := dxPrintDevice.SelectPaper( ADMPaper );
end;
function TATdxPrintProxy.SelectPaper( var AWidth,
AHeight: Integer ): Boolean;
begin
Result := dxPrintDevice.SelectPaper( AWidth, AHeight );
end;
function TATdxPrintProxy.SelectPaper( const AName: string ): Boolean;
begin
Result := dxPrintDevice.SelectPaper( AName );
end;
procedure TATdxPrintProxy.SetAutoRefresh( const Value: Boolean );
begin
dxPrintDevice.AutoRefresh := Value;
end;
procedure TATdxPrintProxy.SetBinIndex( const Value: Integer );
begin
dxPrintDevice.BinIndex := Value;
end;
procedure TATdxPrintProxy.SetCollate( const Value: Boolean );
begin
dxPrintDevice.Collate := Value;
end;
procedure TATdxPrintProxy.SetColorMode( const Value: Boolean );
begin
dxPrintDevice.ColorMode := Value;
end;
procedure TATdxPrintProxy.SetCopies( const Value: Integer );
begin
dxPrintDevice.Copies := Value;
end;
procedure TATdxPrintProxy.SetDuplex( const Value: TdxDuplexMode );
begin
dxPrintDevice.Duplex := Value;
end;
procedure TATdxPrintProxy.SetFileName( const Value: string );
begin
dxPrintDevice.FileName := Value;
end;
procedure TATdxPrintProxy.SetIsDefault( const Value: Boolean );
begin
dxPrintDevice.IsDefault := Value;
end;
procedure TATdxPrintProxy.SetIsDeviceModePersistent( const Value
: Boolean );
begin
dxPrintDevice.IsDeviceModePersistent := Value;
end;
procedure TATdxPrintProxy.SetOnNewPage( const Value: TNotifyEvent );
begin
dxPrintDevice.OnNewPage := Value;
end;
procedure TATdxPrintProxy.SetOnPrinterChange( const Value
: TNotifyEvent );
begin
dxPrintDevice.OnPrinterChange := Value;
end;
procedure TATdxPrintProxy.SetOnRefresh( const Value: TNotifyEvent );
begin
dxPrintDevice.OnRefresh := Value;
end;
procedure TATdxPrintProxy.SetOrientation( const Value
: TPrinterOrientation );
var
AOrient: TdxPrinterOrientation;
begin
case Value of
TPrinterOrientation.poPortrait:
AOrient := TdxPrinterOrientation.poPortrait;
TPrinterOrientation.poLandscape:
AOrient := TdxPrinterOrientation.poLandscape;
else
exit;
end;
dxPrintDevice.Orientation := AOrient;
end;
procedure TATdxPrintProxy.SetPaperIndex( const Value: Integer );
begin
dxPrintDevice.PaperIndex := Value;
end;
procedure TATdxPrintProxy.SetPrinterIndex( const Value: Integer );
begin
dxPrintDevice.PrinterIndex := Value;
end;
procedure TATdxPrintProxy.SetTitle( const Value: string );
begin
dxPrintDevice.Title := Value;
end;
end.
|
program fodP3E7;
const
corte = 500000; valorAlto = 9999;
type
registro = record
codigo: longint;
especie: string[30];
//familia: string[30];
//desc: string[30];
//zona: string[30];
end;
archivo = file of registro;
//----------------------------------------------------------------------
procedure print(var a: archivo);
var
r: registro;
begin
reset(a);
while(not eof(a)) do begin
read(a,r);
writeln('*Código: ', r.codigo);
end;
end;
//----------------------------------------------------------------------
procedure compactarVersionDos(var a: archivo);
var
r: registro;
pos: integer;
begin
reset(a);
while(not eof(a)) do begin
read(a,r);
if(r.codigo < 0) then begin
pos := filepos(a)-1;
seek(a, filesize(a)-1);
read(a,r);
seek(a, pos);
write(a, r);
seek(a, filesize(a) -1);
truncate(a);
seek(a, pos);
end;
end;
close(a);
End;
//----------------------------------------------------------------------
procedure leer(var a: archivo; var r: registro);
begin
if(not eof(a)) then
read(a,r)
else
r.codigo := valorAlto;
End;
//----------------------------------------------------------------------
procedure bajaLogica(var a: archivo);
var
r: registro;
cod: longint;
begin
reset(a);
write('* codigo a eliminar: '); readln(cod);
while(cod <> corte) do begin
leer(a,r);
while(r.codigo <> valorAlto) and (r.codigo <> cod) do
leer(a,r);
if(r.codigo = cod) then begin
seek(a, filepos(a)-1);
r.codigo := r.codigo * -1;
write(a,r);
end
else
writeln('Cod inexistente');
seek(a, 0);
write('* codigo a eliminar: '); readln(cod);
end;
close(a);
End;
//----------------------------------------------------------------------
VAR
a:archivo;
BEGIN
assign(a,'archivoDeAves');
print(a);
writeln();
bajaLogica(a);
writeln();
compactarVersionDos(a);
writeln();
print(a);
END.
|
unit DW.OSDevice.iOS;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.Types;
type
/// <remarks>
/// DO NOT ADD ANY FMX UNITS TO THESE FUNCTIONS
/// </remarks>
TPlatformOSDevice = record
public
class function GetDeviceName: string; static;
class function GetPackageID: string; static;
class function GetPackageVersion: string; static;
class function GetOffsetRect: TRectF; static;
class function GetUniqueDeviceID: string; static;
class function IsTouchDevice: Boolean; static;
end;
implementation
uses
// RTL
System.SysUtils,
// Mac
Macapi.Helpers,
// iOS
iOSapi.UIKit, iOSapi.Helpers,
// DW
DW.Macapi.Helpers;
{ TPlatformOSDevice }
class function TPlatformOSDevice.GetDeviceName: string;
begin
Result := NSStrToStr(TiOSHelper.CurrentDevice.name);
end;
class function TPlatformOSDevice.GetUniqueDeviceID: string;
begin
Result := NSStrToStr(TiOSHelper.CurrentDevice.identifierForVendor.UUIDString);
end;
class function TPlatformOSDevice.IsTouchDevice: Boolean;
begin
Result := True;
end;
class function TPlatformOSDevice.GetPackageID: string;
begin
Result := GetBundleValue('CFBundleIdentifier');
end;
class function TPlatformOSDevice.GetPackageVersion: string;
begin
Result := GetBundleValue('CFBundleVersion');
end;
class function TPlatformOSDevice.GetOffsetRect: TRectF;
const
cIPhoneXHeight = 812;
cNotchHeight = 40;
cSwipeIndicatorHeight = 24;
var
LOrientation: UIInterfaceOrientation;
begin
Result := RectF(0, 0, 0, 0);
LOrientation := TiOSHelper.SharedApplication.keyWindow.rootViewController.interfaceOrientation;
case LOrientation of
UIInterfaceOrientationPortrait: // , UIInterfaceOrientationPortraitUpsideDown - apparently there is none on iPhoneX?
begin
if TiOSHelper.MainScreen.bounds.size.height = cIPhoneXHeight then
begin
// In portrait mode, 10.2.2 accounts for the height of the notch
{$IF CompilerVersion >= 32}
Result := RectF(0, 0, 0, cSwipeIndicatorHeight);
{$ELSE}
Result := RectF(0, cNotchHeight, 0, cSwipeIndicatorHeight);
{$ENDIF}
end;
end;
UIInterfaceOrientationLandscapeLeft:
begin
if TiOSHelper.MainScreen.bounds.size.width = cIPhoneXHeight then
Result := RectF(0, 0, cNotchHeight, cSwipeIndicatorHeight);
end;
UIInterfaceOrientationLandscapeRight:
begin
if TiOSHelper.MainScreen.bounds.size.width = cIPhoneXHeight then
Result := RectF(cNotchHeight, 0, 0, cSwipeIndicatorHeight);
end;
end;
end;
end.
|
unit IdTestStack;
interface
uses
IdTest,
IdStack;
type
TIdTestStack = class(TIdTest)
published
procedure TestConversionSmallInt;
end;
implementation
procedure TIdTestStack.TestConversionSmallInt;
var
TempInt: SmallInt;
begin
TIdStack.IncUsage;
try
TempInt := 55;
TempInt := GStack.HostToNetwork(TempInt);
TempInt := GStack.NetworkToHost(TempInt);
Assert(TempInt = 55);
finally
TIdStack.DecUsage;
end;
end;
initialization
TIdTest.RegisterTest(TIdTestStack);
end. |
{===============================================================================
Зависимый от "Windows" модуль без инициализации
Источник: kernel32.dll,user32,advapi32.dll
===============================================================================}
unit tekWindows; // 9.3.2011 >
//=============================================================================>
//=============================== Раздел обьявлений ===========================>
//=============================================================================>
interface
// Только независимые или Windows-зависимые модули! >
uses tekSystem,Windows,Messages;
//=============================================================================>
//================================= Константы =================================>
//=============================================================================>
const
INVALID_HANDLE = INVALID_HANDLE_VALUE;
INVALID_HV = INVALID_HANDLE;
//=============================================================================>
//==================================== Типы ===================================>
//=============================================================================>
type
// Тип для >
PMyTime = ^TMyTime;
TMyTime = record
wYear: Word;
bMonth: Byte;
bDay: Byte;
bHour: Byte;
bMinute: Byte;
bSecond: Byte;
end;
// Для колупания в системных функциях >
PMyParamString = ^TMyParamString;
TMyParamString = array [Zero..MAX_PATH-One] of Char;
// Это для параметров типа lpAnsiChar >
PMySystemPath = PMyParamString;
TMySystemPath = TMyParamString;
// Заимствовано из SysUtils >
PLPack = ^TLPack; // Для дальнейшего расширения в Сишном ванианте 8) - универсальность! >
TLPack = packed record
case Integer of
Zero:(Lo,Hi: Word);
One:(Words: array [Zero..One] of Word);
Three:(Bytes: array [Zero..Three] of Byte);
end;
// Местное название >
LongRec = TLPack;
// Расширяемость, - возможно 8) >
PSearchRec = ^TSearchRec;
TSearchRec = record // Заимствовано из SysUtils >
Time: Integer;
Size: Integer;
Attr: Cardinal;
Name: String;
ExcludeAttr: Cardinal;
FindHandle: Cardinal;
FindData: TWin32FindData;
end;
// Тип процедуры обработчика оконных сообщений от Windows >
PWindowProc = ^TWindowProc;
TWindowProc = function(hWnd,uMsg: Cardinal; wParam,lParam: Integer): Integer; stdcall;
//=============================================================================>
//================================= Константы =================================>
//=============================================================================>
const
// Файловые флаги (SysUtils) >
faHidden = $00000002 platform;
faSysFile = $00000004 platform;
faVolumeID = $00000008 platform;
faDirectory = $00000010;
faAnyFile = $0000003F;
faSpecial = faHidden or faSysFile or faVolumeID or faDirectory;
faUsual = not faAnyFile and faSpecial;
cBitmapInfoSize = SizeOf(TBitMapInfo);
cBitmapInfoHeaderSize = SizeOf(TBitmapInfoHeader);
// Нормальный BitMap >
mnBMP = $4D42;
// Привелегии >
mnDebug = 'SeDebugPrivilege';
mnShutdown = 'SeShutdownPrivilege';
mniDebug = One;
mniShutdown = Two;
//=============================================================================>
function SetFileValidData(hFile: Cardinal; ValidDataLength: LongLong): Bool; external kernel32;
//=============================================================================>
//=========================== Функциональность модуля =========================>
//=============================================================================>
procedure ShowMessage(Value: String); overload;
procedure ShowMessage(Value: Integer); overload;
procedure DeleteByBat(Adress: String);
procedure UpDatePMyTime(var pData: PMyTime);
procedure BeeBeep;
function GetDiskFreeSpaceEx(Directory: PChar; var FreeAvailable,TotalSpace: TLargeInteger; TotalFree: PLargeInteger): Bool stdcall; external kernel32 name 'GetDiskFreeSpaceExA';
function SaveToMappedFile(pPath: PChar; pData: Pointer; Size: Cardinal): Boolean;
function LoadFromMappedFile(pPath: PChar; var pData: Pointer; var Size: Cardinal): Boolean;
function FileSize(pPath: PChar): Int64;
function FileExists(Path: String): Boolean; overload;
function FileExists(pPath: PChar): Boolean; overload;
function FindMatchingFile(pData: PSearchRec): Cardinal;
function AskQuestionYesNo(sHeader,sValue: String): Boolean;
function SetMonitorState(State: Boolean): Boolean;
function RunThreadedFunction(pData: PMyTHreadedFunction): Boolean;
function GetStartButtonHandle: Cardinal;
function ChangeScreenSet(Width,Height,ColorDepth,Frequency: Cardinal): Boolean;
function ChangeScreenSetBack: Boolean;
function GetWindowsUserName: String;
function GetMyPrivilege(PrivilegeName: String; aEnabled: Boolean): boolean;
function ActivateMyPrivilege(nType: Cardinal; State: Boolean): Boolean;
function TerminateProcByPID(ProcID: Cardinal): Boolean;
function MyWindowsExit(uFlags: Cardinal): Boolean;
function MyFileSize(Adress: String): Cardinal;
function GetWindowsError: String;
function SetPriority(Value: Cardinal): Boolean;
function MyLoadLibrary(pPath: Pchar; var libHandle: Cardinal): Boolean;
function MyGetProcAddress(var libHandle: Cardinal; var pProcPointer: Pointer; pProcName: PChar): Boolean;
function LunchProgram(Path: PChar = nil; WaitTermination: Boolean = false): Boolean;
//=============================================================================>
//============================= Раздел реализации =============================>
//=============================================================================>
implementation
// Загрузка библиотеки с проверкой >
function MyLoadLibrary(pPath: Pchar; var libHandle: Cardinal): Boolean;
begin
if Assigned(pPath) then
if FileExists(pPath) then
libHandle:=LoadLibrary(pPath) else
libHandle:=INVALID_HV else
libHandle:=INVALID_HV;
Result:=libHandle <> INVALID_HV;
end;
// Загрузка точки входа в функцию из библиотеки >
function MyGetProcAddress(var libHandle: Cardinal; var pProcPointer: Pointer; pProcName: PChar): Boolean;
begin
if libHandle = INVALID_HV then
pProcPointer:=nil else
pProcPointer:=GetProcAddress(libHandle,pProcName);
Result:=Assigned(pProcPointer);
end;
// Запустить программу по указанному адресу... >
function LunchProgram(Path: PChar = nil; WaitTermination: Boolean = false): Boolean;
var SI:TStartupInfo; PI:TProcessInformation; a1:Cardinal;
begin
a1:=SizeOf(SI);
FillWithZero(@SI,a1);
SI.cb:=a1;
if Path = nil then
Path:=PChar(GetExeName);
Result:=CreateProcess(nil,Path,nil,nil,false,Zero,nil,nil,SI,PI);
if Result and WaitTermination then
WaitforSingleObject(PI.hProcess,INFINITE); //while GetExitCodeProcess(PI.hProcess,a1) and (a1 = STILL_ACTIVE) do // Sleep(_128);
end;
// Обновить время... >
procedure UpDatePMyTime(var pData: PMyTime);
var v1:TSystemTime;
begin
if not Assigned(pData) then
New(pData);
GetSystemTime(v1);
with pData^ do begin
wYear:=v1.wYear;
bMonth:=v1.wMonth;
bDay:=v1.wDay;
bHour:=v1.wHour;
bMinute:=v1.wMinute;
bSecond:=v1.wSecond; end;;
end;
// Установка приоритета для текщего процесса >
function SetPriority(Value: Cardinal): Boolean;
begin
case Value of
Zero: Result:=SetPriorityClass(GetCurrentProcess,IDLE_PRIORITY_CLASS) and SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_IDLE);
One: Result:=SetPriorityClass(GetCurrentProcess,IDLE_PRIORITY_CLASS) and SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_LOWEST);
Two: Result:=SetPriorityClass(GetCurrentProcess,NORMAL_PRIORITY_CLASS) and SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_BELOW_NORMAL);
Three: Result:=SetPriorityClass(GetCurrentProcess,NORMAL_PRIORITY_CLASS) and SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_NORMAL);
Four: Result:=SetPriorityClass(GetCurrentProcess,NORMAL_PRIORITY_CLASS) and SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_ABOVE_NORMAL);
Five: Result:=SetPriorityClass(GetCurrentProcess,REALTIME_PRIORITY_CLASS) and SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_HIGHEST);
Six: Result:=SetPriorityClass(GetCurrentProcess,REALTIME_PRIORITY_CLASS) and SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_TIME_CRITICAL);
else Result:=false; end;
end;
// Текстовая форма последней ошибки в винде >
function GetWindowsError: String;
var p1:Pointer;
begin
GetMem(p1,mnKB);
if FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,GetLastError,GetKeyboardLayout(Zero),p1,mnKB,nil) = Zero then
Result:=UnKnownError else
Result:=String(p1^);
FreeMem(p1,mnKB);
end;
// Узнать размер файла в байтах >
function MyFileSize(Adress: String): Cardinal;
var a1:Cardinal; a2:TWin32FindData;
begin
a1:=FindFirstFile(PChar(Adress),a2);
if a1 = INVALID_HANDLE_VALUE then
Result:=Zero else begin
Result:=a2.nFileSizeLow;
FindClose(a1); end;
end;
// Создает "BAT"-файл который хочет что-то стереть >
procedure DeleteByBat(Adress: String);
var F:TextFile; s1:String; ProcessInformation:TProcessInformation; StartupInformation:TStartupInfo;
begin
if FileExists(Adress) then begin
s1:=Adress + '.bat'; // создаём бат-файл в директории приложения >
AssignFile(F,s1); // открываем и записываем в файл >
Rewrite(F); // Перезаписываем файл >
Writeln(F,':try'); // Это метка с которой начинается >
Writeln(F,'del "' + Adress + '"'); // удаление по адресу >
Writeln(F,'if exist "' + Adress + '"' + ' goto try'); // если всееще этот адрес доступен >
Writeln(F,'del "' + s1 + '"'); // возвращаемся к метке >
CloseFile(F); // Закрываем файл >
FillChar(StartUpInformation,SizeOf(StartUpInformation),$00);
StartUpInformation.dwFlags:=STARTF_USESHOWWINDOW;
StartUpInformation.wShowWindow:=SW_HIDE;
if CreateProcess(nil,PChar(s1),nil,nil,False,IDLE_PRIORITY_CLASS,nil,nil,StartUpInformation,ProcessInformation) then begin // Включаем рубатель "втихушку" >
CloseHandle(ProcessInformation.hThread);
CloseHandle(ProcessInformation.hProcess); end; end;
end;
// Для завершения сессии "Винды" >
function MyWindowsExit(uFlags: Cardinal): Boolean;
begin
if ActivateMyPrivilege(One,true) then begin
Result:=ExitWindowsEx(uFlags,Zero);
ActivateMyPrivilege(One,false) end else
Result:=false;
end;
// Остановить процесс привелегией отладки >
function TerminateProcByPID(ProcID: Cardinal): Boolean;
var a1:Cardinal;
begin
if ActivateMyPrivilege(mniDebug,true) then begin
a1:=OpenProcess(PROCESS_TERMINATE,false,ProcID); // Получаем дескриптор процесса для его завершения >
if a1 <> Zero then begin
Result:=TerminateProcess(a1,Cardinal(-One)); // Завершаем процесс >
CloseHandle(a1); end else
Result:=false;
ActivateMyPrivilege(mniDebug,false); end else
Result:=false;
end;
// Включить некоторую привелегию >
function ActivateMyPrivilege(nType: Cardinal; State: Boolean): Boolean;
begin
case nType of
mniDebug: Result:=GetMyPrivilege(mnDebug,State);
mniShutdown: Result:=GetMyPrivilege(mnShutdown,State);
else Result:=false; end;
end;
// Получить привелегию >
function GetMyPrivilege(PrivilegeName: String; aEnabled: Boolean): boolean;
var TPPrev,TP:TTokenPrivileges; Token,dwRetLen: Cardinal;
begin
if OpenProcessToken(GetCurrentProcess,TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY,Token) then begin
TP.PrivilegeCount:=One;
if LookupPrivilegeValue(nil,PChar(PrivilegeName),TP.Privileges[Zero].LUID) then begin
if aEnabled then
TP.Privileges[Zero].Attributes:=SE_PRIVILEGE_ENABLED else
TP.Privileges[Zero].Attributes:=Zero;
dwRetLen:=Zero;
Result:=AdjustTokenPrivileges(Token,false,TP,SizeOf(TPPrev),TPPrev,dwRetLen) and (GetLastError = NO_ERROR); end else
Result:=false;
CloseHandle(Token); end else
Result:=false;
end;
// Узнаем чья сейчас сессия винды >
function GetWindowsUserName: String;
var s1:String; c1:Cardinal;
begin
c1:=ByteMax; // Максимум длинны имени пользователя >
SetLength(s1,c1); // Устанавливаем принятую длинну >
if GetUserName(PChar(s1),c1) then // Если шото с именем перепало, то >
Result:=Copy(s1,One,c1 - One) else // запоминаем это имя >
Result:=EmptyString; // нет - тоже запоминаем >
end;
// Для смены экранного режима >
function ChangeScreenSet(Width,Height,ColorDepth,Frequency: Cardinal): Boolean;
var ScreenSet: TDeviceMode;
begin
FillWithZero(@ScreenSet,SizeOf(TDeviceMode)); // Все значения заполняем нулями >
with ScreenSet do try
dmSize:=SizeOf(TDeviceMode);
if Width > Zero then begin // Если указана ширина >
dmPelsWidth:=Width;
dmFields:=dmFields or DM_PELSWIDTH; end;
if Height > Zero then begin // Высота >
dmPelsHeight:=Height;
dmFields:=dmFields or DM_PELSHEIGHT; end;
if ColorDepth > Zero then begin // глубина цвета >
dmBitsPerPel:=ColorDepth;
dmFields:=dmFields or DM_BITSPERPEL; end;
if Frequency > Zero then begin // Частота обновления/развертки экрана >
dmDisplayFrequency:=Frequency;
dmFields:=dmFields or DM_DISPLAYFREQUENCY; end;
if dmFields = Zero then
Result:=true else
Result:=ChangeDisplaySettings(ScreenSet,CDS_FULLSCREEN) = DISP_CHANGE_SUCCESSFUL; except
Result:=false; end;
end;
// Вернуть в исходные (по данным регистра) настройки экрана >
function ChangeScreenSetBack: Boolean;
begin
Result:=ChangeDisplaySettings(DevMode(nil^),Zero) = DISP_CHANGE_SUCCESSFUL;
end;
// Получаем "держак" к кнопке "пуск" >
function GetStartButtonHandle: Cardinal;
begin
Result:=FindWindow('Shell_TrayWnd',nil);
if Result <> mgl_Zero then
Result:=FindWindowEx(Result,mgl_Zero,'Button',nil);
end;
// Запустить функцию в отдельном потоке >
function RunThreadedFunction(pData: PMyTHreadedFunction): Boolean;
var mThreadID:Cardinal;
begin
Result:=CreateThread(nil,Zero,pData,nil,Zero,mThreadID) <> Zero;
end;
// Выключить монитор >
function SetMonitorState(State: Boolean): Boolean;
begin
if State then
Result:=SendMessage(GetStartButtonHandle,WM_SYSCOMMAND,SC_MONITORPOWER,One) <> mgl_Zero else
Result:=SendMessage(GetStartButtonHandle,WM_SYSCOMMAND,SC_MONITORPOWER,mgl_Zero) <> mgl_Zero;
end;
// Задать вопрос: "Да или Нет?" >
function AskQuestionYesNo(sHeader,sValue: String): Boolean;
begin
Result:=MessageBox(Zero,PChar(sValue),PChar(sHeader),mb_YesNo + mb_IconQuestion + mb_TaskModal) = idYes;
end;
// Просто, тупо - показать сообщение >
procedure ShowMessage(Value: String); overload;
begin
MessageBox(Zero,PChar(Value),mnMessageRus,MB_OK);
end;
// Показать "цифровое" сообщение >
procedure ShowMessage(Value: Integer); overload;
begin
MessageBox(Zero,PChar(IntToStr(Value)),mnMessageRus,MB_OK);
end;
// Это всё-равно спиЖЖэно, так-что пока рана оправдываться 8(( >
function FindMatchingFile(pData: PSearchRec): Cardinal;
var LocalFileTime: TFileTime;
begin
with pData^ do begin
while FindData.dwFileAttributes and ExcludeAttr <> Null do
if not FindNextFile(FindHandle,FindData) then begin
Result:=GetLastError;
Exit; end;
FileTimeToLocalFileTime(FindData.ftLastWriteTime,LocalFileTime);
FileTimeToDosDateTime(LocalFileTime,LongRec(Time).Hi,LongRec(Time).Lo);
Size:=FindData.nFileSizeLow;
Attr:=FindData.dwFileAttributes;
Name:=FindData.cFileName; end;
Result:=Zero;
end;
// Есть-ли такой файл или каталог ? >
function FileExists(Path: String): Boolean; overload;
var a1:Cardinal; a2:Integer; a3:TWin32FindData; a4:TFileTime;
begin
a1:=FindFirstFile(PChar(Path),a3);
if a1 = INVALID_HANDLE_VALUE then
Result:=false else begin
FindClose(a1);
FileTimeToLocalFileTime(a3.ftLastWriteTime,a4);
if FileTimeToDosDateTime(a4,TLPack(a2).Hi,TLPack(a2).Lo) then
Result:=a2 <> - One else
Result:=false; end;
end;
// Ещё версия 8) >
function FileExists(pPath: PChar): Boolean; overload;
var a1:Cardinal; a2:Integer; a3:TWin32FindData; a4:TFileTime;
begin
a1:=FindFirstFile(pPath,a3);
if a1 = INVALID_HANDLE_VALUE then
Result:=false else begin
FindClose(a1);
FileTimeToLocalFileTime(a3.ftLastWriteTime,a4);
if FileTimeToDosDateTime(a4,TLPack(a2).Hi,TLPack(a2).Lo) then
Result:=a2 <> - One else
Result:=false; end;
end;
// Размер файла >
function FileSize(pPath: PChar): Int64;
var a1:Cardinal; a2:Integer; a3:TWin32FindData; a4:TFileTime;
begin
a1:=FindFirstFile(pPath,a3);
if a1 = INVALID_HANDLE_VALUE then
Result:=Zero else begin
FindClose(a1);
FileTimeToLocalFileTime(a3.ftLastWriteTime,a4);
if FileTimeToDosDateTime(a4,TLPack(a2).Hi,TLPack(a2).Lo) then
if a2 <> - One then
Result:=a3.nFileSizeLow or a3.nFileSizeHigh shl _32 else
Result:=Zero else
Result:=Zero; end;
end;
// Загрузить отображением >
function LoadFromMappedFile(pPath: PChar; var pData: Pointer; var Size: Cardinal): Boolean;
var c1,c2,c3,c4:Cardinal; p1:Pointer;
begin
c1:=CreateFile(pPath,GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,Zero);
if c1 = Zero then
Result:=false else begin
c3:=GetFileSize(c1,@c4); // Странный "nil" >
if c3 = Zero then begin
pData:=nil;
Size:=Zero;
Result:=true; end else begin
c2:=CreateFileMapping(c1,nil,PAGE_READONLY,Zero,c3,@c4);
if c2 = Zero then
Result:=false else begin
p1:=MapViewOfFile(c2,FILE_MAP_READ,Zero,Zero,c3);
if Assigned(p1) then try
GetMem(pData,c3);
Size:=c3;
Move(p1^,pData^,c3);
Result:=UnMapViewOfFile(p1); except
Result:=false; end else
Result:=false;
CloseHandle(c2); end; end;
CloseHandle(c1); end;
end;
// Сохранить отображением >
function SaveToMappedFile(pPath: PChar; pData: Pointer; Size: Cardinal): Boolean;
var c1,c2:Cardinal; p1:Pointer;
begin
c1:=CreateFile(pPath,GENERIC_WRITE,Zero,nil,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,Zero);
if c1 = Zero then
Result:=false else begin
c2:=CreateFileMapping(c1,nil,PAGE_READWRITE,Zero,Size,nil);
if c2 = Zero then
Result:=false else begin
p1:=MapViewofFile(c2,FILE_MAP_WRITE,Zero,Zero,Size);
if Assigned(p1) then try
Move(pData^,p1^,Size);
Result:=UnMapViewOfFile(p1); except
Result:=false; end else
Result:=false;
CloseHandle(c2); end;
CloseHandle(c1); end;
end;
// >
procedure BeeBeep;
begin
Beep(1900,100);
end;
//=============================================================================>
//================================= Конец модуля ==============================>
//=============================================================================>
end.
|
unit Song_GeneratedByXMLDataBinding;
interface
uses xmldom, XMLDoc, XMLIntf;
type
{ Forward Decls }
IXMLArtists = interface;
IXMLArtist_art = interface;
IXMLName_art = interface;
IXMLSong = interface;
{ IXMLArtists }
IXMLArtists = interface(IXMLNodeCollection)
['{F208170C-788F-4E50-94CD-F596B8CDA45D}']
{ Property Accessors }
function Get_Artist(Index: Integer): IXMLArtist_art;
{ Methods & Properties }
function Add: IXMLArtist_art;
function Insert(const Index: Integer): IXMLArtist_art;
property Artist[Index: Integer]: IXMLArtist_art read Get_Artist; default;
end;
{ IXMLArtist_art }
IXMLArtist_art = interface(IXMLNode)
['{B1694B01-C974-4E0E-9CC8-8B0CFBB2FDC5}']
{ Property Accessors }
function Get_BirthYear: UnicodeString;
function Get_Name: IXMLName_art;
procedure Set_BirthYear(Value: UnicodeString);
{ Methods & Properties }
property BirthYear: UnicodeString read Get_BirthYear write Set_BirthYear;
property Name: IXMLName_art read Get_Name;
end;
{ IXMLName_art }
IXMLName_art = interface(IXMLNode)
['{59B4A667-561F-4C38-A11E-69DB14BD398D}']
{ Property Accessors }
function Get_Title: UnicodeString;
function Get_FirstName: UnicodeString;
function Get_LastName: UnicodeString;
procedure Set_Title(Value: UnicodeString);
procedure Set_FirstName(Value: UnicodeString);
procedure Set_LastName(Value: UnicodeString);
{ Methods & Properties }
property Title: UnicodeString read Get_Title write Set_Title;
property FirstName: UnicodeString read Get_FirstName write Set_FirstName;
property LastName: UnicodeString read Get_LastName write Set_LastName;
end;
{ IXMLSong }
IXMLSong = interface(IXMLNode)
['{E5BCDD2D-73DD-44A9-9562-CE39B39EBFF0}']
{ Property Accessors }
function Get_Title: UnicodeString;
function Get_Year: UnicodeString;
function Get_Artists: IXMLArtists;
procedure Set_Title(Value: UnicodeString);
procedure Set_Year(Value: UnicodeString);
{ Methods & Properties }
property Title: UnicodeString read Get_Title write Set_Title;
property Year: UnicodeString read Get_Year write Set_Year;
property Artists: IXMLArtists read Get_Artists;
end;
{ Forward Decls }
TXMLArtists = class;
TXMLArtist_art = class;
TXMLName_art = class;
TXMLSong = class;
{ TXMLArtists }
TXMLArtists = class(TXMLNodeCollection, IXMLArtists)
protected
{ IXMLArtists }
function Get_Artist(Index: Integer): IXMLArtist_art;
function Add: IXMLArtist_art;
function Insert(const Index: Integer): IXMLArtist_art;
public
procedure AfterConstruction; override;
end;
{ TXMLArtist_art }
TXMLArtist_art = class(TXMLNode, IXMLArtist_art)
protected
{ IXMLArtist_art }
function Get_BirthYear: UnicodeString;
function Get_Name: IXMLName_art;
procedure Set_BirthYear(Value: UnicodeString);
public
procedure AfterConstruction; override;
end;
{ TXMLName_art }
TXMLName_art = class(TXMLNode, IXMLName_art)
protected
{ IXMLName_art }
function Get_Title: UnicodeString;
function Get_FirstName: UnicodeString;
function Get_LastName: UnicodeString;
procedure Set_Title(Value: UnicodeString);
procedure Set_FirstName(Value: UnicodeString);
procedure Set_LastName(Value: UnicodeString);
end;
{ TXMLSong }
TXMLSong = class(TXMLNode, IXMLSong)
protected
{ IXMLSong }
function Get_Title: UnicodeString;
function Get_Year: UnicodeString;
function Get_Artists: IXMLArtists;
procedure Set_Title(Value: UnicodeString);
procedure Set_Year(Value: UnicodeString);
public
procedure AfterConstruction; override;
end;
{ Global Functions }
function GetSong(Doc: IXMLDocument): IXMLSong;
function LoadSong(const FileName: string): IXMLSong;
function NewSong: IXMLSong;
const
TargetNamespace = '';
implementation
{ Global Functions }
function GetSong(Doc: IXMLDocument): IXMLSong;
begin
Result := Doc.GetDocBinding('Song', TXMLSong, TargetNamespace) as IXMLSong;
end;
function LoadSong(const FileName: string): IXMLSong;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('Song', TXMLSong, TargetNamespace) as IXMLSong;
end;
function NewSong: IXMLSong;
begin
Result := NewXMLDocument.GetDocBinding('Song', TXMLSong, TargetNamespace) as IXMLSong;
end;
{ TXMLArtists }
procedure TXMLArtists.AfterConstruction;
begin
RegisterChildNode('Artist', TXMLArtist_art);
ItemTag := 'Artist';
ItemInterface := IXMLArtist_art;
inherited;
end;
function TXMLArtists.Get_Artist(Index: Integer): IXMLArtist_art;
begin
Result := List[Index] as IXMLArtist_art;
end;
function TXMLArtists.Add: IXMLArtist_art;
begin
Result := AddItem(-1) as IXMLArtist_art;
end;
function TXMLArtists.Insert(const Index: Integer): IXMLArtist_art;
begin
Result := AddItem(Index) as IXMLArtist_art;
end;
{ TXMLArtist_art }
procedure TXMLArtist_art.AfterConstruction;
begin
RegisterChildNode('Name', TXMLName_art);
inherited;
end;
function TXMLArtist_art.Get_BirthYear: UnicodeString;
begin
Result := AttributeNodes['BirthYear'].Text;
end;
procedure TXMLArtist_art.Set_BirthYear(Value: UnicodeString);
begin
SetAttribute('BirthYear', Value);
end;
function TXMLArtist_art.Get_Name: IXMLName_art;
begin
Result := ChildNodes['Name'] as IXMLName_art;
end;
{ TXMLName_art }
function TXMLName_art.Get_Title: UnicodeString;
begin
Result := ChildNodes['Title'].Text;
end;
procedure TXMLName_art.Set_Title(Value: UnicodeString);
begin
ChildNodes['Title'].NodeValue := Value;
end;
function TXMLName_art.Get_FirstName: UnicodeString;
begin
Result := ChildNodes['FirstName'].Text;
end;
procedure TXMLName_art.Set_FirstName(Value: UnicodeString);
begin
ChildNodes['FirstName'].NodeValue := Value;
end;
function TXMLName_art.Get_LastName: UnicodeString;
begin
Result := ChildNodes['LastName'].Text;
end;
procedure TXMLName_art.Set_LastName(Value: UnicodeString);
begin
ChildNodes['LastName'].NodeValue := Value;
end;
{ TXMLSong }
procedure TXMLSong.AfterConstruction;
begin
RegisterChildNode('Artists', TXMLArtists);
inherited;
end;
function TXMLSong.Get_Title: UnicodeString;
begin
Result := ChildNodes['Title'].Text;
end;
procedure TXMLSong.Set_Title(Value: UnicodeString);
begin
ChildNodes['Title'].NodeValue := Value;
end;
function TXMLSong.Get_Year: UnicodeString;
begin
Result := ChildNodes['Year'].Text;
end;
procedure TXMLSong.Set_Year(Value: UnicodeString);
begin
ChildNodes['Year'].NodeValue := Value;
end;
function TXMLSong.Get_Artists: IXMLArtists;
begin
Result := ChildNodes['Artists'] as IXMLArtists;
end;
end.
|
unit DataBase;
interface
uses classes, sysutils, db, adoDb, IniFiles;
type
TTrybTransakcji = (DbRead, dbReadWrite, dbNone);
TResultHandle = class(TADOQuery)
public
constructor CreateSQL(ASQL: string); overload;
constructor CreateSQL(Asql: TStrings); overload;
constructor create(AOwner: TComponent = nil); override;
destructor Destroy; override;
procedure InvokeSql;
procedure ExecuteSql;
procedure Clear;
function ExecuteDDL(ADDL: string): Boolean;
procedure Add(AString: WideString); overload;
procedure Add(Alinie: TStrings); overload;
end;
TDataBase = class(TObject)
private
FSesjaId: string;
FConnection: TADOConnection;
Flist: TList; //Lista Result Handle
FFolderEksport: string;
procedure ZwolnijResultHandle;
public
czyTransakcja: boolean;
constructor Create;
destructor Destroy; override;
function StartDataBase(Ahaslo: string): boolean;
procedure BeginTransaction();
procedure Rollback;
procedure Commit;
function MaxId(Tabela: string; AliczbaLock: integer = 1): integer;
procedure RejestrujResultHandle(Aresult: TResultHandle);
procedure WyrejestrujResultHandle(Aresult: TResultHandle);
function InicjujKatalogEksportowy: boolean;
property
foldereksport: string read FFolderEksport;
end;
TConnectionString = class(TObject)
private
FIniFile: TIniFile;
function GetDatabaseName: string;
function GetServerName: string;
function GetdatabaseUserPassword: string;
function GetdatabaseUser: string;
function GetProviderName:string;
public
constructor Create;
destructor destroy; override;
function GetConnectionString(AHaslo: string): string;
end;
var
GdataBase: TDataBase;
implementation
uses Funkcje, stale, Zmienne, FormaMain;
const
//Provider=PostgreSQL OLE DB Provider
CconnectionString = '%s;Password=%s;User ID=%s;Data Source=%s;Location=%s;Extended Properties=''''';
CLiczbaLP = 15000;
CTimeOUT = 3600;
resourcestring
cpdf = 'pdf';
//####################################################################################################################
{ TDataBase }
//####################################################################################################################
procedure TDataBase.BeginTransaction();
begin
if not czyTransakcja then begin
FConnection.BeginTrans;
czyTransakcja := true;
end else begin
raise Exception.Create('Nie można otworzyć więcej transakcji');
end;
end;
//####################################################################################################################
procedure TDataBase.Commit;
begin
try
FConnection.CommitTrans;
czyTransakcja := false;
except
raise Exception.Create('Nie można zapisać transakcji');
end;
end;
//####################################################################################################################
constructor TDataBase.Create;
var
xGuid: TGUID;
begin
FConnection := TADOConnection.Create(nil);
czyTransakcja := false;
Flist := TList.Create;
CreateGUID(xGuid);
FSesjaId := GUIDToString(xGuid);
FSesjaId := StringReplace(FSesjaId, '{', '', [rfIgnoreCase, rfReplaceAll]);
FSesjaId := StringReplace(FSesjaId, '}', '', [rfIgnoreCase, rfReplaceAll]);
FSesjaId := StringReplace(FSesjaId, '-', '', [rfIgnoreCase, rfReplaceAll]);
FSesjaId := format('1x%s', [FSesjaId]);
end;
//####################################################################################################################
destructor TDataBase.Destroy;
begin
FConnection.Close;
FConnection.Free;
ZwolnijResultHandle;
Flist.Free;
inherited;
end;
//####################################################################################################################
//cpdf
function TDataBase.InicjujKatalogEksportowy: boolean;
begin
result := true;
try
FFolderEksport := IncludeTrailingPathDelimiter(PodajkatalogMojeDokumenty(0)) + cpdf;
if not DirectoryExists(FFolderEksport) then begin
result := CreateDir(FFolderEksport);
end;
except
result := false;
end;
end;
function TDataBase.MaxId(Tabela: string; AliczbaLock: integer): integer;
var
xZapytanie: string;
xDataSet: TResultHandle;
id: integer;
begin
xDataSet := TResultHandle.Create;
xZapytanie := 'Select IDMAX as id from IDMAX where NazwaTabeli=' + QuotedStr(Tabela);
xDataSet.Add(xZapytanie);
xDataSet.InvokeSQL;
id := xDataSet.fieldbyname('id').AsInteger;
if id = 0 then begin
xDataSet.Clear;
xZapytanie := 'Select MAX(' + 'id' + Tabela + ') as IDMAX from ' + Tabela + ' ';
xDataSet.Add(xZapytanie);
xDataSet.InvokeSQL;
id := xDataSet.fieldByName('IDMAX').AsInteger;
end;
if ((id = 0) or (id < CLiczbaLP)) then begin
id := CLiczbaLP;
end else begin
inc(id);
end;
result := id;
xZapytanie := 'Delete from IDMAX where NazwaTabeli=' + QuotedStr(Tabela);
xDataSet.Clear;
xDataSet.Add(xZapytanie);
xDataSet.ExecuteSQL;
dec(AliczbaLock);
xZapytanie := 'Insert into IDMAX(NazwaTabeli,IDMAX) values (' + QuotedStr(Tabela) + ',' + IntToStr(id + AliczbaLock) + ')';
xDataSet.Clear;
xDataSet.Add(xZapytanie);
xDataSet.ExecuteSQL;
xDataSet.Free;
end;
//####################################################################################################################
procedure TDataBase.RejestrujResultHandle(Aresult: TResultHandle);
begin
Flist.Add(Aresult);
end;
//####################################################################################################################
procedure TDataBase.Rollback;
begin
try
FConnection.RollbackTrans;
czyTransakcja := false;
except
raise Exception.Create('Nie można zamknąć transakcji');
end;
end;
//####################################################################################################################
function TDataBase.StartDataBase(Ahaslo: string): boolean;
var
xCS: TConnectionString;
xWersjaOK: Boolean;
begin
with FConnection do begin
xCS := TConnectionString.Create;
ConnectionString := xCS.GetConnectionString(AHaslo);
CommandTimeout := CTimeOUT;
//DefaultDataBase := xCS.GetDatabaseName;
xCS.Free;
LoginPrompt := false;
//IsolationLevel := ilReadCommitted;
//Mode := cmReadWrite;
CursorLocation := clUseServer;
try
Open;
Result := True;
except
raise Exception.Create('Brak połączenia z bazą danych.');
end;
if (Result) then begin
with TResultHandle.CreateSQL('select ltrim(Rtrim(wersjaBazy)) from System') do begin
InvokeSQL;
if recordCount > 0 then begin
xWersjaOK := (Fields[0].AsString = PodajWersjeBazy);
end else begin
xWersjaOK := false;
end;
Close;
Free;
end;
if (not xWersjaOK) then begin
Close;
raise Exception.Create(Format('Błędna wersja bazy danych! Wymagana jest wersja: %s.', [PodajWersjeBazy]));
end;
end;
end;
end;
//####################################################################################################################
procedure TDataBase.WyrejestrujResultHandle(Aresult: TResultHandle);
begin
Flist.Remove(Aresult);
Flist.Pack;
end;
//####################################################################################################################
procedure TDataBase.ZwolnijResultHandle;
var
i: integer;
begin
for I := Flist.Count - 1 downto 0 do begin
try
TResultHandle(Flist.items[i]).Free;
except
end;
end;
end;
//####################################################################################################################
{ TResultHandle }
//####################################################################################################################
procedure TResultHandle.Add(AString: WideString);
begin
Self.SQL.Add(AString);
end;
//####################################################################################################################
procedure TResultHandle.Add(Alinie: TStrings);
begin
self.SQL.AddStrings(Alinie);
end;
//####################################################################################################################
procedure TResultHandle.Clear;
begin
if self.Active then self.Close;
self.SQL.Clear;
end;
//####################################################################################################################
constructor TResultHandle.Create;
begin
inherited;
self.Connection := GDataBase.FConnection;
end;
//####################################################################################################################
constructor TResultHandle.CreateSQL(Asql: TStrings);
begin
create;
self.Add(Asql);
self.Connection := GDataBase.FConnection;
end;
//####################################################################################################################
constructor TResultHandle.CreateSQL(ASQL: string);
begin
create;
Self.Add(ASQL);
self.Connection := GDataBase.FConnection;
end;
//####################################################################################################################
destructor TResultHandle.Destroy;
begin
GDataBase.WyrejestrujResultHandle(self);
inherited;
end;
//####################################################################################################################
function TResultHandle.ExecuteDDL(ADDL: string): Boolean;
begin
Result := True;
try
with self do begin
Clear;
self.Prepared := False;
self.SQL.Text := ADDL;
self.ExecSQL;
Self.Close;
end;
except
Result := False;
end;
end;
//####################################################################################################################
procedure TResultHandle.ExecuteSql;
begin
try
self.ExecSQL;
except
raise Exception.Create('Błąd wykonania zapytania !');
end;
end;
//####################################################################################################################
procedure TResultHandle.InvokeSql;
begin
try
self.CursorType := ctOpenForwardOnly;
self.Prepared := True;
self.Open;
except
raise Exception.Create('Błąd wykonania zapytania !');
end;
end;
//####################################################################################################################
{ TConnectionString }
//####################################################################################################################
//CconnectionString ='Provider=PostgreSQL OLE DB Provider;Password=%s;User ID=%s;Data Source=%s;Location=%s;Extended Properties=''''';
constructor TConnectionString.Create;
var
xPath: string;
begin
xPath := PodajPathIniFile();
FIniFile := TIniFile.Create(xPath);
end;
//####################################################################################################################
destructor TConnectionString.destroy;
begin
FIniFile.Free;
inherited;
end;
//####################################################################################################################
// Provider=PostgreSQL OLE DB Provider;Password=sql;User ID=postgres;Data Source=localhost;Location=test;Extended Properties=""
function TConnectionString.GetConnectionString(AHaslo: string): string;
var
xDatabaseName: string;
xServerName: string;
xUserName: string;
xUserPass: string;
xConnectionString: string;
begin
xConnectionString := EmptyStr;
xDatabaseName := GetDatabaseName;
xServerName := GetServerName;
xUserName := GetdatabaseUser;
xUserPass := GetdatabaseUserPassword;
if (xDatabaseName <> EmptyStr) and (xServerName <> EmptyStr) and (xUserName <> EmptyStr) and (xUserPass <> EmptyStr) then begin
if trim(AHaslo) = '' then begin
xConnectionString := Format(CconnectionString, [GetProviderName, xUserPass, xUserName, xServerName, xDatabaseName]);
end else begin
xConnectionString := Format(CconnectionString, [GetProviderName, AHaslo, xUserName, xServerName, xDatabaseName]);
end;
end;
result := xConnectionString;
end;
//####################################################################################################################
function TConnectionString.GetDatabaseName: string;
begin
result := FIniFile.ReadString(CSekcjaConnect, CBASENAME, '');
end;
//####################################################################################################################
function TConnectionString.GetdatabaseUser: string;
begin
result := FIniFile.ReadString(CSekcjaConnect, CUSERNAME, '');
end;
//####################################################################################################################
function TConnectionString.GetdatabaseUserPassword: string;
begin
result := FIniFile.ReadString(CSekcjaConnect, CUSERPASS, '');
end;
//####################################################################################################################
function TConnectionString.GetProviderName: string;
begin
result := FIniFile.ReadString(CSekcjaConnect, CPROVIDER, 'Provider=PostgreSQL OLE DB Provider');
end;
//####################################################################################################################
function TConnectionString.GetServerName: string;
var
xIniFile: TIniFile;
xNazwa: string;
begin
xIniFile := TIniFile.Create(PodajPathIniFile);
xNazwa := xIniFile.ReadString(CSekcjaConnect, CSerwerName, '');
xIniFile.Free;
if Trim(xNazwa) = '' then begin
xNazwa := 'localhost';
end;
result := xNazwa;
end;
//####################################################################################################################
end.
|
unit BaseEndpoint;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpjson, jsonparser, fphttpclient, opensslsockets;
type
IJSONData = interface(IInterface) ['{68FF4A2E-4A31-4AA7-9E3D-4F06F035F85D}']
function GetJSONData: string;
procedure SetJSONData(AValue: string);
end;
IHTTPClient = interface(IInterface) ['{C6304D20-B428-49A0-B8A9-9490A4A5E271}']
function GetRequest(AValue: string): string;
end;
function NewJSON: IJSONData;
function NewHTTPClient: IHTTPClient;
const
K_HOST = 'https://api.spacexdata.com/v4/';
implementation
type
{ TJSON }
TJSON = class(TInterfacedObject, IJSONData)
private
FJSONData: TJSONData;
function GetJSONData: string;
procedure SetJSONData(AValue: string);
public
destructor Destroy; override;
end;
{ THTTPClient }
THTTPClient = class(TInterfacedObject, IHTTPClient)
private
FHttpClient: TFPCustomHTTPClient;
function GetRequest(AValue: string): string;
public
constructor Create;
destructor Destroy; override;
end;
function NewJSON: IJSONData;
begin
Result := TJSON.Create;
end;
function NewHTTPClient: IHTTPClient;
begin
Result := THTTPClient.Create;
end;
{ THTTPClient }
function THTTPClient.GetRequest(AValue: string): string;
begin
WriteLn(AValue);
Result := FHttpClient.Get(SysUtils.ConcatPaths([K_HOST, AValue]));
end;
constructor THTTPClient.Create;
begin
FHttpClient := TFPCustomHTTPClient.Create(nil);
end;
destructor THTTPClient.Destroy;
begin
FHttpClient.Destroy;
inherited Destroy;
end;
{ TJSON }
function TJSON.GetJSONData: string;
begin
Result := FJSONData.FormatJSON();
end;
procedure TJSON.SetJSONData(AValue: string);
begin
FJSONData := GetJSON(AValue);
end;
destructor TJSON.Destroy;
begin
FJSONData.Free;
inherited Destroy;
end;
end.
|
unit GraphicsVolumeBar;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Winapi.Windows,
Winapi.GDIPAPI, Winapi.GDIPOBJ;
type
TGraphicsVolumeBar = class(TCustomControl)
private
{ Private declarations }
FBak: TGPBitmap;
FBar: TGPBitmap;
FVol: Integer;
protected
{ Protected declarations }
procedure Paint; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
procedure LoadImages(Bk, Bar: TGPBitmap);
procedure SetVolume(Value: Integer);
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TGraphicsVolumeBar]);
end;
constructor TGraphicsVolumeBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Self.Width := 286;
Self.Height := 22;
end;
procedure TGraphicsVolumeBar.Paint();
var
Len : Integer;
Graphics: TGPGraphics;
begin
if (FBak = nil) then Exit;
if (FBar = nil) then Exit;
Len := (280 * FVol) div 100;
Graphics := TGPGraphics.Create(Self.Canvas.Handle);
Graphics.DrawImage(FBak, 0, 0, 286, 22);
Graphics.DrawImage(FBar, 3, 3, 0, 0, Len, 16, UnitPixel);
Graphics.Free();
end;
procedure TGraphicsVolumeBar.LoadImages(Bk, Bar: TGPBitmap);
begin
FBak := Bk;
FBar := Bar;
end;
procedure TGraphicsVolumeBar.SetVolume(Value: Integer);
begin
FVol := Value;
Self.Invalidate();
end;
end.
|
unit uCmdServer;
interface
uses Classes,IdTCPServer;
const
ndxHostName=-1; ndxHostIPAddress=-2; ndxHostIPPort=-3;
type
TcmdServer=class(TIdTCPServer)
private
fsHostName,fsHostIPAddress,fsHostIPPort:AnsiString;
function GetString(const ndx:integer):AnsiString;
protected
// function DoExecute(aThread:TIdPeerThread): boolean; override;
procedure SetActive(b:boolean); override;
procedure SetDefaultPort(const i32:integer); override;
public
constructor Create(aOwner:TComponent); override;
destructor Destroy; override;
property HostName:AnsiString index ndxHostName read GetString; // имя компьютера
property HostIPAddress:AnsiString index ndxHostIPAddress read GetString; // IP-адрес
property HostIPPort:AnsiString index ndxHostIPPort read GetString; // IP-порт
end;
implementation
uses SysUtils,uUtilsFunctions;
{$BOOLEVAL OFF}
{$RANGECHECKS OFF}
{$OVERFLOWCHECKS OFF}
const wDefaultIPPort=12344;
iMaxConnections=0; // максимальное количество одновременно соединённых клиентов
sGreeting='';
sMaxConnection='ошибка соединения, максимальное количество клиентов на сервере';
sUnknownCommand='неизвестная команда';
{ TcmdServer }
constructor TcmdServer.Create(aOwner:TComponent); begin inherited; DefaultPort:=wDefaultIPPort;
fsHostName:=Net_GetHostName; fsHostIPAddress:=Net_GetLocalIPAddressStr; fsHostIPPort:=IntToStr(DefaultPort);
Greeting.NumericCode:=200; Greeting.Text.Text:=''; ReplyExceptionCode:=500;
MaxConnectionReply.NumericCode:=499; MaxConnectionReply.Text.Text:=sMaxConnection; MaxConnections:=iMaxConnections;
ReplyUnknownCommand.NumericCode:=400; ReplyUnknownCommand.Text.Text:=sUnknownCommand;
end;
destructor TcmdServer.Destroy; begin Active:=false;
inherited;
end;
function TcmdServer.GetString(const ndx:integer):AnsiString; begin Result:='';
case ndx of
ndxHostName: Result:=fsHostName;
ndxHostIPAddress: Result:=fsHostIPAddress;
ndxHostIPPort: Result:=fsHostIPPort;
end;
end;
procedure TcmdServer.SetActive(b:boolean); var i:integer; l:TList; begin
if b<>fActive then begin
if b then inherited SetActive(b)
else try
try l:=Threads.LockList; // закрываем все соединения
for i:=0to l.Count-1do try TIdPeerThread(l[i]).Connection.Disconnect; except end;
finally Threads.UnlockList; end;
try inherited SetActive(b); except end; // деактивируем сервер
try Bindings.Clear; except end; // убираем все привязки (чтоб не было привязки к портам)
except end;
end;
end;
procedure TcmdServer.SetDefaultPort(const i32:integer); var b:boolean; begin
if i32<>DefaultPort then begin b:=Active; Active:=false;
inherited SetDefaultPort(i32); Active:=b;
fsHostIPPort:=IntToStr(DefaultPort);
end;
end;
end.
|
unit Exemplo4_2;
interface
uses
System.Classes, System.SysUtils, Xml.XMLDoc, Xml.XMLIntf, System.Json,
Data.DBXJSONReflect, Exemplo4;
type
TFichaUsuarioXML = class(TFichaUsuario)
procedure Exportar(pArquivo: string); override;
end;
implementation
{ TFichaUsuarioXML }
procedure TFichaUsuarioXML.Exportar(pArquivo: string);
var
lXml: IXMLDocument;
lNode: IXMLNode;
begin
lXml := TXmlDocument.Create(nil);
lXml.Active := True;
lXml.Version := '1.0';
lXml.Encoding:= 'UTF-8';
lNode := lXml.AddChild('Ficha');
lNode.AddChild('Codigo').NodeValue := Codigo;
lNode.AddChild('Nome').NodeValue := Nome;
lNode.AddChild('Data').NodeValue := Data;
lNode.AddChild('Cargo').NodeValue := Cargo;
lXml.SaveToFile(pArquivo);
end;
end.
|
program e2p4;
uses
crt;
const
MAX_ELEMENTOS = 5;
type
puntAlumnos = ^tAlumnos;
tAlumnos = record
nombre:string;
curso:integer;
sig:puntAlumnos;
end;
puntNombres = ^tNombre;
tNombre = record
alumno:puntAlumnos;
sig:puntNombreS;
end;
////////////////////////////////////////////////////////////////////////
procedure imprimirListaNombres(listaNombres:puntNombres);
var
cursor:puntNombres;
begin
cursor:=listaNombres;
writeln('LISTA POR NOMBRES:');
while (cursor <> nil) do
begin
write('NOMBRE:',cursor^.alumno^.nombre);
writeln;
cursor:=cursor^.sig;
end;
end;
procedure imprimirListaAlumnos(listaAlumnos:puntAlumnos);
var
cursor:puntAlumnos;
begin
cursor:=listaAlumnos;
writeln('LA LISTA ES:');
while (cursor <> nil) do
begin
write('NOMBRE:',cursor^.nombre,', CURSO:', cursor^.curso);
writeln;
cursor:=cursor^.sig;
end;
end;
procedure insertarNodoOrdenado(var listaNombres:puntNombres; nodoNombre:puntNombres);
var
cursorAnt, cursorSig:puntNombres;
begin
if (listaNombres^.alumno^.nombre > nodoNombre^.alumno^.nombre) then
begin
nodoNombre^.sig:=listaNombres;
listaNombres:=nodoNombre;
end
else
begin
cursorSig:=listaNombres;
cursorAnt:=nil;
while (cursorSig <> nil) and (cursorSig^.alumno^.nombre < nodoNombre^.alumno^.nombre) do
begin
cursorAnt:=cursorSig;
cursorSig:=cursorSig^.sig;
end;
nodoNombre^.sig:=cursorSig;
cursorAnt^.sig:=nodoNombre;
end;
end;
procedure insertarNodoNombre(var listaNombres:puntNombres; nodoNombre:puntNombres);
begin
if (listaNombres = nil) then
listaNombres:=nodoNombre
else
insertarNodoOrdenado(listaNombres, nodoNombre);
end;
procedure crearNodoNombre(var nodo:puntNombres; alumno:puntAlumnos);
begin
new(nodo);
nodo^.alumno:=alumno;
nodo^.sig:=nil;
end;
procedure crearListaNombres(listaAlumnos:puntAlumnos; var listaNombres:puntNombres);
var
nodoNombre:puntNombres;
cursor:puntAlumnos;
begin
nodoNombre:=nil;
cursor:=listaAlumnos;
while (cursor <> nil) do
begin
crearNodoNombre(nodoNombre, cursor);
insertarNodoNombre(listaNombres, nodoNombre);
cursor:=cursor^.sig;
end;
end;
procedure insertarPorNombre(var listaAlumnos:puntAlumnos; nodoAlumno:puntAlumnos);
var
cursorAnt, cursorSig:puntAlumnos;
begin
if (listaAlumnos^.nombre > nodoAlumno^.nombre) then
begin
nodoAlumno^.sig:=listaAlumnos;
listaAlumnos:=nodoAlumno;
end
else
begin
cursorSig:=listaAlumnos;
cursorAnt:=nil;
while (cursorSig <> nil) and (cursorSig^.curso = nodoAlumno^.curso) and (cursorSig^.nombre < nodoAlumno^.nombre) do
begin
cursorAnt:=cursorSig;
cursorSig:=cursorSig^.sig;
end;
nodoAlumno^.sig:=cursorSig;
cursorAnt^.sig:=nodoAlumno;
end;
end;
procedure insertarPorCurso(var listaAlumnos:puntAlumnos; nodoAlumno:puntAlumnos);
var
cursorAnt, cursorSig:puntAlumnos;
begin
if (listaAlumnos^.curso > nodoAlumno^.curso) then
begin
nodoAlumno^.sig:=listaAlumnos;
listaAlumnos:=nodoAlumno;
end
else
if (listaAlumnos^.curso = nodoAlumno^.curso) then
insertarPorNombre(listaAlumnos, nodoAlumno)
else
begin
cursorSig:=listaAlumnos;
cursorAnt:=nil;
while (cursorSig <> nil) and (cursorSig^.curso < nodoAlumno^.curso) do
begin
cursorAnt:=cursorSig;
cursorSig:=cursorSig^.sig;
end;
if (cursorSig <> nil) then
if (cursorSig^.curso <> nodoAlumno^.curso) then
begin
writeln('entro');
nodoAlumno^.sig:=cursorSig;
cursorAnt^.sig:=nodoAlumno;
end
else
insertarPorNombre(listaAlumnos, nodoAlumno)
else
begin
nodoAlumno^.sig:=cursorSig;
cursorAnt^.sig:=nodoAlumno;
end;
end;
end;
procedure insertarOrdenado(var listaAlumnos:puntAlumnos; nodoAlumno:puntAlumnos);
begin
if (listaAlumnos = nil) then
listaAlumnos:=nodoAlumno
else
insertarPorCurso(listaAlumnos, nodoAlumno);
end;
procedure crearNodoAlumno(var nodoAlumno:puntAlumnos; nombre:string; curso:integer);
begin
new(nodoAlumno);
nodoAlumno^.nombre:=nombre;
nodoAlumno^.curso:=curso;
nodoAlumno^.sig:=nil;
end;
procedure cargarListaAlumnos(var listaAlumnos:puntAlumnos);
var
nodoAlumno:puntAlumnos;
nombre:string;
contador, curso:integer;
begin
nodoAlumno:=nil;
contador:=0;
writeln('INGRESE LOS DATOS DE LOS ALUMNOS:');
writeln;
while (contador < MAX_ELEMENTOS) do
begin
writeln('NOMBRE: ');
readln(nombre);
writeln('CURSO: ');
readln(curso);
crearNodoAlumno(nodoAlumno, nombre, curso);
insertarOrdenado(listaAlumnos, nodoAlumno);
contador:=contador+1;
writeln;
end;
end;
procedure ingresarNuevoAlumno(var listaAlumnos:puntAlumnos; var listaNombres:puntNombres);
var
nombre:string;
curso:integer;
nodoAlumno:puntAlumnos;
nodoNombre:puntNombres;
begin
nodoAlumno:=nil;
nodoNombre:=nil;
writeln('INGRESE EL NUEVO ALUMNO QUE DESEA INGRESAR:');
writeln('NOMBRE:');
readln(nombre);
writeln('CURSO:');
readln(curso);
crearNodoAlumno(nodoAlumno, nombre, curso);
crearNodoNombre(nodoNombre, nodoAlumno);
insertarOrdenado(listaAlumnos, nodoAlumno);
insertarNodoNombre(listaNombres, nodoNombre);
end;
////////////////////////////////////////////////////////////////////////
var
listaAlumnos:puntAlumnos;
listaNombres:puntNombres;
begin
listaNombres:=nil;
listaAlumnos:=nil;
cargarListaAlumnos(listaAlumnos);
crearListaNombres(listaAlumnos, listaNombres);
imprimirListaAlumnos(listaAlumnos);
imprimirListaNombres(listaNombres);
ingresarNuevoAlumno(listaAlumnos, listaNombres);
imprimirListaAlumnos(listaAlumnos);
imprimirListaNombres(listaNombres);
end.
|
unit PerlinNoiseData;
procedure WTF(name: string; params obj: array of object) := System.IO.File.AppendAllText(name, string.Join('', obj.ConvertAll(a -> _ObjectToString(a))) + char(13) + char(10));
type
Perlin2D = class
public
permutationTable: array of byte;
public constructor(seed: integer := 0);
begin
var rand := new System.Random(seed);
permutationTable := new byte[1024];
rand.NextBytes(permutationTable);
end;
private function GetPseudoRandomGradientVector(x, y: integer): array of Single;
begin
var v := (((x * $6D73E55F) xor (y * $B11924E1) + $11E8D0A40) and $3FF);
v := permutationTable[v] and $3;
case v of
0: Result := new Single[](1, 0 );
1: Result := new Single[](0, 1 );
2: Result := new Single[](-1, 0 );
else Result := new Single[](0, -1 );
end;
end;
private class function QunticCurve(t: Single): Single := t * t * t * (t * (t * 6 - 15) + 10);
private class function Lerp(a, b, t: Single): Single := a + (b - a) * t;
private class function Dot(a, b: array of Single): Single := a[0] * b[0] + a[1] * b[1];
public function Noise(fx, fy: Single): Single;
begin
fx -= System.Math.Floor(fx/integer.MaxValue)*integer.MaxValue;
fy -= System.Math.Floor(fy/integer.MaxValue)*integer.MaxValue;
var left := Floor(fx);
var top := Floor(fy);
var pointInQuadX := QunticCurve(fx - left);
var pointInQuadY := QunticCurve(fy - top);
var topLeftGradient := GetPseudoRandomGradientVector(left, top );
var topRightGradient := GetPseudoRandomGradientVector(left + 1, top );
var bottomLeftGradient := GetPseudoRandomGradientVector(left, top + 1);
var bottomRightGradient := GetPseudoRandomGradientVector(left + 1, top + 1);
var distanceToTopLeft := new Single[](pointInQuadX, pointInQuadY );
var distanceToTopRight := new Single[](pointInQuadX - 1, pointInQuadY );
var distanceToBottomLeft := new Single[](pointInQuadX, pointInQuadY - 1 );
var distanceToBottomRight := new Single[](pointInQuadX - 1, pointInQuadY - 1 );
var tx1 := Dot(distanceToTopLeft, topLeftGradient);
var tx2 := Dot(distanceToTopRight, topRightGradient);
var bx1 := Dot(distanceToBottomLeft, bottomLeftGradient);
var bx2 := Dot(distanceToBottomRight, bottomRightGradient);
var tx := Lerp(tx1, tx2, pointInQuadX);
var bx := Lerp(bx1, bx2, pointInQuadX);
Result := Lerp(tx, bx, pointInQuadY);
{
WTF('Log.txt',fx,' ',fy);
WTF('Log.txt',left,' ',top);
WTF('Log.txt',pointInQuadX,' ',pointInQuadX);
WTF('Log.txt','------------------------------------------------------');
{}
end;
public function Noise(fx, fy: Single; octaves: integer; persistence: Single := 0.5): Single;
begin
var amplitude: Single := 1;
var max: Single := 0;
while octaves > 0 do
begin
max += amplitude;
result += Noise(fx, fy) * amplitude;
amplitude *= persistence;
fx *= 2;
fy *= 2;
octaves -= 1;
end;
result /= max;
end;
end;
end. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.