text stringlengths 14 6.51M |
|---|
unit TitlePage;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.ListView.Types,
FMX.ListView.Appearances,
FMX.ListView.Adapters.Base,
FMX.ListView,
FMX.StdCtrls,
FMX.Controls.Presentation;
type
TLoadThread = class(TThread)
private
FJson: string;
FListFile: TFileName;
FTitles: TStrings;
FLIstView: TListView;
FIndicator: TAniIndicator;
FAllChapter: Boolean;
procedure GetJson;
procedure ParseTitleList;
procedure TitlesChange;
protected
procedure Execute; override;
public
constructor Create(AListView: TListView; AIndicator: TAniIndicator;
AAllChapter: Boolean);
destructor Destroy; override;
end;
TFrmTitle = class(TForm)
LvTitle: TListView;
ToolBar1: TToolBar;
BtnRefresh: TButton;
Label1: TLabel;
Indicator: TAniIndicator;
PnlBottom: TPanel;
SwShow: TSwitch;
LblShow: TLabel;
procedure FormShow(Sender: TObject);
procedure LvTitleItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure BtnRefreshClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure SwShowSwitch(Sender: TObject);
private
procedure Refresh(AAllChapter: Boolean);
{ Private declarations }
public
{ Public declarations }
end;
var
FrmTitle: TFrmTitle;
implementation
{$R *.fmx}
{$R *.NmXhdpiPh.fmx ANDROID}
{$R *.LgXhdpiPh.fmx ANDROID}
{$R *.XLgXhdpiTb.fmx ANDROID}
{$R *.LgXhdpiTb.fmx ANDROID}
uses
SinglePage, System.JSON, System.IOUtils, System.Net.HttpClient, Commons;
const
sUrlAll = 'https://www.cbsanjaya.com/onepiece/all.json';
sUrlLast5 = 'https://www.cbsanjaya.com/onepiece/last5.json';
resourcestring
sShowAllChapter = 'Seluruh Chapter';
sShowOnly5Chapter = 'Lima Chapter Terahir';
procedure TFrmTitle.FormCreate(Sender: TObject);
begin
if not (TDirectory.Exists(CachePath)) then
begin
TDirectory.CreateDirectory(CachePath);
end;
end;
procedure TFrmTitle.FormShow(Sender: TObject);
begin
Refresh(SwShow.IsChecked);
end;
procedure TFrmTitle.BtnRefreshClick(Sender: TObject);
begin
Refresh(SwShow.IsChecked);
end;
procedure TFrmTitle.LvTitleItemClick(const Sender: TObject;
const AItem: TListViewItem);
var
LFrmSingle : TFrmSingle;
begin
LFrmSingle := TFrmSingle.Create(Self, AItem.Text, AItem.Detail);
LFrmSingle.Show;
end;
procedure TFrmTitle.Refresh(AAllChapter: Boolean);
var
FLoadThread : TLoadThread;
begin
FLoadThread := TLoadThread.Create(LvTitle, Indicator, AAllChapter);
FLoadThread.Start;
end;
procedure TFrmTitle.SwShowSwitch(Sender: TObject);
begin
if TSwitch(Sender).IsChecked then
begin
LblShow.Text := sShowAllChapter;
end else
begin
LblShow.Text := sShowOnly5Chapter;
end;
Refresh(SwShow.IsChecked);
end;
{ TLoadThread }
constructor TLoadThread.Create(AListView: TListView; AIndicator: TAniIndicator;
AAllChapter: Boolean);
begin
inherited Create(True);
FreeOnTerminate := True;
FTitles := TStringList.Create;
FIndicator := AIndicator;
FLIstView := ALIstView;
FAllChapter := AAllChapter;
if FAllChapter then
FListFile := TPath.Combine(CachePath, 'all.json') else
FListFile := TPath.Combine(CachePath, 'last5.json');
end;
destructor TLoadThread.Destroy;
begin
FTitles.Free;
inherited;
end;
procedure TLoadThread.GetJson;
var
LClient : THTTPClient;
LResponse : IHTTPResponse;
LUrs: string;
begin
LClient := THTTPClient.Create;
try
try
if FAllChapter then
LUrs := sUrlAll else
LUrs := sUrlLast5;
LResponse := LClient.Get(LUrs);
FJson := LResponse.ContentAsString;
except
end;
finally
LClient.Free;
end;
end;
procedure TLoadThread.TitlesChange;
var
I: Integer;
LItem: TListViewItem;
begin
FLIstView.Items.Clear;
for I := 0 to Pred(FTitles.Count) do
begin
LItem := FLIstView.Items.Add;
LItem.Text := FTitles.KeyNames[I];
LItem.Detail := FTitles.ValueFromIndex[I];
end;
end;
procedure TLoadThread.ParseTitleList;
var
I : integer;
LChapter, LJudul : string;
LValues, LObject : TJSONValue;
begin
if (FJson.IsEmpty) then
begin
if (TFile.Exists(FListFile)) then
FTitles.LoadFromFile(FListFile);
exit;
end;
LValues := TJSONObject.ParseJSONValue(FJson);
FTitles.Clear;
for LObject in LValues as TJSONArray do
begin
LChapter := LObject.GetValue<string>('chapter');
LJudul := LObject.GetValue<string>('title');
FTitles.AddPair(LChapter, LJudul);
end;
FTitles.SaveToFile(FListFile);
end;
procedure TLoadThread.Execute;
begin
FIndicator.Visible := True;
GetJson;
ParseTitleList;
Synchronize(TitlesChange);
FIndicator.Visible := False;
end;
end.
|
{
ID: nghoang4
PROG: barn1
LANG: PASCAL
}
const fi = 'barn1.in';
fo = 'barn1.out';
maxN = 200;
type MyArr = array[1..maxN] of integer;
var a, b: MyArr;
m, s, c: integer;
procedure Init;
var i: integer;
begin
assign(input,fi); reset(input);
readln(m,s,c);
for i:=1 to c do readln(a[i]);
close(input);
end;
procedure Sort(var a: MyArr; n: integer);
var i, j, t: integer;
begin
for i:=1 to n-1 do
for j:=i+1 to n do
if a[i] > a[j] then
begin
t:=a[i];
a[i]:=a[j];
a[j]:=t;
end;
end;
procedure Solve;
var i: integer;
begin
Sort(a,c);
for i:=1 to c-1 do b[i]:=a[i+1]-a[i]-1;
Sort(b,c-1);
s:=0;
for i:=c-1 downto c-m+1 do s:=s+b[i];
s:=a[c]-a[1]+1-s;
end;
procedure PrintResult;
begin
assign(output,fo); rewrite(output);
writeln(s);
close(output);
end;
begin
Init;
Solve;
PrintResult;
end. |
unit UnitMainForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, Menus;
type
TMainForm = class(TForm)
Image: TImage;
MainMenu: TMainMenu;
Hra: TMenuItem;
HraNova: TMenuItem;
HraKoniec: TMenuItem;
procedure HraKoniecClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure HraNovaClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses Constants, ClassLevel;
{$R *.DFM}
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
procedure TMainForm.FormCreate(Sender: TObject);
begin
Level := TLevel.Create;
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Level.Free;
end;
//==============================================================================
//==============================================================================
//
// Main menu
//
//==============================================================================
//==============================================================================
procedure TMainForm.HraKoniecClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.HraNovaClick(Sender: TObject);
begin
Level.LoadFromFile( LEVEL_DIR );
end;
end.
|
unit REST.ClientClass;
interface
uses
REST.Client, System.Generics.Collections, System.Classes, REST.Types, System.JSON;
type
IClientREST = interface
['{3389A380-A0F5-45D6-9CB0-F2DDD7FF6203}']
function execute(): IClientREST;
function GetBaseURL: string;
procedure SetBaseURL(const Value: string);
function GetTimeOut: Integer;
procedure SetTimeOut(const Value: Integer);
function headerAdd(const AName, AValue: string): IClientREST;
function paramsAdd(const AName, AValue: string; const AKind: TRESTRequestParameterKind; AContentType: TRESTContentType; const AOptions: TRESTRequestParameterOptions = []): IClientREST;
function GetJsonText: string;
procedure SetJsonText(const Value: string);
function GetContentType: string;
procedure SetContentType(const Value: string);
function GetMethod: TRESTRequestMethod;
procedure SetMethod(const Value: TRESTRequestMethod);
function toJSONString(): string;
function toJSONValue(): TJSONValue;
property BaseURL: string read GetBaseURL write SetBaseURL;
property TimeOut: Integer read GetTimeOut write SetTimeOut;
property JsonText: string read GetJsonText write SetJsonText;
property ContentType: string read GetContentType write SetContentType;
property Method: TRESTRequestMethod read GetMethod write SetMethod;
end;
TClientREST = class(TInterfacedObject, IClientREST)
protected
FClient: TRESTClient;
FRequest: TRESTRequest;
FResponse: TRESTResponse;
constructor Create();
{ Protected Declarations }
private
FTimeOut: Integer;
FBaseURL: string;
FJsonText: string;
FContentType: string;
FMethod: TRESTRequestMethod;
function GetBaseURL: string;
procedure SetBaseURL(const Value: string);
function GetTimeOut: Integer;
procedure SetTimeOut(const Value: Integer);
function GetJsonText: string;
procedure SetJsonText(const Value: string);
function GetContentType: string;
procedure SetContentType(const Value: string);
function GetMethod: TRESTRequestMethod;
procedure SetMethod(const Value: TRESTRequestMethod);
{ Private Declarations }
public
function execute(): IClientREST;
class function new(): IClientREST;
destructor Destroy; override;
function toJSONString(): string;
function toJSONValue(): TJSONValue;
function headerAdd(const AName, AValue: string): IClientREST;
function paramsAdd(const AName, AValue: string; const AKind: TRESTRequestParameterKind; AContentType: TRESTContentType; const AOptions: TRESTRequestParameterOptions = []): IClientREST;
property BaseURL: string read GetBaseURL write SetBaseURL;
property TimeOut: Integer read GetTimeOut write SetTimeOut;
property JsonText: string read GetJsonText write SetJsonText;
property ContentType: string read GetContentType write SetContentType;
property Method: TRESTRequestMethod read GetMethod write SetMethod;
{ Public Declarations }
end;
implementation
uses
System.SysUtils, REST.HttpClient;
{ TClientREST }
function TClientREST.headerAdd(const AName, AValue: string): IClientREST;
begin
try
FRequest.Params.AddHeader(AName, AValue);
finally
Result := Self;
end;
end;
constructor TClientREST.Create();
begin
FClient := TRESTClient.Create('');
FRequest := TRESTRequest.Create(FClient);
FResponse := TRESTResponse.Create(FClient);
FRequest.Client := FClient;
FRequest.Response := FResponse;
FJsonText := EmptyStr;
end;
destructor TClientREST.Destroy;
begin
FreeAndNil(FClient);
inherited;
end;
function TClientREST.execute: IClientREST;
begin
try
try
FRequest.AcceptCharset := 'UTF-8, *;q=0.8';
FRequest.Execute;
finally
Result := Self;
end;
except
on E: ERESTException do
raise ERESTException.Create(E.Message);
on E: EHTTPProtocolException do
raise EHTTPProtocolException.Create(E.ErrorCode, E.ErrorMessage, E.Message);
on E: Exception do
raise Exception.Create(E.Message);
end;
end;
function TClientREST.GetBaseURL: string;
begin
Result := FBaseURL;
end;
function TClientREST.GetContentType: string;
begin
Result := FContentType;
end;
function TClientREST.GetJsonText: string;
begin
Result := FJsonText;
end;
function TClientREST.GetMethod: TRESTRequestMethod;
begin
Result := FMethod;
end;
function TClientREST.GetTimeOut: Integer;
begin
Result := FTimeOut;
end;
class function TClientREST.new: IClientREST;
begin
Result := Self.Create();
end;
function TClientREST.paramsAdd(const AName, AValue: string; const AKind: TRESTRequestParameterKind; AContentType: TRESTContentType; const AOptions: TRESTRequestParameterOptions = []): IClientREST;
begin
try
FRequest.Params.AddItem(AName, AValue, AKind, AOptions, AContentType);
finally
Result := Self;
end;
end;
procedure TClientREST.SetBaseURL(const Value: string);
begin
FBaseURL := Value;
FClient.BaseURL := Value;
end;
procedure TClientREST.SetContentType(const Value: string);
begin
FContentType := Value;
if Value <> EmptyStr then
FClient.ContentType := Value;
end;
procedure TClientREST.SetJsonText(const Value: string);
begin
FJsonText := Value;
if Value <> EmptyStr then
FRequest.Body.JSONWriter.WriteRaw(Value);
end;
procedure TClientREST.SetMethod(const Value: TRESTRequestMethod);
begin
FMethod := Value;
FRequest.Method := Value;
end;
procedure TClientREST.SetTimeOut(const Value: Integer);
begin
FTimeOut := Value;
FRequest.Timeout := Value;
end;
function TClientREST.toJSONValue(): TJSONValue;
begin
Result := FResponse.JSONValue;
end;
function TClientREST.toJSONString(): string;
begin
Result := FResponse.JSONText;
end;
end.
|
unit rtcBlankOutForm;
{$INCLUDE rtcDefs.inc}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
ExtCtrls,
rtcTypes;
type
TfmBlankoutForm = class(TForm)
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
Image1: TImage;
Timer1: TTimer;
procedure FormResize(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CreateParams(Var params: TCreateParams); override;
private
{ Private declarations }
public
{ Public declarations }
end;
procedure RestoreScreen;
procedure BlankOutScreen(AllMonitors:boolean);
implementation
{$R *.dfm}
procedure TfmBlankOutForm.CreateParams(Var params: TCreateParams);
begin
inherited CreateParams( params );
params.ExStyle := params.ExStyle or
WS_EX_APPWINDOW or
WS_EX_TRANSPARENT or
WS_EX_LAYERED or
WS_EX_NOPARENTNOTIFY or
WS_EX_NOINHERITLAYOUT or
WS_EX_NOACTIVATE;
params.WndParent := GetDesktopWindow;
end;
procedure TfmBlankoutForm.FormResize(Sender: TObject);
begin
Panel1.Left := (ClientWidth - Panel1.Width) div 2;
Panel1.Top := (ClientHeight - Panel1.Height) div 2;
end;
procedure TfmBlankoutForm.Timer1Timer(Sender: TObject);
begin
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or
SWP_NOACTIVATE);
SetWindowPos(Handle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or
SWP_NOACTIVATE);
end;
var
fBlankoutForms : TList = nil;
procedure RestoreScreen;
var
i: integer;
begin
if assigned(fBlankOutForms) then
begin
if fBlankoutForms.Count > 0 then
begin
for i := 0 to fBlankoutForms.Count - 1 do
TObject(fBlankoutForms[i]).Free;
fBlankoutForms.Clear;
end;
RtcFreeAndNil(fBlankOutForms);
end;
end;
procedure BlankOutScreen(AllMonitors:boolean);
var
hUser32 : HMODULE;
SetLayeredWindowAttributes: TSetLayeredWindowAttributes;
rect : TRect;
i : integer;
ablnkform : TForm;
begin
if assigned(fBlankoutForms) then RestoreScreen;
hUser32 := GetModuleHandle('USER32.DLL');
if hUser32 <> 0 then
begin
@SetLayeredWindowAttributes := GetProcAddress(hUser32,'SetLayeredWindowAttributes');
// If the import did not succeed, make sure our app can handle it!
if @SetLayeredWindowAttributes <> nil then
begin
fBlankoutForms := TList.Create;
for i := 0 to Screen.MonitorCount - 1 do
begin
if AllMonitors or ( (Screen.Monitors[i].Left=0) and (Screen.Monitors[i].Top=0) ) then
begin
ablnkform := TfmBlankoutForm.Create(nil);
ablnkform.WindowState := wsNormal;
ablnkform.FormStyle := fsNormal;
ablnkform.HandleNeeded;
ablnkform.ClientWidth:=1;
ablnkform.ClientHeight:=1;
ablnkform.Show;
ablnkform.Hide;
rect := Screen.Monitors[i].BoundsRect;
ablnkform.BoundsRect := rect;
fBlankoutForms.Add(ablnkform);
ablnkform.Show;
SetWindowPos(ablnkform.Handle, HWND_TOP, rect.Left, rect.Top,
ablnkform.Width, ablnkform.Height, 0);
ablnkform.FormStyle:=fsStayOnTop;
end;
end;
end;
end;
end;
procedure TfmBlankoutForm.FormCreate(Sender: TObject);
begin
SetWindowLong(Handle, GWL_EXSTYLE,
GetWindowLong(Handle, GWL_EXSTYLE) or
WS_EX_LAYERED or
WS_EX_TRANSPARENT or
WS_EX_TOPMOST);
// The SetLayeredWindowAttributes function sets the opacity and
// transparency color key of a layered window
SetLayeredWindowAttributes(Handle, 0,
Trunc((255 / 100) * (100 - 0)),
LWA_ALPHA);
end;
procedure TfmBlankoutForm.FormShow(Sender: TObject);
begin
FormCreate(nil);
SetWindowPos(Handle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or
SWP_NOACTIVATE);
end;
initialization
finalization
RestoreScreen;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_Recast;
interface
uses
Math, SysUtils, RN_Helper;
type
/// Recast log categories.
/// @see rcContext
TrcLogCategory = (
RC_LOG_PROGRESS = 1, ///< A progress log entry.
RC_LOG_WARNING, ///< A warning log entry.
RC_LOG_ERROR ///< An error log entry.
);
/// Recast performance timer categories.
/// @see rcContext
TrcTimerLabel =
(
/// The user defined total time of the build.
RC_TIMER_TOTAL,
/// A user defined build time.
RC_TIMER_TEMP,
/// The time to rasterize the triangles. (See: #rcRasterizeTriangle)
RC_TIMER_RASTERIZE_TRIANGLES,
/// The time to build the compact heightfield. (See: #rcBuildCompactHeightfield)
RC_TIMER_BUILD_COMPACTHEIGHTFIELD,
/// The total time to build the contours. (See: #rcBuildContours)
RC_TIMER_BUILD_CONTOURS,
/// The time to trace the boundaries of the contours. (See: #rcBuildContours)
RC_TIMER_BUILD_CONTOURS_TRACE,
/// The time to simplify the contours. (See: #rcBuildContours)
RC_TIMER_BUILD_CONTOURS_SIMPLIFY,
/// The time to filter ledge spans. (See: #rcFilterLedgeSpans)
RC_TIMER_FILTER_BORDER,
/// The time to filter low height spans. (See: #rcFilterWalkableLowHeightSpans)
RC_TIMER_FILTER_WALKABLE,
/// The time to apply the median filter. (See: #rcMedianFilterWalkableArea)
RC_TIMER_MEDIAN_AREA,
/// The time to filter low obstacles. (See: #rcFilterLowHangingWalkableObstacles)
RC_TIMER_FILTER_LOW_OBSTACLES,
/// The time to build the polygon mesh. (See: #rcBuildPolyMesh)
RC_TIMER_BUILD_POLYMESH,
/// The time to merge polygon meshes. (See: #rcMergePolyMeshes)
RC_TIMER_MERGE_POLYMESH,
/// The time to erode the walkable area. (See: #rcErodeWalkableArea)
RC_TIMER_ERODE_AREA,
/// The time to mark a box area. (See: #rcMarkBoxArea)
RC_TIMER_MARK_BOX_AREA,
/// The time to mark a cylinder area. (See: #rcMarkCylinderArea)
RC_TIMER_MARK_CYLINDER_AREA,
/// The time to mark a convex polygon area. (See: #rcMarkConvexPolyArea)
RC_TIMER_MARK_CONVEXPOLY_AREA,
/// The total time to build the distance field. (See: #rcBuildDistanceField)
RC_TIMER_BUILD_DISTANCEFIELD,
/// The time to build the distances of the distance field. (See: #rcBuildDistanceField)
RC_TIMER_BUILD_DISTANCEFIELD_DIST,
/// The time to blur the distance field. (See: #rcBuildDistanceField)
RC_TIMER_BUILD_DISTANCEFIELD_BLUR,
/// The total time to build the regions. (See: #rcBuildRegions, #rcBuildRegionsMonotone)
RC_TIMER_BUILD_REGIONS,
/// The total time to apply the watershed algorithm. (See: #rcBuildRegions)
RC_TIMER_BUILD_REGIONS_WATERSHED,
/// The time to expand regions while applying the watershed algorithm. (See: #rcBuildRegions)
RC_TIMER_BUILD_REGIONS_EXPAND,
/// The time to flood regions while applying the watershed algorithm. (See: #rcBuildRegions)
RC_TIMER_BUILD_REGIONS_FLOOD,
/// The time to filter out small regions. (See: #rcBuildRegions, #rcBuildRegionsMonotone)
RC_TIMER_BUILD_REGIONS_FILTER,
/// The time to build heightfield layers. (See: #rcBuildHeightfieldLayers)
RC_TIMER_BUILD_LAYERS,
/// The time to build the polygon mesh detail. (See: #rcBuildPolyMeshDetail)
RC_TIMER_BUILD_POLYMESHDETAIL,
/// The time to merge polygon mesh details. (See: #rcMergePolyMeshDetails)
RC_TIMER_MERGE_POLYMESHDETAIL,
/// The maximum number of timers. (Used for iterating timers.)
RC_MAX_TIMERS
);
/// Provides an interface for optional logging and performance tracking of the Recast
/// build process.
/// @ingroup recast
TrcContext = class
public
/// Contructor.
/// @param[in] state TRUE if the logging and performance timers should be enabled. [Default: true]
constructor Create(state: Boolean = true);//: m_logEnabled(state), m_timerEnabled(state) {}
/// Enables or disables logging.
/// @param[in] state TRUE if logging should be enabled.
procedure enableLog(state: Boolean); { m_logEnabled = state; }
/// Clears all log entries.
procedure resetLog(); { if (m_logEnabled) doResetLog(); }
/// Logs a message.
/// @param[in] category The category of the message.
/// @param[in] format The message.
procedure log(category: TrcLogCategory; msg: string);
/// Enables or disables the performance timers.
/// @param[in] state TRUE if timers should be enabled.
procedure enableTimer(state: Boolean); { m_timerEnabled = state; }
/// Clears all peformance timers. (Resets all to unused.)
procedure resetTimers(); { if (m_timerEnabled) doResetTimers(); }
/// Starts the specified performance timer.
/// @param label The category of timer.
procedure startTimer(aLabel: TrcTimerLabel); { if (m_timerEnabled) doStartTimer(label); }
/// Stops the specified performance timer.
/// @param label The category of the timer.
procedure stopTimer(aLabel: TrcTimerLabel); { if (m_timerEnabled) doStopTimer(label); }
/// Returns the total accumulated time of the specified performance timer.
/// @param label The category of the timer.
/// @return The accumulated time of the timer, or -1 if timers are disabled or the timer has never been started.
function getAccumulatedTime(aLabel: TrcTimerLabel): Integer; { return m_timerEnabled ? doGetAccumulatedTime(label) : -1; }
protected
/// True if logging is enabled.
m_logEnabled: Boolean;
/// True if the performance timers are enabled.
m_timerEnabled: Boolean;
/// Clears all log entries.
procedure doResetLog(); virtual; abstract;
/// Logs a message.
/// @param[in] category The category of the message.
/// @param[in] msg The formatted message.
/// @param[in] len The length of the formatted message.
procedure doLog(category: TrcLogCategory; msg: string); virtual; abstract;
/// Clears all timers. (Resets all to unused.)
procedure doResetTimers(); virtual; abstract;
/// Starts the specified performance timer.
/// @param[in] label The category of timer.
procedure doStartTimer(const &label: TrcTimerLabel); virtual; abstract;
/// Stops the specified performance timer.
/// @param[in] label The category of the timer.
procedure doStopTimer(const &label: TrcTimerLabel); virtual; abstract;
/// Returns the total accumulated time of the specified performance timer.
/// @param[in] label The category of the timer.
/// @return The accumulated time of the timer, or -1 if timers are disabled or the timer has never been started.
function doGetAccumulatedTime(const &label: TrcTimerLabel): Integer; virtual; { return -1; }
end;
/// Specifies a configuration to use when performing Recast builds.
/// @ingroup recast
TrcConfig = record
/// The width of the field along the x-axis. [Limit: >= 0] [Units: vx]
width: Integer;
/// The height of the field along the z-axis. [Limit: >= 0] [Units: vx]
height: Integer;
/// The width/height size of tile's on the xz-plane. [Limit: >= 0] [Units: vx]
tileSize: Integer;
/// The size of the non-navigable border around the heightfield. [Limit: >=0] [Units: vx]
borderSize: Integer;
/// The xz-plane cell size to use for fields. [Limit: > 0] [Units: wu]
cs: Single;
/// The y-axis cell size to use for fields. [Limit: > 0] [Units: wu]
ch: Single;
/// The minimum bounds of the field's AABB. [(x, y, z)] [Units: wu]
bmin: array [0..2] of Single;
/// The maximum bounds of the field's AABB. [(x, y, z)] [Units: wu]
bmax: array [0..2] of Single;
/// The maximum slope that is considered walkable. [Limits: 0 <= value < 90] [Units: Degrees]
walkableSlopeAngle: Single;
/// Minimum floor to 'ceiling' height that will still allow the floor area to
/// be considered walkable. [Limit: >= 3] [Units: vx]
walkableHeight: Integer;
/// Maximum ledge height that is considered to still be traversable. [Limit: >=0] [Units: vx]
walkableClimb: Integer;
/// The distance to erode/shrink the walkable area of the heightfield away from
/// obstructions. [Limit: >=0] [Units: vx]
walkableRadius: Integer;
/// The maximum allowed length for contour edges along the border of the mesh. [Limit: >=0] [Units: vx]
maxEdgeLen: Integer;
/// The maximum distance a simplfied contour's border edges should deviate
/// the original raw contour. [Limit: >=0] [Units: vx]
maxSimplificationError: Single;
/// The minimum number of cells allowed to form isolated island areas. [Limit: >=0] [Units: vx]
minRegionArea: Integer;
/// Any regions with a span count smaller than this value will, if possible,
/// be merged with larger regions. [Limit: >=0] [Units: vx]
mergeRegionArea: Integer;
/// The maximum number of vertices allowed for polygons generated during the
/// contour to polygon conversion process. [Limit: >= 3]
maxVertsPerPoly: Integer;
/// Sets the sampling distance to use when generating the detail mesh.
/// (For height detail only.) [Limits: 0 or >= 0.9] [Units: wu]
detailSampleDist: Single;
/// The maximum distance the detail mesh surface should deviate from heightfield
/// data. (For height detail only.) [Limit: >=0] [Units: wu]
detailSampleMaxError: Single;
end;
/// Defines the number of bits allocated to rcSpan::smin and rcSpan::smax.
const RC_SPAN_HEIGHT_BITS = 13;
/// Defines the maximum value for rcSpan::smin and rcSpan::smax.
const RC_SPAN_MAX_HEIGHT = 8191;//(1<<RC_SPAN_HEIGHT_BITS)-1;
/// The number of spans allocated per span spool.
/// @see rcSpanPool
const RC_SPANS_PER_POOL = 2048;
type
/// Represents a span in a heightfield.
/// @see rcHeightfield
PrcSpan = ^TrcSpan;
TrcSpan = record
smin: Word; //: 13; ///< The lower limit of the span. [Limit: < #smax]
smax: Word; //: 13; ///< The upper limit of the span. [Limit: <= #RC_SPAN_MAX_HEIGHT]
area: Byte; //: 6; ///< The area id assigned to the span.
next: PrcSpan; ///< The next span higher up in column.
end;
/// A memory pool used for quick allocation of spans within a heightfield.
/// @see rcHeightfield
PrcSpanPool = ^TrcSpanPool;
TrcSpanPool = record
next: PrcSpanPool; ///< The next span pool.
items: array [0..RC_SPANS_PER_POOL-1] of TrcSpan; ///< Array of spans in the pool.
end;
/// A dynamic heightfield representing obstructed space.
/// @ingroup recast
TrcHeightfield = record
width: Integer; ///< The width of the heightfield. (Along the x-axis in cell units.)
height: Integer; ///< The height of the heightfield. (Along the z-axis in cell units.)
bmin: array [0..2] of Single; ///< The minimum bounds in world space. [(x, y, z)]
bmax: array [0..2] of Single; ///< The maximum bounds in world space. [(x, y, z)]
cs: Single; ///< The size of each cell. (On the xz-plane.)
ch: Single; ///< The height of each cell. (The minimum increment along the y-axis.)
spans: array of PrcSpan; ///< Heightfield of spans (width*height).
pools: PrcSpanPool; ///< Linked list of span pools.
freelist: PrcSpan; ///< The next free span.
end;
PrcHeightfield = ^TrcHeightfield;
/// Provides information on the content of a cell column in a compact heightfield.
TrcCompactCell = record
index: Cardinal;// : 24; ///< Index to the first span in the column.
count: Byte;// : 8; ///< Number of spans in the column.
end;
PrcCompactCell = ^TrcCompactCell;
/// Represents a span of unobstructed space within a compact heightfield.
TrcCompactSpan = record
y: Word; ///< The lower extent of the span. (Measured from the heightfield's base.)
reg: Word; ///< The id of the region the span belongs to. (Or zero if not in a region.)
con: Cardinal;// : 24; ///< Packed neighbor connection data.
h: Byte;// : 8; ///< The height of the span. (Measured from #y.)
end;
PrcCompactSpan = ^TrcCompactSpan;
/// A compact, static heightfield representing unobstructed space.
/// @ingroup recast
TrcCompactHeightfield = record
width: Integer; ///< The width of the heightfield. (Along the x-axis in cell units.)
height: Integer; ///< The height of the heightfield. (Along the z-axis in cell units.)
spanCount: Integer; ///< The number of spans in the heightfield.
walkableHeight: Integer; ///< The walkable height used during the build of the field. (See: rcConfig::walkableHeight)
walkableClimb: Integer; ///< The walkable climb used during the build of the field. (See: rcConfig::walkableClimb)
borderSize: Integer; ///< The AABB border size used during the build of the field. (See: rcConfig::borderSize)
maxDistance: Word; ///< The maximum distance value of any span within the field.
maxRegions: Word; ///< The maximum region id of any span within the field.
bmin: array [0..2] of Single; ///< The minimum bounds in world space. [(x, y, z)]
bmax: array [0..2] of Single; ///< The maximum bounds in world space. [(x, y, z)]
cs: Single; ///< The size of each cell. (On the xz-plane.)
ch: Single; ///< The height of each cell. (The minimum increment along the y-axis.)
cells: array of TrcCompactCell; ///< Array of cells. [Size: #width*#height]
spans: array of TrcCompactSpan; ///< Array of spans. [Size: #spanCount]
dist: PWord; ///< Array containing border distance data. [Size: #spanCount]
areas: PByte; ///< Array containing area id data. [Size: #spanCount]
end;
PrcCompactHeightfield = ^TrcCompactHeightfield;
/// Represents a heightfield layer within a layer set.
/// @see rcHeightfieldLayerSet
TrcHeightfieldLayer = record
bmin: array [0..2] of Single; ///< The minimum bounds in world space. [(x, y, z)]
bmax: array [0..2] of Single; ///< The maximum bounds in world space. [(x, y, z)]
cs: Single; ///< The size of each cell. (On the xz-plane.)
ch: Single; ///< The height of each cell. (The minimum increment along the y-axis.)
width: Integer; ///< The width of the heightfield. (Along the x-axis in cell units.)
height: Integer; ///< The height of the heightfield. (Along the z-axis in cell units.)
minx: Integer; ///< The minimum x-bounds of usable data.
maxx: Integer; ///< The maximum x-bounds of usable data.
miny: Integer; ///< The minimum y-bounds of usable data. (Along the z-axis.)
maxy: Integer; ///< The maximum y-bounds of usable data. (Along the z-axis.)
hmin: Integer; ///< The minimum height bounds of usable data. (Along the y-axis.)
hmax: Integer; ///< The maximum height bounds of usable data. (Along the y-axis.)
heights: PByte; ///< The heightfield. [Size: width * height]
areas: PByte; ///< Area ids. [Size: Same as #heights]
cons: PByte; ///< Packed neighbor connection information. [Size: Same as #heights]
end;
PrcHeightfieldLayer = ^TrcHeightfieldLayer;
/// Represents a set of heightfield layers.
/// @ingroup recast
/// @see rcAllocHeightfieldLayerSet, rcFreeHeightfieldLayerSet
TrcHeightfieldLayerSet = record
layers: array of TrcHeightfieldLayer; ///< The layers in the set. [Size: #nlayers]
nlayers: Integer; ///< The number of layers in the set.
end;
/// Represents a simple, non-overlapping contour in field space.
TrcContour = record
verts: PInteger; ///< Simplified contour vertex and connection data. [Size: 4 * #nverts]
nverts: Integer; ///< The number of vertices in the simplified contour.
rverts: PInteger; ///< Raw contour vertex and connection data. [Size: 4 * #nrverts]
nrverts: Integer; ///< The number of vertices in the raw contour.
reg: Word; ///< The region id of the contour.
area: Byte; ///< The area id of the contour.
end;
PrcContour = ^TrcContour;
/// Represents a group of related contours.
/// @ingroup recast
TrcContourSet = record
conts: array of TrcContour; ///< An array of the contours in the set. [Size: #nconts]
nconts: Integer; ///< The number of contours in the set.
bmin: array [0..2] of Single; ///< The minimum bounds in world space. [(x, y, z)]
bmax: array [0..2] of Single; ///< The maximum bounds in world space. [(x, y, z)]
cs: Single; ///< The size of each cell. (On the xz-plane.)
ch: Single; ///< The height of each cell. (The minimum increment along the y-axis.)
width: Integer; ///< The width of the set. (Along the x-axis in cell units.)
height: Integer; ///< The height of the set. (Along the z-axis in cell units.)
borderSize: Integer; ///< The AABB border size used to generate the source data from which the contours were derived.
end;
PrcContourSet = ^TrcContourSet;
/// Represents a polygon mesh suitable for use in building a navigation mesh.
/// @ingroup recast
TrcPolyMesh = record
verts: PWord; ///< The mesh vertices. [Form: (x, y, z) * #nverts]
polys: PWord; ///< Polygon and neighbor data. [Length: #maxpolys * 2 * #nvp]
regs: PWord; ///< The region id assigned to each polygon. [Length: #maxpolys]
flags: PWord; ///< The user defined flags for each polygon. [Length: #maxpolys]
areas: PByte; ///< The area id assigned to each polygon. [Length: #maxpolys]
nverts: Integer; ///< The number of vertices.
npolys: Integer; ///< The number of polygons.
maxpolys: Integer; ///< The number of allocated polygons.
nvp: Integer; ///< The maximum number of vertices per polygon.
bmin: array [0..2] of Single; ///< The minimum bounds in world space. [(x, y, z)]
bmax: array [0..2] of Single; ///< The maximum bounds in world space. [(x, y, z)]
cs: Single; ///< The size of each cell. (On the xz-plane.)
ch: Single; ///< The height of each cell. (The minimum increment along the y-axis.)
borderSize: Integer; ///< The AABB border size used to generate the source data from which the mesh was derived.
end;
PrcPolyMesh = ^TrcPolyMesh;
/// Contains triangle meshes that represent detailed height data associated
/// with the polygons in its associated polygon mesh object.
/// @ingroup recast
TrcPolyMeshDetail = record
meshes: PCardinal; ///< The sub-mesh data. [Size: 4*#nmeshes]
verts: PSingle; ///< The mesh vertices. [Size: 3*#nverts]
tris: PByte; ///< The mesh triangles. [Size: 4*#ntris]
nmeshes: Integer; ///< The number of sub-meshes defined by #meshes.
nverts: Integer; ///< The number of vertices in #verts.
ntris: Integer; ///< The number of triangles in #tris.
end;
PrcPolyMeshDetail = ^TrcPolyMeshDetail;
/// @name Allocation Functions
/// Functions used to allocate and de-allocate Recast objects.
/// @see rcAllocSetCustom
/// @{
/// Allocates a heightfield object using the Recast allocator.
/// @return A heightfield that is ready for initialization, or null on failure.
/// @ingroup recast
/// @see rcCreateHeightfield, rcFreeHeightField
//rcHeightfield* rcAllocHeightfield();
/// Frees the specified heightfield object using the Recast allocator.
/// @param[in] hf A heightfield allocated using #rcAllocHeightfield
/// @ingroup recast
/// @see rcAllocHeightfield
//void rcFreeHeightField(rcHeightfield* hf);
/// Allocates a compact heightfield object using the Recast allocator.
/// @return A compact heightfield that is ready for initialization, or null on failure.
/// @ingroup recast
/// @see rcBuildCompactHeightfield, rcFreeCompactHeightfield
//rcCompactHeightfield* rcAllocCompactHeightfield();
/// Frees the specified compact heightfield object using the Recast allocator.
/// @param[in] chf A compact heightfield allocated using #rcAllocCompactHeightfield
/// @ingroup recast
/// @see rcAllocCompactHeightfield
//void rcFreeCompactHeightfield(rcCompactHeightfield* chf);
/// Allocates a heightfield layer set using the Recast allocator.
/// @return A heightfield layer set that is ready for initialization, or null on failure.
/// @ingroup recast
/// @see rcBuildHeightfieldLayers, rcFreeHeightfieldLayerSet
//rcHeightfieldLayerSet* rcAllocHeightfieldLayerSet();
/// Frees the specified heightfield layer set using the Recast allocator.
/// @param[in] lset A heightfield layer set allocated using #rcAllocHeightfieldLayerSet
/// @ingroup recast
/// @see rcAllocHeightfieldLayerSet
//void rcFreeHeightfieldLayerSet(rcHeightfieldLayerSet* lset);
/// Allocates a contour set object using the Recast allocator.
/// @return A contour set that is ready for initialization, or null on failure.
/// @ingroup recast
/// @see rcBuildContours, rcFreeContourSet
//rcContourSet* rcAllocContourSet();
/// Frees the specified contour set using the Recast allocator.
/// @param[in] cset A contour set allocated using #rcAllocContourSet
/// @ingroup recast
/// @see rcAllocContourSet
//void rcFreeContourSet(rcContourSet* cset);
/// Allocates a polygon mesh object using the Recast allocator.
/// @return A polygon mesh that is ready for initialization, or null on failure.
/// @ingroup recast
/// @see rcBuildPolyMesh, rcFreePolyMesh
//rcPolyMesh* rcAllocPolyMesh();
/// Frees the specified polygon mesh using the Recast allocator.
/// @param[in] pmesh A polygon mesh allocated using #rcAllocPolyMesh
/// @ingroup recast
/// @see rcAllocPolyMesh
//void rcFreePolyMesh(rcPolyMesh* pmesh);
/// Allocates a detail mesh object using the Recast allocator.
/// @return A detail mesh that is ready for initialization, or null on failure.
/// @ingroup recast
/// @see rcBuildPolyMeshDetail, rcFreePolyMeshDetail
//rcPolyMeshDetail* rcAllocPolyMeshDetail();
/// Frees the specified detail mesh using the Recast allocator.
/// @param[in] dmesh A detail mesh allocated using #rcAllocPolyMeshDetail
/// @ingroup recast
/// @see rcAllocPolyMeshDetail
//void rcFreePolyMeshDetail(rcPolyMeshDetail* dmesh);
/// @}
/// Heighfield border flag.
/// If a heightfield region ID has this bit set, then the region is a border
/// region and its spans are considered unwalkable.
/// (Used during the region and contour build process.)
/// @see rcCompactSpan::reg
const RC_BORDER_REG = $8000;
/// Border vertex flag.
/// If a region ID has this bit set, then the associated element lies on
/// a tile border. If a contour vertex's region ID has this bit set, the
/// vertex will later be removed in order to match the segments and vertices
/// at tile boundaries.
/// (Used during the build process.)
/// @see rcCompactSpan::reg, #rcContour::verts, #rcContour::rverts
const RC_BORDER_VERTEX = $10000;
/// Area border flag.
/// If a region ID has this bit set, then the associated element lies on
/// the border of an area.
/// (Used during the region and contour build process.)
/// @see rcCompactSpan::reg, #rcContour::verts, #rcContour::rverts
const RC_AREA_BORDER = $20000;
const
/// Contour build flags.
/// @see rcBuildContours
//TrcBuildContoursFlags =
//(
RC_CONTOUR_TESS_WALL_EDGES = $01; ///< Tessellate solid (impassable) edges during contour simplification.
RC_CONTOUR_TESS_AREA_EDGES = $02; ///< Tessellate edges between areas during contour simplification.
//);
/// Applied to the region id field of contour vertices in order to extract the region id.
/// The region id field of a vertex may have several flags applied to it. So the
/// fields value can't be used directly.
/// @see rcContour::verts, rcContour::rverts
const RC_CONTOUR_REG_MASK = $ffff;
/// An value which indicates an invalid index within a mesh.
/// @note This does not necessarily indicate an error.
/// @see rcPolyMesh::polys
const RC_MESH_NULL_IDX = $ffff;
/// Represents the null area.
/// When a data element is given this value it is considered to no longer be
/// assigned to a usable area. (E.g. It is unwalkable.)
const RC_NULL_AREA = 0;
/// The default area id used to indicate a walkable polygon.
/// This is also the maximum allowed area id, and the only non-null area id
/// recognized by some steps in the build process.
const RC_WALKABLE_AREA = 63;
/// The value returned by #rcGetCon if the specified direction is not connected
/// to another span. (Has no neighbor.)
const RC_NOT_CONNECTED = $3f;
/// @}
/// @name Heightfield Functions
/// @see rcHeightfield
/// @{
/// Calculates the bounding box of an array of vertices.
/// @ingroup recast
/// @param[in] verts An array of vertices. [(x, y, z) * @p nv]
/// @param[in] nv The number of vertices in the @p verts array.
/// @param[out] bmin The minimum bounds of the AABB. [(x, y, z)] [Units: wu]
/// @param[out] bmax The maximum bounds of the AABB. [(x, y, z)] [Units: wu]
procedure rcCalcBounds(const verts: PSingle; nv: Integer; bmin, bmax: PSingle);
/// Calculates the grid size based on the bounding box and grid cell size.
/// @ingroup recast
/// @param[in] bmin The minimum bounds of the AABB. [(x, y, z)] [Units: wu]
/// @param[in] bmax The maximum bounds of the AABB. [(x, y, z)] [Units: wu]
/// @param[in] cs The xz-plane cell size. [Limit: > 0] [Units: wu]
/// @param[out] w The width along the x-axis. [Limit: >= 0] [Units: vx]
/// @param[out] h The height along the z-axis. [Limit: >= 0] [Units: vx]
procedure rcCalcGridSize(const bmin, bmax: PSingle; cs: Single; w,h: PInteger);
/// Initializes a new heightfield.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in,out] hf The allocated heightfield to initialize.
/// @param[in] width The width of the field along the x-axis. [Limit: >= 0] [Units: vx]
/// @param[in] height The height of the field along the z-axis. [Limit: >= 0] [Units: vx]
/// @param[in] bmin The minimum bounds of the field's AABB. [(x, y, z)] [Units: wu]
/// @param[in] bmax The maximum bounds of the field's AABB. [(x, y, z)] [Units: wu]
/// @param[in] cs The xz-plane cell size to use for the field. [Limit: > 0] [Units: wu]
/// @param[in] ch The y-axis cell size to use for field. [Limit: > 0] [Units: wu]
function rcCreateHeightfield(ctx: TrcContext; var hf: TrcHeightfield; width, height: Integer;
const bmin, bmax: PSingle;
cs, ch: Single): Boolean;
/// Sets the area id of all triangles with a slope below the specified value
/// to #RC_WALKABLE_AREA.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in] walkableSlopeAngle The maximum slope that is considered walkable.
/// [Limits: 0 <= value < 90] [Units: Degrees]
/// @param[in] verts The vertices. [(x, y, z) * @p nv]
/// @param[in] nv The number of vertices.
/// @param[in] tris The triangle vertex indices. [(vertA, vertB, vertC) * @p nt]
/// @param[in] nt The number of triangles.
/// @param[out] areas The triangle area ids. [Length: >= @p nt]
procedure rcMarkWalkableTriangles(ctx: TrcContext; const walkableSlopeAngle: Single; const verts: PSingle; nv: Integer;
const tris: PInteger; nt: Integer; areas: PByte);
/// Sets the area id of all triangles with a slope greater than or equal to the specified value to #RC_NULL_AREA.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in] walkableSlopeAngle The maximum slope that is considered walkable.
/// [Limits: 0 <= value < 90] [Units: Degrees]
/// @param[in] verts The vertices. [(x, y, z) * @p nv]
/// @param[in] nv The number of vertices.
/// @param[in] tris The triangle vertex indices. [(vertA, vertB, vertC) * @p nt]
/// @param[in] nt The number of triangles.
/// @param[out] areas The triangle area ids. [Length: >= @p nt]
procedure rcClearUnwalkableTriangles(ctx: TrcContext; const walkableSlopeAngle: Single; const verts: PSingle; const nv: Integer;
const tris: PInteger; nt: Integer; out areas: PInteger);
/// Returns the number of spans contained in the specified heightfield.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in] hf An initialized heightfield.
/// @returns The number of spans in the heightfield.
function rcGetHeightFieldSpanCount(ctx: TrcContext; hf: PrcHeightfield): Integer;
/// @}
/// @name Compact Heightfield Functions
/// @see rcCompactHeightfield
/// @{
/// Builds a compact heightfield representing open space, from a heightfield representing solid space.
/// @ingroup recast
/// @param[in,out] ctx The build context to use during the operation.
/// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area
/// to be considered walkable. [Limit: >= 3] [Units: vx]
/// @param[in] walkableClimb Maximum ledge height that is considered to still be traversable.
/// [Limit: >=0] [Units: vx]
/// @param[in] hf The heightfield to be compacted.
/// @param[out] chf The resulting compact heightfield. (Must be pre-allocated.)
/// @returns True if the operation completed successfully.
function rcBuildCompactHeightfield(ctx: TrcContext; const walkableHeight, walkableClimb: Integer;
hf: PrcHeightfield; chf: PrcCompactHeightfield): Boolean;
implementation
uses
RN_RecastHelper;
procedure rcCalcBounds(const verts: PSingle; nv: Integer; bmin, bmax: PSingle);
var i: Integer; v: PSingle;
begin
// Calculate bounding box.
rcVcopy(bmin, verts);
rcVcopy(bmax, verts);
for i := 1 to nv - 1 do
begin
v := @verts[i*3];
rcVmin(bmin, v);
rcVmax(bmax, v);
end;
end;
procedure rcCalcGridSize(const bmin, bmax: PSingle; cs: Single; w,h: PInteger);
begin
w^ := Trunc((bmax[0] - bmin[0])/cs+0.5);
h^ := Trunc((bmax[2] - bmin[2])/cs+0.5);
end;
/// @par
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcAllocHeightfield, rcHeightfield
function rcCreateHeightfield(ctx: TrcContext; var hf: TrcHeightfield; width, height: Integer;
const bmin, bmax: PSingle;
cs, ch: Single): Boolean;
begin
//rcIgnoreUnused(ctx);
hf.width := width;
hf.height := height;
rcVcopy(@hf.bmin[0], bmin);
rcVcopy(@hf.bmax[0], bmax);
hf.cs := cs;
hf.ch := ch;
SetLength(hf.spans, hf.width * hf.height);
Result := true;
end;
procedure calcTriNormal(const v0, v1, v2: PSingle; norm: PSingle);
var e0, e1: array [0..2] of Single;
begin
rcVsub(@e0[0], v1, v0);
rcVsub(@e1[0], v2, v0);
rcVcross(norm, @e0[0], @e1[0]);
rcVnormalize(norm);
end;
/// @par
///
/// Only sets the aread id's for the walkable triangles. Does not alter the
/// area id's for unwalkable triangles.
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles
procedure rcMarkWalkableTriangles(ctx: TrcContext; const walkableSlopeAngle: Single; const verts: PSingle; nv: Integer;
const tris: PInteger; nt: Integer; areas: PByte);
var walkableThr: Single; norm: array [0..2] of Single; i: Integer; tri: PInteger;
begin
//rcIgnoreUnused(ctx);
walkableThr := cos(walkableSlopeAngle/180*Pi);
for i := 0 to nt - 1 do
begin
tri := @tris[i*3];
calcTriNormal(@verts[tri[0]*3], @verts[tri[1]*3], @verts[tri[2]*3], @norm[0]);
// Check if the face is walkable.
if (norm[1] > walkableThr) then
areas[i] := RC_WALKABLE_AREA;
end;
end;
/// @par
///
/// Only sets the aread id's for the unwalkable triangles. Does not alter the
/// area id's for walkable triangles.
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcHeightfield, rcClearUnwalkableTriangles, rcRasterizeTriangles
procedure rcClearUnwalkableTriangles(ctx: TrcContext; const walkableSlopeAngle: Single; const verts: PSingle; const nv: Integer;
const tris: PInteger; nt: Integer; out areas: PInteger);
var walkableThr: Single; norm: array [0..2] of Single; i: Integer; tri: PInteger;
begin
//rcIgnoreUnused(ctx);
walkableThr := cos(walkableSlopeAngle/180.0*PI);
for i := 0 to nt - 1 do
begin
tri := @tris[i*3];
calcTriNormal(@verts[tri[0]*3], @verts[tri[1]*3], @verts[tri[2]*3], @norm[0]);
// Check if the face is walkable.
if (norm[1] <= walkableThr) then
areas[i] := RC_NULL_AREA;
end;
end;
function rcGetHeightFieldSpanCount(ctx: TrcContext; hf: PrcHeightfield): Integer;
var y,x,w,h,spanCount: Integer; s: PrcSpan;
begin
w := hf.width;
h := hf.height;
spanCount := 0;
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
s := hf.spans[x + y*w];
while s <> nil do
begin
if (s.area <> RC_NULL_AREA) then
Inc(spanCount);
s := s.next;
end;
end;
end;
Result := spanCount;
end;
/// @par
///
/// This is just the beginning of the process of fully building a compact heightfield.
/// Various filters may be applied applied, then the distance field and regions built.
/// E.g: #rcBuildDistanceField and #rcBuildRegions
///
/// See the #rcConfig documentation for more information on the configuration parameters.
///
/// @see rcAllocCompactHeightfield, rcHeightfield, rcCompactHeightfield, rcConfig
function rcBuildCompactHeightfield(ctx: TrcContext; const walkableHeight, walkableClimb: Integer;
hf: PrcHeightfield; chf: PrcCompactHeightfield): Boolean;
const MAX_HEIGHT = $ffff;
const MAX_LAYERS = RC_NOT_CONNECTED-1;
var w,h,spanCount: Integer; idx,x,y: Integer; s: PrcSpan; c, nc: PrcCompactCell; bot,top: Integer;
tooHighNeighbour: Integer; nx,ny: Integer; cs, ncs: PrcCompactSpan;
i,dir,k: Integer; lidx: Integer;
begin
//rcAssert(ctx);
ctx.startTimer(RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
w := hf.width;
h := hf.height;
spanCount := rcGetHeightFieldSpanCount(ctx, hf);
// Fill in header.
chf.width := w;
chf.height := h;
chf.spanCount := spanCount;
chf.walkableHeight := walkableHeight;
chf.walkableClimb := walkableClimb;
chf.maxRegions := 0;
rcVcopy(@chf.bmin[0], @hf.bmin[0]);
rcVcopy(@chf.bmax[0], @hf.bmax[0]);
chf.bmax[1] := chf.bmax[1] + walkableHeight*hf.ch;
chf.cs := hf.cs;
chf.ch := hf.ch;
SetLength(chf.cells, w*h);
SetLength(chf.spans, spanCount);
GetMem(chf.areas, sizeof(Byte)*spanCount);
FillChar(chf.areas[0], sizeof(Byte)*spanCount, RC_NULL_AREA);
// Fill in cells and spans.
idx := 0;
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
s := hf.spans[x + y*w];
// If there are no spans at this cell, just leave the data to index=0, count=0.
if (s = nil) then Continue;
c := @chf.cells[x+y*w];
c.index := idx;
c.count := 0;
while (s <> nil) do
begin
if (s.area <> RC_NULL_AREA) then
begin
bot := Integer(s.smax);
if s.next <> nil then top := Integer(s.next.smin) else top := MAX_HEIGHT;
chf.spans[idx].y := Word(rcClamp(bot, 0, $ffff));
chf.spans[idx].h := Byte(rcClamp(top - bot, 0, $ff));
chf.areas[idx] := s.area;
Inc(idx);
Inc(c.count);
end;
s := s.next;
end;
end;
end;
// Find neighbour connections.
//const int MAX_LAYERS = RC_NOT_CONNECTED-1;
tooHighNeighbour := 0;
for y := 0 to h - 1 do
begin
for x := 0 to w - 1 do
begin
c := @chf.cells[x+y*w];
for i := c.index to Integer(c.index+c.count) - 1 do
begin
cs := @chf.spans[i]; // s-> cs
for dir := 0 to 3 do
begin
rcSetCon(cs, dir, RC_NOT_CONNECTED);
nx := x + rcGetDirOffsetX(dir);
ny := y + rcGetDirOffsetY(dir);
// First check that the neighbour cell is in bounds.
if (nx < 0) or (ny < 0) or (nx >= w) or (ny >= h) then
Continue;
// Iterate over all neighbour spans and check if any of the is
// accessible from current cell.
nc := @chf.cells[nx+ny*w];
for k := nc.index to Integer(nc.index+nc.count) - 1 do
begin
ncs := @chf.spans[k]; // ns -> ncs
bot := rcMax(cs.y, ncs.y);
top := rcMin(cs.y+cs.h, ncs.y+ncs.h);
// Check that the gap between the spans is walkable,
// and that the climb height between the gaps is not too high.
if ((top - bot) >= walkableHeight) and (Abs(ncs.y - cs.y) <= walkableClimb) then
begin
// Mark direction as walkable.
lidx := k - nc.index;
if (lidx < 0) or (lidx > MAX_LAYERS) then
begin
tooHighNeighbour := rcMax(tooHighNeighbour, lidx);
Continue;
end;
rcSetCon(cs, dir, lidx);
break;
end;
end;
end;
end;
end;
end;
if (tooHighNeighbour > MAX_LAYERS) then
begin
ctx.log(RC_LOG_ERROR, Format('rcBuildCompactHeightfield: Heightfield has too many layers %d (max: %d)',
[tooHighNeighbour, MAX_LAYERS]));
end;
ctx.stopTimer(RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
Result := True;
end;
{ TrcContext }
constructor TrcContext.Create(state: Boolean);
begin
m_logEnabled := state;
m_timerEnabled := state;
end;
function TrcContext.doGetAccumulatedTime(const &label: TrcTimerLabel): Integer;
begin
Result := -1;
end;
procedure TrcContext.enableLog(state: Boolean);
begin
m_logEnabled := state;
end;
procedure TrcContext.enableTimer(state: Boolean);
begin
m_timerEnabled := state;
end;
function TrcContext.getAccumulatedTime(aLabel: TrcTimerLabel): Integer;
begin
if m_timerEnabled then Result := doGetAccumulatedTime(alabel) else Result := -1;
end;
procedure TrcContext.log(category: TrcLogCategory; msg: string);
const MSG_SIZE = 512;
var len: Integer;
begin
if (not m_logEnabled) then
Exit;
len := Length(msg);
if (len >= MSG_SIZE) then
begin
len := MSG_SIZE-1;
SetLength(msg, len);
end;
doLog(category, msg);
end;
procedure TrcContext.resetLog;
begin
if (m_logEnabled) then doResetLog();
end;
procedure TrcContext.resetTimers;
begin
if (m_timerEnabled) then doResetTimers();
end;
procedure TrcContext.startTimer(aLabel: TrcTimerLabel);
begin
if (m_timerEnabled) then doStartTimer(aLabel);
end;
procedure TrcContext.stopTimer(aLabel: TrcTimerLabel);
begin
if (m_timerEnabled) then doStopTimer(aLabel);
end;
end.
|
{
Single Source Shortest Paths - Without Negative Weight Edges
Dijkstra Algorthm O(N2)
Input:
G: Directed weighted graph (No Edge = Infinity)
N: Number of vertices
S: The source vertex
Output:
D[I]: Length of minimum path from S to I (No Path = Infinity)
P[I]: Parent of vertex I in its path from S, P[S] = 0, (No Path->P[I]=0)
Note:
Infinity should be less than the max value of its type
No negative edge
Reference:
CLR, p527
By Ali
}
program
Dijkstra;
const
MaxN = 100 + 1;
Infinity = 10000;
var
N, S: Integer;
G: array [1 .. MaxN, 1 .. MaxN] of Integer;
D, P: Array[1..MaxN] of Integer;
NoAnswer: Boolean;
Mark: array[1 .. MaxN] of Boolean;
procedure Relax(V, U: Integer);
begin
if D[U] > D[V] + G[V, U] then
begin
D[U] := D[V] + G[V, U];
P[U] := V;
end;
end;
procedure SSSP;
var
I, U, Step: Integer;
Min: Integer;
begin
FillChar(Mark, SizeOf(Mark), 0);
FillChar(P, SizeOf(P), 0);
for I := 1 to N do
D[I] := Infinity;
D[S] := 0;
for Step := 1 to N do
begin
Min := Infinity;
for I := 1 to N do
if not Mark[I] and (D[I] < Min) then
begin
U := I;
Min := D[I];
end;
if Min = Infinity then
Break;
Mark[U] := True;
for I := 1 to N do
Relax(U, I);
end;
end;
begin
SSSP;
end.
|
UNIT FileUtil;
interface
uses DOS, CRT;
function Exists(name: STRING):Boolean;
PROCEDURE ChooseFile (VAR NameOfFile : STRING);
procedure BackUpFile(origfilename, tempfilename : STRING);
{leave unaltered file with a '.BAK' extension
Rename tempfilename as old file name.}
implementation
function Exists(name: STRING):Boolean;
var
Fil: file;
begin
If length(name) < 1 THEN Exists := FALSE
ELSE BEGIN
Assign(Fil,name);
{$I-}
Reset(Fil);
Close(Fil);
{$I+}
Exists := (IOresult = 0);
END;
end; {exist}
PROCEDURE ChooseFile (VAR NameOfFile : STRING);
begin
Writeln ('Name of file (include extension)?'); ClrEol;
Readln(NameOfFile);ClrEol;
if NOT Exists(NameOfFile) then
BEGIN
writeln('File ',NameOfFile,' does not exist here.');ClrEol;
writeln('Choose again or <Ctrl><Break> to exit.');ClrEol;
writeln;
Choosefile(NameOfFile); (* recursive call *)
END;
end; {choosefile}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure BackUpFile(origfilename, tempfilename : STRING);
{leave unaltered file with a '.BAK' extension
Rename TEMP file as old file name.}
var temp : STRING;
tempfile : file;
begin
if pos('.',origfilename)<>0 then
temp := copy(origfileName,1,pos('.',origfilename)-1)+ '.BAK'
else
temp := origfilename + '.BAK';
if Exists(temp) then
begin
Assign(tempfile,temp);
Erase(tempfile);
end;
(* assign original to backup *)
Assign(tempfile,origfilename);
Rename(tempfile,temp);
(* assign temp to original *)
Assign(tempfile,tempfilename);
Rename(tempfile,origfilename);
end; {BackUpFile}
BEGIN
END. |
{================================================================================================ }
{ FMOD Types header file. Copyright (c), Firelight Technologies Pty, Ltd. 1999-2004. }
{ =============================================================================================== }
{
NOTE: For the demos to run you must have either fmod.dll (in Windows)
or libfmod-3.75.so (in Linux) installed.
In Windows, copy the fmod.dll file found in the api directory to either of
the following locations (in order of preference)
- your application directory
- Windows\System (95/98) or WinNT\System32 (NT/2000/XP)
In Linux, make sure you are signed in as root and copy the libfmod-3.75.so
file from the api directory to your /usr/lib/ directory.
Then via a command line, navigate to the /usr/lib/ directory and create
a symbolic link between libfmod-3.75.so and libfmod.so. This is done with
the following command (assuming you are in /usr/lib/)...
ln -s libfmod-3.75.so libfmod.so.
}
{ =============================================================================================== }
unit fmodtypes;
interface
{$IFDEF MSWINDOWS}
uses
Windows;
{$ENDIF}
{ =============================================================================================== }
{ DEFINITIONS }
{ =============================================================================================== }
{
Force four-byte enums
}
{$Z4}
const
FMOD_VERSION: Single = 3.75;
{
FMOD defined types
}
type
PFSoundSample = Pointer;
PFSoundStream = Pointer;
PFSoundDSPUnit = Pointer;
PFMusicModule = Pointer;
PFSyncPoint = Pointer;
PFSoundVector = ^TFSoundVector;
TFSoundVector = record
x: Single;
y: Single;
z: Single;
end;
{
Callback types
}
TFSoundStreamCallback = function (Stream: PFSoundStream; Buff: Pointer; Length, Param: Integer): ByteBool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFSoundDSPCallback = function (OriginalBuffer: Pointer; NewBuffer: Pointer; Length, Param: Integer): Pointer; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFMusicCallback = procedure (Module: PFMusicModule; Param: Byte); {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFSoundOpenCallback = function (Name: PChar): Cardinal; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFSoundCloseCallback = procedure (Handle: Cardinal); {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFSoundReadCallback = function (Buffer: Pointer; Size: Cardinal; Handle: Cardinal): Cardinal; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFSoundSeekCallback = procedure (Handle: Cardinal; Pos: Cardinal; Mode: Byte); {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFSoundTellCallback = function (Handle: Cardinal): Cardinal; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFSoundAllocCallback = function(Size: Cardinal): Pointer; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFSoundReallocCallback = function(Ptr: Pointer; Size: Cardinal): Pointer; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFSoundFreeCallback = procedure(Ptr: Pointer); {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
TFMetaDataCallback = function(Name: PChar; Value: PChar; userdata: Integer): ByteBool; {$IFDEF UNIX} cdecl {$ELSE} stdcall {$ENDIF};
{
[ENUM]
[
[DESCRIPTION]
On failure of commands in FMOD, use FSOUND_GetError to attain what happened.
[SEE_ALSO]
FSOUND_GetError
]
}
type
TFModErrors = (
FMOD_ERR_NONE, // No errors
FMOD_ERR_BUSY, // Cannot call this command after FSOUND_Init. Call FSOUND_Close first.
FMOD_ERR_UNINITIALIZED, // This command failed because FSOUND_Init was not called
FMOD_ERR_INIT, // Error initializing output device.
FMOD_ERR_ALLOCATED, // Error initializing output device, but more specifically, the output device is already in use and cannot be reused.
FMOD_ERR_PLAY, // Playing the sound failed.
FMOD_ERR_OUTPUT_FORMAT, // Soundcard does not support the features needed for this soundsystem (16bit stereo output)
FMOD_ERR_COOPERATIVELEVEL, // Error setting cooperative level for hardware.
FMOD_ERR_CREATEBUFFER, // Error creating hardware sound buffer.
FMOD_ERR_FILE_NOTFOUND, // File not found
FMOD_ERR_FILE_FORMAT, // Unknown file format
FMOD_ERR_FILE_BAD, // Error loading file
FMOD_ERR_MEMORY, // Not enough memory or resources
FMOD_ERR_VERSION, // The version number of this file format is not supported
FMOD_ERR_INVALID_PARAM, // An invalid parameter was passed to this function
FMOD_ERR_NO_EAX, // Tried to use an EAX command on a non EAX enabled channel or output.
FMOD_ERR_CHANNEL_ALLOC, // Failed to allocate a new channel
FMOD_ERR_RECORD, // Recording is not supported on this machine
FMOD_ERR_MEDIAPLAYER, // Windows Media Player not installed so cannot play wma or use internet streaming. */
FMOD_ERR_CDDEVICE // An error occured trying to open the specified CD device
);
{
[ENUM]
[
[DESCRIPTION]
These output types are used with FSOUND_SetOutput, to choose which output driver to use.
FSOUND_OUTPUT_DSOUND will not support hardware 3d acceleration if the sound card driver
does not support DirectX 6 Voice Manager Extensions.
FSOUND_OUTPUT_WINMM is recommended for NT and CE.
[SEE_ALSO]
FSOUND_SetOutput
FSOUND_GetOutput
]
}
type
TFSoundOutputTypes = (
FSOUND_OUTPUT_NOSOUND, // NoSound driver, all calls to this succeed but do nothing.
FSOUND_OUTPUT_WINMM, // Windows Multimedia driver.
FSOUND_OUTPUT_DSOUND, // DirectSound driver. You need this to get EAX2 or EAX3 support, or FX api support.
FSOUND_OUTPUT_A3D, // A3D driver.
FSOUND_OUTPUT_OSS, // Linux/Unix OSS (Open Sound System) driver, i.e. the kernel sound drivers.
FSOUND_OUTPUT_ESD, // Linux/Unix ESD (Enlightment Sound Daemon) driver.
FSOUND_OUTPUT_ALSA, // Linux Alsa driver.
FSOUND_OUTPUT_ASIO, // Low latency ASIO driver.
FSOUND_OUTPUT_XBOX, // Xbox driver.
FSOUND_OUTPUT_PS2, // PlayStation 2 driver.
FSOUND_OUTPUT_MAC, // Mac SoundMager driver.
FSOUND_OUTPUT_GC, // Gamecube driver.
FSOUND_OUTPUT_PSP, // PlayStation Portable driver.
FSOUND_OUTPUT_NOSOUND_NONREALTIME // This is the same as nosound, but the sound generation is driven by FSOUND_Update
);
{
[ENUM]
[
[DESCRIPTION]
These mixer types are used with FSOUND_SetMixer, to choose which mixer to use, or to act
upon for other reasons using FSOUND_GetMixer.
It is not necessary to set the mixer. FMOD will autodetect the best mixer for you.
[SEE_ALSO]
FSOUND_SetMixer
FSOUND_GetMixer
]
}
type
TFSoundMixerTypes = (
FSOUND_MIXER_AUTODETECT, // CE/PS2/GC Only - Non interpolating/low quality mixer.
FSOUND_MIXER_BLENDMODE, // Removed / obsolete
FSOUND_MIXER_MMXP5, // Removed / obsolete
FSOUND_MIXER_MMXP6, // Removed / obsolete
FSOUND_MIXER_QUALITY_AUTODETECT,// All platforms - Autodetect the fastest quality mixer based on your cpu.
FSOUND_MIXER_QUALITY_FPU, // Win32/Linux only - Interpolating/volume ramping FPU mixer.
FSOUND_MIXER_QUALITY_MMXP5, // Win32/Linux only - Interpolating/volume ramping P5 MMX mixer.
FSOUND_MIXER_QUALITY_MMXP6, // Win32/Linux only - Interpolating/volume ramping ppro+ MMX mixer.
FSOUND_MIXER_MONO, // CE/PS2/GC only - MONO non interpolating/low quality mixer. For speed
FSOUND_MIXER_QUALITY_MONO, // CE/PS2/GC only - MONO Interpolating mixer. For speed
FSOUND_MIXER_MAX
);
{
[ENUM]
[
[DESCRIPTION]
These definitions describe the type of song being played.
[SEE_ALSO]
FMUSIC_GetType
]
}
type
TFMusicTypes = (
FMUSIC_TYPE_NONE,
FMUSIC_TYPE_MOD, // Protracker / FastTracker
FMUSIC_TYPE_S3M, // ScreamTracker 3
FMUSIC_TYPE_XM, // FastTracker 2
FMUSIC_TYPE_IT, // Impulse Tracker
FMUSIC_TYPE_MIDI, // MIDI file
FMUSIC_TYPE_FSB // FMOD Sample Bank file
);
{
[DEFINE_START]
[
[NAME]
FSOUND_DSP_PRIORITIES
[DESCRIPTION]
These default priorities are used by FMOD internal system DSP units. They describe the
position of the DSP chain, and the order of how audio processing is executed.
You can actually through the use of FSOUND_DSP_GetxxxUnit (where xxx is the name of the DSP
unit), disable or even change the priority of a DSP unit.
[SEE_ALSO]
FSOUND_DSP_Create
FSOUND_DSP_SetPriority
FSOUND_DSP_GetSpectrum
]
}
const
FSOUND_DSP_DEFAULTPRIORITY_CLEARUNIT = 0; // DSP CLEAR unit - done first
FSOUND_DSP_DEFAULTPRIORITY_SFXUNIT = 100; // DSP SFX unit - done second
FSOUND_DSP_DEFAULTPRIORITY_MUSICUNIT = 200; // DSP MUSIC unit - done third
FSOUND_DSP_DEFAULTPRIORITY_USER = 300; // User priority, use this as reference for your own DSP units
FSOUND_DSP_DEFAULTPRIORITY_FFTUNIT = 900; // This reads data for FSOUND_DSP_GetSpectrum, so it comes after user units
FSOUND_DSP_DEFAULTPRIORITY_CLIPANDCOPYUNIT = 1000; // DSP CLIP AND COPY unit - last
// [DEFINE_END]
{
[DEFINE_START]
[
[NAME]
FSOUND_CAPS
[DESCRIPTION]
Driver description bitfields. Use FSOUND_Driver_GetCaps to determine if a driver enumerated
has the settings you are after. The enumerated driver depends on the output mode, see
FSOUND_OUTPUTTYPES
[SEE_ALSO]
FSOUND_GetDriverCaps
FSOUND_OUTPUTTYPES
]
}
const
FSOUND_CAPS_HARDWARE = $1; // This driver supports hardware accelerated 3d sound.
FSOUND_CAPS_EAX2 = $2; // This driver supports EAX 2 reverb
FSOUND_CAPS_EAX3 = $10; // This driver supports EAX 3 reverb
// [DEFINE_END]
{
[DEFINE_START]
[
[NAME]
FSOUND_MODES
[DESCRIPTION]
Sample description bitfields, OR them together for loading and describing samples.
NOTE. If the file format being loaded already has a defined format, such as WAV or MP3, then
trying to override the pre-defined format with a new set of format flags will not work. For
example, an 8 bit WAV file will not load as 16bit if you specify FSOUND_16BITS. It will just
ignore the flag and go ahead loading it as 8bits. For these type of formats the only flags
you can specify that will really alter the behaviour of how it is loaded, are the following.
Looping behaviour - FSOUND_LOOP_OFF, FSOUND_LOOP_NORMAL, FSOUND_LOOP_BIDI
Load destination - FSOUND_HW3D, FSOUND_HW2D, FSOUND_2D
Loading behaviour - FSOUND_NONBLOCKING, FSOUND_LOADMEMORY, FSOUND_LOADRAW, FSOUND_MPEGACCURATE, FSOUND_MPEGHALFRATE, FSOUND_FORCEMONO
Playback behaviour - FSOUND_STREAMABLE, FSOUND_ENABLEFX
PlayStation 2 only - FSOUND_USECORE0, FSOUND_USECORE1, FSOUND_LOADMEMORYIOP
See flag descriptions for what these do.
]
}
const
FSOUND_LOOP_OFF = $00000001; // For non looping samples.
FSOUND_LOOP_NORMAL = $00000002; // For forward looping samples.
FSOUND_LOOP_BIDI = $00000004; // For bidirectional looping samples. (no effect if in hardware).
FSOUND_8BITS = $00000008; // For 8 bit samples.
FSOUND_16BITS = $00000010; // For 16 bit samples.
FSOUND_MONO = $00000020; // For mono samples.
FSOUND_STEREO = $00000040; // For stereo samples.
FSOUND_UNSIGNED = $00000080; // For user created source data containing unsigned samples.
FSOUND_SIGNED = $00000100; // For user created source data containing signed data.
FSOUND_DELTA = $00000200; // For user created source data stored as delta values.
FSOUND_IT214 = $00000400; // For user created source data stored using IT214 compression.
FSOUND_IT215 = $00000800; // For user created source data stored using IT215 compression.
FSOUND_HW3D = $00001000; // Attempts to make samples use 3d hardware acceleration. (if the card supports it)
FSOUND_2D = $00002000; // Ignores any 3d processing. Overrides FSOUND_HW3D. Located in software.
FSOUND_STREAMABLE = $00004000; // For a streamimg sound where you feed the data to it. */
FSOUND_LOADMEMORY = $00008000; // "name" will be interpreted as a pointer to data for streaming and samples.
FSOUND_LOADRAW = $00010000; // Will ignore file format and treat as raw pcm.
FSOUND_MPEGACCURATE = $00020000; // For FSOUND_Stream_OpenFile - for accurate FSOUND_Stream_GetLengthMs/FSOUND_Stream_SetTime. WARNING, see FSOUND_Stream_OpenFile for inital opening time performance issues.
FSOUND_FORCEMONO = $00040000; // For forcing stereo streams and samples to be mono - needed if using FSOUND_HW3D and stereo data - incurs a small speed hit for streams
FSOUND_HW2D = $00080000; // 2D hardware sounds. allows hardware specific effects
FSOUND_ENABLEFX = $00100000; // Allows DX8 FX to be played back on a sound. Requires DirectX 8 - Note these sounds cannot be played more than once, be 8 bit, be less than a certain size, or have a changing frequency
FSOUND_MPEGHALFRATE = $00200000; // For FMODCE only - decodes mpeg streams using a lower quality decode, but faster execution
FSOUND_XADPCM = $00400000; // For XBOX only - Contents are compressed as XADPCM */
FSOUND_VAG = $00800000; // For PS2 only - Contents are compressed as Sony VAG format */
FSOUND_NONBLOCKING = $01000000; // For FSOUND_Stream_OpenFile - Causes stream to open in the background and not block the foreground app - stream plays only when ready.
FSOUND_GCADPCM = $02000000; // For Gamecube only - Contents are compressed as Gamecube DSP-ADPCM format
FSOUND_MULTICHANNEL = $04000000; // For PS2 only - Contents are interleaved into a multi-channel (more than stereo) format
FSOUND_USECORE0 = $08000000; // For PS2 only - Sample/Stream is forced to use hardware voices 00-23
FSOUND_USECORE1 = $10000000; // For PS2 only - Sample/Stream is forced to use hardware voices 24-47
FSOUND_LOADMEMORYIOP = $20000000; // For PS2 only - "name" will be interpreted as a pointer to data for streaming and samples. The address provided will be an IOP address
const
FSOUND_NORMAL = (FSOUND_16BITS or FSOUND_SIGNED or FSOUND_MONO);
// [DEFINE_END]
{
[DEFINE_START]
[
[NAME]
FSOUND_CDPLAYMODES
[DESCRIPTION]
Playback method for a CD Audio track, using FSOUND_CD_SetPlayMode
[SEE_ALSO]
FSOUND_CD_SetPlayMode
FSOUND_CD_Play
]
}
const
FSOUND_CD_PLAYCONTINUOUS = 0; // Starts from the current track and plays to end of CD.
FSOUND_CD_PLAYONCE = 1; // Plays the specified track then stops.
FSOUND_CD_PLAYLOOPED = 2; // Plays the specified track looped, forever until stopped manually.
FSOUND_CD_PLAYRANDOM = 3; // Plays tracks in random order
// [DEFINE_END]
{
[DEFINE_START]
[
[NAME]
FSOUND_CHANNELSAMPLEMODE
[DESCRIPTION]
Miscellaneous values for FMOD functions.
[SEE_ALSO]
FSOUND_PlaySound
FSOUND_PlaySoundEx
FSOUND_Sample_Alloc
FSOUND_Sample_Load
FSOUND_SetPan
]
}
const
FSOUND_FREE = -1; // value to play on any free channel, or to allocate a sample in a free sample slot.
FSOUND_UNMANAGED = -2; // value to allocate a sample that is NOT managed by FSOUND or placed in a sample slot.
FSOUND_ALL = -3; // for a channel index , this flag will affect ALL channels available! Not supported by every function.
FSOUND_STEREOPAN = -1; // value for FSOUND_SetPan so that stereo sounds are not played at half volume. See FSOUND_SetPan for more on this.
FSOUND_SYSTEMCHANNEL = -1000; // special 'channel' ID for all channel based functions that want to alter the global FSOUND software mixing output
FSOUND_SYSTEMSAMPLE = -1000; // special 'sample' ID for all sample based functions that want to alter the global FSOUND software mixing output sample
// [DEFINE_END]
{
[STRUCT_START]
[
[NAME]
FSOUND_REVERB_PROPERTIES
[DESCRIPTION]
Structure defining a reverb environment.
[REMARKS]
For more indepth descriptions of the reverb properties under win32, please see the EAX2/EAX3
documentation at http://developer.creative.com/ under the 'downloads' section.
If they do not have the EAX3 documentation, then most information can be attained from
the EAX2 documentation, as EAX3 only adds some more parameters and functionality on top of
EAX2.
Note the default reverb properties are the same as the FSOUND_PRESET_GENERIC preset.
Note that integer values that typically range from -10,000 to 1000 are represented in
decibels, and are of a logarithmic scale, not linear, wheras float values are typically linear.
PORTABILITY: Each member has the platform it supports in braces ie (win32/xbox).
Some reverb parameters are only supported in win32 and some only on xbox. If all parameters are set then
the reverb should product a similar effect on either platform.
Only WIN32 supports the reverb api.
The numerical values listed below are the maximum, minimum and default values for each variable respectively.
[SEE_ALSO]
FSOUND_Reverb_SetProperties
FSOUND_Reverb_GetProperties
FSOUND_REVERB_PRESETS
FSOUND_REVERB_FLAGS
]
}
type
TFSoundReverbProperties = record // MIN MAX DEFAULT DESCRIPTION
Environment: Cardinal; // 0 25 0 sets all listener properties (win32 only)
EnvSize: Single; // 1.0 100.0 7.5 environment size in meters (win32 only)
EnvDiffusion: Single; // 0.0 1.0 1.0 environment diffusion (win32/xbox)
Room: Integer; // -10000 0 -1000 room effect level (at mid frequencies) (win32/xbox)
RoomHF: Integer; // -10000 0 -100 relative room effect level at high frequencies (win32/xbox)
RoomLF: Integer; // -10000 0 0 relative room effect level at low frequencies (win32 only)
DecayTime: Single; // 0.1 20.0 1.49 reverberation decay time at mid frequencies (win32/xbox)
DecayHFRatio: Single; // 0.1 2.0 0.83 high-frequency to mid-frequency decay time ratio (win32/xbox)
DecayLFRatio: Single; // 0.1 2.0 1.0 low-frequency to mid-frequency decay time ratio (win32 only)
Reflections: Integer; // -10000 1000 -2602 early reflections level relative to room effect (win32/xbox)
ReflectionsDelay: Single; // 0.0 0.3 0.007 initial reflection delay time (win32/xbox)
ReflectionsPan: array [0..2] of Single; // 0,0,0 early reflections panning vector (win32 only)
Reverb: Integer; // -10000 2000 200 late reverberation level relative to room effect (win32/xbox)
ReverbDelay: Single; // 0.0 0.1 0.011 late reverberation delay time relative to initial reflection (win32/xbox)
ReverbPan: array [0..2] of Single; // 0,0,0 late reverberation panning vector (win32 only)
EchoTime: Single; // .075 0.25 0.25 echo time (win32 only)
EchoDepth: Single; // 0.0 1.0 0.0 echo depth (win32 only)
ModulationTime: Single; // 0.04 4.0 0.25 modulation time (win32 only)
ModulationDepth: Single; // 0.0 1.0 0.0 modulation depth (win32 only)
AirAbsorptionHF: Single; // -100 0.0 -5.0 change in level per meter at high frequencies (win32 only)
HFReference: Single; // 1000.0 20000 5000.0 reference high frequency (hz) (win32/xbox)
LFReference: Single; // 20.0 1000.0 250.0 reference low frequency (hz) (win32 only)
RoomRolloffFactor: Single; // 0.0 10.0 0.0 like FSOUND_3D_SetRolloffFactor but for room effect (win32/xbox)
Diffusion: Single; // 0.0 100.0 100.0 Value that controls the echo density in the late reverberation decay. (xbox only)
Density: Single; // 0.0 100.0 100.0 Value that controls the modal density in the late reverberation decay (xbox only)
Flags: Cardinal; // FSOUND_REVERB_PROPERTYFLAGS - modifies the behavior of above properties (win32 only)
end;
// [STRUCT_END]
{
[DEFINE_START]
[
[NAME]
FSOUND_REVERB_FLAGS
[DESCRIPTION]
Values for the Flags member of the FSOUND_REVERB_PROPERTIES structure.
[SEE_ALSO]
FSOUND_REVERB_PROPERTIES
]
}
const
FSOUND_REVERBFLAGS_DECAYTIMESCALE = $00000001; // EnvironmentSize affects reverberation decay time
FSOUND_REVERBFLAGS_REFLECTIONSSCALE = $00000002; // EnvironmentSize affects reflection level
FSOUND_REVERBFLAGS_REFLECTIONSDELAYSCALE = $00000004; // EnvironmentSize affects initial reflection delay time
FSOUND_REVERBFLAGS_REVERBSCALE = $00000008; // EnvironmentSize affects reflections level
FSOUND_REVERBFLAGS_REVERBDELAYSCALE = $00000010; // EnvironmentSize affects late reverberation delay time
FSOUND_REVERBFLAGS_DECAYHFLIMIT = $00000020; // AirAbsorptionHF affects DecayHFRatio
FSOUND_REVERBFLAGS_ECHOTIMESCALE = $00000040; // EnvironmentSize affects echo time
FSOUND_REVERBFLAGS_MODULATIONTIMESCALE = $00000080; // EnvironmentSize affects modulation time
FSOUND_REVERB_FLAGS_CORE0 = $00000100; // PS2 Only - Reverb is applied to CORE0 (hw voices 0-23)
FSOUND_REVERB_FLAGS_CORE1 = $00000200; // PS2 Only - Reverb is applied to CORE1 (hw voices 24-47)
FSOUND_REVERBFLAGS_DEFAULT = FSOUND_REVERBFLAGS_DECAYTIMESCALE or FSOUND_REVERBFLAGS_REFLECTIONSSCALE or
FSOUND_REVERBFLAGS_REFLECTIONSDELAYSCALE or FSOUND_REVERBFLAGS_REVERBSCALE or
FSOUND_REVERBFLAGS_REVERBDELAYSCALE or FSOUND_REVERBFLAGS_DECAYHFLIMIT or
FSOUND_REVERB_FLAGS_CORE0 or FSOUND_REVERB_FLAGS_CORE1;
// [DEFINE_END]
{
[DEFINE_START]
[
[NAME]
FSOUND_REVERB_PRESETS
[DESCRIPTION]
A set of predefined environment PARAMETERS, created by Creative Labs
These are used to initialize an FSOUND_REVERB_PROPERTIES structure statically.
ie
FSOUND_REVERB_PROPERTIES prop = FSOUND_PRESET_GENERIC;
[SEE_ALSO]
FSOUND_Reverb_SetProperties
]
}
{
const
// Env Size Diffus Room RoomHF RmLF DecTm DecHF DecLF Refl RefDel RefPan Revb RevDel ReverbPan EchoTm EchDp ModTm ModDp AirAbs HFRef LFRef RRlOff Diffus Densty FLAGS
FSOUND_PRESET_OFF = 0, 7.5f, 1.00f, -10000, -10000, 0, 1.00f, 1.00f, 1.0f, -2602, 0.007f, 0.0f,0.0f,0.0f, 200, 0.011f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 0.0f, 0.0f, 0x3f ;
FSOUND_PRESET_GENERIC = 0, 7.5f, 1.00f, -1000, -100, 0, 1.49f, 0.83f, 1.0f, -2602, 0.007f, 0.0f,0.0f,0.0f, 200, 0.011f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_PADDEDCELL = 1, 1.4f, 1.00f, -1000, -6000, 0, 0.17f, 0.10f, 1.0f, -1204, 0.001f, 0.0f,0.0f,0.0f, 207, 0.002f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_ROOM = 2, 1.9f, 1.00f, -1000, -454, 0, 0.40f, 0.83f, 1.0f, -1646, 0.002f, 0.0f,0.0f,0.0f, 53, 0.003f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_BATHROOM = 3, 1.4f, 1.00f, -1000, -1200, 0, 1.49f, 0.54f, 1.0f, -370, 0.007f, 0.0f,0.0f,0.0f, 1030, 0.011f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 60.0f, 0x3f ;
FSOUND_PRESET_LIVINGROOM = 4, 2.5f, 1.00f, -1000, -6000, 0, 0.50f, 0.10f, 1.0f, -1376, 0.003f, 0.0f,0.0f,0.0f, -1104, 0.004f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_STONEROOM = 5, 11.6f, 1.00f, -1000, -300, 0, 2.31f, 0.64f, 1.0f, -711, 0.012f, 0.0f,0.0f,0.0f, 83, 0.017f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_AUDITORIUM = 6, 21.6f, 1.00f, -1000, -476, 0, 4.32f, 0.59f, 1.0f, -789, 0.020f, 0.0f,0.0f,0.0f, -289, 0.030f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_CONCERTHALL = 7, 19.6f, 1.00f, -1000, -500, 0, 3.92f, 0.70f, 1.0f, -1230, 0.020f, 0.0f,0.0f,0.0f, -2, 0.029f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_CAVE = 8, 14.6f, 1.00f, -1000, 0, 0, 2.91f, 1.30f, 1.0f, -602, 0.015f, 0.0f,0.0f,0.0f, -302, 0.022f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x1f ;
FSOUND_PRESET_ARENA = 9, 36.2f, 1.00f, -1000, -698, 0, 7.24f, 0.33f, 1.0f, -1166, 0.020f, 0.0f,0.0f,0.0f, 16, 0.030f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_HANGAR = 10, 50.3f, 1.00f, -1000, -1000, 0, 10.05f, 0.23f, 1.0f, -602, 0.020f, 0.0f,0.0f,0.0f, 198, 0.030f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_CARPETTEDHALLWAY = 11, 1.9f, 1.00f, -1000, -4000, 0, 0.30f, 0.10f, 1.0f, -1831, 0.002f, 0.0f,0.0f,0.0f, -1630, 0.030f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_HALLWAY = 12, 1.8f, 1.00f, -1000, -300, 0, 1.49f, 0.59f, 1.0f, -1219, 0.007f, 0.0f,0.0f,0.0f, 441, 0.011f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_STONECORRIDOR = 13, 13.5f, 1.00f, -1000, -237, 0, 2.70f, 0.79f, 1.0f, -1214, 0.013f, 0.0f,0.0f,0.0f, 395, 0.020f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_ALLEY = 14, 7.5f, 0.30f, -1000, -270, 0, 1.49f, 0.86f, 1.0f, -1204, 0.007f, 0.0f,0.0f,0.0f, -4, 0.011f, 0.0f,0.0f,0.0f, 0.125f, 0.95f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_FOREST = 15, 38.0f, 0.30f, -1000, -3300, 0, 1.49f, 0.54f, 1.0f, -2560, 0.162f, 0.0f,0.0f,0.0f, -229, 0.088f, 0.0f,0.0f,0.0f, 0.125f, 1.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 79.0f, 100.0f, 0x3f ;
FSOUND_PRESET_CITY = 16, 7.5f, 0.50f, -1000, -800, 0, 1.49f, 0.67f, 1.0f, -2273, 0.007f, 0.0f,0.0f,0.0f, -1691, 0.011f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 50.0f, 100.0f, 0x3f ;
FSOUND_PRESET_MOUNTAINS = 17, 100.0f, 0.27f, -1000, -2500, 0, 1.49f, 0.21f, 1.0f, -2780, 0.300f, 0.0f,0.0f,0.0f, -1434, 0.100f, 0.0f,0.0f,0.0f, 0.250f, 1.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 27.0f, 100.0f, 0x1f ;
FSOUND_PRESET_QUARRY = 18, 17.5f, 1.00f, -1000, -1000, 0, 1.49f, 0.83f, 1.0f, -10000, 0.061f, 0.0f,0.0f,0.0f, 500, 0.025f, 0.0f,0.0f,0.0f, 0.125f, 0.70f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
FSOUND_PRESET_PLAIN = 19, 42.5f, 0.21f, -1000, -2000, 0, 1.49f, 0.50f, 1.0f, -2466, 0.179f, 0.0f,0.0f,0.0f, -1926, 0.100f, 0.0f,0.0f,0.0f, 0.250f, 1.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 21.0f, 100.0f, 0x3f ;
FSOUND_PRESET_PARKINGLOT = 20, 8.3f, 1.00f, -1000, 0, 0, 1.65f, 1.50f, 1.0f, -1363, 0.008f, 0.0f,0.0f,0.0f, -1153, 0.012f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x1f ;
FSOUND_PRESET_SEWERPIPE = 21, 1.7f, 0.80f, -1000, -1000, 0, 2.81f, 0.14f, 1.0f, 429, 0.014f, 0.0f,0.0f,0.0f, 1023, 0.021f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 0.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 80.0f, 60.0f, 0x3f ;
FSOUND_PRESET_UNDERWATER = 22, 1.8f, 1.00f, -1000, -4000, 0, 1.49f, 0.10f, 1.0f, -449, 0.007f, 0.0f,0.0f,0.0f, 1700, 0.011f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 1.18f, 0.348f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x3f ;
// Non I3DL2 presets
FSOUND_PRESET_DRUGGED = 23, 1.9f, 0.50f, -1000, 0, 0, 8.39f, 1.39f, 1.0f, -115, 0.002f, 0.0f,0.0f,0.0f, 985, 0.030f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 0.25f, 1.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x1f ;
FSOUND_PRESET_DIZZY = 24, 1.8f, 0.60f, -1000, -400, 0, 17.23f, 0.56f, 1.0f, -1713, 0.020f, 0.0f,0.0f,0.0f, -613, 0.030f, 0.0f,0.0f,0.0f, 0.250f, 1.00f, 0.81f, 0.310f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x1f ;
FSOUND_PRESET_PSYCHOTIC = 25, 1.0f, 0.50f, -1000, -151, 0, 7.56f, 0.91f, 1.0f, -626, 0.020f, 0.0f,0.0f,0.0f, 774, 0.030f, 0.0f,0.0f,0.0f, 0.250f, 0.00f, 4.00f, 1.000f, -5.0f, 5000.0f, 250.0f, 0.0f, 100.0f, 100.0f, 0x1f ;
}
// [DEFINE_END]
{
[STRUCTURE]
[
[DESCRIPTION]
Structure defining the properties for a reverb source, related to a FSOUND channel.
For more indepth descriptions of the reverb properties under win32, please see the EAX3
documentation at http://developer.creative.com/ under the 'downloads' section.
If they do not have the EAX3 documentation, then most information can be attained from
the EAX2 documentation, as EAX3 only adds some more parameters and functionality on top of
EAX2.
Note the default reverb properties are the same as the FSOUND_PRESET_GENERIC preset.
Note that integer values that typically range from -10,000 to 1000 are represented in
decibels, and are of a logarithmic scale, not linear, wheras float values are typically linear.
PORTABILITY: Each member has the platform it supports in braces ie (win32/xbox).
Some reverb parameters are only supported in win32 and some only on xbox. If all parameters are set then
the reverb should product a similar effect on either platform.
Linux and FMODCE do not support the reverb api.
The numerical values listed below are the maximum, minimum and default values for each variable respectively.
[SEE_ALSO]
FSOUND_Reverb_SetChannelProperties
FSOUND_Reverb_GetChannelProperties
FSOUND_REVERB_CHANNELFLAGS
]
}
type
TFSoundReverbChannelProperties = record // MIN MAX DEFAULT
Direct: Integer; // -10000 1000 0 direct path level (at low and mid frequencies) (win32/xbox)
DirectHF: Integer; // -10000 0 0 relative direct path level at high frequencies (win32/xbox)
Room: Integer; // -10000 1000 0 room effect level (at low and mid frequencies) (win32/xbox)
RoomHF: Integer; // -10000 0 0 relative room effect level at high frequencies (win32/xbox)
Obstruction: Integer; // -10000 0 0 main obstruction control (attenuation at high frequencies) (win32/xbox)
ObstructionLFRatio: Single; // 0.0 1.0 0.0 obstruction low-frequency level re. main control (win32/xbox)
Occlusion: Integer; // -10000 0 0 main occlusion control (attenuation at high frequencies) (win32/xbox)
OcclusionLFRatio: Single; // 0.0 1.0 0.25 occlusion low-frequency level re. main control (win32/xbox)
OcclusionRoomRatio: Single; // 0.0 10.0 1.5 relative occlusion control for room effect (win32)
OcclusionDirectRatio: Single; // 0.0 10.0 1.0 relative occlusion control for direct path (win32)
Exclusion: Integer; // -10000 0 0 main exlusion control (attenuation at high frequencies) (win32)
ExclusionLFRatio: Single; // 0.0 1.0 1.0 exclusion low-frequency level re. main control (win32)
OutsideVolumeHF: Integer; // -10000 0 0 outside sound cone level at high frequencies (win32)
DopplerFactor: Single; // 0.0 10.0 0.0 like DS3D flDopplerFactor but per source (win32)
RolloffFactor: Single; // 0.0 10.0 0.0 like DS3D flRolloffFactor but per source (win32)
RoomRolloffFactor: Single; // 0.0 10.0 0.0 like DS3D flRolloffFactor but for room effect (win32/xbox)
AirAbsorptionFactor: Single; // 0.0 10.0 1.0 multiplies AirAbsorptionHF member of FSOUND_REVERB_PROPERTIES (win32)
Flags: Integer; // FSOUND_REVERB_CHANNELFLAGS - modifies the behavior of properties (win32)
end;
// [STRUCT_END]
{
[DEFINE_START]
[
[NAME]
FSOUND_REVERB_CHANNELFLAGS
[DESCRIPTION]
Values for the Flags member of the FSOUND_REVERB_CHANNELPROPERTIES structure.
[SEE_ALSO]
FSOUND_REVERB_CHANNELPROPERTIES
]
}
const
FSOUND_REVERB_CHANNELFLAGS_DIRECTHFAUTO = $01; // Automatic setting of 'Direct' due to distance from listener
FSOUND_REVERB_CHANNELFLAGS_ROOMAUTO = $02; // Automatic setting of 'Room' due to distance from listener
FSOUND_REVERB_CHANNELFLAGS_ROOMHFAUTO = $04; // Automatic setting of 'RoomHF' due to distance from listener
FSOUND_REVERB_CHANNELFLAGS_DEFAULT = FSOUND_REVERB_CHANNELFLAGS_DIRECTHFAUTO or
FSOUND_REVERB_CHANNELFLAGS_ROOMAUTO or
FSOUND_REVERB_CHANNELFLAGS_ROOMHFAUTO;
// [DEFINE_END]
{
[ENUM]
[
[DESCRIPTION]
These values are used with FSOUND_FX_Enable to enable DirectX 8 FX for a channel.
[SEE_ALSO]
FSOUND_FX_Enable
FSOUND_FX_Disable
FSOUND_FX_SetChorus
FSOUND_FX_SetCompressor
FSOUND_FX_SetDistortion
FSOUND_FX_SetEcho
FSOUND_FX_SetFlanger
FSOUND_FX_SetGargle
FSOUND_FX_SetI3DL2Reverb
FSOUND_FX_SetParamEQ
FSOUND_FX_SetWavesReverb
]
}
type
TFSoundFXModes = (
FSOUND_FX_CHORUS,
FSOUND_FX_COMPRESSOR,
FSOUND_FX_DISTORTION,
FSOUND_FX_ECHO,
FSOUND_FX_FLANGER,
FSOUND_FX_GARGLE,
FSOUND_FX_I3DL2REVERB,
FSOUND_FX_PARAMEQ,
FSOUND_FX_WAVES_REVERB,
FSOUND_FX_MAX
);
// [DEFINE_END]
{
[ENUM]
[
[DESCRIPTION]
These are speaker types defined for use with the FSOUND_SetSpeakerMode command.
Note - Only reliably works with FSOUND_OUTPUT_DSOUND or FSOUND_OUTPUT_XBOX output modes. Other output modes will only
interpret FSOUND_SPEAKERMODE_MONO and set everything else to be stereo.
[SEE_ALSO]
FSOUND_SetSpeakerMode
[REMARKS]
Note - Only reliably works with FSOUND_OUTPUT_DSOUND or FSOUND_OUTPUT_XBOX output modes. Other output modes will only
interpret FSOUND_SPEAKERMODE_MONO and set everything else to be stereo.
Using either DolbyDigital or DTS will use whatever 5.1 digital mode is available if destination hardware is unsure.
]
}
type
TFSoundSpeakerModes =
(
FSOUND_SPEAKERMODE_DOLBYDIGITAL, // The audio is played through a speaker arrangement of surround speakers with a subwoofer.
FSOUND_SPEAKERMODE_HEADPHONES, // The speakers are headphones.
FSOUND_SPEAKERMODE_MONO, // The speakers are monaural.
FSOUND_SPEAKERMODE_QUAD, // The speakers are quadraphonic.
FSOUND_SPEAKERMODE_STEREO, // The speakers are stereo (default value).
FSOUND_SPEAKERMODE_SURROUND, // The speakers are surround sound.
FSOUND_SPEAKERMODE_DTS // The audio is played through a speaker arrangement of surround speakers with a subwoofer.
);
FSOUND_SPEAKERMODES = TFSoundSpeakerModes;
{
[DEFINE_START]
[
[NAME]
FSOUND_INIT_FLAGS
[DESCRIPTION]
Initialization flags. Use them with FSOUND_Init in the flags parameter to change various behaviour.
FSOUND_INIT_ENABLESYSTEMCHANNELFX Is an init mode which enables the FSOUND mixer buffer to be affected by DirectX 8 effects.
Note that due to limitations of DirectSound, FSOUND_Init may fail if this is enabled because the buffersize is too small.
This can be fixed with FSOUND_SetBufferSize. Increase the BufferSize until it works.
When it is enabled you can use the FSOUND_FX api, and use FSOUND_SYSTEMCHANNEL as the channel id when setting parameters.
[SEE_ALSO]
FSOUND_Init
]
}
const
FSOUND_INIT_USEDEFAULTMIDISYNTH = $01; // Causes MIDI playback to force software decoding.
FSOUND_INIT_GLOBALFOCUS = $02; // For DirectSound output - sound is not muted when window is out of focus.
FSOUND_INIT_ENABLESYSTEMCHANNELFX = $04; // For DirectSound output - Allows FSOUND_FX api to be used on global software mixer output!
FSOUND_INIT_ACCURATEVULEVELS = $08; // This latency adjusts FSOUND_GetCurrentLevels, but incurs a small cpu and memory hit.
FSOUND_INIT_PS2_DISABLECORE0REVERB = $10; // PS2 only - Disable reverb on CORE 0 to regain SRAM.
FSOUND_INIT_PS2_DISABLECORE1REVERB = $20; // PS2 only - Disable reverb on CORE 1 to regain SRAM.
FSOUND_INIT_PS2_SWAPDMACORES = $40; // PS2 only - By default FMOD uses DMA CH0 for mixing, CH1 for uploads, this flag swaps them around.
FSOUND_INIT_DONTLATENCYADJUST = $80; // Callbacks are not latency adjusted, and are called at mix time. Also information functions are immediate.
FSOUND_INIT_GC_INITLIBS = $100; // Gamecube only - Initializes GC audio libraries.
FSOUND_INIT_STREAM_FROM_MAIN_THREAD = $200; // Turns off fmod streamer thread, and makes streaming update from FSOUND_Update called by the user.
FSOUND_INIT_PS2_USEVOLUMERAMPING = $400; // PS2 only - Turns on volume ramping system to remove hardware clicks.
FSOUND_INIT_DSOUND_DEFERRED = $800; // Win32 only - For DirectSound output. 3D commands are batched together and executed at FSOUND_Update.
FSOUND_INIT_DSOUND_HRTF_LIGHT = $1000; // Win32 only - For DirectSound output. FSOUND_HW3D buffers use a slightly higher quality algorithm when 3d hardware acceleration is not present.
FSOUND_INIT_DSOUND_HRTF_FULL = $2000; // Win32 only - For DirectSound output. FSOUND_HW3D buffers use full quality 3d playback when 3d hardware acceleration is not present.
FSOUND_INIT_XBOX_REMOVEHEADROOM = $4000; // XBox only - By default directsound attenuates all sound by 6db to avoid clipping/distortion. CAUTION. If you use this flag you are responsible for the final mix to make sure clipping / distortion doesn't happen.
FSOUND_INIT_PSP_SILENCEONUNDERRUN = $8000; // PSP only - If streams skip / stutter when device is powered on, either increase stream buffersize, or use this flag instead to play silence while the UMD is recovering.
// [DEFINE_END]
(*
[ENUM]
[
[DESCRIPTION]
Status values for internet streams. Use FSOUND_Stream_Net_GetStatus to get the current status of an internet stream.
[SEE_ALSO]
FSOUND_Stream_Net_GetStatus
]
*)
type
TFSoundStreamNetStatus =
(
FSOUND_STREAM_NET_NOTCONNECTED, (* Stream hasn't connected yet *)
FSOUND_STREAM_NET_CONNECTING, (* Stream is connecting to remote host *)
FSOUND_STREAM_NET_BUFFERING, (* Stream is buffering data *)
FSOUND_STREAM_NET_READY, (* Stream is ready to play *)
FSOUND_STREAM_NET_ERROR (* Stream has suffered a fatal error *)
);
(*
[ENUM]
[
[DESCRIPTION]
Describes the type of a particular tag field.
[SEE_ALSO]
FSOUND_Stream_GetNumTagFields
FSOUND_Stream_GetTagField
FSOUND_Stream_FindTagField
]
*)
type
TFSoundTagFieldType =
(
FSOUND_TAGFIELD_VORBISCOMMENT, (* A vorbis comment *)
FSOUND_TAGFIELD_ID3V1, (* Part of an ID3v1 tag *)
FSOUND_TAGFIELD_ID3V2, (* An ID3v2 frame *)
FSOUND_TAGFIELD_SHOUTCAST, (* A SHOUTcast header line *)
FSOUND_TAGFIELD_ICECAST, (* An Icecast header line *)
FSOUND_TAGFIELD_ASF (* An Advanced Streaming Format header line *)
);
(*
[DEFINE_START]
[
[NAME]
FSOUND_STATUS_FLAGS
[DESCRIPTION]
These values describe the protocol and format of an internet stream. Use FSOUND_Stream_Net_GetStatus to retrieve this information for an open internet stream.
[SEE_ALSO]
FSOUND_Stream_Net_GetStatus
]
*)
const
FSOUND_PROTOCOL_SHOUTCAST = $00000001;
FSOUND_PROTOCOL_ICECAST = $00000002;
FSOUND_PROTOCOL_HTTP = $00000004;
FSOUND_FORMAT_MPEG = $00010000;
FSOUND_FORMAT_OGGVORBIS = $00020000;
(* [DEFINE_END] *)
{
[STRUCTURE]
[
[DESCRIPTION]
Structure defining a CD table of contents. This structure is returned as a tag from FSOUND_Stream_FindTagField when the tag name "CD_TOC" is specified.
Note: All tracks on the CD - including data tracks- will be represented in this structure so it's use for anything other than generating disc id information is not recommended.
See the cdda example program for info on retrieving and using this structure.
[SEE_ALSO]
FSOUND_Stream_Open
FSOUND_Stream_FindTagField
]
}
type
TFSoundTOCTag = record
Name: array [0..3] of AnsiChar; // The string "TOC" (4th character is 0), just in case this structure is accidentally treated as a string.
NumTracks: Integer; // The number of tracks on the CD.
Min: array [0..99] of Integer; // The start offset of each track in minutes.
Sec: array [0..99] of Integer; // The start offset of each track in seconds.
Frame: array [0..99] of Integer; // The start offset of each track in frames.
end;
// [STRUCT_END]
implementation
end.
|
unit GateClass;
interface
uses
System.SysUtils, GateInterface;
type
TGate = class
private
State: IGate;
public
constructor Create();
procedure Pass;
procedure PayGate;
procedure Paid;
procedure ChangeState(State: IGate);
end;
implementation
uses
CloseGateState;
procedure TGate.ChangeState(State: IGate);
begin
Self.State := State;
end;
constructor TGate.Create;
begin
Self.State := TCloseGate.Create(Self);
end;
procedure TGate.Pass;
begin
Self.State.Enter;
end;
procedure TGate.Paid;
begin
Self.State.PayOk;
end;
procedure TGate.PayGate;
begin
Self.State.Pay;
end;
end.
|
program Podantious;
{*** Again, made by Nicholas Hill - when oh when will I stop making these
brilliant games? (C) 1999 Connivex ***}
uses crt, graph, DOS, poengine;
var
Ch: Char;
{* If keys are set up or not}
KeysSetup: Array[1..15] of ShortInt;
{* Setup for levels}
NumLevels: Integer;
LevNumObjects: Integer;
PlLives,PlMaxActiveMissiles: Array[1..15] of Integer;
{* Variables for end of level}
MaxKills,MinKills,BestPlayer,WorstPlayer: Integer;
Winner: Integer;
OKToCont: Integer;
procedure CalcDelay;
var H1,M1,S1,MS1,H2,M2,S2,MS2,NUM: Word;
begin
TextColor(7); ClrScr;
WriteLn('Connivex 1999'); WriteLn;
Writeln('Nicholas Hill''s delay calculation routine.');
Writeln('Calculating delays...');
GetTime(h1,m1,s1,ms1); NUM:=0;
repeat
DELAY(100); NUM:=NUM+1;
GetTime(h2,m2,s2,ms2);
GotoXY(1,5); Write(NUM); GotoXY(7,5); Writeln(H2:2,':',M2:2,':',S2:2);
until (((S2-S1)*100)+(MS2-MS1))>=300;
writeln('Took ',NUM,' loops of 100 for 3s.');
SDelay:=(NUM*100) div 3;
Delay(SDelay);
end;
procedure StartLevel;
var E: Integer;
begin
{* Draw players... etc}
for E:=1 to NumPlayers do begin
if StillInGame[E]=1 then begin
Sound(E*10); Delay(SDelay div 10); DrawPlayer(E);
NoSound; Delay(SDelay div 15);
end;
end;
for E:=1 to 3 do begin
Sound(E*300); Delay(SDelay div 4);
NoSound; Delay(SDelay div 4);
end;
for E:=1 to 2 do begin
Sound(120); Delay(SDelay div 10);
NoSound; Delay(SDelay div 18);
end;
end;
procedure EndLevel;
var
B,E: Integer;
S1,S2: String;
begin
MaxKills:=0;
for B:=1 to NumPlayers do if Alive[B]=1 then Winner:=B;
for B:=1 to 3 do begin
for E:=10 downto 1 do begin
Sound(E*10+100); Delay(SDelay div 50);
Sound(E*10+120); Delay(SDelay div 50);
end;
end; NoSound;
Delay(SDelay*2); SetFillStyle(1,0);
for E:=0 to 63 do begin
Bar(E*10,0,E*10+10,480); Delay(SDelay div 32);
end;
SetTextStyle(TripleXFont, HorizDir, 1);
for B:=1 to NumPlayers do begin
if StillInGame[B]=1 then begin
SetColor(B); Str(B,S1); Str(NumKills[B],S2);
OutTextXY(1,B*22,'Player '+S1+' had '+S2+' hits.');
end;
end;
{* Find maximum and minimum kills}
MaxKills:=0;
for B:=1 to NumPlayers do begin
if StillInGame[B]=1 then begin
if NumKills[B]>MaxKills then begin
MaxKills:=NumKills[B];
BestPlayer:=B;
end;
end;
end;
MinKills:=MaxKills;
for B:=1 to NumPlayers do begin
if StillInGame[B]=1 then begin
if NumKills[B]<=MinKills then begin
MinKills:=NumKills[B];
WorstPlayer:=B;
end;
end;
end;
SetColor(9); Rectangle(0,BestPlayer*22+3,320,BestPlayer*22+23);
SetColor(4); Rectangle(0,WorstPlayer*22+3,320,WorstPlayer*22+23);
SetTextStyle(SansSerifFont, HorizDir, 4);
SetColor(15); OutTextXY(1,350,'Level over - Press ''C'' to continue...');
REPEAT UNTIL UpCase(ReadKey)='C';
end;
procedure GameInit;
var grDriver, grMode, ErrCode: Integer;
begin
{* Initialise graphics}
grDriver:=Detect; InitGraph(grDriver,grMode,'');
ErrCode:=GraphResult; if ErrCode<>grOk then Halt(1);
SetTextStyle(DefaultFont, HorizDir, 1);
for A:=1 to 15 do KeysSetup[A]:=0;
end;
procedure SetupPlayer(PLN: Integer);
var S1: String;
begin
if StillInGame[PLN]=1 then begin
{* Main player variables, x,y...etc, and get keys for each player}
X[PLN]:=Random(500)+20; Y[PLN]:=Random(430)+20; DIR[PLN]:=Random(4)+1;
PCOL[PLN]:=PLN; NumActiveMissiles[PLN]:=0; Alive[PLN]:=1;
NumLives[PLN]:=PlLives[PLN];
MaxActiveMissiles[PLN]:=PlMaxActiveMissiles[PLN];
if (PLN<=NumHumanPlayers) and (KeysSetup[PLN]<>1) then begin
SetColor(15); Rectangle(290,70,600,148);
SetFillStyle(1,0); Bar(291,71,599,147);
SetColor(PLN); Str(PLN,S1);
OutTextXY(300,80,'Player '+S1+' - Press key for UP:');
KUp[PLN]:=UpCase(ReadKey);
OutTextXY(300,92,'Player '+S1+' - Press key for DOWN:');
KDown[PLN]:=UpCase(ReadKey);
OutTextXY(300,104,'Player '+S1+' - Press key for LEFT:');
KLeft[PLN]:=UpCase(ReadKey);
OutTextXY(300,116,'Player '+S1+' - Press key for RIGHT:');
KRight[PLN]:=UpCase(ReadKey);
OutTextXY(300,128,'Player '+S1+' - Press key for FIRE:');
KFire[PLN]:=UpCase(ReadKey);
KeysSetup[PLN]:=1;
end;
{* Set initial AI victims :}
if (PLN>NumHumanPlayers) and (Random(10)>4) then
VICTIM[PLN]:=Random(NumPlayers+1);
end else Alive[PLN]:=0;
end;
procedure InitLevel(NumHuman,NumAI,AISkill: Integer);
var E: Integer;
begin
for E:=1 to 15 do begin
NumKills[E]:=0; Alive[E]:=0;
end;
{* Number of each thing}
NumHumanPlayers:=NumHuman;
NumAIPlayers:=NumAI;
NumPlayers:=NumAIPlayers+NumHumanPlayers;
NumPlayersAlive:=0;
for E:=1 to NumPlayers do begin
if StillInGame[E]=1 then NumPlayersAlive:=NumPlayersAlive+1;
end;
NumObjects:=0; MaxObjects:=LevNumObjects;
LevAISkill:=AISkill;
end;
procedure GetPlayerTypes(HumanYN,AIYN: Integer);
var S1: String;
begin
SetColor(15); Rectangle(50,350,400,420);
SetFillStyle(1,0); Bar(51,351,399,419);
if HumanYN=1 then repeat
OutTextXY(60,370,'Enter number of human players (0-8): ');
ReadLn(NumHumanPlayers);
until (NumHumanPlayers>-1) and (NumHumanPlayers<9);
if AIYN=1 then repeat
Str(15-NumHumanPlayers,S1);
OutTextXY(60,390,'Enter number of AI players (0-'+S1+'): ');
Readln(NumAIPlayers);
until (NumAIPlayers>-1) and (NumAIPlayers<(16-NumHumanPlayers));
end;
procedure SetupCustomLevel;
var E: Integer;
begin
GetPlayerTypes(1,1); {* Player setup}
InitLevel(NumHumanPlayers,NumAIPlayers,LevAISkill);
SetColor(15); Rectangle(90,10,400,100);
SetFillStyle(1,0); Bar(91,11,399,99);
SetTextStyle(DefaultFont,HorizDir,1);
{* User input setup}
OutTextXY(100,20,'Enter AI skill level (1-5):'); Readln(LevAISkill);
OutTextXY(100,40,'Enter maximum objects (0-20):');
repeat
ReadLn(LevNumObjects);
until (LevNumObjects>-1) and (LevNumObjects<21);
OutTextXY(100,60,'Enter starting lives (1-5):');
repeat
ReadLn(PlLives[1]);
until (PlLives[1]>0) and (PlLives[1]<6);
for E:=1 to NumPlayers do PlLives[E]:=PlLives[1];
OutTextXY(100,80,'Enter maximum missiles (0-20):');
repeat
ReadLn(PlMaxActiveMissiles[1]);
until (PlMaxActiveMissiles[1]>-1) and (PlMaxActiveMissiles[1]<21);
for E:=1 to NumPlayers do PlMaxActiveMissiles[E]:=PlMaxActiveMissiles[1];
end;
procedure SetupCampaignLevel(L: Integer);
var E: Integer;
begin
if L=1 then begin
LevNumObjects:=15; InitLevel(1,1,1);
PlLives[1]:=5; PlMaxActiveMissiles[1]:=10;
PlLives[2]:=2; PlMaxActiveMissiles[2]:=1;
end;
if L=2 then begin
LevNumObjects:=8; InitLevel(1,7,1);
PlLives[1]:=5; PlMaxActiveMissiles[1]:=3;
for E:=2 to 8 do PlLives[E]:=1;
for E:=2 to 8 do PlMaxActiveMissiles[E]:=1;
end;
if L=3 then begin
LevNumObjects:=5; InitLevel(1,3,2);
PlLives[1]:=4; PlMaxActiveMissiles[1]:=2;
for E:=2 to 4 do PlLives[E]:=2;
for E:=2 to 4 do PlMaxActiveMissiles[E]:=2;
end;
if L=4 then begin
LevNumObjects:=5; InitLevel(1,2,2);
PlLives[1]:=5; PlMaxActiveMissiles[1]:=2;
for E:=2 to 3 do PlLives[E]:=5;
for E:=2 to 3 do PlMaxActiveMissiles[E]:=2;
end;
if L=5 then begin
LevNumObjects:=3; InitLevel(1,2,2);
PlLives[1]:=4; PlMaxActiveMissiles[1]:=1;
for E:=2 to 3 do PlLives[E]:=5;
for E:=2 to 3 do PlMaxActiveMissiles[E]:=2;
end;
if L=6 then begin
LevNumObjects:=3; InitLevel(1,14,3);
PlLives[1]:=4; PlMaxActiveMissiles[1]:=3;
for E:=2 to 15 do PlLives[E]:=1;
for E:=2 to 15 do PlMaxActiveMissiles[E]:=2;
end;
if L=7 then begin
LevNumObjects:=0; InitLevel(1,1,5);
PlLives[1]:=3; PlMaxActiveMissiles[1]:=1;
PlLives[2]:=5; PlMaxActiveMissiles[2]:=2;
end;
if L=8 then begin
LevNumObjects:=2; InitLevel(1,14,3);
PlLives[1]:=5; PlMaxActiveMissiles[1]:=4;
for E:=2 to 15 do PlLives[E]:=3;
for E:=2 to 15 do PlMaxActiveMissiles[E]:=3;
end;
if L=9 then begin
LevNumObjects:=1; InitLevel(1,9,3);
PlLives[1]:=2; PlMaxActiveMissiles[1]:=1;
for E:=2 to 10 do PlLives[E]:=2;
for E:=2 to 10 do PlMaxActiveMissiles[E]:=2;
end;
if L=10 then begin
LevNumObjects:=2; InitLevel(1,14,3);
PlLives[1]:=5; PlMaxActiveMissiles[1]:=1;
for E:=2 to 5 do PlLives[E]:=5;
for E:=2 to 5 do PlMaxActiveMissiles[E]:=5;
for E:=6 to 9 do PlLives[E]:=3;
for E:=6 to 9 do PlMaxActiveMissiles[E]:=3;
for E:=10 to 14 do PlLives[E]:=1;
for E:=10 to 14 do PlMaxActiveMissiles[E]:=1;
end;
if L=11 then begin
LevNumObjects:=1; InitLevel(1,3,4);
PlLives[1]:=2; PlMaxActiveMissiles[1]:=1;
PlLives[2]:=3; PlMaxActiveMissiles[2]:=1;
PlLives[3]:=4; PlMaxActiveMissiles[3]:=1;
PlLives[4]:=5; PlMaxActiveMissiles[4]:=5;
end;
if L=12 then begin
LevNumObjects:=0; InitLevel(1,2,4);
PlLives[1]:=2; PlMaxActiveMissiles[1]:=2;
for E:=2 to 3 do PlLives[E]:=4;
for E:=2 to 3 do PlMaxActiveMissiles[E]:=5;
end;
if L=13 then begin
LevNumObjects:=1; InitLevel(1,14,4);
PlLives[1]:=5; PlMaxActiveMissiles[1]:=2;
for E:=2 to 15 do PlLives[E]:=4;
for E:=2 to 15 do PlMaxActiveMissiles[E]:=3;
end;
if L=14 then begin
LevNumObjects:=20; InitLevel(1,9,4);
PlLives[1]:=2; PlMaxActiveMissiles[1]:=1;
for E:=2 to 9 do PlLives[E]:=3;
for E:=2 to 9 do PlMaxActiveMissiles[E]:=2;
PlLives[10]:=5; PlMaxActiveMissiles[10]:=1;
end;
if L=15 then begin
LevNumObjects:=0; InitLevel(1,2,5);
PlLives[1]:=2; PlMaxActiveMissiles[1]:=0;
PlLives[2]:=2; PlMaxActiveMissiles[1]:=1;
PlLives[3]:=5; PlMaxActiveMissiles[1]:=5;
end;
if L=16 then begin
LevNumObjects:=2; InitLevel(1,14,5);
PlLives[1]:=2; PlMaxActiveMissiles[1]:=1;
for E:=2 to 15 do PlLives[E]:=5;
for E:=2 to 15 do PlMaxActiveMissiles[E]:=5;
end;
for E:=1 to NumPlayers do SetupPlayer(E);
{* Specify X and Y positions for some levels}
if L=1 then begin
X[1]:=100; Y[1]:=50; Dir[1]:=2;
X[2]:=100; Y[2]:=400; Dir[2]:=2;
end;
if L=4 then begin
for E:=1 to NumPlayers do Y[E]:=300;
end;
if L=8 then begin
for E:=1 to 15 do begin
X[E]:=E*30; if (E mod 2)=1 then Y[E]:=200 else Y[E]:=180;
end;
end;
if L=10 then begin
for E:=1 to 15 do begin
Y[E]:=E*22; if (E mod 2)=1 then X[E]:=20 else X[E]:=525;
if (E mod 2)=1 then DIR[E]:=4 else DIR[E]:=3;
end;
end;
if L=12 then begin
X[1]:=20; Y[1]:=460; DIR[1]:=1;
X[2]:=300; Y[2]:=100; DIR[2]:=2;
X[3]:=60; Y[3]:=460; DIR[3]:=1;
end;
if L=16 then begin
X[1]:=30; Y[1]:=30; DIR[1]:=4;
X[2]:=515; Y[2]:=30; DIR[2]:=3;
X[3]:=30; Y[3]:=450; DIR[3]:=4;
X[4]:=515; Y[4]:=450; DIR[4]:=3;
X[5]:=50; Y[5]:=50; DIR[5]:=4;
X[6]:=495; Y[6]:=50; DIR[6]:=3;
X[7]:=50; Y[7]:=430; DIR[7]:=4;
X[8]:=495; Y[8]:=430; DIR[8]:=3;
X[9]:=70; Y[9]:=70; DIR[9]:=4;
X[10]:=475; Y[10]:=70; DIR[10]:=3;
X[11]:=70; Y[11]:=410; DIR[11]:=4;
X[12]:=475; Y[12]:=410; DIR[12]:=3;
X[13]:=90; Y[13]:=90; DIR[13]:=4;
X[14]:=455; Y[14]:=90; DIR[14]:=3;
X[15]:=90; Y[15]:=390; DIR[15]:=4;
end;
end;
procedure ShowMessage(Msg: String);
begin
SetColor(15); Rectangle(100,100,540,150);
SetFillStyle(1,0); Bar(101,101,539,149);
SetTextStyle(DefaultFont,HorizDir,1);
OutTextXY(110,110,Msg);
OutTextXY(110,130,'Press the ''C'' key to continue...');
REPEAT UNTIL UpCase(ReadKey)='C';
end;
procedure PlayGame(GameType: Char);
var
E, Level: Integer;
S1: String;
begin
TextColor(15); SetColor(15);
if GameType='A' then NumLevels:=16;
if GameType='B' then begin
NumLevels:=14; GetPlayerTypes(1,0); {* Player setup}
NumAIPlayers:=15-NumHumanPlayers;
end;
if (GameType='C') or (GameType='D') then begin
NumLevels:=1; GetPlayerTypes(1,1); {* Player setup}
end;
if GameType='E' then NumLevels:=1;
OKToCont:=1; Level:=0;
while OKToCont=1 do begin
Level:=Level+1;
if Level>=NumLevels then OKToCont:=0;
Str(Level,S1);
{* Initialise level: NumHuman,NumAI,AISKILL or Setup player: PLN};
if GameType='A' then SetupCampaignLevel(Level);
if GameType='B' then begin
LevNumObjects:=15-Level;
InitLevel(NumHumanPlayers,NumAIPlayers,(NumLevels+1) div 3);
for E:=1 to NumPlayers do SetupPlayer(E);
if Level>0 then for E:=1 to NumPlayers do PlLives[E]:=5;
if Level>5 then for E:=1 to NumPlayers do PlLives[E]:=4;
if Level>10 then for E:=1 to NumPlayers do PlLives[E]:=3;
if Level>0 then for E:=1 to NumPlayers do PlMaxActiveMissiles[E]:=2;
if Level>3 then for E:=1 to NumPlayers do PlMaxActiveMissiles[E]:=1;
end;
if (GameType='C') or (GameType='D') then begin
if GameType='C' then LevNumObjects:=15;
if GameType='D' then LevNumObjects:=0;
InitLevel(NumHumanPlayers,NumAIPlayers,3);
for E:=1 to 15 do PlLives[E]:=5;
if GameType='C' then for E:=1 to 15 do PlMaxActiveMissiles[E]:=1;
if GameType='D' then for E:=1 to 15 do PlMaxActiveMissiles[E]:=3;
for E:=1 to NumPlayers do SetupPlayer(E);
end;
if GameType='E' then begin
SetupCustomLevel;
InitLevel(NumHumanPlayers,NumAIPlayers,(NumLevels+1) div 3);
for E:=1 to NumPlayers do SetupPlayer(E);
end;
{* Play level}
ShowMessage('You are on level '+S1+'.');
DrawBoard; {* Draw the board}
StartLevel; {* The startup sequence for the level}
PlayLevel; {* Main playing part of the game}
EndLevel; {* End the level}
{* Perform checks for game type - if alive or not}
if (GameType='A') and (Alive[1]=0) then begin
OKToCont:=0;
ShowMessage('You died! Game over!');
end;
if GameType='B' then StillInGame[WorstPlayer]:=0;
end;
if (GameType='C') or (GameType='D') or (GameType='E') then begin
Str(Winner,S1);
ShowMessage('This level is finished. Winner was player '+S1+'.');
end;
if (GameType='A') and (Level=16) then begin
ShowMessage('Congratulations! Your insanity has helped you, OB1!');
ShowMessage('You have completed the campaign.');
ShowMessage('Be sure to email connivex@callnetuk.com!');
end;
if (GameType='B') then begin
Str(BestPlayer,S1);
ShowMessage('Survival game is over - winner was '+S1);
end;
end;
procedure ShowMenu;
begin
{* Display the menu}
SetFillStyle(1,0); Bar(0,0,640,480);
SetColor(15); Rectangle(100,50,540,430);
SetFillStyle(1,9); Bar(105,55,535,100);
SetTextStyle(SansSerifFont,HorizDir,5);
OutTextXY(108,48,'Podantious! 1999');
SetColor(8);
MoveTo(110,110); LineTo(110,420);
LineTo(530,265); LineTo(110,110);
SetTextStyle(DefaultFont,HorizDir,1);
SetColor(15);
OutTextXY(105,120,'A] Campaign');
OutTextXY(105,170,'B] Survival of the fittest');
OutTextXY(105,240,'C] Single game - powerups');
OutTextXY(105,300,'D] Single game - no powerups');
OutTextXY(105,360,'E] Custom game');
OutTextXY(105,410,'X] Exit game');
SetColor(7);
OutTextXY(135,140,'Go through 16 predesigned levels.');
OutTextXY(135,190,'Use your insanity to complete 14 levels, where the');
OutTextXY(135,200,'worst player is thrown out of the game after each');
OutTextXY(135,210,'level of madness.');
OutTextXY(135,260,'A small skirmish, in which only one survives.');
OutTextXY(135,270,'Powerups are available');
OutTextXY(135,320,'Same as above, but without powerups, and 3 active');
OutTextXY(135,330,'missiles at any one time.');
OutTextXY(135,380,'Customise your game to one that suits you.');
Ch:='1';
While (Ch<>'A') and (CH<>'B') and (Ch<>'C')
and (CH<>'D') and (CH<>'E') and (Ch<>'X') do Ch:=UpCase(ReadKey);
end;
begin
{*** The main program ***}
CalcDelay; {* Calculate delays}
GameInit; {* Init game}
repeat
{* Make all players still in game}
for A:=1 to 15 do StillInGame[A]:=1;
ShowMenu; {* Show the menu, and get settings}
if Ch='A' then PlayGame(Ch); {* Play the game with menu choice}
if Ch='B' then PlayGame(Ch);
if Ch='C' then PlayGame(Ch);
if Ch='D' then PlayGame(Ch);
if Ch='E' then PlayGame(Ch);
until Ch='X';
end. |
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls,
Graphics, Dialogs, StdCtrls,strUtils,
PythonEngine,Testthds;
type
{ TForm1 }
TForm1 = class(TForm)
ScriptBtn: TButton;
ThreadBtn: TButton;
StopThreadBtn: TButton;
Memo1: TMemo;
PythonEngine1: TPythonEngine;
procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
procedure ScriptBtnClick(Sender: TObject);
procedure StopThreadBtnClick(Sender: TObject);
procedure ThreadBtnClick(Sender: TObject);
private
OwnThreadState: PPyThreadState;
ThreadsRunning: Integer;
procedure ThreadDone(Sender: TObject);
procedure InitThreads(ThreadExecMode: TThreadExecMode);
public
Thread1 : TTestThread;
Thread2 : TTestThread;
Thread3 : TTestThread;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.InitThreads(ThreadExecMode: TThreadExecMode);
var script1,script2,script3 : TStringList;
begin
script1 := TStringList.Create();
script2 := TStringList.Create();
script3 := TStringList.Create();
script1.LoadFromFile('testThread.py');
ThreadsRunning := 3;
Memo1.Clear;
Memo1.Append('Starting 3 threads');
with GetPythonEngine do
begin
OwnThreadState := PyEval_SaveThread();
Thread1 := TTestThread.Create( ThreadExecMode, script1);
Thread1.OnTerminate := @ThreadDone;
script2.Text := ReplaceStr(script1.Text,'Thread1','Thread2');
script2.Text := ReplaceStr(script2.Text,'(1.0)','(1.4)');
Thread2 := TTestThread.Create( ThreadExecMode, script2);
Thread2.OnTerminate := @ThreadDone;
script3.Text := ReplaceStr(script1.Text,'Thread1','Thread3');
script3.Text := ReplaceStr(script3.Text,'(1.0)','(1.9)');
Thread3 := TTestThread.Create( ThreadExecMode, script3);
Thread3.OnTerminate := @ThreadDone;
end;
ScriptBtn.Enabled := False;
ThreadBtn.Enabled := False;
StopThreadBtn.Enabled := True;
end;
procedure TForm1.ThreadDone(Sender: TObject);
begin
Dec(ThreadsRunning);
if ThreadsRunning = 0 then
begin
Memo1.Append('all the threads Terminated');
GetPythonEngine.PyEval_RestoreThread(OwnThreadState);
ScriptBtn.Enabled := True;
ThreadBtn.Enabled := True;
StopThreadBtn.Enabled := False;
Thread1 := nil;
Thread2 := nil;
Thread3 := nil;
end;
end;
procedure TForm1.ScriptBtnClick(Sender: TObject);
var script : TStringList;
begin
script := TStringList.Create();
script.LoadFromFile('testThread.py');
script.Text := ReplaceStr(script.Text,'Thread1','Script');
Memo1.Clear;
Memo1.Append('Starting Python Script');
GetPythonEngine.ExecStrings(script);
Memo1.Append('Python Script Terminated');
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: boolean);
begin
CanClose := ThreadsRunning = 0;
end;
procedure TForm1.ThreadBtnClick(Sender: TObject);
begin
InitThreads(emNewInterpreter);
end;
procedure TForm1.StopThreadBtnClick(Sender: TObject);
begin
if Assigned(Thread1) and not Thread1.Finished then Thread1.Stop();
if Assigned(Thread2) and not Thread2.Finished then Thread2.Stop();
if Assigned(Thread3) and not Thread3.Finished then Thread3.Stop();
end;
end.
|
Unit NewRemDiskForm;
Interface
Uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, RemDiskDll,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls;
Type
TNewRemDiskFrm = Class(TForm)
MainPanel: TPanel;
StornoButton: TButton;
OkButton: TButton;
EncryptionGroupBox: TGroupBox;
GeneralGroupBox: TGroupBox;
DiskTypeComboBox: TComboBox;
DiskSizeEdit: TEdit;
FileNameEdit: TEdit;
WritableCheckBox: TCheckBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
BrowseButton: TButton;
EncryptedCheckBox: TCheckBox;
Password1Edit: TEdit;
Password2Edit: TEdit;
ShowCharactersCheckBox: TCheckBox;
Label5: TLabel;
Label6: TLabel;
FilenameOpenDialog: TOpenDialog;
SparseFIleCheckBox: TCheckBox;
procedure EncryptedCheckBoxClick(Sender: TObject);
procedure BrowseButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure DiskTypeComboBoxChange(Sender: TObject);
procedure StornoButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure ShowCharactersCheckBoxClick(Sender: TObject);
Private
FCreateFlags : Cardinal;
FSparseFile : Boolean;
FDiskSize : UInt64;
FFileName : WideString;
FPassword : WideString;
FDiskType : ERemDiskType;
FCancelled : Boolean;
Public
Property Cancelled : Boolean Read FCancelled;
Property DiskSize : UInt64 Read FDisKSize;
Property Disktype : EREMDiskType Read FDiskType;
Property FileName : WideString Read FFileName;
Property Password : WideString Read FPassword;
Property SparseFile : Boolean Read FSparseFIle;
Property CreateFlags : Cardinal Read FCreateFlags;
end;
Implementation
{$R *.DFM}
Procedure TNewRemDiskFrm.BrowseButtonClick(Sender: TObject);
begin
If FileNameOpenDialog.Execute Then
FileNameEdit.Text := FIleNameOpenDialog.FileName;
end;
Procedure TNewRemDiskFrm.DiskTypeComboBoxChange(Sender: TObject);
begin
SparseFIleCheckBox.Enabled := (EREMDiskType(DiskTypeComboBox.ItemIndex) = rdtFileDisk);
end;
Procedure TNewRemDiskFrm.EncryptedCheckBoxClick(Sender: TObject);
begin
If EncryptedCheckBox.Checked Then
begin
Password1Edit.ReadOnly := False;
Password1Edit.Color := clWindow;
Password2Edit.ReadOnly := False;
Password2Edit.Color := clWindow;
ShowCharactersCheckBox.Enabled := True;
end
Else begin
Password1Edit.ReadOnly := True;
Password1Edit.Color := clBtnFace;
Password2Edit.ReadOnly := True;
Password2Edit.Color := clBtnFace;
ShowCharactersCheckBox.Enabled := False;
end;
end;
Procedure TNewRemDiskFrm.FormCreate(Sender: TObject);
begin
FCancelled := True;
EncryptedCheckBoxClick(EncryptedCheckBox);
DiskTypeComboBoxChange(DiskTypeComboBox);
end;
Procedure TNewRemDiskFrm.OkButtonClick(Sender: TObject);
begin
If (Not EncryptedCheckBox.Checked) Or
((Password1Edit.Text <> '') And (Password1Edit.Text = Password2Edit.Text)) Then
begin
FCancelled := False;
FDiskType := EREMDiskType(DiskTypeComboBox.ItemIndex);
FDiskSize := StrToInt64(DiskSizeEdit.Text)*1024*1024;
FFileName := FileNameEdit.Text;
FCreateFlags := 0;
If WritableCheckBox.Checked Then
FCreateFlags := (FCreateFlags Or REMDISK_FLAG_WRITABLE);
If EncryptedCheckBox.Checked Then
FCreateFlags := (FCreateFlags Or REMDISK_FLAG_ENCRYPTED);
If SparseFileCheckBox.Checked Then
FCreateFlags := (FCreateFlags Or REMDISK_FLAG_SPARSE_FILE);
FPassword := Password1Edit.Text;
FSparseFile := SparseFileCheckBox.Checked;
Close;
end;
end;
Procedure TNewRemDiskFrm.ShowCharactersCheckBoxClick(Sender: TObject);
begin
If ShowCharactersCheckBox.Checked Then
begin
Password1Edit.PasswordChar := #0;
Password2Edit.PasswordChar := #0;
end
Else begin
Password1Edit.PasswordChar := '*';
Password2Edit.PasswordChar := '*';
end;
end;
Procedure TNewRemDiskFrm.StornoButtonClick(Sender: TObject);
begin
Close;
end;
End.
|
unit TestCases;
interface
uses
DUnitX.TestFramework, Classes, BD.Handler, OXmlPDOM;
type
TMyTestObject = class
private
FName: String;
FAge: Integer;
FSex: Char;
published
property Name: String read FName write FName;
property Age: Integer read FAge write FAge;
property Sex: Char read FSex write FSex;
end;
[TestFixture]
TTestHandlerObject = class(TObject)
private
Xml: IXMLDocument;
Map: TMapList;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure TestFylkeLoadFromXML;
[Test]
procedure TestFylkeLoadFromXMLAttribute;
end;
implementation
procedure TTestHandlerObject.Setup;
begin
Xml := TXMlDocument.Create();
Xml.LoadFromXML('<P><PersonName Sex="M">Abc</PersonName><PersonAge>80</PersonAge></P>');
Map := TMapList.Create();
end;
procedure TTestHandlerObject.TearDown;
begin
Map.Free;
end;
procedure TTestHandlerObject.TestFylkeLoadFromXML;
var
T: TMyTestObject;
begin
Map.Clear;
Map.Add('Age', 'PersonAge');
T := THandler.LoadFromXML<TMyTestObject>(Xml.DocumentElement, Map);
Assert.AreEqual(80, T.Age);
if Assigned(T) then
T.Free;
end;
procedure TTestHandlerObject.TestFylkeLoadFromXMLAttribute;
var
T: TMyTestObject;
begin
Map.Clear;
Map.Add('Sex', 'PersonName.Sex');
T := THandler.LoadFromXML<TMyTestObject>(Xml.DocumentElement, Map);
Assert.AreEqual('M', T.Sex);
if Assigned(T) then
T.Free;
end;
initialization
TDUnitX.RegisterTestFixture(TTestHandlerObject);
end.
|
unit vr_types;
{$mode delphi}{$H+}
{$I vrode.inc}
interface
uses Types, SysUtils,{$IFDEF WINDOWS}Windows{$ELSE}LMessages{$ENDIF};
resourcestring
RS_Create = 'Create';
RS_Delete = 'Delete';
RS_Remove = 'Remove';
RS_Overwrite = 'Overwrite';
RS_Continue = 'Continue';
RS_COPY = 'Copy';
RS_CUT = 'Cut';
RS_PASTE = 'Paste';
RS_FileNotExists = 'File or folder "%s" is not exists';
RS_InvalidPath = 'Invalid Path';
RS_InvalidFile = 'Invalid File "%s"';
//RS_FileNotExistsCreate = 'File or folder "%s" is not exists. Create?';
RS_SaveChanges = 'Save changes in "%s"';
RS_SaveAllChanges = 'Save all changes?';
RS_FileAlreadyExists = 'File or folder "%s" is already exists.';
RS_FileModifiedOnDisk = 'File "%s" has changed on disk. Reload?';
RS_FilesModifiedOnDisk = 'Some files have changed on disk. Reload?';
RS_ErrCreateFile = 'Cannot create file "%s"';
RS_ErrCopyFile = 'Cannot copy file "%s"';
RS_ErrRenameFile = 'Cannot rename file "%s"';
RS_ErrCreateDir = 'Cannot create directory "%s"';
RS_ErrSaveFile = 'Cannot save file "%s"';
RS_ErrFileWrite = '"%s" write access denied';
RS_ErrFileRead = 'Cannot read file "%s"';
//RS_ErrReadFile = 'Read file "%s" error';
RS_ErrDeleteFile = 'Unable to delete file or folder "%s"';
RS_ErrFileExecute = 'Cannot exectute file "%s"';
RS_NewDocCaption = 'Untitle';
RS_TextNotFound = 'Text not found';
RS_AskReplace = 'Replace this occurence of "%s"?';
//RS_ActiveDoc = 'Active Document';
//RS_ActiveDocFolder = 'Active Document Folder';
//RS_SiteRoot = 50142; //Site Root';
RS_DeleteItem = 'Delete "%s"?';
RS_DeleteAll = 'Delete all?';
RS_DeleteSelected = 'Delete Selected Items?';
RS_DeleteOldFile = 'Delete old file "%s"?';
RS_DirNotEmpty = 'Directory "%s" is not empty.';
//RS_UpdatingDocTemp = 'Updating documents that use template';
//RS_FileOutOfSite = 'The file can not be saved outside of a site';
//RS_DefDbgNotInstalled = 5019; //Default Debugger is not installed';
RS_ProgVerOrHigher = '%s %s or higher version is necessary';
RS_WSHVerOrHigher = 'Windows Script Host version "%s" or higher is necessary';
RS_ErrFileNotFound = 'File "%s" not found';
RS_NotFound = 'Not Found';
RS_NotFoundSearch = 'Search string "%s" not found!';
RS_NoFilesFound = 'No files found';
RS_DS_FieldIsEmpty = 'Field "%s" is empty';
RS_DEFAULT = 'Default';
RS_CURRENT = 'Current';
RS_ACTIVE = 'Active';
RS_SET_DEFAULT = 'Set Default';
RS_CUSTOMIZE = 'Customize';
RS_CHECK_UNCECK_ALL = 'Check/Uncheck All';
RS_EMailIsNotValid = 'EMail "%s" is not valid';
RS_ErrInternetNeed = 'No Internet Connection';
RS_InstallingWWW = 'Installing %s (need internet connection)';
RS_NeedInternet = ' (need internet connection)';
RS_AllRight = 'OK';
RS_Error = 'ERROR';
RS_NOT_INSTALLED = '"%s" is not installed';
RS_QUEST_DOWNLOAD = 'Download from %s ?';
RS_QUEST_INSTALL = 'Install?';
S_NotImplemented = 'Not Implemented';
function RS_PROMPT_DOWNLOAD: string;
function RS_PROMPT_INSTALL: string;
function S_FileOwerriteConfirm(const AFileName: string): string;
function S_ResultOfAction(const AnAction: string; AResult: Boolean): string;
const
SIZE_SMALLINT = SizeOf(Smallint);
SIZE_INT = SizeOf(Integer);
SIZE_INT64 = SizeOf(Int64);
SIZE_WIDECHAR = 2;
SDefaultFilter = 'All files (*.*)|*.*';
LETTERS_COMMON = '0123456789QWERTYUIOPASDFGHJKLZXCVBNM';
GS_EXT_VR_FILES = '.vrfls';
S_DEFAULT: string = 'Default';
EXEC_OK = 0;
EXEC_FAIL = -1;
EXEC_TIME_OUT = -2;
type
TExecProgramFlag = (epfNone, epfWait, epfNewGroup,
epfInheritHandles, epfNewConsole, epfHidden,
//epfSuspended,
epfKillIfTimeOut);
TExecProgramFlags = set of TExecProgramFlag;
TOpenDocRec = record
FileName: string;
IsUpdatePopup: Boolean;
AsText: Boolean;
IsSilent: Boolean;
IsSetActive: Boolean;
end;
POpenDocRec = ^TOpenDocRec;
PPoint = types.PPoint;
{$IFDEF WINDOWS}
TMessage = Windows.TMessage;
{$ELSE}{$IFNDEF ANDROID}
TMessage = TLMessage;
TWndMethod = procedure(var msg : TMessage) of object;
LONG = longint;
TSize = Types.TSize;{$ENDIF}
const
WM_USER = LMessages.WM_USER;
{$ENDIF}
type
{$IFDEF WINDOWS}
TOSEvent = PMsg;{$ELSE}
TOSEvent = Pointer;{$ENDIF}
TDocEditType = (etDesign, etCode, etBrowse);
TStringFormatHow = (sfhBoth, sfhLeft, sfhRight);
TProcessId = PtrInt;
PProcessId = ^TProcessId;
//{$IFNDEF WINDOWS}{$IFNDEF ANDROID}//Redefined in LCLType
//THandle = LCLType.THandle;{$ENDIF}{$ENDIF}
THandle = System.THandle;
PHandle = ^System.THandle;
TIntArray = array of PtrInt;
PIntArray = ^TIntArray;
TStringArray = TStringDynArray;//array of string;
PStringArray = ^TStringDynArray;
TCharsSet = TSysCharSet;
TWideStringArray = TWideStringDynArray;//array of WideString;
PWideStringArray = TWideStringArray;
TInterfaceArray = array of IInterface;
THandleArray = array of THandle;
TFileNameArray = TStringArray;
TWideFileNameArray = TWideStringArray;
TPIntArray = array of PPtrInt;
TObjectMethod = procedure of object;
TDataProc = procedure(AData: PtrInt);
TDataMethod = procedure(AData: PtrInt) of object;
TPointerProc = procedure(const P: Pointer);
TPointerMethod = procedure(const P: Pointer) of object;
THandleProc = procedure(AHandle: THandle);
THandleMethod = procedure(AHandle: THandle) of object;
TInterfaceProc = procedure(const AIntf: IUnknown);
TInterfaceMethod = procedure(const AIntf: IUnknown) of object;
TNotifyProcedure = procedure(Sender: TObject);
TNotifyStringProc = procedure(const AString: string; AData: Pointer);
TNotifyStringMethod = procedure(const AString: string; AData: Pointer) of object;
TNotifyProc = procedure(const Sender: TObject; const AData: Pointer);
TNotifyMethod = procedure(const Sender: TObject; const AData: Pointer) of object;
TNewLineMethod = function(const ALine: string; AData: Pointer;
AIsAddToLastLine: Boolean): Integer of object;
TGetBooleanObjectFunc = function: Boolean of object;
TGetStringEvent = function: string of object;
TGetStringByIdObjectFunc = function(AId: Integer): string of object;
TProcWithVarString = procedure(var AStr: string);
TBooleanDynArray = Types.TBooleanDynArray;
TByteDynArray = Types.TByteDynArray;
PByteDynArray = ^TByteDynArray;
TIntegerDynArray = Types.TIntegerDynArray;
TWordDynArray = Types.TWordDynArray;
TEnvironmentScope = (esApp, esUser, esSystem);
TGArray<T> = array of T;
function IntArray(arr: array of Integer): TIntArray;
procedure EmptyNotifyPoc(Sender: TObject);
implementation
function IntArray(arr: array of Integer): TIntArray;
var
i: Integer;
begin
SetLength(Result{%H-}, Length(arr));
for i := 0 to Length(arr) - 1 do
begin
Result[i] := arr[i];
end;
end;
procedure EmptyNotifyPoc(Sender: TObject);
begin
end;
function RS_PROMPT_DOWNLOAD: string;
begin
Result := Format('%s.%s%s', [RS_NOT_INSTALLED, sLineBreak, RS_QUEST_DOWNLOAD]);
end;
function RS_PROMPT_INSTALL: string;
begin
Result := Format('%s.%s%s', [RS_NOT_INSTALLED, sLineBreak, RS_QUEST_INSTALL]);
end;
function S_FileOwerriteConfirm(const AFileName: string): string;
begin
Result := Format(RS_FileAlreadyExists, [AFileName]) + sLineBreak +
RS_Overwrite + '?';
end;
function S_ResultOfAction(const AnAction: string; AResult: Boolean): string;
begin
Result := AnAction + ': ';
if AResult then Result += RS_AllRight else Result += RS_Error;
end;
end.
|
// ##################################
// # TPLVisor - Michel Kunkler 2013 #
// ##################################
(*
Error Records und Konstanten.
Einmal für den Parser und einmal für den Interpreter.
*)
unit TPLErrors;
interface
type
TParserError = Record
InZeile : string;
UngZustand : string;
UngBefehl : string;
NichtImAlphabet : string;
NichtSchreibbar : string;
UngZiel : string;
JumpErwartet : string;
KeinParameter : string;
KeinBefehl : string;
end;
TInterpreterError = Record
NichtGeparst : string;
KeinBefehl : string;
UngZiel : string;
end;
const
ParserError : TParserError =
(
InZeile : 'Fehler in Zeile %d : ';
UngZustand : 'Ungültiger Zustand : "%s"';
UngBefehl : 'Ungültiger Befehl : "%s"';
NichtImAlphabet : 'Zeichen nicht im Alphabet : "%s"';
NichtSchreibbar : 'Zeichen "%s" nicht schreibbar';
UngZiel : 'Ungültiger Zielzustand : "%s"';
JumpErwartet : 'Jump Erwartet : "%s" gefunden';
KeinParameter : 'Kein weiterer Parameter erwartet : "%s" gefunden';
KeinBefehl : 'Kein Befehl gefunden';
);
InterpreterError : TInterpreterError =
(
NichtGeparst : 'Erst Parsen';
KeinBefehl : 'Kein Befehl gefunden';
UngZiel : 'Das Ziel %i existiert nicht';
);
implementation
end.
|
{**********************************************}
{ TeeChart PageNum Tool }
{ Copyright (c) 2000-2004 by David Berneda }
{**********************************************}
unit TeePageNumTool;
{$I TeeDefs.inc}
// This unit implements a Chart Tool example:
{
TPageNumTool
This tool derives from Annotation tool.
It is used to display the current chart page number.
The Chart MaxPointsPerPage property should be bigger than zero,
to divide a chart in pages.
Can be useful both for screen and print / print preview.
This tool is automatically used by the Chart Editor dialog at
"Paging" tab, when this unit is used in your application.
}
interface
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
Classes, TeCanvas, TeEngine, Chart, TeeTools;
type
TPageNumTool=class(TAnnotationTool)
private
Function GetFormat:String;
function IsFormatStored: Boolean;
protected
Function GetText:String; override;
public
Constructor Create(AOwner:TComponent); override;
class Function Description:String; override;
published
property Format:String read GetFormat write SetText stored IsFormatStored;
end;
implementation
Uses SysUtils, TeeConst, TeeProcs, TeeProCo;
{ TPageNumTool }
Constructor TPageNumTool.Create(AOwner: TComponent);
begin
inherited;
Format:=TeeMsg_PageOfPages;
end;
Function TPageNumTool.GetText:String;
begin
result:= SysUtils.Format( Format,
[TCustomChart(ParentChart).Page,TCustomChart(ParentChart).NumPages]);
end;
class function TPageNumTool.Description: String;
begin
result:=TeeMsg_PageNumber;
end;
function TPageNumTool.IsFormatStored: Boolean;
begin
result:=Format<>TeeMsg_PageOfPages;
end;
function TPageNumTool.GetFormat: String;
begin
result:=Text;
end;
initialization
RegisterTeeTools([TPageNumTool]);
TeePageNumToolClass:=TPageNumTool;
finalization
TeePageNumToolClass:=nil;
UnRegisterTeeTools([TPageNumTool]);
end.
|
unit Nathan.Firebird.Validator.Syntax.Keywords.Parser;
interface
uses
System.Generics.Collections,
Nathan.Firebird.Validator.Syntax.Keywords.Intf;
{$M+}
type
TFb25Parser = class(TInterfacedObject, IFb25Parser)
strict private
FTokens: TList<IFb25Token>;
FOnNotify: TFb25ParserNotifyEvent;
private
function GetTokens(): TList<IFb25Token>;
procedure SetTokens(Value: TList<IFb25Token>);
function GetOnNotify(): TFb25ParserNotifyEvent;
procedure SetOnNotify(Value: TFb25ParserNotifyEvent);
public
// function PredictiveAnalytics(): Boolean;
procedure Accept(Visitor: IVisitor);
end;
TFb25VisitorArguments = class(TInterfacedObject, IVisitor)
public
procedure Visit(Instance: IFb25Parser);
end;
TFb25TerminatorCharacters = class(TInterfacedObject, IVisitor)
public
procedure Visit(Instance: IFb25Parser);
end;
{$M-}
implementation
uses
System.SysUtils,
Nathan.Firebird.Validator.Syntax.Keywords.Types;
{ **************************************************************************** }
{ TFb25Parser }
function TFb25Parser.GetTokens(): TList<IFb25Token>;
begin
Result := FTokens;
end;
function TFb25Parser.GetOnNotify(): TFb25ParserNotifyEvent;
begin
Result := FOnNotify;
end;
procedure TFb25Parser.SetTokens(Value: TList<IFb25Token>);
begin
FTokens := Value;
end;
procedure TFb25Parser.SetOnNotify(Value: TFb25ParserNotifyEvent);
begin
FOnNotify := Value;
end;
procedure TFb25Parser.Accept(Visitor: IVisitor);
begin
Visitor.Visit(Self);
end;
{ **************************************************************************** }
{ TFb25VisitorArguments }
procedure TFb25VisitorArguments.Visit(Instance: IFb25Parser);
var
ListOfTokens: TList<IFb25Token>;
Each: IFb25Token;
ArgLeft: TArray<string>;
ArgRight: TArray<string>;
begin
ListOfTokens := Instance.Tokens;
// Check whether all arguments match...
ArgLeft := nil;
ArgRight := nil;
for Each in ListOfTokens do
begin
if (Each.Token = TFb25TokenKind.fb25Arguments) then
begin
if Assigned(ArgLeft) then
begin
ArgRight := Each.Value.Split([','], '''');
if (Assigned(Instance.OnNotify) and (not (High(ArgLeft) = High(ArgRight)))) then
Instance.OnNotify(Each);
ArgLeft := nil;
ArgRight := nil;
end
else
ArgLeft := Each.Value.Split([','], '''');
end;
end;
end;
{ **************************************************************************** }
{ TFb25TerminatorCharacters }
procedure TFb25TerminatorCharacters.Visit(Instance: IFb25Parser);
var
ListOfTokens: TList<IFb25Token>;
Each: IFb25Token;
begin
ListOfTokens := Instance.Tokens;
// Check whether all lines has a terminator character...
for Each in ListOfTokens do
if (Each.Token = TFb25TokenKind.fb25TerminatorCharacter)
and Assigned(Instance.OnNotify) then
Instance.OnNotify(Each);
end;
end.
|
unit Vigilante.Configuracao.Impl;
interface
uses
System.SysUtils, Vigilante.Configuracao;
type
{$M+}
TConfiguracao = class(TInterfacedObject, IConfiguracao)
private
FSimularBuild: boolean;
FAtualizacoesAutomaticas: boolean;
FAtualizacoesIntervalo: integer;
function GetSimularBuild: boolean;
function GetAtualizacoesAutomaticas: boolean;
function GetAtualizacoesIntervalo: integer;
procedure SetSimularBuild(const Value: boolean);
procedure SetAtualizacoesAutomaticas(const Value: boolean);
procedure SetAtualizacoesIntervalo(const Value: integer);
function PegarPathArquivo: TFileName;
public
class function New: IConfiguracao;
constructor Create;
destructor Destroy; override;
procedure CarregarConfiguracoes;
procedure PersistirConfiguracoes;
end;
implementation
uses
System.IniFiles, Vigilante.Configuracao.Observer, ContainerDI;
const
ARQUIVO_CONFIG = 'CONFIG.INI';
constructor TConfiguracao.Create;
begin
CarregarConfiguracoes;
end;
destructor TConfiguracao.Destroy;
begin
PersistirConfiguracoes;
inherited;
end;
function TConfiguracao.GetAtualizacoesAutomaticas: boolean;
begin
Result := FAtualizacoesAutomaticas and (FAtualizacoesIntervalo > 0);
end;
function TConfiguracao.GetAtualizacoesIntervalo: integer;
begin
Result := FAtualizacoesIntervalo;
end;
function TConfiguracao.GetSimularBuild: boolean;
begin
Result := FSimularBuild;
end;
class function TConfiguracao.New: IConfiguracao;
begin
Result := Create;
end;
procedure TConfiguracao.CarregarConfiguracoes;
var
_ini: TIniFile;
begin
_ini := TIniFile.Create(PegarPathArquivo);
try
FSimularBuild := _ini.ReadBool('DADOS', 'SIMULADO', True);
FAtualizacoesAutomaticas := _ini.ReadBool('ATUALIZACOES', 'LIGADO', True);
FAtualizacoesIntervalo := _ini.ReadInteger('ATUALIZACOES', 'INTERVALO', 15000);
finally
_ini.Free;
end;
end;
function TConfiguracao.PegarPathArquivo: TFileName;
var
_caminho: TFileName;
begin
_caminho := ExtractFilePath(ParamStr(0));
_caminho := IncludeTrailingPathDelimiter(_caminho);
Result := _caminho + '\' + ARQUIVO_CONFIG;
end;
procedure TConfiguracao.PersistirConfiguracoes;
var
_ini: TIniFile;
begin
_ini := TIniFile.Create(PegarPathArquivo);
try
_ini.WriteBool('DADOS', 'SIMULADO', FSimularBuild);
_ini.WriteBool('ATUALIZACOES', 'LIGADO', FAtualizacoesAutomaticas);
_ini.WriteInteger('ATUALIZACOES', 'INTERVALO', FAtualizacoesIntervalo);
finally
_ini.Free;
end;
CDI.Resolve<IConfiguracaoSubject>.Notificar(Self);
end;
procedure TConfiguracao.SetAtualizacoesAutomaticas(const Value: boolean);
begin
FAtualizacoesAutomaticas := Value;
end;
procedure TConfiguracao.SetAtualizacoesIntervalo(const Value: integer);
begin
FAtualizacoesIntervalo := Value;
end;
procedure TConfiguracao.SetSimularBuild(const Value: boolean);
begin
FSimularBuild := Value;
end;
initialization
DefinirConfiguracoes(TConfiguracao.New);
end.
|
unit EncodingsTestForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo, FMX.Edit, FMX.Controls.Presentation, FMX.ScrollBox;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
procedure Show (const msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.Button1Click(Sender: TObject);
var
Utf8string: TBytes;
Utf16string: string;
UniBytes: TBytes;
AByte: Byte;
begin
// process Utf8data
SetLength (Utf8string, 3);
Utf8string[0] := Ord ('a'); // single byte ANSI char < 128
Utf8string[1] := $c9; // double byte reversed latin a
Utf8string[2] := $90;
Utf16string := TEncoding.UTF8.GetString(Utf8string);
Show ('Unicode: ' + Utf16string);
Show ('Utf8 bytes:');
for AByte in Utf8String do
Show (AByte.ToString);
Show ('Utf16 bytes:');
UniBytes := TEncoding.Unicode.GetBytes (Utf16string);
for AByte in UniBytes do
Show (AByte.ToString);
// error: cannot use char > 128
Utf8string[0] := Ord ('à');
Utf16string := TEncoding.UTF8.GetString(Utf8string);
Show ('Wrong high ANSI: ' + Utf16string);
// try different conversion
Utf16string := TEncoding.ANSI.GetString(Utf8string);
Show ('Wrong double byte: ' + Utf16string);
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Utf8string: TBytes;
Utf16string: string;
I: Integer;
begin
Utf16string := 'This is my nice string with à and Æ';
Show ('Initial: ' + Utf16string);
Utf8string := TEncoding.UTF8.GetBytes(Utf16string);
for I := 0 to High(Utf8string) do
if Utf8string[I] = Ord('i') then
Utf8string[I] := Ord('I');
Utf16string := TEncoding.UTF8.GetString(Utf8string);
Show ('Final: ' + Utf16string);
end;
procedure TForm1.Show(const Msg: string);
begin
Memo1.Lines.Add(Msg);
end;
end.
|
UNIT complex;
{$MACRO ON}
INTERFACE
USES sysutils,math;
TYPE
T_Complex =record re,im:double; end;
P_Complex =^T_Complex;
T_arrayOfComplex=array of T_Complex;
CONST
II:T_Complex=(re:0; im:1);
C_invalidComplex:T_Complex=(re:Nan; im:Nan);
TYPE
T_boundingBox=record
x0,y0,x1,y1:double;
end;
T_scaler=object
private
//input
relativeZoom,
rotation:double;
worldCenter:T_Complex;
screenWidth ,screenHeight:longint;
//derived:
zoomRot,invZoomRot:T_Complex;
screenCenter:T_Complex;
PROCEDURE recalc;
public
FUNCTION getCenterX:double;
PROCEDURE setCenterX(CONST value:double);
FUNCTION getCenterY:double;
PROCEDURE setCenterY(CONST value:double);
FUNCTION getZoom:double;
PROCEDURE setZoom(CONST value:double);
FUNCTION getRotation:double;
PROCEDURE setRotation(CONST value:double);
CONSTRUCTOR create (CONST width,height:longint; CONST centerX,centerY,zoom,rotationInDegrees:double);
PROCEDURE recreate(CONST width,height:longint; CONST centerX,centerY,zoom,rotationInDegrees:double);
DESTRUCTOR destroy;
FUNCTION transform(CONST x,y:double ):T_Complex;
FUNCTION mrofsnart(CONST x,y:double ):T_Complex;
PROCEDURE rescale (CONST newWidth,newHeight:longint);
PROCEDURE recenter(CONST newCenter:T_Complex);
PROCEDURE moveCenter(CONST dx,dy:double);
PROCEDURE rotateToHorizontal(CONST screenDx,screenDy:longint);
FUNCTION getAbsoluteZoom:T_Complex;
FUNCTION getPositionString(CONST x,y:double; CONST Separator:ansistring='+i*'):ansistring;
FUNCTION getPixelsBoundingBox:T_boundingBox;
FUNCTION getWorldBoundingBox:T_boundingBox;
end;
OPERATOR :=(CONST x:double):T_Complex; inline;
OPERATOR +(CONST x,y:T_Complex):T_Complex; inline;
OPERATOR -(CONST x,y:T_Complex):T_Complex; inline;
OPERATOR *(CONST x,y:T_Complex):T_Complex; inline;
FUNCTION inverse(CONST x:T_Complex):T_Complex; inline;
OPERATOR /(CONST x,y:T_Complex):T_Complex; inline;
OPERATOR **(x:T_Complex; y:longint):T_Complex; inline;
OPERATOR **(x:T_Complex; CONST y:double):T_Complex; inline;
OPERATOR **(x:T_Complex; CONST y:T_Complex):T_Complex; inline;
FUNCTION abs(CONST x:double):double; inline;
FUNCTION abs(CONST x:T_Complex):double; inline;
FUNCTION arg(CONST x:T_Complex):double; inline;
FUNCTION sqr(CONST x:T_Complex):T_Complex; inline;
FUNCTION sqrabs(CONST x:T_Complex):double; inline;
FUNCTION exp(CONST x:double):double; inline;
FUNCTION exp(CONST x:T_Complex):T_Complex; inline;
FUNCTION ln (CONST x:T_Complex):T_Complex; inline;
FUNCTION sin(x:T_Complex):T_Complex; inline;
FUNCTION cos(x:T_Complex):T_Complex; inline;
FUNCTION tan(CONST x:T_Complex):T_Complex; inline;
FUNCTION isValid(CONST c:T_Complex):boolean; inline;
FUNCTION bbIntersect(CONST b1,b2:T_boundingBox):T_boundingBox;
FUNCTION allOutside(CONST b:T_boundingBox; CONST p0,p1,p2 :T_Complex):boolean;
FUNCTION allOutside(CONST b:T_boundingBox; CONST p0,p1,p2,p3 :T_Complex):boolean;
FUNCTION allOutside(CONST b:T_boundingBox; CONST p0,p1,p2,p3,p4,p5:T_Complex):boolean;
FUNCTION DiscreteFourierTransform(CONST X:T_arrayOfComplex; CONST inverse:boolean):T_arrayOfComplex;
FUNCTION FastFourierTransform(CONST X:T_arrayOfComplex; CONST inverse:boolean):T_arrayOfComplex;
IMPLEMENTATION
FUNCTION abs(CONST x:double):double;
begin
if x>0 then result:=x else result:=-x;
end;
OPERATOR :=(CONST x:double):T_Complex;
begin
result.re:=x; result.im:=0;
end;
OPERATOR +(CONST x,y:T_Complex):T_Complex;
begin
result.re:=x.re+y.re;
result.im:=x.im+y.im;
end;
OPERATOR -(CONST x,y:T_Complex):T_Complex;
begin
result.re:=x.re-y.re;
result.im:=x.im-y.im;
end;
OPERATOR *(CONST x,y:T_Complex):T_Complex;
begin
result.re:=x.re*y.re-x.im*y.im;
result.im:=x.re*y.im+x.im*y.re;
end;
FUNCTION inverse(CONST x:T_Complex):T_Complex;
begin
result.im:=1/(x.re*x.re+x.im*x.im);
result.re:= x.re*result.im;
result.im:=-x.im*result.im;
end;
OPERATOR /(CONST x,y:T_Complex):T_Complex;
begin
result.im:=1/(y.re*y.re+y.im*y.im);
result.re:=(x.re*y.re+x.im*y.im)*result.im;
result.im:=(x.im*y.re-x.re*y.im)*result.im;
end;
FUNCTION exp(CONST x:double):double; inline;
begin
{$ifdef CPU32}
result:=system.exp(x);
{$else}
if x<-745.133219101925 then result:=0
else if x> 709.782712893375 then result:=infinity
else result:=system.exp(x);
{$endif}
end;
OPERATOR **(x:T_Complex; CONST y:T_Complex):T_Complex;
begin
//result:=exp(ln(x)*y);
result.re:=x.re*x.re+x.im*x.im;
result.re:=0.5*system.ln(result.re);
result.im:=arctan2(x.im,x.re);
x.re:=result.re*y.re-result.im*y.im;
x.im:=result.im*y.re+result.re*y.im;
result.im:=exp(x.re);
result.re:=system.cos(x.im)*result.im;
result.im:=system.sin(x.im)*result.im;
end;
OPERATOR **(x:T_Complex; CONST y:double):T_Complex;
begin
//result:=exp(ln(x)*y);
result.re:=x.re*x.re+x.im*x.im;
result.re:=0.5*system.ln(result.re);
result.im:=arctan2(x.im,x.re);
x.re:=result.re*y;
x.im:=result.im*y;
result.im:=exp(x.re);
result.re:=system.cos(x.im)*result.im;
result.im:=system.sin(x.im)*result.im;
end;
OPERATOR **(x:T_Complex; y:longint):T_Complex;
//Note: This implementation is 100% equivalent to the
// academical recursive implementation, but it
// avoids the recursion, thus reducing both stack
// usage and overhead due to function calls.
// Computational cost is in log(y)
VAR k :longint;
begin
if y=0 then result:=1
else begin
if y<0 then begin x:=1/x; y:=-y; end;
result:=1;
k:=1;
while y>0 do begin
if (y and k)=k then begin
result:=result*x;
dec(y,k);
end;
k:=k+k;
x:=sqr(x);
end;
end;
end;
FUNCTION abs(CONST x:T_Complex):double;
begin
result:=sqrt(x.re*x.re+x.im*x.im);
end;
FUNCTION arg(CONST x:T_Complex):double ;
begin
result:=arctan2(x.im,x.re);
end;
FUNCTION sqr(CONST x:T_Complex):T_Complex;
begin
result.re:=x.re*x.re-x.im*x.im;
result.im:=2*x.re*x.im;
end;
FUNCTION sqrabs(CONST x:T_Complex):double; inline;
begin result:=x.re*x.re+x.im*x.im; if isNan(result) then result:=infinity; end;
FUNCTION exp(CONST x:T_Complex):T_Complex;
begin
result.im:=exp(x.re);
result.re:=system.cos(x.im)*result.im;
result.im:=system.sin(x.im)*result.im;
end;
FUNCTION ln (CONST x:T_Complex):T_Complex;
begin
result.re:=0.5*system.ln(x.re*x.re+x.im*x.im);
result.im:=arctan2(x.im,x.re);
end;
FUNCTION sin(x:T_Complex):T_Complex;
begin
//result:=exp(i*x) --------------------//
result.im:=exp(-x.im);
result.re:=system.cos( x.re)*result.im;//
result.im:=system.sin( x.re)*result.im;//
//-------------------------------------//
//result:=result-1/result ------------------------//
x.im:=1/(result.re*result.re+result.im*result.im);//
result.re:=result.re-result.re*x.im; //
result.im:=result.im+result.im*x.im; //
//------------------------------------------------//
//result:=result/(2*i)=-0.5*i*result //
x.re:= 0.5*result.im; //
result.im:=-0.5*result.re; //
result.re:=x.re; //
//-----------------------------------//
end;
FUNCTION cos(x:T_Complex):T_Complex;
begin
//result:=exp(i*x) --------------------//
result.im:=exp(-x.im);
result.re:=system.cos( x.re)*result.im;//
result.im:=system.sin( x.re)*result.im;//
//-------------------------------------//
//result:=result+1/result ------------------------//
x.im:=1/(result.re*result.re+result.im*result.im);//
result.re:=result.re+result.re*x.im; //
result.im:=result.im-result.im*x.im; //
//------------------------------------------------//
//result:=result/(2)=-0.5*result //
result.re:=result.re*0.5; //
result.im:=result.im*0.5; //
//-------------------------------//
end;
FUNCTION tan(CONST x:T_Complex):T_Complex;
begin
result:=sin(x)/cos(x);
end;
FUNCTION isValid(CONST c:T_Complex):boolean; inline;
begin
result:=not(isNan (c.re) or
isInfinite(c.re) or
isNan (c.im) or
isInfinite(c.im));
end;
FUNCTION bbIntersect(CONST b1,b2:T_boundingBox):T_boundingBox;
begin
result.x0:=max(b1.x0,b2.x0); result.y0:=max(b1.y0,b2.y0);
result.x1:=min(b1.x1,b2.x1); result.y1:=min(b1.y1,b2.y1);
end;
FUNCTION allOutside(CONST b:T_boundingBox; CONST p0,p1,p2 :T_Complex):boolean;
begin
result:=(max(p0.re,max(p1.re,p2.re))<b.x0) or
(min(p0.re,min(p1.re,p2.re))>b.x1) or
(max(p0.im,max(p1.im,p2.im))<b.y0) or
(min(p0.im,min(p1.im,p2.im))>b.y1);
end;
FUNCTION allOutside(CONST b:T_boundingBox; CONST p0,p1,p2,p3 :T_Complex):boolean;
begin
result:=(max(p0.re,max(p1.re,max( p2.re,p3.re)))<b.x0) or
(min(p0.re,min(p1.re,min( p2.re,p3.re)))>b.x1) or
(max(p0.im,max(p1.im,max( p2.im,p3.im)))<b.y0) or
(min(p0.im,min(p1.im,min( p2.im,p3.im)))>b.y1);
end;
FUNCTION allOutside(CONST b:T_boundingBox; CONST p0,p1,p2,p3,p4,p5:T_Complex):boolean;
begin
result:=(max(p0.re,max(p1.re,max( p2.re,max(p3.re,max(p4.re,p5.re)))))<b.x0) or
(min(p0.re,min(p1.re,min( p2.re,min(p3.re,min(p4.re,p5.re)))))>b.x1) or
(max(p0.im,max(p1.im,max( p2.im,max(p3.im,max(p4.im,p5.im)))))<b.y0) or
(min(p0.im,min(p1.im,min( p2.im,min(p3.im,min(p4.im,p5.im)))))>b.y1);
end;
//T_scaler:======================================================================================================================================
CONSTRUCTOR T_scaler.create(CONST width, height: longint; CONST centerX,centerY, zoom, rotationInDegrees: double);
begin
recreate(width,height,centerX,centerY,zoom,rotationInDegrees);
end;
PROCEDURE T_scaler.recreate(CONST width, height: longint; CONST centerX,centerY, zoom, rotationInDegrees: double);
begin
screenWidth :=width;
screenHeight:=height;
worldCenter.re:=centerX;
worldCenter.im:=centerY;
relativeZoom:=zoom;
rotation:=rotationInDegrees*pi/180;
recalc;
end;
DESTRUCTOR T_scaler.destroy; begin end;
PROCEDURE T_scaler.recalc;
begin
zoomRot.re:=system.cos(rotation);
zoomRot.im:=system.sin(rotation);
zoomRot:=zoomRot/(relativeZoom*sqrt(screenWidth*screenWidth+screenHeight*screenHeight));
invZoomRot:=1/zoomRot;
screenCenter.re:=0.5*screenWidth;
screenCenter.im:=0.5*screenHeight;
end;
FUNCTION T_scaler.getCenterX: double;
begin
result:=worldCenter.re;
end;
PROCEDURE T_scaler.setCenterX(CONST value: double);
begin
worldCenter.re:=value;
recalc;
end;
FUNCTION T_scaler.getCenterY: double;
begin
result:=worldCenter.im;
end;
PROCEDURE T_scaler.setCenterY(CONST value: double);
begin
worldCenter.im:=value;
recalc;
end;
PROCEDURE T_scaler.recenter(CONST newCenter:T_Complex);
begin
worldCenter:=newCenter;
recalc;
end;
FUNCTION T_scaler.getZoom: double;
begin
result:=relativeZoom;
end;
PROCEDURE T_scaler.setZoom(CONST value: double);
begin
relativeZoom:=value;
recalc;
end;
FUNCTION T_scaler.getRotation: double;
begin
result:=rotation/pi*180;
end;
PROCEDURE T_scaler.setRotation(CONST value: double);
begin
rotation:=value/180*pi;
while rotation<-pi do rotation:=rotation+2*pi;
while rotation> pi do rotation:=rotation-2*pi;
recalc;
end;
FUNCTION T_scaler.transform(CONST x, y: double): T_Complex;
begin
result.re:=x;
result.im:=screenHeight-y;
result:=(result-screenCenter)*zoomRot+worldCenter;
end;
FUNCTION T_scaler.mrofsnart(CONST x, y: double): T_Complex;
begin
result.re:=x;
result.im:=y;
result:=(result-worldCenter)*invZoomRot+screenCenter;
result.im:=screenHeight-result.im;
end;
PROCEDURE T_scaler.rescale(CONST newWidth, newHeight: longint);
begin
screenWidth:=newWidth;
screenHeight:=newHeight;
recalc;
end;
PROCEDURE T_scaler.moveCenter(CONST dx, dy: double);
VAR delta:T_Complex;
begin
delta.re:= dx;
delta.im:=-dy;
worldCenter:=worldCenter+delta*zoomRot;
recalc;
end;
PROCEDURE T_scaler.rotateToHorizontal(CONST screenDx,screenDy:longint);
begin
rotation:=rotation-arctan2(screenDy,screenDx);
recalc;
end;
FUNCTION T_scaler.getAbsoluteZoom: T_Complex;
begin
result:=zoomRot;
end;
FUNCTION T_scaler.getPositionString(CONST x, y: double; CONST Separator: ansistring): ansistring;
VAR p:T_Complex;
begin
p:=transform(x,y);
result:=floatToStr(p.re)+Separator+floatToStr(p.im);
end;
FUNCTION T_scaler.getPixelsBoundingBox:T_boundingBox;
begin
result.x0:=0;
result.y0:=0;
result.x1:=screenWidth ;
result.y1:=screenHeight;
end;
FUNCTION T_scaler.getWorldBoundingBox:T_boundingBox;
VAR p:T_Complex;
begin
p:=transform(0,0);
result.x0:=p.re;
result.x1:=p.re;
result.y0:=p.im;
result.y1:=p.im;
p:=transform(screenWidth,0);
result.x0:=min(result.x0,p.re);
result.x1:=max(result.x1,p.re);
result.y0:=min(result.y0,p.im);
result.y1:=max(result.y1,p.im);
p:=transform(screenWidth,screenHeight);
result.x0:=min(result.x0,p.re);
result.x1:=max(result.x1,p.re);
result.y0:=min(result.y0,p.im);
result.y1:=max(result.y1,p.im);
p:=transform(0,screenHeight);
result.x0:=min(result.x0,p.re);
result.x1:=max(result.x1,p.re);
result.y0:=min(result.y0,p.im);
result.y1:=max(result.y1,p.im);
end;
FUNCTION rootOfUnity(CONST alpha:double):T_Complex; inline;
begin
result.re:=system.cos(alpha);
result.im:=system.sin(alpha);
end;
FUNCTION DiscreteFourierTransform(CONST X:T_arrayOfComplex; CONST inverse:boolean):T_arrayOfComplex;
VAR i,j:longint;
r:T_Complex;
commonFactor:double;
begin
if inverse
then commonFactor:= 2*pi/length(X)
else commonFactor:=-2*pi/length(X);
setLength(result,length(X));
for j:=0 to length(result)-1 do begin
r:=0;
for i:=0 to length(X)-1 do r+=X[i]*rootOfUnity(commonFactor*i*j);
if inverse
then result[j]:=r*(1/length(X))
else result[j]:=r;
end;
end;
FUNCTION FastFourierTransform(CONST X:T_arrayOfComplex; CONST inverse:boolean):T_arrayOfComplex;
CONST Q3a:T_Complex=(re:-0.5;im:-0.86602540378443837);
Q3b:T_Complex=(re:-0.5;im: 0.86602540378443837);
Q5a:T_Complex=(re: 0.3090169943749474; im:-0.951056516295153);
Q5b:T_Complex=(re:-0.8090169943749474; im:-0.587785252292473);
Q5c:T_Complex=(re:-0.8090169943749474; im: 0.587785252292473);
Q5d:T_Complex=(re: 0.3090169943749474; im: 0.951056516295153);
VAR N1:longint=2;
N2:longint;
commonFactor:double;
innerX ,
innerFT:array of T_arrayOfComplex;
i,j,k:longint;
begin
N2:=length(x);
//Find smallest divider of length(X) by trial division
while (N1*N1<N2) and (N2 mod N1<>0) do inc(N1);
//Revert to DFT for prime cases
if N2 mod N1 <> 0 then exit(DiscreteFourierTransform(X,inverse));
N2:=N2 div N1;
setLength(innerX ,N1);
for i:=0 to N1-1 do setLength(innerX[i],N2);
j:=0;
k:=0;
for i:=0 to length(X)-1 do begin
innerX[j,k]:=X[i];
inc(j);
if j>=N1 then begin j:=0; inc(k); end;
end;
setLength(innerFT,N1);
for i:=0 to N1-1 do innerFT[i]:=FastFourierTransform(innerX[i],inverse);
//Twiddle...
for k:=1 to N1-1 do begin
if inverse
then commonFactor:= 2*pi/length(x)*k
else commonFactor:=-2*pi/length(x)*k;
for i:=0 to N2-1 do innerFT[k,i]*=rootOfUnity(commonFactor*i);
end;
setLength(result,length(X));
if N1=2 then begin
if inverse
then commonFactor:=1/2
else commonFactor:=1;
for i:=0 to N2-1 do result[ i]:=(innerFT[0,i]+innerFT[1,i])*commonFactor;
for i:=0 to N2-1 do result[N2+i]:=(innerFT[0,i]-innerFT[1,i])*commonFactor;
end else if N1=3 then begin
if inverse then begin
commonFactor:=1/3;
for i:=0 to N2-1 do result[ i]:=(innerFT[0,i]+innerFT[1,i] +innerFT[2,i] )*commonFactor;
for i:=0 to N2-1 do result[ N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q3b+innerFT[2,i]*Q3a)*commonFactor;
for i:=0 to N2-1 do result[N2+N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q3a+innerFT[2,i]*Q3b)*commonFactor;
end else begin
for i:=0 to N2-1 do result[ i]:=(innerFT[0,i]+innerFT[1,i] +innerFT[2,i] );
for i:=0 to N2-1 do result[ N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q3a+innerFT[2,i]*Q3b);
for i:=0 to N2-1 do result[N2+N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q3b+innerFT[2,i]*Q3a);
end;
end else if N1=5 then begin
if inverse then begin
commonFactor:=1/5;
for i:=0 to N2-1 do result[ i]:=(innerFT[0,i]+innerFT[1,i] +innerFT[2,i] +innerFT[3,i] +innerFT[4,i] )*commonFactor;
for i:=0 to N2-1 do result[ N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q5d+innerFT[2,i]*Q5c+innerFT[3,i]*Q5b+innerFT[4,i]*Q5a)*commonFactor;
for i:=0 to N2-1 do result[ N2+N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q5c+innerFT[2,i]*Q5a+innerFT[3,i]*Q5d+innerFT[4,i]*Q5b)*commonFactor;
for i:=0 to N2-1 do result[ N2+N2+N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q5b+innerFT[2,i]*Q5d+innerFT[3,i]*Q5a+innerFT[4,i]*Q5c)*commonFactor;
for i:=0 to N2-1 do result[N2+N2+N2+N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q5a+innerFT[2,i]*Q5b+innerFT[3,i]*Q5c+innerFT[4,i]*Q5d)*commonFactor;
end else begin
for i:=0 to N2-1 do result[ i]:=(innerFT[0,i]+innerFT[1,i] +innerFT[2,i] +innerFT[3,i] +innerFT[4,i] );
for i:=0 to N2-1 do result[ N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q5a+innerFT[2,i]*Q5b+innerFT[3,i]*Q5c+innerFT[4,i]*Q5d);
for i:=0 to N2-1 do result[ N2+N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q5b+innerFT[2,i]*Q5d+innerFT[3,i]*Q5a+innerFT[4,i]*Q5c);
for i:=0 to N2-1 do result[ N2+N2+N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q5c+innerFT[2,i]*Q5a+innerFT[3,i]*Q5d+innerFT[4,i]*Q5b);
for i:=0 to N2-1 do result[N2+N2+N2+N2+i]:=(innerFT[0,i]+innerFT[1,i]*Q5d+innerFT[2,i]*Q5c+innerFT[3,i]*Q5b+innerFT[4,i]*Q5a);
end;
end else begin
setLength(innerX,N2);
//Map 0,0 0,1 0,2 ... 0,N2-1 (N1 arrays of length N2 each)
// 1,0 1,1 1,2 ... 1,N2-1
// ... ...
// N1-1,0 ... N1-1,N2-1
// to 0,0 1,0 2,0 ... N1-1,0 (N2 array of length N1 each)
// 0,1 1,1 2,1 ... N1-1,1
// ... ...
// 0,N2-1 ... N1-1,N2-1
for i:=0 to N2-1 do setLength(innerX[i],N1);
for j:=0 to N2-1 do for k:=0 to N1-1 do innerX[j,k]:=innerFT[k,j];
//Note: N1 is prime by construction, so...
setLength(innerFT,N2);
for i:=0 to N2-1 do innerFT[i]:=DiscreteFourierTransform(innerX[i],inverse);
j:=0;
k:=0;
for i:=0 to length(X)-1 do begin
result[i]:=innerFT[j,k];
inc(j);
if j>=N2 then begin j:=0; inc(k); end;
end;
end;
end;
INITIALIZATION
randomize;
end.
|
unit MB3DMeshMergeUI;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls,
JvExStdCtrls, JvGroupBox, Vcl.ExtCtrls, Contnrs;
type
TMB3DMeshMergeFrm = class(TForm)
Panel2: TPanel;
Label13: TLabel;
Button1: TButton;
CalculateBtn: TButton;
ProgressBar: TProgressBar;
CancelBtn: TButton;
Panel1: TPanel;
SmoothGBox: TJvGroupBox;
Label11: TLabel;
Label21: TLabel;
Label22: TLabel;
TaubinSmoothLambaEdit: TEdit;
TaubinSmoothLambaUpDown: TUpDown;
TaubinSmoothMuEdit: TEdit;
TaubinSmoothMuUpDown: TUpDown;
TaubinSmoothPassesEdit: TEdit;
TaubinSmoothPassesEditUpDown: TUpDown;
LoadPartsBtn: TButton;
PartsMemo: TMemo;
OpenDialog: TOpenDialog;
MeshReductionGBox: TJvGroupBox;
Label25: TLabel;
Label26: TLabel;
MeshReductionRetainRatioEdit: TEdit;
MeshReductionRetainRatioUpDown: TUpDown;
MeshReductionAgressivenessEdit: TEdit;
MeshReductionAgressivenessUpDown: TUpDown;
procedure Button1Click(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
procedure CalculateBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure LoadPartsBtnClick(Sender: TObject);
procedure TaubinSmoothLambaUpDownClick(Sender: TObject; Button: TUDBtnType);
procedure TaubinSmoothMuUpDownClick(Sender: TObject; Button: TUDBtnType);
procedure TaubinSmoothPassesEditUpDownClick(Sender: TObject;
Button: TUDBtnType);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FCalculating, FForceAbort: boolean;
function GetOutputMeshFilename: string;
procedure EnableControls;
procedure FillPartsMemo( const Filename: string );
function ReadParts: TObjectList;
public
{ Public declarations }
end;
var
MB3DMeshMergeFrm: TMB3DMeshMergeFrm;
implementation
{$R *.dfm}
uses
BulbTracerUITools, VertexList, DateUtils, Generics.Collections,
MeshWriter, MeshReader, MeshIOUtil, MeshSimplifier, IOUtils;
procedure TMB3DMeshMergeFrm.Button1Click(Sender: TObject);
begin
if not FCalculating then
Close;
end;
function TMB3DMeshMergeFrm.GetOutputMeshFilename: string;
var
I: Integer;
Filename, BasePath, BaseFilename: String;
begin
Result := '';
if PartsMemo.Lines.Count > 0 then begin
Filename := PartsMemo.Lines[ 0 ];
BasePath := ExtractFilePath( Filename );
for I:=Length(BasePath) downto 1 do begin
if BasePath[I] = '\' then begin
BasePath := Copy( BasePath, 1, I - 1 );
break;
end;
end;
BaseFilename := ChangeFileExt( ExtractFileName( BasePath ), '.obj' );
Result := IncludeTrailingBackslash( TDirectory.GetParent(ExcludeTrailingPathDelimiter(BasePath)) ) + BaseFilename;
end;
end;
procedure TMB3DMeshMergeFrm.LoadPartsBtnClick(Sender: TObject);
begin
OpenDialog.DefaultExt := cMB3DMeshSegFileExt;
OpenDialog.Filter := 'Mesh Part (*.lwo)|*.lwo';
if OpenDialog.Execute(Self.Handle) then
FillPartsMemo( OpenDialog.FileName );
end;
procedure TMB3DMeshMergeFrm.CalculateBtnClick(Sender: TObject);
const
MergeRatio: Single = 0.1;
var
T0: Int64;
FacesList: TFacesList;
DoPostProcessing: Boolean;
FThreadVertexLists: TObjectList;
MaxFaces: Integer;
begin
FCalculating := True;
try
ProgressBar.Max := 5;
ProgressBar.Step := 0;
EnableControls;
T0 := DateUtils.MilliSecondsBetween(Now, 0);
FThreadVertexLists := ReadParts;
ProgressBar.StepIt;
try
FacesList := TFacesList.MergeFacesLists( FThreadVertexLists, False );
ProgressBar.StepIt;
try
DoPostProcessing := SmoothGBox.Checked;
FacesList.DoCenter(1.0);
MaxFaces := Round( FacesList.Count * MergeRatio );
if FacesList.Count > MaxFaces then begin
with TMeshSimplifier.Create(FacesList) do try
SimplifyMesh( MaxFaces );
finally
Free;
end;
end;
ProgressBar.StepIt;
if SmoothGBox.Checked then begin
FacesList.TaubinSmooth(StrToFloat(TaubinSmoothLambaEdit.Text), StrToFloat(TaubinSmoothMuEdit.Text), StrToInt(TaubinSmoothPassesEdit.Text));
end;
ProgressBar.StepIt;
if not FForceAbort then begin
// TLightwaveObjFileWriter.SaveToFile(GetOutputMeshFilename, FacesList);
TObjFileWriter.SaveToFile(GetOutputMeshFilename, FacesList);
end;
ProgressBar.StepIt;
FThreadVertexLists.Clear;
finally
FacesList.Free;
end;
finally
FThreadVertexLists.Free;
end;
OutputDebugString(PChar('TOTAL: '+IntToStr(DateUtils.MilliSecondsBetween(Now, 0)-T0)+' ms'));
if not FForceAbort then
Label13.Caption := 'Elapsed time: ' + IntToStr(Round((DateUtils.MilliSecondsBetween(Now, 0)-T0)/1000.0))+' s';
finally
FCalculating := False;
EnableControls;
end;
end;
procedure TMB3DMeshMergeFrm.CancelBtnClick(Sender: TObject);
begin
if FCalculating and (MessageDlg('Do you want to cancel?', mtConfirmation, mbYesNo, 0)=mrOK) then begin
if FCalculating then begin
FForceAbort := True;
end;
end;
end;
procedure TMB3DMeshMergeFrm.EnableControls;
var
HasParts: boolean;
begin
HasParts := ( PartsMemo.Lines.Count > 0 ) and ( Trim( PartsMemo.Text ) <> '' );
CalculateBtn.Enabled := HasParts and ( not FCalculating );
end;
procedure TMB3DMeshMergeFrm.FormCreate(Sender: TObject);
begin
TaubinSmoothLambaEdit.Text := FloatToStr(0.42);
TaubinSmoothMuEdit.Text := FloatToStr(-0.45);
TaubinSmoothPassesEdit.Text := IntToStr(12);
MeshReductionRetainRatioEdit.Text := FloatToStr(0.25);
MeshReductionAgressivenessEdit.Text := FloatToStr(7.0);
end;
procedure TMB3DMeshMergeFrm.FormShow(Sender: TObject);
begin
EnableControls;
end;
procedure TMB3DMeshMergeFrm.FillPartsMemo( const Filename: string );
var
BasePath, BaseFilename, CurrFilename: string;
I: integer;
begin
// mb3d_mesh_03.lwo
BasePath := ExtractFilePath( Filename );
BaseFilename := ChangeFileExt( ExtractFileName( Filename ), '' );
for I := Length( BaseFilename ) downto 1 do begin
if BaseFilename[ I ] = '_' then begin
BaseFilename := Copy( BaseFilename, 1, I - 1 );
break;
end;
end;
PartsMemo.Lines.Clear;
EnableControls;
I:=0;
while( True ) do begin
CurrFilename := IncludeTrailingBackslash( BasePath ) + TUnprocessedMeshFileWriter.CreatePartFilename( I );
if FileExists( CurrFilename ) then
PartsMemo.Lines.Add( CurrFilename )
else
break;
Inc( I );
end;
EnableControls;
end;
procedure TMB3DMeshMergeFrm.TaubinSmoothLambaUpDownClick(Sender: TObject;
Button: TUDBtnType);
var
Value: Double;
begin
Value := StrToFloatSafe(TaubinSmoothLambaEdit.Text, 0.0) + UpDownBtnValue(Button, 0.1);
TaubinSmoothLambaEdit.Text := FloatToStr(Value);
end;
procedure TMB3DMeshMergeFrm.TaubinSmoothMuUpDownClick(Sender: TObject;
Button: TUDBtnType);
var
Value: Double;
begin
Value := StrToFloatSafe(TaubinSmoothMuEdit.Text, 0.0) + UpDownBtnValue(Button, 0.1);
TaubinSmoothMuEdit.Text := FloatToStr(Value);
end;
procedure TMB3DMeshMergeFrm.TaubinSmoothPassesEditUpDownClick(Sender: TObject;
Button: TUDBtnType);
var
Value: Double;
begin
Value := StrToFloatSafe(TaubinSmoothPassesEdit.Text, 0.0) + UpDownBtnValue(Button, 1);
if Value < 0 then
Value := 0.0;
TaubinSmoothPassesEdit.Text := IntToStr(Round(Value));
end;
{ ---------------------------- TLoadPartThread ------------------------------- }
type
TLoadPartThread = class(TThread)
private
FDone: boolean;
FFilename: string;
FFacesList: TFacesList;
procedure ReadPart;
public
constructor Create( const Filename: string; FacesList: TFacesList );
protected
procedure Execute; override;
function IsDone: boolean;
end;
constructor TLoadPartThread.Create( const Filename: string; FacesList: TFacesList );
begin
inherited Create( True );
FFilename := Filename;
FFacesList := FacesList;
end;
procedure TLoadPartThread.Execute;
begin
ReadPart;
end;
procedure TLoadPartThread.ReadPart;
const
HeaderMaxSize = 20;
var
I: integer;
Reader: TLightwaveObjFileReader;
begin
FDone := false;
try
with TLightwaveObjFileReader.Create do try
LoadFromFile( FFilename, FFacesList );
finally
Free;
end;
finally
FDone := true;
end;
end;
function TLoadPartThread.IsDone: boolean;
begin
Result := FDone;
end;
{ ---------------------------- TLoadPartThread ------------------------------- }
function TMB3DMeshMergeFrm.ReadParts: TObjectList;
var
I: integer;
IsDone: boolean;
CurrFacesList: TFacesList;
CurrThread: TLoadPartThread;
Threads: TObjectList;
begin
Result := TObjectList.Create;
try
Threads := TObjectList.Create.Create;
try
for I := 0 to PartsMemo.Lines.Count - 1 do begin
CurrFacesList := TFacesList.Create;
Result.Add( CurrFacesList );
CurrThread := TLoadPartThread.Create( PartsMemo.Lines[I], CurrFacesList );
Threads.Add( CurrThread );
CurrThread.Start;
end;
IsDone := false;
while( not IsDone ) do begin
IsDone := true;
for I := 0 to Threads.Count - 1 do begin
if( not TLoadPartThread(Threads[I]).IsDone ) then begin
IsDone := false;
break;
end;
Sleep(10);
end;
end;
finally
Threads.Free;
end;
except
Result.Free;
raise;
end;
end;
end.
|
{
@html(<b>)
Encryption/Decryption Plug-in
@html(</b>)
- Copyright (c) Danijel Tkalcec
@html(<br><br>)
This unit defines a Plug-in class, which should be extended when implementing
third-party plug-ins for SSL/SSH encryption/decryption using RTC SDK components.
}
unit rtcPlugins;
interface
{$include rtcDefs.inc}
uses
Classes;
type
TRtcConnID = longint;
{ @abstract(Cryptography Plugin)
This is a basic class for any kind of third-party encryption/decryption
plug-ins used by rtcHttpClient and rtcHttpServer components. }
TRtcCryptPlugin = class(TComponent)
public
{ Called after a new connection was established.
OutData = data which has to be sent out immediately. }
procedure AfterConnect(ID:TRtcConnID; var OutData:string); virtual; abstract;
{ Called before we do a graceful disconnect, in case some data has to be sent out. }
procedure BeforeDisconnect(ID:TRtcConnID; var OutData:string); virtual; abstract;
{ Called after a connection was closed. }
procedure AfterDisconnect(ID:TRtcConnID); virtual; abstract;
{ Called when data arrived.
InData = data received from recipient (decode that!)
OutData = data prepared by "decoder" for sending back to recipient (encoded data)
OutPlainText = decrypted input data (for use by application) }
procedure DataReceived(ID:TRtcConnID; const InData:string; var OutData:string; var OutPlainText:string); virtual; abstract;
{ Called when data needs to be sent.
InData = application data which we want to be encoded for sending
OutData = encoded data which should be sent out }
procedure DataToSend(ID:TRtcConnID; const InData:string; var OutData:string); virtual; abstract;
end;
implementation
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLRenderContextInfo<p>
Stores contextual info useful during rendering methods.<p>
<b>History : </b><font size=-1><ul>
<li>23/08/10 - Yar - Removed modelViewMatrix, lightDisableCounter. Added PipelineTransformation.
<li>22/02/10 - Yar - Added bufferLighting, bufferFog, bufferDepthTest to TRenderContextInfo
<li>14/03/09 - DanB - Removed IsVolumeClipped functions, instead replaced with
IsVolumeClipped functions in GLVectorGeometry.pas that use TFrustrum
<li>09/10/08 - DanB - Added TRenderContextClippingInfo + IsVolumeClipped
functions from GLVectorGeometry.pas, added nearClippingDistance
<li>05/10/08 - DanB - Created from GLTexture.pas split
</ul></font>
}
unit GLRenderContextInfo;
interface
{$I GLScene.inc}
uses
GLPersistentClasses, GLVectorGeometry, GLState,
GLPipelineTransformation, GLColor;
type
TDrawState = (dsRendering, dsPicking, dsPrinting);
TGLSize = record
cx: Longint;
cy: Longint;
end;
// TGLObjectsSorting
//
{: Determines if objects are sorted, and how.<p>
Sorting is done level by level (and not for all entities), values are :<ul>
<li>osInherited : use inherited sorting mode, defaults to osRenderFarthestFirst
<li>osNone : do not sort objects.
<li>osRenderFarthestFirst : render objects whose Position is the farthest from
the camera first.
<li>osRenderBlendedLast : opaque objects are not sorted and rendered
first, blended ones are rendered afterwards and depth sorted.
<li>osRenderNearestFirst : render objects whose Position is the nearest to
the camera first.
</ul> }
TGLObjectsSorting = (osInherited, osNone,
osRenderFarthestFirst, osRenderBlendedLast,
osRenderNearestFirst);
// TGLVisibilityCulling
//
{: Determines the visibility culling mode.
Culling is done level by level, allowed values are:<ul>
<li>vcInherited : use inherited culling value, if selected for the root
level, defaults to vcNone
<li>vcNone : no visibility culling is performed
<li>vcObjectBased : culling is done on a per-object basis, each object may
or may not be culled base on its own AxisAlignedDimensions,
culling has no impact on the visibility of its children
<li>vcHierarchical : culling is performed hierarchically, using hierarchical
bounding boxes, if a parent is culled, all of its children, whatever their
culling options are invisible.
<li><br>Depending on the structure of your scene the most efficient culling
method will be either vcObjectBased or vcHierarchical. Also note that if
you use many objects with "static" geometry and have a T&L graphics
board, it may be faster not to cull at all (ie. leave this to the hardware). }
TGLVisibilityCulling = (vcInherited, vcNone, vcObjectBased, vcHierarchical);
// TRenderContextClippingInfo
//
TRenderContextClippingInfo = record
origin: TVector;
clippingDirection: TVector;
viewPortRadius: Single; // viewport bounding radius per distance unit
nearClippingDistance: Single;
farClippingDistance: Single;
frustum: TFrustum;
end;
// TRenderContextInfo
//
{: Stores contextual info useful during rendering methods. }
TRenderContextInfo = record
scene: TObject; //usually TGLScene
buffer: TObject; //usually TGLSceneBuffer
cameraPosition: TVector;
cameraDirection, cameraUp: TVector;
viewPortSize: TGLSize;
renderDPI: Integer;
materialLibrary: TObject; //usually TGLMaterialLibrary;
lightmapLibrary: TObject; //usually TGLMaterialLibrary;
fogDisabledCounter: Integer;
drawState: TDrawState;
objectsSorting: TGLObjectsSorting;
visibilityCulling: TGLVisibilityCulling;
GLStates: TGLStateCache;
PipelineTransformation: TGLTransformation;
rcci: TRenderContextClippingInfo;
sceneAmbientColor: TColorVector;
bufferFaceCull: Boolean;
bufferLighting: Boolean;
bufferFog: Boolean;
bufferDepthTest: Boolean;
proxySubObject: Boolean;
ignoreMaterials: Boolean;
ignoreBlendingRequests: Boolean;
ignoreDepthRequests: Boolean;
amalgamating: Boolean;
lights: TPersistentObjectList;
afterRenderEffects: TPersistentObjectList;
currentMaterialLevel: TGLMaterialLevel;
primitiveMask: TGLMeshPrimitives;
orderCounter: Integer;
end;
PRenderContextInfo = ^TRenderContextInfo;
implementation
end.
|
{A benchmark replaying the allocations/deallocations performed by a user
application}
unit ReplayBenchmarkUnit;
{$mode delphi}
interface
uses
Windows, SysUtils, Classes, Dialogs, BenchmarkClassUnit, Math;
type
{A single operation}
PMMOperation = ^TMMOperation;
TMMOperation = packed record
{The old pointer number. Will be < 0 for GetMem requests, non-zero otherwise.}
OldPointerNumber: Integer;
{The requested size. Will be zero for FreeMem requests, non-zero otherwise.}
RequestedSize: Integer;
{The new pointer number. Will be < 0 for FreeMem requests, non-zero otherwise.}
NewPointerNumber: Integer;
end;
{The single-thread replay benchmark ancestor}
TReplayBenchmark = class(TFastcodeMMBenchmark)
protected
{The operations}
FOperations: string;
FPointers: array of pointer;
{The log file name, can be specified by descendant}
FUsageLogFileName: string;
{Gets the memory overhead of the benchmark that should be subtracted}
function GetBenchmarkOverhead: Cardinal; override;
procedure RunReplay;
public
constructor CreateBenchmark; override;
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function RunByDefault: boolean; override;
class function GetCategory: TBenchmarkCategory; override;
{repeat count for replay log}
class function RepeatCount: integer; virtual;
end;
{The multi-threaded replay benchmark ancestor}
TMultiThreadReplayBenchmark = class(TReplayBenchmark)
public
procedure RunBenchmark; override;
class function GetCategory: TBenchmarkCategory; override;
{number of simultaneously running threads}
class function RunningThreads: Integer; virtual;
{total number of threads running}
class function ThreadCount: Integer; virtual;
end;
{Single-threaded replays}
TReservationsSystemBenchmark = class(TReplayBenchmark)
public
constructor CreateBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function RunByDefault: boolean; override;
class function RepeatCount: integer; override;
end;
TXMLParserBenchmark = class(TReplayBenchmark)
public
constructor CreateBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function RunByDefault: boolean; override;
class function RepeatCount: integer; override;
end;
TDocumentClassificationBenchmark = class(TReplayBenchmark)
public
constructor CreateBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function RunByDefault: boolean; override;
class function RepeatCount: integer; override;
end;
{Multi-threaded replays}
TeLinkBenchmark = class(TMultiThreadReplayBenchmark)
public
constructor CreateBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function RunByDefault: boolean; override;
class function RunningThreads: Integer; override;
class function ThreadCount: Integer; override;
end;
TeLinkComServerBenchmark = class(TMultiThreadReplayBenchmark)
public
constructor CreateBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function RunByDefault: boolean; override;
class function RunningThreads: Integer; override;
class function ThreadCount: Integer; override;
end;
TWebbrokerReplayBenchmark = class(TMultiThreadReplayBenchmark)
public
constructor CreateBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function RunByDefault: boolean; override;
class function RunningThreads: Integer; override;
class function ThreadCount: Integer; override;
class function RepeatCount: Integer; override;
end;
TBeyondCompareBenchmark = class(TMultiThreadReplayBenchmark)
public
constructor CreateBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function RunByDefault: boolean; override;
class function RunningThreads: Integer; override;
class function ThreadCount: Integer; override;
class function RepeatCount: integer; override;
class function GetSpeedWeight: double; override;
end;
implementation
uses BenchmarkUtilities;
type
{The replay thread used in multi-threaded replay benchmarks}
TReplayThread = class(TThread)
private
FRepeatCount: integer;
FOperations: string;
FBenchmark: TFastcodeMMBenchmark;
procedure ExecuteReplay;
public
constructor Create(Suspended: Boolean; ABenchmark: TFastcodeMMBenchmark; RepeatCount: integer);
procedure Execute; override;
property Operations: string read FOperations write FOperations;
end;
{Reads a file in its entirety and returns the contents as a string. Returns a
blank string on error.}
function LoadFile(const AFileName: string): string;
var
LFileInfo: OFSTRUCT;
LHandle: HFILE;
LFileSize: integer;
LBytesRead: Cardinal;
begin
{Default to empty string (file not found)}
Result := '';
{Try to open the file}
LHandle := OpenFile(PChar(AFileName), LFileInfo, OF_READ);
if LHandle <> HFILE_ERROR then
begin
try
{Find the FileSize}
LFileSize := SetFilePointer(LHandle, 0, nil, FILE_END);
{Read the file}
if LFileSize > 0 then
begin
{Allocate the buffer}
SetLength(Result, LFileSize);
{Go back to the start of the file}
if SetFilePointer(LHandle, 0, nil, FILE_BEGIN) = 0 then
begin
{Read the file}
Windows.ReadFile(LHandle, Result[1], LFileSize, LBytesRead, nil);
{Was all the data read?}
if LBytesRead <> Cardinal(LFileSize) then
Result := '';
end;
end;
finally
{Close the file}
CloseHandle(LHandle);
end;
end;
end;
{ TReplayBenchmark }
constructor TReplayBenchmark.CreateBenchmark;
begin
inherited;
{Try to load the usage log}
if FUsageLogFileName <> '' then
begin
// descendant has specified usage log file
FOperations := LoadFile(FUsageLogFileName);
if FOperations = '' then
FCanRunBenchmark := False;
// raise Exception.CreateFmt('The file "%s" could not be found in the current folder', [FUsageLogFileName]);
end
else
begin
// use default usage log file
FOperations := LoadFile('MMUsage.Log');
if FOperations = '' then
begin
FOperations := LoadFile('c:\MMUsage.Log');
if FOperations = '' then
raise Exception.Create('The file MMUsage.Log could not be found in the current folder or c:\');
end;
end;
{Set the list of pointers}
SetLength(FPointers, length(FOperations) div SizeOf(TMMOperation));
Sleep(2000); // RH let system relax after big file load... seems to be useful to get consistent results
end;
class function TReplayBenchmark.GetBenchmarkDescription: string;
begin
Result := 'Plays back the memory operations of another application as '
+ 'recorded by the MMUsageLogger utility. To record and replay the '
+ 'operations performed by your application:'#13#10
+ '1) Place MMUsageLogger.pas as the first unit in the .dpr of your app.'#13#10
+ '2) Run the application (a file c:\MMUsage.log will be created).'#13#10
+ '3) Copy the .log into the B&V folder.'#13#10
+ '4) Run the B&V tool with the replacement MM that you want to test as the '
+ 'first unit in the B&V .dpr.'#13#10
+ '5) Select this benchmark and run it.'#13#10
+ '6) The B&V tool will replay the exact sequence of '
+ 'allocations/deallocations/reallocations of your application, giving you a '
+ 'good idea of how your app will perform with the given memory manager.';
end;
class function TReplayBenchmark.GetBenchmarkName: string;
begin
Result := 'Usage Replay Benchmark';
end;
procedure TReplayBenchmark.RunReplay;
var
LPOperation: PMMOperation;
LInd, LOperationCount, LOffset: integer;
begin
{Get a pointer to the first operation}
LPOperation := pointer(FOperations);
{Get the number of operations to perform}
LOperationCount := length(FPointers);
{Perform all the operations}
for LInd := 0 to LOperationCount - 1 do
begin
{Perform the operation}
if LPOperation.NewPointerNumber >= 0 then
begin
if LPOperation.OldPointerNumber <> LPOperation.NewPointerNumber then
begin
{GetMem}
GetMem(FPointers[LPOperation.NewPointerNumber], LPOperation.RequestedSize);
end
else
begin
{ReallocMem}
ReallocMem(FPointers[LPOperation.OldPointerNumber], LPOperation.RequestedSize);
end;
{Touch every 4K page}
LOffset := 0;
while LOffset < LPOperation.RequestedSize do
begin
PByte(Integer(FPointers[LPOperation.NewPointerNumber]) + LOffset)^ := 1;
Inc(LOffset, 4096);
end;
{Touch the last byte}
PByte(integer(FPointers[LPOperation.NewPointerNumber]) + LPOperation.RequestedSize - 1)^ := 1;
end
else
begin
{FreeMem}
FreeMem(FPointers[LPOperation.OldPointerNumber]);
FPointers[LPOperation.OldPointerNumber] := nil;
end;
{Next operation}
Inc(LPOperation);
{Log peak usage every 1024 operations}
if LInd and $3ff = 0 then
UpdateUsageStatistics;
end;
{Make sure all memory is released to avoid memory leaks in benchmark}
for LInd := 0 to High(FPointers) do
if FPointers[LInd] <> nil then
FreeMem(FPointers[LInd]);
end;
class function TReplayBenchmark.RunByDefault: boolean;
begin
Result := False;
end;
procedure TReplayBenchmark.RunBenchmark;
var
i: integer;
begin
inherited;
for i := 1 to RepeatCount do
RunReplay;
end;
class function TReplayBenchmark.RepeatCount: integer;
begin
Result := 1;
end;
class function TReplayBenchmark.GetCategory: TBenchmarkCategory;
begin
Result := bmSingleThreadReplay;
end;
function TReplayBenchmark.GetBenchmarkOverhead: Cardinal;
begin
{Take into account the size of the replay file}
Result := InitialAddressSpaceUsed + (length(FOperations) + length(FPointers) * 4) shr 10;
end;
{ TReplayThread }
constructor TReplayThread.Create(Suspended: Boolean; ABenchmark: TFastcodeMMBenchmark; RepeatCount: integer);
begin
inherited Create(Suspended);
FreeOnTerminate := False;
Priority := tpNormal;
FBenchmark := ABenchmark;
FRepeatCount := RepeatCount;
end;
procedure TReplayThread.Execute;
var
i: Integer;
begin
// Repeat the replay log RepeatCount times
for i := 1 to FRepeatCount do
ExecuteReplay;
end;
procedure TReplayThread.ExecuteReplay;
var
LPOperation: PMMOperation;
LInd, LOperationCount, LOffset: integer;
FPointers: array of pointer;
begin
{Set the list of pointers}
SetLength(FPointers, length(FOperations) div SizeOf(TMMOperation));
{Get a pointer to the first operation}
LPOperation := pointer(FOperations);
{Get the number of operations to perform}
LOperationCount := length(FPointers);
{Perform all the operations}
for LInd := 0 to LOperationCount - 1 do
begin
{Perform the operation}
if LPOperation.NewPointerNumber >= 0 then
begin
if LPOperation.OldPointerNumber <> LPOperation.NewPointerNumber then
begin
{GetMem}
GetMem(FPointers[LPOperation.NewPointerNumber], LPOperation.RequestedSize);
end
else
begin
{ReallocMem}
ReallocMem(FPointers[LPOperation.OldPointerNumber], LPOperation.RequestedSize);
end;
{Touch every 4K page}
LOffset := 0;
while LOffset < LPOperation.RequestedSize do
begin
PByte(Integer(FPointers[LPOperation.NewPointerNumber]) + LOffset)^ := 1;
Inc(LOffset, 4096);
end;
{Touch the last byte}
PByte(integer(FPointers[LPOperation.NewPointerNumber]) + LPOperation.RequestedSize - 1)^ := 1;
end
else
begin
{FreeMem}
FreeMem(FPointers[LPOperation.OldPointerNumber]);
FPointers[LPOperation.OldPointerNumber] := nil;
end;
{Next operation}
Inc(LPOperation);
{Log peak usage every 1024 operations}
if LInd and $3ff = 0 then
FBenchMark.UpdateUsageStatistics;
{the replay is probably running about 10 to 50 times faster than reality}
{force thread switch every 8192 operations to prevent whole benchmark from running in a single time-slice}
if LInd and $1fff = 0 then
Sleep(0);
end;
{Make sure all memory is released to avoid memory leaks in benchmark}
for LInd := 0 to High(FPointers) do
if FPointers[LInd] <> nil then
FreeMem(FPointers[LInd]);
end;
{ TMultiThreadReplayBenchmark }
class function TMultiThreadReplayBenchmark.ThreadCount: Integer;
begin
Result := 100;
end;
class function TMultiThreadReplayBenchmark.RunningThreads: Integer;
begin
Result := 4;
end;
procedure TMultiThreadReplayBenchmark.RunBenchmark;
var
i, rc, slot : Integer;
WT : TReplayThread;
ThreadArray : array[0..63] of TReplayThread;
HandleArray : array[0..63] of THandle;
begin
inherited;
Assert(RunningThreads <= 64, 'Maximum 64 simultaneously running threads in TMultiThreadReplayBenchmark');
{create threads to start with}
for i := 0 to RunningThreads - 1 do
begin
WT := TReplayThread.Create(True, Self, RepeatCount);
WT.Operations := FOperations;
HandleArray[i] := WT.Handle;
ThreadArray[i] := WT;
end;
{start threads...}
for i := 0 to RunningThreads - 1 do
ThreadArray[i].Resume;
{loop to replace terminated threads}
for i := RunningThreads + 1 to ThreadCount do
begin
rc := WaitForMultipleObjects(RunningThreads, @HandleArray, False, INFINITE);
slot := rc - WAIT_OBJECT_0;
if (slot < 0) or (slot >= RunningThreads) then
begin
MessageDlg(SysErrorMessage(GetLastError), mtError, [mbOK], 0);
Exit;
end;
ThreadArray[slot].Free;
WT := TReplayThread.Create(True, Self, RepeatCount);
WT.Operations := FOperations;
HandleArray[slot] := WT.Handle;
ThreadArray[slot] := WT;
WT.Resume;
end;
rc := WaitForMultipleObjects(RunningThreads, @HandleArray, True, INFINITE);
for i := 0 to RunningThreads - 1 do
ThreadArray[i].Free;
if rc < WAIT_OBJECT_0 then
MessageDlg(SysErrorMessage(GetLastError), mtError, [mbOK], 0);
end;
// add your replay benchmarks below...
class function TMultiThreadReplayBenchmark.GetCategory: TBenchmarkCategory;
begin
Result := bmMultiThreadReplay;
end;
{ TeLinkBenchmark }
constructor TeLinkBenchmark.CreateBenchmark;
begin
FUsageLogFileName := 'eLink_MMUsage.log';
inherited;
end;
class function TeLinkBenchmark.GetBenchmarkName: string;
begin
Result := Format('Replay: eLink - %d threads', [RunningThreads]);
end;
class function TeLinkBenchmark.GetBenchmarkDescription: string;
begin
Result := 'A play-back of the generation of about 300 web pages with '
+ 'the eLink application, a real-world Apache/ISAPI web server extension '
+ '(see www.nextapplication.com). The application involves mostly string '
+ 'manipulations.';
end;
class function TeLinkBenchmark.RunByDefault: boolean;
begin
Result := True;
end;
class function TeLinkBenchmark.ThreadCount: Integer;
begin
Result := 200;
end;
class function TeLinkBenchmark.RunningThreads: Integer;
begin
Result := 16;
end;
{ TeLinkComServerBenchmark }
constructor TeLinkComServerBenchmark.CreateBenchmark;
begin
FUsageLogFileName := 'LinkCom+Server_MMUsage.log';
inherited;
end;
class function TeLinkComServerBenchmark.GetBenchmarkName: string;
begin
Result := Format('Replay: Link COM+ Server - %d threads', [RunningThreads]);
end;
class function TeLinkComServerBenchmark.GetBenchmarkDescription: string;
begin
Result := 'A play-back of the COM+ server side of the eLink application '
+ '(see eLink Benchmark). The application involves mostly database operations: '
+ 'constructing and executing SQL queries and retrieving results in datasets.';
end;
class function TeLinkComServerBenchmark.RunByDefault: boolean;
begin
Result := True;
end;
class function TeLinkComServerBenchmark.ThreadCount: Integer;
begin
Result := 200;
end;
class function TeLinkComServerBenchmark.RunningThreads: Integer;
begin
Result := 4;
end;
{ TWebbrokerReplayBenchmark }
constructor TWebbrokerReplayBenchmark.CreateBenchmark;
begin
FUsageLogFileName := 'WebBroker_MMUsage.log';
inherited;
end;
class function TWebbrokerReplayBenchmark.GetBenchmarkDescription: string;
begin
Result := 'Plays back the memory operations of a webbroker app that was '
+ 'recorded by the MMUsageLogger utility. The recording is played back '
+ IntToStr(RepeatCount * ThreadCount) + ' times using a maximum of '
+ IntToStr(RunningThreads) + ' thread(s).';
end;
class function TWebbrokerReplayBenchmark.GetBenchmarkName: string;
begin
Result := 'Replay: Webbroker - ' + IntToStr(RunningThreads) + ' thread(s)';
end;
class function TWebbrokerReplayBenchmark.RunningThreads: Integer;
begin
Result := 8;
end;
class function TWebbrokerReplayBenchmark.RunByDefault: boolean;
begin
Result := True;
end;
class function TWebbrokerReplayBenchmark.ThreadCount: Integer;
begin
Result := 16;
end;
class function TWebbrokerReplayBenchmark.RepeatCount: Integer;
begin
Result := 1;
end;
{ TReservationsSystemBenchmark }
constructor TReservationsSystemBenchmark.CreateBenchmark;
begin
FUsageLogFileName := 'Reservations_System_MMUsage.log';
inherited;
end;
class function TReservationsSystemBenchmark.GetBenchmarkDescription: string;
begin
Result := 'A replay of typical operations performed by a reservations system: Bookings and clients are created and checked in/out and transactions are processed.';
end;
class function TReservationsSystemBenchmark.GetBenchmarkName: string;
begin
Result := 'Replay: Reservations System';
end;
class function TReservationsSystemBenchmark.RepeatCount: integer;
begin
Result := 50;
end;
class function TReservationsSystemBenchmark.RunByDefault: boolean;
begin
Result := True;
end;
{ TXMLParserBenchmark }
constructor TXMLParserBenchmark.CreateBenchmark;
begin
FUsageLogFileName := 'XMLParser_MMUsage.log';
inherited;
end;
class function TXMLParserBenchmark.GetBenchmarkDescription: string;
begin
Result := 'A recording of a XML parser opening an 11 MB XML file'
+ ' (an Openoffice spreadsheet) and building a complete DOM'
+ ' (the spreadsheet is then altered in memory and saved back).'
+ ' It is characterized by the allocation of a'
+ ' lot of small blocks.';
end;
class function TXMLParserBenchmark.GetBenchmarkName: string;
begin
Result := 'Replay: XML Parser';
end;
class function TXMLParserBenchmark.RepeatCount: integer;
begin
Result := 15;
end;
class function TXMLParserBenchmark.RunByDefault: boolean;
begin
Result := True;
end;
{ TBeyondCompareBenchmark }
constructor TBeyondCompareBenchmark.CreateBenchmark;
begin
FUsageLogFileName := 'BeyondCompare3_MMUsage.log';
inherited;
end;
class function TBeyondCompareBenchmark.GetBenchmarkDescription: string;
begin
Result := 'A recording of the Beyond Compare application comparing two files (www.scootersoftware.com).';
end;
class function TBeyondCompareBenchmark.GetBenchmarkName: string;
begin
Result := 'Replay: Beyond Compare 3 - 4 threads';
end;
class function TBeyondCompareBenchmark.GetSpeedWeight: double;
begin
{Lower speed weight as requested by Craig Peterson (the submitter of the
replay)}
Result := 0.4;
end;
class function TBeyondCompareBenchmark.RepeatCount: integer;
begin
Result := 15;
end;
class function TBeyondCompareBenchmark.RunByDefault: boolean;
begin
Result := True;
end;
class function TBeyondCompareBenchmark.RunningThreads: Integer;
begin
Result := 4;
end;
class function TBeyondCompareBenchmark.ThreadCount: Integer;
begin
Result := 4;
end;
{ TDocumentClassificationBenchmark }
constructor TDocumentClassificationBenchmark.CreateBenchmark;
begin
FUsageLogFileName := 'Document_Classification_MMUsage.log';
inherited;
end;
class function TDocumentClassificationBenchmark.GetBenchmarkDescription: string;
begin
Result := 'A recording of a document indexing and classification application (www.provalisresearch.com).';
end;
class function TDocumentClassificationBenchmark.GetBenchmarkName: string;
begin
Result := 'Replay: Document Classification';
end;
class function TDocumentClassificationBenchmark.RepeatCount: integer;
begin
Result := 30;
end;
class function TDocumentClassificationBenchmark.RunByDefault: boolean;
begin
Result := True;
end;
end.
|
program generic_test;
{$mode objfpc}{H+}
uses
SysUtils;
generic procedure GSwap<T>(var L, R: T);
var
Tmp: T;
begin
Tmp := L;
L := R;
R := Tmp;
end;
var
I, J: Integer;
begin
I := 100;
J := 11;
WriteLn('I = ', I, ', J = ', J);
specialize GSwap<Integer>(I, J);
WriteLn('I = ', I, ', J = ', J);
end.
|
unit uWaitForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, uAnimationThread;
type
TfrmWait = class(TForm)
grp1: TGroupBox;
pnl1: TPanel;
lblCaption: TLabel;
private
{ Private declarations }
public
{ Public declarations }
end;
procedure ShowWait(AColor: TColor);
procedure UpdateCaption(TextCaption: string);
procedure HideWait;
implementation
{$R *.dfm}
var
WaitForm: TfrmWait = nil;
FormList: Pointer;
ani: TAnimationThread;
R: TRect;
procedure ShowWait(AColor: TColor);
begin
if not Assigned(WaitForm) then
WaitForm := TfrmWait.Create(Application.MainForm)
else
WaitForm.BringToFront;
WaitForm.Show;
FormList := DisableTaskWindows(WaitForm.Handle);
WaitForm.Update;
r := WaitForm.pnl1.clientrect;
InflateRect(r, - WaitForm.pnl1.bevelwidth, - WaitForm.pnl1.bevelwidth);
ani := TanimationThread.Create(WaitForm.pnl1, r, WaitForm.pnl1.color, AColor, 10);
Application.ProcessMessages;
end;
procedure UpdateCaption(TextCaption: string);
begin
if Assigned(WaitForm) then
begin
WaitForm.lblCaption.Caption := TextCaption;
WaitForm.Update;
Application.ProcessMessages;
end;
end;
procedure HideWait;
begin
if not Assigned(WaitForm) then Exit;
// Останавливаем поток
ani.Terminate;
EnableTaskWindows(FormList);
WaitForm.Hide;
Application.ProcessMessages;
WaitForm.Free;
WaitForm := nil;
end;
end.
|
unit BCEditor.Print.Margins;
interface
uses
Classes, SysUtils, Graphics, BCEditor.Print.Types, BCEditor.Print.PrinterInfo, BCEditor.Utils;
type
TBCEditorPrintMargins = class(TPersistent)
strict private
FBottom: Double;
FFooter: Double;
FHeader: Double;
FInternalMargin: Double;
FLeft: Double;
FLeftTextIndent: Double;
FMargin: Double;
FMirrorMargins: Boolean;
FRight: Double;
FRightTextIndent: Double;
FTop: Double;
FUnitSystem: TBCEditorUnitSystem;
function ConvertFrom(Value: Double): Double;
function ConvertTo(Value: Double): Double;
function GetBottom: Double;
function GetFooter: Double;
function GetHeader: Double;
function GetInternalMargin: Double;
function GetLeft: Double;
function GetLeftTextIndent: Double;
function GetMargin: Double;
function GetRight: Double;
function GetRightTextIndent: Double;
function GetTop: Double;
procedure SetBottom(const Value: Double);
procedure SetFooter(const Value: Double);
procedure SetHeader(const Value: Double);
procedure SetInternalMargin(const Value: Double);
procedure SetLeft(const Value: Double);
procedure SetLeftTextIndent(const Value: Double);
procedure SetMargin(const Value: Double);
procedure SetRight(const Value: Double);
procedure SetRightTextIndent(const Value: Double);
procedure SetTop(const Value: Double);
public
PixelBottom: Integer;
PixelFooter: Integer;
PixelHeader: Integer;
PixelInternalMargin: Integer;
PixelLeft: Integer;
PixelLeftTextIndent: Integer;
PixelMargin: Integer;
PixelRight: Integer;
PixelRightTextIndent: Integer;
PixelTop: Integer;
constructor Create;
procedure Assign(Source: TPersistent); override;
procedure InitPage(ACanvas: TCanvas; PageNum: Integer; PrinterInfo: TBCEditorPrinterInfo;
LineNumbers, LineNumbersInMargin: Boolean; MaxLineNum: Integer);
procedure LoadFromStream(AStream: TStream);
procedure SaveToStream(AStream: TStream);
published
property Bottom: Double read GetBottom write SetBottom;
property Footer: Double read GetFooter write SetFooter;
property Header: Double read GetHeader write SetHeader;
property InternalMargin: Double read GetInternalMargin write SetInternalMargin;
property Left: Double read GetLeft write SetLeft;
property LeftTextIndent: Double read GetLeftTextIndent write SetLeftTextIndent;
property Margin: Double read GetMargin write SetMargin;
property MirrorMargins: Boolean read FMirrorMargins write FMirrorMargins;
property Right: Double read GetRight write SetRight;
property RightTextIndent: Double read GetRightTextIndent write SetRightTextIndent;
property Top: Double read GetTop write SetTop;
property UnitSystem: TBCEditorUnitSystem read FUnitSystem write FUnitSystem default usMM;
end;
implementation
{ TBCEditorPrintMargins }
const
mmPrInch = 25.4;
mmPrCm = 10;
constructor TBCEditorPrintMargins.Create;
begin
inherited;
FUnitSystem := usMM;
FLeft := BCEDITOR_DEFAULT_LEFT_MARGIN_MM;
FRight := BCEDITOR_DEFAULT_RIGHT_MARGIN_MM;
FTop := BCEDITOR_DEFAULT_TOP_MARGIN_MM;
FBottom := BCEDITOR_DEFAULT_BOTTOM_MM;
FHeader := BCEDITOR_DEFAULT_HEADER_MM;
FFooter := BCEDITOR_DEFAULT_FOOTER_MM;
FLeftTextIndent := BCEDITOR_DEFAULT_LEFT_TEXT_INDENT_MM;
FRightTextIndent := BCEDITOR_DEFAULT_RIGHT_TEXT_INDENT_MM;
FInternalMargin := BCEDITOR_DEFAULT_INTERNAL_MARGIN_MM;
FMargin := BCEDITOR_DEFAULT_MARGIN_MM;
FMirrorMargins := False;
end;
function TBCEditorPrintMargins.ConvertTo(Value: Double): Double;
begin
case FUnitSystem of
usCM:
Result := Value * mmPrCm;
usInch:
Result := Value * mmPrInch;
muThousandthsOfInches:
Result := mmPrInch * Value / 1000;
else
Result := Value;
end;
end;
function TBCEditorPrintMargins.ConvertFrom(Value: Double): Double;
begin
case FUnitSystem of
usCM:
Result := Value / mmPrCm;
usInch:
Result := Value / mmPrInch;
muThousandthsOfInches:
Result := 1000 * Value / mmPrInch;
else
Result := Value;
end;
end;
function TBCEditorPrintMargins.GetBottom: Double;
begin
Result := ConvertFrom(FBottom);
end;
function TBCEditorPrintMargins.GetFooter: Double;
begin
Result := ConvertFrom(FFooter);
end;
function TBCEditorPrintMargins.GetMargin: Double;
begin
Result := ConvertFrom(FMargin);
end;
function TBCEditorPrintMargins.GetHeader: Double;
begin
Result := ConvertFrom(FHeader);
end;
function TBCEditorPrintMargins.GetLeft: Double;
begin
Result := ConvertFrom(FLeft);
end;
function TBCEditorPrintMargins.GetRight: Double;
begin
Result := ConvertFrom(FRight);
end;
function TBCEditorPrintMargins.GetTop: Double;
begin
Result := ConvertFrom(FTop);
end;
function TBCEditorPrintMargins.GetLeftTextIndent: Double;
begin
Result := ConvertFrom(FLeftTextIndent);
end;
function TBCEditorPrintMargins.GetRightTextIndent: Double;
begin
Result := ConvertFrom(FRightTextIndent);
end;
function TBCEditorPrintMargins.GetInternalMargin: Double;
begin
Result := ConvertFrom(FInternalMargin);
end;
procedure TBCEditorPrintMargins.SetBottom(const Value: Double);
begin
FBottom := ConvertTo(Value);
end;
procedure TBCEditorPrintMargins.SetFooter(const Value: Double);
begin
FFooter := ConvertTo(Value);
end;
procedure TBCEditorPrintMargins.SetMargin(const Value: Double);
begin
FMargin := ConvertTo(Value);
end;
procedure TBCEditorPrintMargins.SetHeader(const Value: Double);
begin
FHeader := ConvertTo(Value);
end;
procedure TBCEditorPrintMargins.SetLeft(const Value: Double);
begin
FLeft := ConvertTo(Value);
end;
procedure TBCEditorPrintMargins.SetRight(const Value: Double);
begin
FRight := ConvertTo(Value);
end;
procedure TBCEditorPrintMargins.SetTop(const Value: Double);
begin
FTop := ConvertTo(Value);
end;
procedure TBCEditorPrintMargins.SetLeftTextIndent(const Value: Double);
begin
FLeftTextIndent := ConvertTo(Value);
end;
procedure TBCEditorPrintMargins.SetRightTextIndent(const Value: Double);
begin
FRightTextIndent := ConvertTo(Value);
end;
procedure TBCEditorPrintMargins.SetInternalMargin(const Value: Double);
begin
FInternalMargin := ConvertTo(Value);
end;
procedure TBCEditorPrintMargins.InitPage(ACanvas: TCanvas; PageNum: Integer; PrinterInfo: TBCEditorPrinterInfo;
LineNumbers, LineNumbersInMargin: Boolean; MaxLineNum: Integer);
begin
if FMirrorMargins and ((PageNum mod 2) = 0) then
begin
PixelLeft := PrinterInfo.PixFromLeft(FRight);
PixelRight := PrinterInfo.PrintableWidth - PrinterInfo.PixFromRight(FLeft + FMargin);
end
else
begin
PixelLeft := PrinterInfo.PixFromLeft(FLeft + FMargin);
PixelRight := PrinterInfo.PrintableWidth - PrinterInfo.PixFromRight(FRight);
end;
if LineNumbers and (not LineNumbersInMargin) then
PixelLeft := PixelLeft + TextWidth(ACanvas, IntToStr(MaxLineNum) + ': ');
PixelTop := PrinterInfo.PixFromTop(FTop);
PixelBottom := PrinterInfo.PrintableHeight - PrinterInfo.PixFromBottom(FBottom);
PixelHeader := PrinterInfo.PixFromTop(FHeader);
PixelFooter := PrinterInfo.PrintableHeight - PrinterInfo.PixFromBottom(FFooter);
PixelInternalMargin := Round(PrinterInfo.YPixPermm * FInternalMargin);
PixelMargin := Round(PrinterInfo.XPixPermm * FMargin);
PixelRightTextIndent := PixelRight - Round(PrinterInfo.XPixPermm * FRightTextIndent);
PixelLeftTextIndent := PixelLeft + Round(PrinterInfo.XPixPermm * FLeftTextIndent);
end;
procedure TBCEditorPrintMargins.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TBCEditorPrintMargins) then
with Source as TBCEditorPrintMargins do
begin
Self.FLeft := FLeft;
Self.FRight := FRight;
Self.FTop := FTop;
Self.FBottom := FBottom;
Self.FHeader := FHeader;
Self.FFooter := FFooter;
Self.FLeftTextIndent := FLeftTextIndent;
Self.FRightTextIndent := FRightTextIndent;
Self.FInternalMargin := FInternalMargin;
Self.FMargin := FMargin;
Self.FMirrorMargins := FMirrorMargins;
Self.FUnitSystem := FUnitSystem;
end
else
inherited;
end;
procedure TBCEditorPrintMargins.LoadFromStream(AStream: TStream);
begin
with AStream do
begin
Read(FUnitSystem, SizeOf(FUnitSystem));
Read(FLeft, SizeOf(FLeft));
Read(FRight, SizeOf(FRight));
Read(FTop, SizeOf(FTop));
Read(FBottom, SizeOf(FBottom));
Read(FHeader, SizeOf(FHeader));
Read(FFooter, SizeOf(FFooter));
Read(FLeftTextIndent, SizeOf(FLeftTextIndent));
Read(FRightTextIndent, SizeOf(FRightTextIndent));
Read(FInternalMargin, SizeOf(FInternalMargin));
Read(FMargin, SizeOf(FMargin));
Read(FMirrorMargins, SizeOf(FMirrorMargins));
end;
end;
procedure TBCEditorPrintMargins.SaveToStream(AStream: TStream);
begin
with AStream do
begin
Write(FUnitSystem, SizeOf(FUnitSystem));
Write(FLeft, SizeOf(FLeft));
Write(FRight, SizeOf(FRight));
Write(FTop, SizeOf(FTop));
Write(FBottom, SizeOf(FBottom));
Write(FHeader, SizeOf(FHeader));
Write(FFooter, SizeOf(FFooter));
Write(FLeftTextIndent, SizeOf(FLeftTextIndent));
Write(FRightTextIndent, SizeOf(FRightTextIndent));
Write(FInternalMargin, SizeOf(FInternalMargin));
Write(FMargin, SizeOf(FMargin));
Write(FMirrorMargins, SizeOf(FMirrorMargins));
end;
end;
end.
|
unit LuaDialogs;
interface
Uses LuaPas, Controls, Dialogs;
function LuaShowMessage(L: Plua_State): Integer; cdecl;
function LuaMessageDlg(L: Plua_State): Integer; cdecl;
implementation
Uses Lua, Typinfo;
// ***********************************************
function LuaShowMessage(L: Plua_State): Integer; cdecl;
begin
ShowMessage(AnsiToUTF8(lua_tostring(L,-1)));
Result := 0;
end;
procedure AddToButtonSet(var BSet:TMsgDlgButtons; But:String);
begin
Include(BSet,TMsgDlgBtn(GetEnumValue(TypeInfo(TMsgDlgBtn),But)));
end;
// mtConfirmation
// mtInformation
// mtError
function LuaMessageDlg(L: Plua_State): Integer; cdecl;
var
res: Integer;
Mdb: TMsgDlgButtons;
n: Integer;
Msg: String;
MsgType: TMsgDlgType;
begin
CheckArg(L, 3);
n := lua_gettop(L);
Msg := AnsiToUTF8(lua_tostring(L,1));
MsgType := TMsgDlgType(GetEnumValue(TypeInfo(TMsgDlgType),lua_tostring(L,2)));
Mdb := [];
if lua_istable(L,3) then begin
lua_pushnil(L);
while (lua_next(L, n) <> 0) do begin
AddToButtonSet(Mdb,lua_tostring(L, -1));
lua_pop(L, 1);
end;
end else
AddToButtonSet(Mdb,lua_tostring(L,3));
res := MessageDlg( Msg, MsgType, Mdb, 0 );
lua_pushstring(L,pchar(ButtonResult[res]));
Result := 1;
end;
end.
|
unit StructureViewServices;
interface
uses
DataExplorerAPI,
System.Bindings.Factories, System.Bindings.Expression, System.Bindings.Outputs,
System.Bindings.Helper, System.StrUtils, System.Bindings.Consts, System.Rtti,
System.Classes, System.SysUtils, System.Bindings.EvalProtocol, System.Bindings.Methods,
System.Bindings.EvalSys, System.Bindings.ObjEval,
System.Generics.Collections;
type
IScopes = Interface
['{1CEE87BB-4AC8-4002-B7F0-AC591594C9CD}']
function GetCount: Integer;
function GetItem(I: Integer): TScope;
procedure Add(AScope: TScope);
function ToArray: TScopesArray;
end;
TScopes = class(TInterfacedObject, IScopes)
private
FList: TList<TScope>;
public
constructor Create;
destructor Destroy; override;
function GetCount: Integer;
function GetItem(I: Integer): TScope;
procedure Add(AScope: TScope);
function ToArray: TScopesArray;
end;
IDECommands = Interface
['{C9AAA794-C844-4ED6-B697-76C5F93BFAB4}']
function GetCount: Integer;
function GetItem(I: Integer): IOTADataExplorerCommand;
procedure Add(ACommand: IOTADataExplorerCommand);
function ToArray: TDECommandsArray;
End;
TDECommands = class(TInterfacedObject, IDECommands)
private
FList: IInterfaceListEx;
function GetCount: Integer;
function GetItem(I: Integer): IOTADataExplorerCommand;
function ToArray: TDECommandsArray;
public
constructor Create;
procedure Add(ACommand: IOTADataExplorerCommand);
property Count: Integer read GetCount;
property Items[I: Integer]: IOTADataExplorerCommand read GetItem;
end;
TDEComponentStream = class abstract(TInterfacedObject, IOTADataExplorerComponentStream)
protected
function GetFormat: Word; virtual;
function GetCaption: string; virtual;
function GetEnabled: Boolean; virtual;
function GetVisible: Boolean; virtual;
public
property Caption: string read GetCaption;
property Enabled: Boolean read GetEnabled;
property Visible: Boolean read GetVisible;
property Format: Word read GetFormat;
function GetStream(AItem: IOTADataExplorerItem; AScopes: TScopesArray; AStream: TStream): Boolean; virtual; abstract;
procedure Update(AItem: IOTADataExplorerItem; AScopes: TScopesArray); virtual;
end;
IOTADataExplorerComponentStreamForObject = Interface(IOTADataExplorerComponentStream)
['{BAFFA45F-402E-434A-9BF1-A967C6F286CC}']
function GetStreamForObject(AObject: TObject; AStream: TStream): Boolean;
End;
TDEComponentStreamForObject = class(TDEComponentStream, IOTADataExplorerComponentStreamForObject)
protected
function GetStreamForObject(AObject: TObject; AStream: TStream): Boolean; virtual;
end;
IDEComponentStreams = Interface
['{7B90C43B-34BD-4FF2-85C6-45145D4286A3}']
function GetCount: Integer;
function GetItem(I: Integer): IOTADataExplorerComponentStream;
procedure Add(AStream: IOTADataExplorerComponentStream);
function ToArray: TDEComponentStreamArray;
End;
TDEComponentStreams = class(TInterfacedObject, IDEComponentStreams)
private
FList: IInterfaceListEx;
function GetCount: Integer;
function GetItem(I: Integer): IOTADataExplorerComponentStream;
public
constructor Create;
procedure Add(AStream: IOTADataExplorerComponentStream);
property Count: Integer read GetCount;
property Items[I: Integer]: IOTADataExplorerComponentStream read GetItem;
function ToArray: TDEComponentStreamArray;
end;
TExprItem = class;
IDEItems = Interface
['{DC80F67D-E27F-49C8-8B18-5AB528F78EBC}']
function GetCount: Integer;
function GetItem(I: Integer): IOTADataExplorerItem;
procedure Add(AItem: IOTADataExplorerItem);
function ToArray: TDEItemsArray;
End;
TExprItems = class(TInterfacedObject, IDEItems)
private
FList: IInterfaceListEx;
FOwner: TExprItem;
protected
function GetCount: Integer;
function GetItem(I: Integer): IOTADataExplorerItem;
function ToArray: TDEItemsArray;
public
constructor Create(AOwner: TExprItem);
procedure Add(AItem: IOTADataExplorerItem);
property Item[I: Integer]: IOTADataExplorerItem read GetItem;
property Count: Integer read GetCount;
end;
TExprNodeCollectionItem = class;
TExprStaticNodeItem = class;
IExprItem = Interface(IOTADataExplorerItem)
['{C2D0E9F5-7AB0-46AF-BABF-7295CF21F032}']
function AddCollectionItem(const AEnumeratorScopeName: string = ''; const AEnumeratorValue: string = ''): TExprNodeCollectionItem;
function AddStaticItem(const AIdentity: string = '';
const AName: string = ''; const ADisplayName: string = ''): TExprStaticNodeItem;
procedure AddCommand(const ACaptionExpr, AExecuteExpr, AEnabledExpr, AVisibleExpr: string); overload;
procedure AddCommand(const ACaptionExpr, AExecuteExpr: string); overload;
End;
TExprItem = class(TInterfacedObject, IOTADataExplorerItem, IExprItem)
private
FScopes: IScopes;
FItems: IDEItems;
FParent: TExprItem;
FCommands: IDECommands;
FNameExpression: string;
FIdentityExpression: string;
FEnabledExpression: string;
function GetEnabled(AScopes: TScopesArray): Boolean; virtual;
protected
function EvaluateValueRec(const AValueRec: TDEValueRec; AScopes: TScopesArray): TValue;
function GetItemCount: Integer;
function GetItemsArray: TDEItemsArray;
function GetScopesArray: TScopesArray;
function GetCommandsArray: TDECommandsArray;
function IsRoot: Boolean;
function GetParent: TExprItem;
procedure SetParent(const AParent: TExprItem);
function GetScopes: IScopes; virtual;
function GetCommands: IDECommands;
function GetItems: IDEItems;
function GetNameValue: TDEValueRec;
procedure SetNameValue(const AValue: TDEValueRec);
function GetIdentityValue: TDEValueRec;
procedure SetIdentityValue(const AValue: TDEValueRec);
function GetEnabledValue: TDEValueRec;
procedure SetEnabledValue(const AValue: TDEValueRec);
property Items: IDEItems read GetItems;
public
constructor Create;
function AddCollectionItem(const AEnumeratorScopeName: string = ''; const AEnumeratorValue: string = ''): TExprNodeCollectionItem;
function AddStaticItem(const AIdentity: string = '';
const AName: string = ''; const ADisplayName: string = ''): TExprStaticNodeItem;
procedure AddCommand(const ACaptionExpr, AExecuteExpr: string); overload;
procedure AddCommand(const ACaptionExpr, AExecuteExpr, AEnabledExpr, AVisibleExpr: string); overload;
property Parent: TExprItem read GetParent;
property Scopes: IScopes read GetScopes;
property Commands: IDECommands read GetCommands;
property NameValue: TDEValueRec read GetNameValue write SetNameValue;
property IdentityValue: TDEValueRec read GetIdentityValue write SetIdentityValue;
property EnabledValue: TDEValueRec read GetEnabledValue write SetEnabledValue;
end;
TExprNodeCollectionItem = class(TExprItem, IOTADataExplorerNodeCollectionItem)
private
FEnumeratorExpression: string;
FRefreshExpression: string;
FEnumeratorScopeName: string;
function GetEnumeratorValue: TDEValueRec;
procedure SetEnumeratorValue(const AValue: TDEValueRec);
function GetEnumeratorScopeName: string;
procedure SetEnumeratorScopeName(const AValue: string);
function GetRefreshValue: TDEValueRec;
procedure SetRefreshValue(const AValue: TDEValueRec);
public
constructor Create;
property EnumeratorValue: TDEValueRec read GetEnumeratorValue write SetEnumeratorValue;
property RefreshValue: TDEValueRec read GetRefreshValue write SetRefreshValue;
property EnumeratorScopeName: string read GetEnumeratorScopeName write SetEnumeratorScopeName;
end;
TExprStaticNodeItem = class(TExprItem, IOTADataExplorerStaticNodeItem)
private
FComponentStreams: IDEComponentStreams;
FDisplayNameExpression: string;
FObjectExpression: string;
FImageIndex: Integer;
FImageIndexExpression: string;
function GetImageIndex: Integer;
procedure SetImageIndex(const AIndex: Integer);
function GetDisplayNameValue: TDEValueRec;
procedure SetDisplayNameValue(const AValue: TDEValueRec);
function GetImageIndexValue: TDEValueRec;
procedure SetImageIndexValue(const AValue: TDEValueRec);
function GetObjectValue: TDEValueRec;
procedure SetObjectValue(const AValue: TDEValueRec);
function GetEnabled(AScopes: TScopesArray): Boolean; override;
function GetComponentStreams: IDEComponentStreams;
function GetComponentStreamsArray: TDEComponentStreamArray;
public
constructor Create;
property ImageIndex: Integer read GetImageIndex write SetImageIndex;
property DisplayNameValue: TDEValueRec read GetDisplayNameValue write SetDisplayNameValue;
property ImageIndexValue: TDEValueRec read GetImageIndexValue write SetImageIndexValue;
property ObjectValue: TDEValueRec read GetObjectValue write SetObjectValue;
property ComponentStreams: IDEComponentStreams read GetComponentStreams;
end;
TExprRootItem = class(TExprStaticNodeItem, IOTADataExplorerStaticNodeItem, IOTADataExplorerRootItem)
public
constructor Create(const AIdentity, AName, ADisplayName: string; const AScopes: Array of TScope);
end;
IExprCommand = Interface
['{6323FEF7-E555-4DF5-A07B-69122AED1220}']
function GetCaptionExpression: string;
procedure SetCaptionExpression(const AValue: string);
function GetEnabledExpression: string;
procedure SetEnabledExpression(const AValue: string);
function GetExecuteExpression: string;
procedure SetExecuteExpression(const AValue: string);
function GetVisibleExpression: string;
procedure SetVisibleExpression(const AValue: string);
property CaptionExpression: string read GetCaptionExpression write SetCaptionExpression;
property EnabledExpression: string read GetEnabledExpression write SetEnabledExpression;
property ExecuteExpression: string read GetExecuteExpression write SetExecuteExpression;
property VisibleExpression: string read GetVisibleExpression write SetVisibleExpression;
End;
TExpressionCommand = class(TInterfacedObject, IOTADataExplorerCommand, IExprCommand)
private
FCaptionExpression: string;
FEnabledExpression: string;
FExecuteExpression: string;
FVisibleExpression: string;
FVisible: Boolean;
FCaption: string;
FEnabled: Boolean;
protected
function GetCaption: string;
function GetEnabled: Boolean;
function GetVisible: Boolean;
function GetCaptionExpression: string;
procedure SetCaptionExpression(const AValue: string);
function GetEnabledExpression: string;
procedure SetEnabledExpression(const AValue: string);
function GetExecuteExpression: string;
procedure SetExecuteExpression(const AValue: string);
function GetVisibleExpression: string;
procedure SetVisibleExpression(const AValue: string);
public
constructor Create;
property Caption: string read GetCaption;
property Enabled: Boolean read GetEnabled;
property Visible: Boolean read GetVisible;
property CaptionExpression: string read GetCaptionExpression write SetCaptionExpression;
property EnabledExpression: string read GetEnabledExpression write SetEnabledExpression;
property ExecuteExpression: string read GetExecuteExpression write SetExecuteExpression;
property VisibleExpression: string read GetVisibleExpression write SetVisibleExpression;
procedure Execute(AItem: IOTADataExplorerItem; AScopes: TScopesArray);
procedure Update(AItem: IOTADataExplorerItem; AScopes: TScopesArray);
end;
TExprComponentStreamForObject = class(TDEComponentStreamForObject, IOTADataExplorerComponentStreamForObject)
public
function GetStream(AItem: IOTADataExplorerItem; AScopes: TScopesArray; AStream: TStream): Boolean; override;
end;
var
CF_COMPONENTS: Word;
implementation
uses
WinApi.Windows;
const
cfDelphiComponents = 'Delphi Components';
{ TExpressionCommand }
constructor TExpressionCommand.Create;
begin
FEnabled := True;
FVisible := True;
end;
procedure TExpressionCommand.Execute(AItem: IOTADataExplorerItem; AScopes: TScopesArray);
begin
if Self.FExecuteExpression <> '' then
AItem.EvaluateValueRec(TDEValueRec.Create(FExecuteExpression), AScopes);
end;
function TExpressionCommand.GetCaption: string;
begin
Result := FCaption;
end;
function TExpressionCommand.GetCaptionExpression: string;
begin
Result := FCaptionExpression;
end;
function TExpressionCommand.GetEnabled: Boolean;
begin
Result := FEnabled;
end;
function TExpressionCommand.GetEnabledExpression: string;
begin
Result := FEnabledExpression;
end;
function TExpressionCommand.GetExecuteExpression: string;
begin
Result := FExecuteExpression;
end;
function TExpressionCommand.GetVisible: Boolean;
begin
Result := FVisible;
end;
function TExpressionCommand.GetVisibleExpression: string;
begin
Result := FVisibleExpression;
end;
procedure TExpressionCommand.SetCaptionExpression(const AValue: string);
begin
FCaptionExpression := AValue;
end;
procedure TExpressionCommand.SetEnabledExpression(const AValue: string);
begin
FEnabledExpression := AValue;
end;
procedure TExpressionCommand.SetExecuteExpression(const AValue: string);
begin
FExecuteExpression := AValue;
end;
procedure TExpressionCommand.SetVisibleExpression(const AValue: string);
begin
FVisibleExpression := AValue;
end;
procedure TExpressionCommand.Update(AItem: IOTADataExplorerItem; AScopes: TScopesArray);
begin
if Self.FCaptionExpression <> '' then
FCaption := AItem.EvaluateValueRec(TDEValueRec.Create(FCaptionExpression), AScopes).AsString;
if Self.FEnabledExpression <> '' then
FEnabled := AItem.EvaluateValueRec(TDEValueRec.Create(FEnabledExpression), AScopes).AsBoolean;
if Self.FVisibleExpression <> '' then
FVisible := AItem.EvaluateValueRec(TDEValueRec.Create(FVisibleExpression), AScopes).AsBoolean;
end;
{ TExprComponentStreamForObject }
function TExprComponentStreamForObject.GetStream(AItem: IOTADataExplorerItem; AScopes: TScopesArray;
AStream: TStream): Boolean;
var
LObject: TObject;
LValue: TValue;
LStaticItem: IOTADataExplorerStaticNodeItem;
begin
Result := False;
if Supports(AItem, IOTADataExplorerStaticNodeItem, LStaticItem) then
begin
LValue := LStaticItem.EvaluateValueRec(LStaticItem.ObjectValue, AScopes);
if LValue.IsType<TPersistent> then
LObject := LValue.AsType<TPersistent>
else
LObject := nil;
if LObject <> nil then
Result := Self.GetStreamForObject(LObject, AStream);
end;
end;
{ TExprRootItem }
constructor TExprRootItem.Create(const AIdentity, AName, ADisplayName: string; const AScopes: Array of TScope);
var
LScope: TScope;
begin
inherited Create;
DisplayNameValue := TDEValueRec.Create(ADisplayName);
NameValue := TDEValueRec.Create(AName);
IdentityValue := TDEValueRec.Create(AIdentity);
if AIdentity <> '' then
ObjectValue := TDEValueRec.Create(AIdentity);
for LScope in AScopes do
Scopes.Add(LScope);
end;
{ TExprStaticNodeItem }
constructor TExprStaticNodeItem.Create;
begin
inherited;
FImageIndex := -1;
FComponentStreams := TDEComponentStreams.Create;
end;
function TExprStaticNodeItem.GetComponentStreams: IDEComponentStreams;
begin
Result := FComponentStreams;
end;
function TExprStaticNodeItem.GetComponentStreamsArray: TDEComponentStreamArray;
begin
Result := ComponentStreams.ToArray;
end;
function TExprStaticNodeItem.GetDisplayNameValue: TDEValueRec;
begin
Result := TDEValueRec.Create(FDisplayNameExpression);
end;
function TExprStaticNodeItem.GetEnabled(AScopes: TScopesArray): Boolean;
var
LValue: TValue;
begin
if Length(AScopes) > 0 then
LValue := EvaluateValueRec(GetEnabledValue, AScopes)
else
LValue := EvaluateValueRec(GetEnabledValue, GetScopesArray);
if (not LValue.IsEmpty) and LValue.IsType<Boolean> then
Result := LValue.AsBoolean
else
Result := True;
end;
function TExprStaticNodeItem.GetImageIndex: Integer;
begin
Result := FImageIndex;
end;
function TExprStaticNodeItem.GetImageIndexValue: TDEValueRec;
begin
Result := TDEValueRec.Create(FImageIndexExpression);
end;
function TExprStaticNodeItem.GetObjectValue: TDEValueRec;
begin
Result := TDEValueRec.Create(FObjectExpression);
end;
procedure TExprStaticNodeItem.SetDisplayNameValue(const AValue: TDEValueRec);
begin
FDisplayNameExpression := AValue.Value;
end;
procedure TExprStaticNodeItem.SetImageIndex(const AIndex: Integer);
begin
//ImageIndex properties should be mutually exclusive
FImageIndexExpression := '';
FImageIndex := AIndex;
end;
procedure TExprStaticNodeItem.SetImageIndexValue(const AValue: TDEValueRec);
begin
//ImageIndex properties should be mutually exclusive
FImageIndex := -1;
FImageIndexExpression := AValue.Value;
end;
procedure TExprStaticNodeItem.SetObjectValue(const AValue: TDEValueRec);
begin
FObjectExpression := AValue.Value;
end;
{ TExprItem }
constructor TExprItem.Create;
begin
inherited;
FScopes := TScopes.Create;
FItems := TExprItems.Create(Self);
FCommands := TDECommands.Create;
end;
function TExprItem.EvaluateValueRec(const AValueRec: TDEValueRec;
AScopes: TScopesArray): TValue;
var
LDictionaryScope: TDictionaryScope;
LItem: IOTADataExplorerItem;
LItemScope: TScope;
LObjectScope: IScope;
LBindingExpression: TBindingExpression;
LScopeIntf: IScope;
LPair: TScope;
LValue: IValue;
I: Integer;
LScopes: TScopesArray;
begin
if AValueRec.Value = '' then
Exit(TValue.Empty);
LDictionaryScope := TDictionaryScope.Create;
LScopeIntf := LDictionaryScope; // be sure this object is freed even if except
if Supports(Self, IOTADataExplorerItem, LItem) then
begin
LObjectScope := WrapObject(TObject(LItem));
// Pass tree object named _Item
LDictionaryScope.Map.Add('_Item', LObjectScope);
end;
while LItem <> nil do
begin
LScopes := LItem.GetScopesArray;
for I := 0 to Length(LScopes) - 1 do
begin
LItemScope := TScope.Create(LScopes[I].Name, LScopes[I].Obj);
LObjectScope := WrapObject(LItemScope.Obj);
LDictionaryScope.Map.Add(LItemScope.Name, LObjectScope);
end;
LItem := TExprItem(LItem).Parent;
end;
if AScopes <> nil then
for LPair in AScopes do
begin
LObjectScope := WrapObject(LPair.Obj);
if not LDictionaryScope.Map.ContainsKey(LPair.Name) then
LDictionaryScope.Map.Add(LPair.Name, LObjectScope);
end;
LScopeIntf := TNestedScope.Create(TBindingMethodsFactory.GetMethodScope, LScopeIntf);
LBindingExpression := TBindings.CreateExpression(
LScopeIntf,
AValueRec.Value);
try
//Note: We must retrieve the TValue before freeing the TBindingExpression
// otherwise the interfaced objects containing the data will be gone as well
LValue := LBindingExpression.Evaluate;
if LValue = nil then
Result := TValue.Empty
else
Result := LValue.GetValue;
finally
LBindingExpression.Free;
end;
end;
function TExprItem.GetCommandsArray: TDECommandsArray;
var
LCommands: IDECommands;
begin
if Supports(FCommands, IDECommands, LCommands) then
Result := LCommands.ToArray
else
Result := nil;
end;
function TExprItem.GetEnabled(AScopes: TScopesArray): Boolean;
begin
Result := True;
end;
function TExprItem.GetEnabledValue: TDEValueRec;
begin
Result := TDEValueRec.Create(FEnabledExpression);
end;
function TExprItem.GetScopesArray: TScopesArray;
var
LScopes: IScopes;
begin
if Supports(FScopes, IScopes, LScopes) then
Result := LScopes.ToArray
else
Result := nil;
end;
function TExprItem.GetItemsArray: TDEItemsArray;
begin
if FItems = nil then
Result := nil
else
Result := FItems.ToArray;
end;
function TExprItem.IsRoot: Boolean;
begin
if Supports(Self, IOTADataExplorerRootItem) then
Result := True
else
Result := False;
end;
procedure TExprItem.SetParent(const AParent: TExprItem);
begin
FParent := AParent;
end;
function TExprItem.GetParent: TExprItem;
begin
Result := FParent;
end;
function TExprItem.GetScopes: IScopes;
begin
Result := FScopes;
end;
function TExprItem.GetItemCount: Integer;
begin
Result := FItems.GetCount;
end;
function TExprItem.GetItems: IDEItems;
begin
Result := FItems;
end;
function TExprItem.GetCommands: IDECommands;
begin
Result := FCommands;
end;
procedure TExprItem.AddCommand(const ACaptionExpr, AExecuteExpr: string);
begin
AddCommand(ACaptionExpr, AExecuteExpr, '', '');
end;
procedure TExprItem.AddCommand(const ACaptionExpr, AExecuteExpr, AEnabledExpr, AVisibleExpr: string);
var
LCommand: IExprCommand;
begin
LCommand := TExpressionCommand.Create;
LCommand.CaptionExpression := ACaptionExpr;
LCommand.ExecuteExpression := AExecuteExpr;
LCommand.EnabledExpression := AEnabledExpr;
LCommand.VisibleExpression := AVisibleExpr;
Commands.Add(LCommand as IOTADataExplorerCommand);
end;
function TExprItem.AddStaticItem(const AIdentity: string = '';
const AName: string = ''; const ADisplayName: string = ''): TExprStaticNodeItem;
begin
Result := TExprStaticNodeItem.Create;
Items.Add(Result);
Result.DisplayNameValue := TDEValueRec.Create(ADisplayName);
Result.NameValue := TDEValueRec.Create(AName);
Result.IdentityValue := TDEValueRec.Create(AIdentity);
if AIdentity <> '' then
Result.ObjectValue := TDEValueRec.Create(AIdentity);
end;
function TExprItem.AddCollectionItem(const AEnumeratorScopeName, AEnumeratorValue: string): TExprNodeCollectionItem;
begin
Result := TExprNodeCollectionItem.Create;
Items.Add(Result);
Result.EnumeratorScopeName := AEnumeratorScopeName;
Result.EnumeratorValue := TDEValueRec.Create(AEnumeratorValue);
end;
function TExprItem.GetNameValue: TDEValueRec;
begin
Result := TDEValueRec.Create(FNameExpression);
end;
procedure TExprItem.SetNameValue(const AValue: TDEValueRec);
begin
FNameExpression := AValue.Value;
end;
function TExprItem.GetIdentityValue: TDEValueRec;
begin
Result := TDEValueRec.Create(FIdentityExpression);
end;
procedure TExprItem.SetEnabledValue(const AValue: TDEValueRec);
begin
FEnabledExpression := AValue.Value;
end;
procedure TExprItem.SetIdentityValue(const AValue: TDEValueRec);
begin
FIdentityExpression := AValue.Value;
end;
{ TExprNodeCollectionItem }
function TExprNodeCollectionItem.GetEnumeratorScopeName: string;
begin
Result := FEnumeratorScopeName;
end;
function TExprNodeCollectionItem.GetEnumeratorValue: TDEValueRec;
begin
Result := TDEValueRec.Create(FEnumeratorExpression);
end;
function TExprNodeCollectionItem.GetRefreshValue: TDEValueRec;
begin
Result := TDEValueRec.Create(FRefreshExpression);
end;
procedure TExprNodeCollectionItem.SetEnumeratorScopeName(const AValue: string);
begin
FEnumeratorScopeName := AValue;
end;
procedure TExprNodeCollectionItem.SetEnumeratorValue(const AValue: TDEValueRec);
begin
FEnumeratorExpression := AValue.Value;
end;
procedure TExprNodeCollectionItem.SetRefreshValue(const AValue: TDEValueRec);
begin
FRefreshExpression := AValue.Value;
end;
constructor TExprNodeCollectionItem.Create;
begin
inherited;
end;
{ TScopes }
procedure TScopes.Add(AScope: TScope);
begin
FList.Add(AScope);
end;
function TScopes.ToArray: TScopesArray;
begin
Result := FList.toArray;
end;
constructor TScopes.Create;
begin
inherited Create;
FList := TList<TScope>.Create;
end;
destructor TScopes.Destroy;
begin
FList.Free;
inherited;
end;
function TScopes.GetCount: Integer;
begin
Result := FList.Count;
end;
function TScopes.GetItem(I: Integer): TScope;
begin
Result := FList[I];
end;
{ TExprItems }
constructor TExprItems.Create(AOwner: TExprItem);
begin
inherited Create;
FOwner := AOwner;
FList := TInterfaceList.Create;
end;
procedure TExprItems.Add(AItem: IOTADataExplorerItem);
function FindParentStaticNode(const AItem: TExprItem): TExprStaticNodeItem;
begin
Result := nil;
if (AItem <> nil) then
begin
if AItem is TExprStaticNodeItem then
Exit(AItem as TExprStaticNodeItem);
if AItem is TExprItem then
Result := FindParentStaticNode(TExprItem(AItem.Parent))
end;
end;
var
LStaticItem: TExprStaticNodeItem;
begin
FList.Add(AItem);
if AItem is TExprItem then
begin
Assert(TExprItem(AItem).Parent = nil);
TExprItem(AItem).SetParent(FOwner);
if FOwner <> nil then
begin
if AItem is TExprStaticNodeItem then
begin
LStaticItem := FindParentStaticNode(FOwner);
if LStaticItem <> nil then
begin
if LStaticItem.ImageIndex = -1 then
TExprStaticNodeItem(AItem).ImageIndexValue := LStaticItem.ImageIndexValue
else
TExprStaticNodeItem(AItem).ImageIndex := LStaticItem.ImageIndex;
end;
end;
end;
end;
end;
function TExprItems.GetCount: Integer;
begin
Result := FList.Count;
end;
function TExprItems.GetItem(I: Integer): IOTADataExplorerItem;
begin
Result := FList[I] as IOTADataExplorerItem;
end;
function TExprItems.ToArray: TDEItemsArray;
var
I: Integer;
begin
SetLength(Result, FList.Count);
for I := 0 to FList.Count - 1 do
Result[I] := FList.Items[I] as IOTADataExplorerItem;
end;
{ TDECommands }
procedure TDECommands.Add(ACommand: IOTADataExplorerCommand);
begin
FList.Add(ACommand);
end;
constructor TDECommands.Create;
begin
inherited;
FList := TInterfaceList.Create;
end;
function TDECommands.GetCount: Integer;
begin
Result := FList.Count;
end;
function TDECommands.GetItem(I: Integer): IOTADataExplorerCommand;
begin
Result := FList[I] as IOTADataExplorerCommand;
end;
function TDECommands.ToArray: TDECommandsArray;
var
I: Integer;
begin
SetLength(Result, FList.Count);
for I := 0 to FList.Count - 1 do
Result[I] := FList.Items[I] as IOTADataExplorerCommand;
end;
{ TDEComponentStreams }
procedure TDEComponentStreams.Add(AStream: IOTADataExplorerComponentStream);
begin
FList.Add(AStream);
end;
function TDEComponentStreams.ToArray: TDEComponentStreamArray;
var
I: Integer;
begin
SetLength(Result, FList.Count);
for I := 0 to FList.Count - 1 do
Result[I] := FList.Items[I] as IOTADataExplorerComponentStream;
end;
constructor TDEComponentStreams.Create;
begin
inherited;
FList := TInterfaceList.Create;
end;
function TDEComponentStreams.GetCount: Integer;
begin
Result := FList.Count;
end;
function TDEComponentStreams.GetItem(I: Integer): IOTADataExplorerComponentStream;
begin
Result := FList[I] as IOTADataExplorerComponentStream;
end;
{ TDEComponentStreamForObject }
function TDEComponentStreamForObject.GetStreamForObject(AObject: TObject; AStream: TStream): Boolean;
begin
Result := False;
assert(False);
end;
{ TDEComponentStream }
function TDEComponentStream.GetCaption: string;
begin
Result := '';
end;
function TDEComponentStream.GetEnabled: Boolean;
begin
Result := True;
end;
function TDEComponentStream.GetFormat: Word;
begin
Result := CF_COMPONENTS;
end;
function TDEComponentStream.GetVisible: Boolean;
begin
Result := True;
end;
procedure TDEComponentStream.Update(AItem: IOTADataExplorerItem; AScopes: TScopesArray);
begin
//
end;
initialization
CF_COMPONENTS := RegisterClipboardFormat(cfDelphiComponents);
end.
|
unit UnitFormProductsData;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, UnitFormExpander, UnitFormProductsDataTable,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections,
thrift.Collections, apitypes, Vcl.Grids, UnitFormPopup2, Vcl.StdCtrls,
UnitFormProductsCalcTable, Vcl.ExtCtrls;
type
TFormProductsData = class(TForm)
Panel1: TPanel;
Label1: TLabel;
ComboBox1: TComboBox;
procedure FormCreate(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
private
{ Private declarations }
FExpanders: TList<TFormExpander>;
FFormPopup2: TFormPopup2;
FFormProductsCalcTable: TFormProductsCalcTable;
FFormProductsDataTable: TFormProductsDataTable;
procedure FFormPopup2ToolButton3Click(Sender: TObject);
procedure setupDataTable;
procedure setupCalcTable;
public
{ Public declarations }
FPartyProductsValues: IPartyProductsValues;
procedure setup(x: IPartyProductsValues);
procedure init;
end;
var
FormProductsData: TFormProductsData;
implementation
{$R *.dfm}
uses UnitApiClient,
stringgridutils;
procedure TFormProductsData.FormCreate(Sender: TObject);
begin
FExpanders := TList<TFormExpander>.create;
FFormPopup2 := TFormPopup2.create(self);
FFormPopup2.Parent := self;
FFormPopup2.Align := alBottom;
FFormPopup2.ToolButton3.OnClick := FFormPopup2ToolButton3Click;
FFormProductsCalcTable := TFormProductsCalcTable.create(self);
FFormProductsDataTable := TFormProductsDataTable.create(self);;
end;
procedure TFormProductsData.init;
begin
with FFormProductsCalcTable do
begin
BorderStyle := bsNone;
Parent := self;
Align := alClient;
end;
with FFormProductsDataTable do
begin
BorderStyle := bsNone;
Parent := self;
Align := alClient;
FFormPopup2 := self.FFormPopup2;
end;
end;
procedure TFormProductsData.setupDataTable;
var
sect: ISectionProductParamsValues;
ACol, ARow: integer;
begin
sect := FPartyProductsValues.Sections[ComboBox1.ItemIndex];
FFormProductsDataTable.setup(FPartyProductsValues.Products, sect);
FFormProductsDataTable.Show;
end;
procedure TFormProductsData.setupCalcTable;
var
sect: ICalcSection;
ACol, ARow: integer;
begin
sect := FPartyProductsValues.Calc
[ComboBox1.ItemIndex - FPartyProductsValues.Sections.Count];
FFormProductsCalcTable.setup(FPartyProductsValues.Products, sect);
FFormProductsCalcTable.Show;
end;
procedure TFormProductsData.ComboBox1Change(Sender: TObject);
var
sect: ISectionProductParamsValues;
ACol, ARow: integer;
begin
if (ComboBox1.ItemIndex < 0) or not Assigned(FPartyProductsValues) or
not Assigned(FPartyProductsValues.Sections) then
begin
FFormProductsDataTable.hide;
FFormProductsCalcTable.hide;
exit;
end;
if ComboBox1.ItemIndex < FPartyProductsValues.Sections.Count then
begin
FFormProductsCalcTable.hide;
setupDataTable;
exit;
end;
FFormProductsDataTable.hide;
setupCalcTable;
end;
procedure TFormProductsData.FFormPopup2ToolButton3Click(Sender: TObject);
begin
FFormPopup2.hide;
end;
procedure TFormProductsData.setup(x: IPartyProductsValues);
var
n, I: integer;
sect: ISectionProductParamsValues;
sectCalc: ICalcSection;
begin
FPartyProductsValues := x;
n := ComboBox1.ItemIndex;
ComboBox1.OnChange := nil;
ComboBox1.Clear;
for I := 0 to x.Sections.Count - 1 do
begin
sect := x.Sections[I];
ComboBox1.Items.Add(sect.Section);
end;
for I := 0 to x.Calc.Count - 1 do
begin
sectCalc := x.Calc[I];
ComboBox1.Items.Add(sectCalc.Name);
end;
ComboBox1.ItemIndex := n;
ComboBox1.OnChange := ComboBox1Change;
ComboBox1Change(ComboBox1);
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSSetUp.Config;
interface
uses System.Classes, System.IniFiles;
type
TEMSManagementRegistry = class
public type
TConnectionProperties = record
public
ProfileName: string;
Host: string;
Port: integer;
Protocol: string;
BaseURL: string;
Timeout: integer;
ProxyServer: string;
ProxyPort: integer;
end;
public type
TCredentialsProperties = record
public
ServerPassword: string;
ServerUserName: string;
UseMasterSecret: Boolean;
MasterSecret: string;
AppSecret: string;
ApplicationID: string;
GCMAppID: string;
TenantID: string;
TenantSecret: string;
end;
public const
sRegKeyProfiles = '\Software\Embarcadero\EMS\Profiles';
sEMSConnectionProperties = 'Default';
sLastProfUsed = 'LastProfileUsed';
sConnection = 'Connection';
sCredentials = 'Credentials';
sProfileName = 'ProfileName';
sHost = 'Host';
sPort = 'Port';
sProtocol = 'Protocol';
sBaseURL = 'BaseURL';
sTimeout = 'Timeout';
sProxyServer = 'ProxyServer';
sProxyPort = 'ProxyPort';
sServerPassword = 'Password';
sServerUserName = 'User';
sUseMasterSecret = 'UseMasterSevret';
sMasterSecret = 'MasterSecret';
sAppSecret = 'AppSecret';
sApplicationID = 'ApplicationID';
sGCMAppID = 'GCMAppID';
sTenantID = 'TenantID';
sTenantSecret = 'TenantSecret';
private
FFileName: String;
FRegSettingMofified: Boolean;
FConnection: TConnectionProperties;
FCredentials: TCredentialsProperties;
procedure SetConnectionRegistry(const Value: TConnectionProperties);
procedure SetCredentialsRegistry(const Value: TCredentialsProperties);
procedure ReadValuesFromRegistry(const ConnectionSection,
CredentialSection: string; Registry: TCustomIniFile);
procedure WriteValuesToRegistry(const ConnectionSection, CredentialSection,
ProfileName: string; Registry: TCustomIniFile);
public
function SaveProfileToRegistry(const AProfileName: string = ''): Boolean;
function SavedLastProfileUsed(const AProfileName: string): Boolean;
function SaveProfileToRegistryAs(AConnection: TConnectionProperties;
ACredentials: TCredentialsProperties; const AName: string = ''): Boolean;
function ExportProfiles: Boolean;
function SaveProfileFile(const AProfileName, ConnectionIndex: string): Boolean;
function DeleteProfileFromRegistry(const AName: string): Boolean;
function ImportProfiles: Boolean;
function LoadProfileFile(const AIndex: string): Boolean;
function LoadProfileNamesFromRegistry(var AProfilesList: TStringList): Boolean;
function LoadProfileFromRegistry(const AProfileName: string = ''): Boolean;
function GetLastProfile: string;
property Filename: String read FFileName write FFileName;
property RegSettingsMofified: Boolean read FRegSettingMofified write FRegSettingMofified;
property Connection: TConnectionProperties read FConnection write SetConnectionRegistry;
property Credentials: TCredentialsProperties read FCredentials write SetCredentialsRegistry;
end;
implementation
uses Winapi.Windows, System.Win.Registry,
System.SysUtils, System.NetEncoding;
{ TEMSManagementRegistry }
function TEMSManagementRegistry.GetLastProfile: string;
var
LReg: TRegistryIniFile;
begin
Result := sEMSConnectionProperties;
LReg := TRegistryIniFile.Create('', KEY_READ);
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, False) then
Result := LReg.ReadString('', sLastProfUsed, sEMSConnectionProperties);
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.LoadProfileFromRegistry(const AProfileName: string = ''): Boolean;
var
LReg: TRegistryIniFile;
LsEMSConnectionProperties: string;
begin
LsEMSConnectionProperties := sEMSConnectionProperties;
Result := False;
if AProfileName <> '' then
LsEMSConnectionProperties := AProfileName;
LReg := TRegistryIniFile.Create('', KEY_READ);
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, False) then
begin
SavedLastProfileUsed(AProfileName);
ReadValuesFromRegistry(LsEMSConnectionProperties,
LsEMSConnectionProperties, LReg);
Result := True;
end
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.DeleteProfileFromRegistry(const AName: string): Boolean;
var
LReg: TRegistryIniFile;
LsEMSConnectionProperties: string;
begin
LsEMSConnectionProperties := sEMSConnectionProperties;
Result := False;
LReg := TRegistryIniFile.Create('', KEY_WRITE);
if AName <> '' then
LsEMSConnectionProperties := AName;
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, True) then
begin
LReg.EraseSection(AName);
Result := True;
end
else
Assert(False);
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.ImportProfiles: Boolean;
var
I, LIndex: integer;
LIndexStr: string;
LProfiles: TStringList;
begin
LProfiles := TStringList.Create;
try
LoadProfileNamesFromRegistry(LProfiles);
I := 0;
while LoadProfileFile(IntToStr(I)) do
begin
LIndex := 0;
LIndexStr := '';
while LProfiles.IndexOf(FConnection.ProfileName + LIndexStr) >= 0 do
begin
Inc(LIndex);
LIndexStr := '.' + IntToStr(LIndex)
end;
SaveProfileToRegistry(FConnection.ProfileName + LIndexStr);
Inc(I);
end;
Result := True;
finally
LProfiles.Free;
end;
end;
function TEMSManagementRegistry.LoadProfileFile(const AIndex: string): Boolean;
var
LReg: TIniFile;
begin
Result := False;
LReg := TIniFile.Create(FFileName);
try
ReadValuesFromRegistry(sConnection + AIndex, sCredentials + AIndex, LReg);
if FConnection.ProfileName <> '' then
Result := True;
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.LoadProfileNamesFromRegistry(var AProfilesList: TStringList): Boolean;
var
LReg: TRegistryIniFile;
begin
Result := False;
LReg := TRegistryIniFile.Create('', KEY_READ);
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, False) then
begin
LReg.ReadSections(AProfilesList);
Result := True;
end;
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.SaveProfileToRegistryAs(AConnection: TConnectionProperties;
ACredentials: TCredentialsProperties; const AName: string = ''): Boolean;
begin
SetConnectionRegistry(AConnection);
SetCredentialsRegistry(ACredentials);
Result := SaveProfileToRegistry(AName);
end;
function TEMSManagementRegistry.SavedLastProfileUsed(const AProfileName: string): Boolean;
var
LReg: TRegistryIniFile;
LsEMSConnectionProperties: string;
begin
LsEMSConnectionProperties := sEMSConnectionProperties;
Result := False;
LReg := TRegistryIniFile.Create('', KEY_WRITE);
if AProfileName <> '' then
LsEMSConnectionProperties := AProfileName;
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, True) then
begin
LReg.WriteString('', sLastProfUsed, AProfileName);
Result := True;
end
else
Assert(False);
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.SaveProfileToRegistry(const AProfileName: string = ''): Boolean;
var
LReg: TRegistryIniFile;
LsEMSConnectionProperties: string;
begin
LsEMSConnectionProperties := sEMSConnectionProperties;
Result := False;
LReg := TRegistryIniFile.Create('', KEY_WRITE);
if AProfileName <> '' then
LsEMSConnectionProperties := AProfileName;
try
if LReg.RegIniFile.OpenKey(sRegKeyProfiles, True) then
begin
LReg.WriteString('', sLastProfUsed, AProfileName);
WriteValuesToRegistry(LsEMSConnectionProperties,
LsEMSConnectionProperties, AProfileName, LReg);
Result := True;
end
else
Assert(False);
finally
LReg.Free;
end;
end;
function TEMSManagementRegistry.ExportProfiles: Boolean;
var
I: integer;
LProfiles: TStringList;
begin
LProfiles := TStringList.Create;
try
LoadProfileNamesFromRegistry(LProfiles);
for I := 0 to LProfiles.Count - 1 do
begin
LoadProfileFromRegistry(LProfiles[I]);
SaveProfileFile(LProfiles[I], IntToStr(I));
end;
Result := True;
finally
LProfiles.Free;
end;
end;
function TEMSManagementRegistry.SaveProfileFile(const AProfileName,
ConnectionIndex: string): Boolean;
var
LReg: TIniFile;
begin
LReg := TIniFile.Create(FFileName);
try
LReg.WriteString(sConnection + ConnectionIndex, sProfileName, AProfileName);
WriteValuesToRegistry(sConnection + ConnectionIndex,
sCredentials + ConnectionIndex, AProfileName, LReg);
Result := True;
finally
LReg.Free;
end;
end;
procedure TEMSManagementRegistry.SetConnectionRegistry(const Value: TConnectionProperties);
begin
FConnection := Value;
end;
procedure TEMSManagementRegistry.SetCredentialsRegistry(const Value: TCredentialsProperties);
begin
FCredentials := Value;
end;
procedure TEMSManagementRegistry.ReadValuesFromRegistry(const ConnectionSection,
CredentialSection: string; Registry: TCustomIniFile);
begin
FConnection.ProfileName := Registry.ReadString(ConnectionSection, sProfileName, '');
FConnection.Host := Registry.ReadString(ConnectionSection, sHost, '');
FConnection.Port := Registry.ReadInteger(ConnectionSection, sPort, 0);
FConnection.Protocol := Registry.ReadString(ConnectionSection, sProtocol, '');
FConnection.BaseURL := Registry.ReadString(ConnectionSection, sBaseURL, '');
FConnection.Timeout := Registry.ReadInteger(ConnectionSection, sTimeout, 30000);
FConnection.ProxyServer := Registry.ReadString(ConnectionSection, sProxyServer, '');
FConnection.ProxyPort := Registry.ReadInteger(ConnectionSection, sProxyPort, 0);
FCredentials.ServerPassword := TNetEncoding.Base64.Decode(
Registry.ReadString(CredentialSection, sServerPassword, ''));
FCredentials.ServerUserName := Registry.ReadString(CredentialSection, sServerUserName, '');
FCredentials.UseMasterSecret := Registry.ReadBool(CredentialSection, sUseMasterSecret, False);
FCredentials.MasterSecret := Registry.ReadString(CredentialSection, sMasterSecret, '');
FCredentials.AppSecret := Registry.ReadString(CredentialSection, sAppSecret, '');
FCredentials.ApplicationID := Registry.ReadString(CredentialSection, sApplicationID, '');
FCredentials.GCMAppID := Registry.ReadString(CredentialSection, sGCMAppID, '');
FCredentials.TenantID := Registry.ReadString(CredentialSection, sTenantID, '');
FCredentials.TenantSecret := Registry.ReadString(CredentialSection, sTenantSecret, '');
end;
procedure TEMSManagementRegistry.WriteValuesToRegistry(const ConnectionSection,
CredentialSection, ProfileName: string; Registry: TCustomIniFile);
begin
Registry.WriteString(ConnectionSection, sProfileName, ProfileName);
Registry.WriteString(ConnectionSection, sHost, FConnection.Host);
Registry.WriteInteger(ConnectionSection, sPort, FConnection.Port);
Registry.WriteString(ConnectionSection, sProtocol, FConnection.Protocol);
Registry.WriteString(ConnectionSection, sBaseURL, FConnection.BaseURL);
Registry.WriteInteger(ConnectionSection, sTimeout, FConnection.Timeout);
Registry.WriteString(ConnectionSection, sProxyServer, FConnection.ProxyServer);
Registry.WriteInteger(ConnectionSection, sProxyPort, FConnection.ProxyPort);
Registry.WriteString(CredentialSection, sServerPassword,
TNetEncoding.Base64.Encode(FCredentials.ServerPassword));
Registry.WriteString(CredentialSection, sServerUserName, FCredentials.ServerUserName);
Registry.WriteBool(CredentialSection, sUseMasterSecret, FCredentials.UseMasterSecret);
Registry.WriteString(CredentialSection, sMasterSecret, FCredentials.MasterSecret);
Registry.WriteString(CredentialSection, sAppSecret, FCredentials.AppSecret);
Registry.WriteString(CredentialSection, sApplicationID, FCredentials.ApplicationID);
Registry.WriteString(CredentialSection, sGCMAppID, FCredentials.GCMAppID);
Registry.WriteString(CredentialSection, sTenantID, FCredentials.TenantID);
Registry.WriteString(CredentialSection, sTenantSecret, FCredentials.TenantSecret);
end;
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
$Log$
Rev 1.6 6/29/04 12:27:14 PM RLebeau
Updated to remove DotNet conditionals
Updated constructor to call SetDataString()
Rev 1.5 2004.02.03 5:44:52 PM czhower
Name changes
Rev 1.4 2004.02.03 2:12:04 PM czhower
$I path change
Rev 1.3 24/01/2004 19:07:18 CCostelloe
Cleaned up warnings
Rev 1.2 14/12/2003 18:07:16 CCostelloe
Changed GetDataString to avoiud error 'String element cannot be passed to var
parameter'
Rev 1.1 13/05/2003 20:28:04 CCostelloe
Bug fix: remove default values in Create to avoid ambiguities with
Create(TCollection)
Rev 1.0 11/14/2002 02:12:46 PM JPMugaas
}
unit IdAttachmentMemory;
interface
{$I IdCompilerDefines.inc}
uses
Classes, IdAttachment, IdMessageParts, IdGlobal;
type
TIdAttachmentMemory = class(TIdAttachment)
protected
FDataStream: TStream;
FDataStreamBeforeLoadPosition: TIdStreamSize;
function GetDataString: string;
procedure SetDataStream(const Value: TStream);
procedure SetDataString(const Value: string);
public
{CC: Bug fix, remove default values to resolve ambiguities with Create(TCollection).}
constructor Create(Collection: TCollection); overload; override;
constructor Create(Collection: TIdMessageParts; const CopyFrom: TStream); reintroduce; overload;
constructor Create(Collection: TIdMessageParts; const CopyFrom: String); reintroduce; overload;
destructor Destroy; override;
property DataStream: TStream read FDataStream write SetDataStream;
property DataString: string read GetDataString write SetDataString;
function OpenLoadStream: TStream; override;
procedure CloseLoadStream; override;
procedure FinishTempStream; override;
function PrepareTempStream: TStream; override;
end;
implementation
uses
SysUtils;
{ TIdAttachmentMemory }
constructor TIdAttachmentMemory.Create(Collection: TCollection);
begin
inherited Create(Collection);
FDataStream := TMemoryStream.Create;
end;
constructor TIdAttachmentMemory.Create(Collection: TIdMessageParts;
const CopyFrom: TStream);
begin
inherited Create(Collection);
FDataStream := TMemoryStream.Create;
if Assigned(CopyFrom) then begin
FDataStream.CopyFrom(CopyFrom, CopyFrom.Size);
end;
end;
constructor TIdAttachmentMemory.Create(Collection: TIdMessageParts;
const CopyFrom: String);
begin
inherited Create(Collection);
FDataStream := TMemoryStream.Create;
SetDataString(CopyFrom);
end;
destructor TIdAttachmentMemory.Destroy;
begin
FreeAndNil(FDataStream);
inherited Destroy;
end;
procedure TIdAttachmentMemory.CloseLoadStream;
begin
DataStream.Position := FDataStreamBeforeLoadPosition;
end;
function TIdAttachmentMemory.GetDataString: string;
var
Pos: TIdStreamSize;
begin
Pos := FDataStream.Position;
try
FDataStream.Position := 0;
Result := ReadStringFromStream(FDataStream, FDataStream.Size);
finally
FDataStream.Position := Pos;
end;
end;
function TIdAttachmentMemory.OpenLoadStream: TStream;
begin
FDataStreamBeforeLoadPosition := DataStream.Position;
DataStream.Position := 0;
Result := DataStream;
end;
procedure TIdAttachmentMemory.SetDataStream(const Value: TStream);
begin
FDataStream.Size := 0;
FDataStream.CopyFrom(Value, Value.Size);
end;
procedure TIdAttachmentMemory.SetDataString(const Value: string);
begin
FDataStream.Size := 0;
WriteStringToStream(FDataStream, Value);
end;
procedure TIdAttachmentMemory.FinishTempStream;
begin
DataStream.Position := 0;
end;
function TIdAttachmentMemory.PrepareTempStream: TStream;
begin
DataStream.Size := 0;
Result := DataStream;
end;
end.
|
unit TestGoto;
{ AFS 9 Jan 2000
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
This unit tests use of label & goto statements
which you should NEVER HAVE TO USE!
}
interface
function JumpAllAround: integer;
procedure ForLoop;
procedure UntilLoop;
implementation
uses SysUtils, Dialogs;
label fred;
{ spagetti code }
function JumpAllAround: integer;
label
ProcStart, ProcMid, ProcEnd;
begin
Result := 0;
Goto ProcMid;
ProcStart: inc (Result);
ProcMid: Result := Result + Random (10) - Random (9);
if Result < 10 then
Goto ProcStart;
if Result > 20 then
Goto ProcEnd
else
goto procMid;
ProcEnd:;
end;
procedure ForLoop;
label
LoopStart;
var
liLoop: integer;
label
Loopend;
const
LOOPMAX = 20;
begin
liLoop := 0;
LoopStart:
begin
ShowMessage ('Loop # ' + IntToStr (liLoop));
inc (liLoop);
if liLoop > LOOPMAX then
goto LoopEnd
else
goto LoopStart;
end;
LoopEnd:;
end;
procedure UntilLoop;
label
LoopStart;
var
liLoop: integer;
const
LOOPMAX = 20;
begin
liLoop := 0;
LoopStart:
ShowMessage ('Loop # ' + IntToStr (liLoop));
inc (liLoop);
if (liLoop < LOOPMAX) or (random (10) = 3) then
goto LoopStart;
end;
procedure TestLabelUntil;
var
i: integer;
b: boolean;
label
lbl;
begin
repeat
if b then
goto lbl;
lbl:
until b;
end;
label Jim;
begin
Goto Jim;
Fred: ShowMessage ('Fred was here ');
Jim:;
end.
|
//-----------------------------------------
// Maciej Czekański
// maves90@gmail.com
//-----------------------------------------
program Game;
uses Arkanoid, Allegro, AlBlend, Math, Utility, sysutils;
TYPE
TGame = object
public
function Init: boolean;
procedure DeInit;
function Start: boolean;
function Draw: boolean;
procedure UpdateTime;
function Update: boolean;
private
procedure InitBounds;
procedure AddBrick;
procedure SaveLevel;
mDeltaTime: Real;
mFps: Real;
mFrames: longint;
mCurrentTime, mPrevTime, mLastFpsUpdateTime, mRunningTime: Real;
mBuffer: AL_BITMAPptr;
mGameRunning: boolean; // jeżeli false, to wyłączamy grę
mFont: AL_FONTptr;
//Gra
function LoadBitmaps: boolean;
procedure FreeBitmaps;
mBrickBmp: AL_BITMAPptr;
mBrickRock1Bmp, mBrickRock2Bmp, mBrickSolidBmp: AL_BITMAPptr;
mBackgroundBmp: AL_BITMAPptr;
brickX, brickY: longint;
mMouseLeft, mMouseRight: boolean;
mBounds: array[0..2, 0..1] of TVector2;
mBricks: array[0..MAX_ELEMENT_COUNT] of TBrick;
mBrickCount: longint;
mColors: array[0..10] of longint;
mColorNames: array[0..10] of string;
mCurrentColor: longint;
mTypes: array[0..2] of longint;
mTypeNames: array[0..2] of string;
mCurrentType: longint;
end;
//------------------------------------------------------------------------------------------------
// F U N C T I O N S
//------------------------------------------------------------------------------------------------
// Inicjalizuje edytor
function TGame.Init: boolean;
begin
if al_init = false then
begin
Log('Cant init Allegro!');
result:= false;
exit;
end
else
Log('Allegro initialised.');
al_set_color_depth(al_desktop_color_depth);
if al_install_keyboard = false then
begin
Log('Cant init keyboard.');
result:= false;
exit;
end
else
Log('Keyboard installed.');
if al_install_mouse = -1 then
begin
Log('Cant init mouse.');
result:= false;
exit;
end
else
Log('Mouse installed');
al_set_window_title('Arkanoid');
al_set_gfx_mode(AL_GFX_AUTODETECT_WINDOWED, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0);
mBuffer:= al_create_bitmap(SCREEN_WIDTH, SCREEN_HEIGHT);
mFont:= al_load_bitmap_font('font.pcx', nil, nil);
if mFont = nil then begin
Log('Cant load font.pcx from file.');
end;
LoadBitmaps;
InitBounds;
mCurrentColor:= 0;
mColors[0]:= al_makecol(255, 0, 0);
mColorNames[0]:= 'Red';
mColors[1]:= al_makecol(128, 0, 0);
mColorNames[1]:= 'Maroon';
mColors[2]:= al_makecol(0, 255, 0);
mColorNames[2]:= 'Lime';
mColors[3]:= al_makecol(0, 128, 0);
mColorNames[3]:= 'Green';
mColors[4]:= al_makecol(0, 0, 255);
mColorNames[4]:= 'Blue';
mColors[5]:= al_makecol(0, 0, 128);
mColorNames[5]:= 'Navy';
mColors[6]:= al_makecol(127, 127, 127);
mColorNames[6]:= 'Grey';
mColors[7]:= al_makecol(255, 0, 255);
mColorNames[7]:= 'Pink';
mColors[8]:= al_makecol(0, 255, 255);
mColorNames[8]:= 'Cyan';
mColors[9]:= al_makecol(255, 255, 0);
mColorNames[9]:= 'Yellow';
mColors[10]:= al_makecol(255, 127, 0);
mColorNames[10]:= 'Orange';
mCurrentType:= 0;
mTypes[0]:= BT_NORMAL;
mTypeNames[0]:= 'Normal';
mTypes[1]:= BT_ROCK;
mTypeNames[1]:= 'Rock';
mTypes[2]:= BT_SOLID;
mTypeNames[2]:= 'Solid';
end;
// Wczytuje wsyzstkie bitmapy z plików.
function TGame.LoadBitmaps: boolean;
begin
mBrickBmp:= al_load_bitmap('gfx/brick.tga', nil);
if mBrickBmp = nil then begin
Log('Cant load brick.tga from file.');
end;
mBrickRock1Bmp:= al_load_bitmap('gfx/brick_rock1.tga', nil);
if mBrickRock1Bmp = nil then begin
Log('Cant load brick_rock1.tga from file.');
end;
mBrickRock2Bmp:= al_load_bitmap('gfx/brick_rock2.tga', nil);
if mBrickRock2Bmp = nil then begin
Log('Cant load brick_rock2.tga from file.');
end;
mBrickSolidBmp:= al_load_bitmap('gfx/brick_solid.tga', nil);
if mBrickSolidBmp = nil then begin
Log('Cant load brick_solid.tga from file.');
end;
mBackgroundBmp:= al_load_bitmap('gfx/background.tga', nil);
if mBackgroundBmp = nil then begin
Log('Cant load background.tga from file.');
end;
result:= true;
end;
// Zwalnia pamięć zajmowaną przez bitmapy.
procedure TGame.FreeBitmaps;
begin
if mBrickBmp <> nil then begin
al_destroy_bitmap(mBrickBmp);
end;
if mBrickRock1Bmp <> nil then begin
al_destroy_bitmap(mBrickRock1Bmp);
end;
if mBrickRock2Bmp <> nil then begin
al_destroy_bitmap(mBrickRock2Bmp);
end;
if mBrickSolidBmp <> nil then begin
al_destroy_bitmap(mBrickSolidBmp);
end;
if mBackgroundBmp <> nil then begin
al_destroy_bitmap(mBackgroundBmp);
end;
end;
// Inicjalizuje granice planszy
procedure TGame.InitBounds;
begin
mBounds[0,0].x := BOUND;
mBounds[0,0].y := BOUND;
mBounds[0,1].x := BOUND;
mBounds[0,1].y := SCREEN_HEIGHT - BOUND;
mBounds[1,0].x := SCREEN_WIDTH - BOUND;
mBounds[1,0].y := BOUND;
mBounds[1,1].x := SCREEN_WIDTH - BOUND;
mBounds[1,1].y := SCREEN_HEIGHT - BOUND;
mBounds[2,0].x := BOUND;
mBounds[2,0].y := BOUND;
mBounds[2,1].x := SCREEN_WIDTH - BOUND;
mBounds[2,1].y := BOUND;
end;
//------------------------------------------------------------------------------------------------
// Zwalnia wszelkie zasoby
procedure TGame.DeInit;
begin
if mFont <> nil then begin
al_destroy_font(mFont);
Log('Font destroyed');
end;
if mBuffer <> nil then begin
al_destroy_bitmap(mBuffer);
Log('Buffer destroyed');
end;
FreeBitmaps;
al_exit;
end;
//------------------------------------------------------------------------------------------------
// Rozpoczyna główną pętlę programu
function TGame.Start: boolean;
begin
mGameRunning:= true;
mPrevTime:= GetTime;
mLastFpsUpdateTime:= GetTime;
mFrames:= 0;
while mGameRunning do
begin
UpdateTime;
Update;
Draw;
Sleep(5);
end;
result:= true;
end;
//------------------------------------------------------------------------------------------------
// Aktualizuje aktualny czas gry oraz licznik FPS
procedure TGame.UpdateTime;
begin
mCurrentTime:= GetTime;
mDeltaTime:= mCurrentTime - mPrevTime;
mPrevTime:= mCurrentTime;
mRunningTime := mRunningTime + mDeltaTime;
Inc(mFrames);
if mCurrentTime - mLastFpsUpdateTime > 1.0 then
begin
mFps := mFrames*(mCurrentTime - mLastFpsUpdateTime);
mFrames:= 0;
mLastFpsUpdateTime:= mCurrentTime;
end;
end;
//------------------------------------------------------------------------------------------------
// Aktualizuje edytor
function TGame.Update: boolean;
var
key: longint;
rect: TRectF;
collide: boolean;
i: longint;
begin
if al_keypressed then
key:= al_readkey;
if key shr 8 = AL_KEY_ESC then
mGameRunning:= false;
brickX:= al_mouse_x;
brickY:= al_mouse_y;
if brickX < BOUND then
brickX:= BOUND;
if brickX > SCREEN_WIDTH - BOUND - 80 then
brickX:= SCREEN_WIDTH - BOUND - 80;
if brickY < BOUND then
brickY:= BOUND;
// Wyrównanie pozycji klocka do siatki
if al_key[AL_KEY_LCONTROL] <> 0 then begin
brickX:= brickX - (brickX mod 40);
brickY:= brickY - (brickY mod 20);
end;
// Zmiana koloru
if key shr 8 = AL_KEY_1 then begin
Inc(mCurrentColor);
if mCurrentColor > high(mColors) then
mCurrentColor:= 0;
end;
if key shr 8 = AL_KEY_Q then begin
Dec(mCurrentColor);
if mCurrentColor < 0 then
mCurrentColor:= high(mColors);
end;
// Zmiana typu klocka
if key shr 8 = AL_KEY_2 then begin
Inc(mCurrentType);
if mCurrentType > high(mTypes) then
mCurrentType:= 0;
end;
if key shr 8 = AL_KEY_W then begin
Dec(mCurrentType);
if mCurrentType < 0 then
mCurrentType:= high(mTypes);
end;
// Zapisanie planszy
if key shr 8 = AL_KEY_ENTER then begin
SaveLevel;
end;
// Sprawdzanie kolizji z pozostałymi klockami
if ((al_mouse_b and 1) <> 0) and (not mMouseLeft) then begin
mMouseLeft:= true;
collide:= false;
for i:= 0 to high(mBricks) do begin
rect.x:= brickX;
rect.y:= brickY;
rect.width:= BRICK_WIDTH;
rect.height:= BRICK_HEIGHT;
if mBricks[i].alive and RectToRect(rect, mBricks[i].rect) then begin
collide:= true;
break;
end;
end;
if not collide then
AddBrick;
end;
if (al_mouse_b and 1) = 0 then
mMouseLeft:= false;
// Kasowanie klocka
if ((al_mouse_b and 2) <> 0) and (not mMouseRight) then begin
for i:= 0 to high(mBricks) do begin
if mBricks[i].alive AND PointInRect(al_mouse_x, al_mouse_y, mBricks[i].rect) then begin
mBricks[i].alive:= false;
Dec(mBrickCount);
WriteLn('Removed brick');
end;
end;
end;
if (al_mouse_b and 1) = 0 then
mMouseRight:= false;
result:= true;
end;
//------------------------------------------------------------------------------------------------
function TGame.Draw: boolean;
var
i: longint;
begin
al_clear_bitmap(mBuffer);
al_draw_sprite(mBuffer, mBackgroundBmp, 0, 0);
// Rysowanie klocków
for i:= 0 to high(mBricks) do begin
if (mBricks[i].alive = true) then begin
with mBricks[i] do begin
al_set_trans_blender(r, g, b, 255);
if brickType = BT_NORMAL then
al_draw_lit_sprite(mBuffer, mBrickBmp, Round(rect.x), Round(rect.y), 127)
else if brickType = BT_ROCK then begin
if hitsToBreak = 2 then
al_draw_lit_sprite(mBuffer, mBrickRock1Bmp, Round(rect.x), Round(rect.y), 127)
else
al_draw_lit_sprite(mBuffer, mBrickRock2Bmp, Round(rect.x), Round(rect.y), 127);
end
else if brickType = BT_SOLID then
al_draw_lit_sprite(mBuffer, mBrickSolidBmp, Round(rect.x), Round(rect.y), 127);
end;
end;
end;
al_set_trans_blender(al_getr(mColors[mCurrentColor]), al_getg(mColors[mCurrentColor]), al_getb(mColors[mCurrentColor]), 255);
if mTypes[mCurrentType] = BT_NORMAL then
al_draw_lit_sprite(mBuffer, mBrickBmp, brickX, brickY, 127)
else if mTypes[mCurrentType] = BT_ROCK then begin
al_draw_lit_sprite(mBuffer, mBrickRock1Bmp, brickX, brickY, 127);
end
else if mTypes[mCurrentType] = BT_SOLID then
al_draw_lit_sprite(mBuffer, mBrickSolidBmp, brickX, brickY, 127);
al_textout_ex(mBuffer, mFont, 'Type: ' + mTypeNames[mCurrentType], 50, 10, al_makecol(255, 255, 255), -1);
al_textout_ex(mBuffer, mFont, 'Color: ' + mColorNames[mCurrentColor], 250, 10, al_makecol(255, 255, 255), -1);
al_textout_ex(mbuffer, mFont, 'BrickCount: ' + IntToStr(mBrickCount), 450, 10, al_makecol(255, 255, 255), -1);
al_textout_ex(mbuffer, al_font, 'Press 1/Q to change color, 2/W to change type. Enter - save map. ', 10, SCREEN_HEIGHT - 50, al_makecol(255, 255, 255), -1);
al_blit(mBuffer, al_screen, 0, 0, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
result:= true;
end;
//------------------------------------------------------------------------------------------------
// Dodanie nowego klocka na planszę
procedure TGame.AddBrick;
var
i: longint;
begin
for i:= 0 to high(mBricks) do begin
if mBricks[i].alive = false then begin
mBricks[i].alive:= true;
mBricks[i].rect.x:= brickX;
mBricks[i].rect.y:= brickY;
mBricks[i].rect.width:= BRICK_WIDTH;
mBricks[i].rect.height:= BRICK_HEIGHt;
mBricks[i].r:= al_getr(mColors[mCurrentColor]);
mBricks[i].g:= al_getg(mColors[mCurrentColor]);
mBricks[i].b:= al_getb(mColors[mCurrentColor]);
mBricks[i].brickType:= mTypes[mCurrentType];
if mCurrentType = BT_NORMAL then
mBricks[i].hitsToBreak:= 1
else
mBricks[i].hitsToBreak:= 2;
Inc(mBrickCount);
WriteLn('Added brick number ' + IntToStr(mBrickCount) + ' at (' + IntToStr(brickX) + ', ' + IntToStr(brickY) + ')');
break;
end;
end;
end;
// Zapisuje obecną mapę do pliku o nazwie %d.lvl w folderze Levels,
// gdzie %d oznacza numer planszy.
// Przykład: przyjmijmy, że folder Levels jest pusty. Zapisanie planszy
// utworzy w tym folderze plik 1.lvl. Zapisanie kolejnej utworzy plik 2.lvl itd
procedure TGame.SaveLevel;
var
f: Text;
i, level: longint;
begin
level:= 0;
{$i-}
repeat
Inc(level);
Assign(f, 'levels/' +
IntToStr(level) + '.lvl');
Reset(f);
Close(f);
until IOResult <> 0;
{$i+}
Rewrite(f);
WriteLn(f, mBrickCount);
WriteLn(f, Round(BRICK_WIDTH));
WriteLn(f, Round(BRICK_HEIGHT));
for i:= 0 to high(mBricks) do begin
with mBricks[i] do begin
if not alive then
continue;
WriteLn(f, Round(rect.x));
WriteLn(f, Round(rect.y));
WriteLn(f, al_makecol(r, g, b) );
WriteLn(f, brickType);
end;
end;
Close(f);
end;
VAR
gGame: TGame;
//------------------------------------------------------------------------------------------------
// M A I N P R O G R A M
//------------------------------------------------------------------------------------------------
BEGIN
gGame.Init;
gGame.Start;
gGame.DeInit;
END.
|
{******************************************************************************
* *
* TINY PASCAL BASIC *
* *
* 1980 S. A. MOORE *
* *
* Implements a small basic in Pascal. An example of how small a program can *
* be to implement a simple language. *
* Variables are allowed, using the letters "a" thru "z". Integers are denoted *
* by the letters alone. Strings are denoted by "a$" form. *
* The following statements are implemented: *
* *
* input <variable> Reads the contents of the variable from the user. *
* If the variable is integer, a line is read from the *
* user, then any spaces on the line skipped, then a *
* number read. *
* If the variable is string, the entire line is *
* assigned to it, including any spaces. *
* *
* print <expr> [,<expr].. [;] Prints the expression. The expression can be *
* integer or string. If a trailing ";" exists, the next *
* print will resume on the same line. Any number of *
* items may appear to be printed on the same line, *
* separated by ",". *
* *
* goto <integer> Control resumes at the line specified by the integer. *
* Note that no "calculated gotos" are allowed. *
* *
* if <expr> then <statement> The expression must be a integer. If the *
* condition is 0, control resumes on the next line. *
* if the condition is not 0, the statement after "then" *
* is executed (as well as the rest of the line). *
* *
* rem <line> The entire rest of the line is ignored. *
* *
* stop Terminates program execution. The values of variables *
* are not cleared. *
* *
* run All variables are cleared, with integers becoming 0, *
* and strings becoming empty. Then control passes to *
* the first statement in the program. *
* *
* list [<start>[,<end>]] Lists all program lines between the given lines. *
* The default if no lines are given is the starting *
* and ending lines of the entire program. *
* *
* new Clears the entire program and stops execution. *
* *
* [let] <var> = <expr> Assigns the value of the expression to the *
* variable. The variable must be the same type (string *
* or integer) as the expression. The "let" keyword is *
* optional. *
* *
* bye Exits basic for the operating system. *
* *
* Expressions can contain the following operators: *
* *
* <, >, =, <>, <=, >= Comparision. *
* +, -, *, /, mod Basic math. *
* left$(<str>, <expr>) The leftmost characters of the string. *
* right$(<str>, <expr>) The rightmost characters of the string. *
* mid$(<str>, <start>, <len>) The middle characters of the string. *
* str$(<expr>) The string form of the integer expression. *
* val(<str>) The integer equivalent of the string. *
* chr(<str>) The ascii value of the first character. *
* *
* The internal form of the program is keyword compressed for effiency, which *
* both allows for a smaller internal program, and simplifies the decoding of *
* keywords. *
* *
* *
* Notes: *
* *
* 1. If the program store were of the same form as basic strings, routines *
* that handle both in common could be used (example: getting a number from *
* the string). *
* *
******************************************************************************}
program basics(input, output);
label 88, 77, 99;
const maxlin = 9999; { maximum line number }
maxpgm = 100; { maximum line store }
maxstk = 10; { maximum temp count }
maxkey = 29; { maximum key store }
{ key codes }
cinput = 1; cprint = 2; cgoto = 3; cif = 4;
crem = 5; cstop = 6; crun = 7; clist = 8;
cnew = 9; clet = 10; cbye = 11; clequ = 12;
cgequ = 13; cequ = 14; cnequ = 15; cltn = 16;
cgtn = 17; cadd = 18; csub = 19; cmult = 20;
cdiv = 21; cmod = 22; cleft = 23; cright = 24;
cmid = 25; cthen = 26; cstr = 27; cval = 28;
cchr = 29;
type string10 = packed array [1..10] of char; { key }
string80 = packed array [1..80] of char; { general string }
bstring80 = record
len : integer;
str : string80
end;
vartyp = (tint, tstr); { variable type }
{ error codes }
errcod = (eitp, estate, eexmi, eeque, estyp, epbful, eiovf, evare,
elabnf, einte, econv, elntl, ewtyp, erpe, eexc, emqu,
eifact, elintl, estrovf, eedlexp, elpe, ecmaexp, estre,
estrinx);
var prgm: array [0..maxpgm] of string80; { program store }
strs: array ['a'..'z'] of bstring80; { string store }
ints: array ['a'..'z'] of integer; { integer store }
keywd: array [cinput..cchr] of string10; { keywords }
temp: array [1..maxstk] of record
typ : vartyp;
int : integer;
bstr : bstring80
end;
prgmc, { program counter (0 = input line) }
top, { current temps top }
linec: integer; { character position }
{ print key compressed line }
procedure prtlin(var str : string80);
var i, j: integer;
procedure prtkey(var str : string10);
var i, j: integer;
begin { prtkey }
j := 10;
while (str[j] = ' ') and (j > 0) do j := j - 1;
j := j + 1;
i := 1;
while i < j do begin write(str[i]); i := i + 1 end
end; { prtkey }
begin { prtlin }
j := 80;
while (str[j] = ' ') and (j > 0) do j := j - 1;
j := j + 1;
i := 1;
while i < j do begin
if ord(str[i]) < ord(' ') then prtkey(keywd[ord(str[i])])
else write(str[i]);
i := i + 1
end;
writeln
end; { prtlin }
{ print error }
procedure prterr(err : errcod);
begin
if prgmc <> 0 then prtlin(prgm[prgmc]);
write('*** ');
case err of
eitp: writeln('Interpreter error');
estate: writeln('Statement expected');
eexmi: writeln('Expression must be integer');
eeque: writeln('"=" expected');
estyp: writeln('Operands not of same type');
epbful: writeln('Program buffer full');
eiovf: writeln('Input overflow');
evare: writeln('Variable expected');
elabnf: writeln('Statement label not found');
einte: writeln('Integer expected');
econv: writeln('Conversion error');
elntl: writeln('Line number too large');
ewtyp: writeln('Operand(s) of wrong type');
erpe: writeln('")" expected');
eexc: writeln('Expression too complex');
emqu: writeln('Missing quote');
eifact: writeln('Invalid factor');
elintl: writeln('Line number too large');
estrovf: writeln('String overflow');
eedlexp: writeln('End of line expected');
elpe: writeln('"(" expected');
ecmaexp: writeln('"," expected');
estre: writeln('String expected');
estrinx: writeln('String indexing error')
end;
goto 88 { loop to ready }
end;
{ check character }
function chkchr : char;
var c: char;
begin
if linec <= 80 then c := prgm[prgmc][linec]
else c := ' ';
chkchr := c
end;
{ check end of line }
function chkend: boolean;
begin
chkend := linec > 80 { past end of line }
end;
{ get character }
function getchr: char;
begin
getchr := chkchr;
if not chkend then linec := linec + 1
end;
{ check next character }
function chknxt(c : char) : boolean;
begin
chknxt := c = chkchr;
if c = chkchr then c := getchr
end;
{ skip spaces }
procedure skpspc;
var c: char;
begin
while (chkchr = ' ') and not chkend do c := getchr;
end;
{ check end of statement }
function chksend: boolean;
begin
skpspc; { skip spaces }
chksend := chkend or (chkchr = ':') { check eoln or ':' }
end;
{ check null string }
function null(var str : string80) : boolean;
var i: integer;
f: boolean;
begin
f := true;
for i := 1 to 80 do if str[i] <> ' ' then f := false;
null := f
end;
{ check digit }
function digit(c : char) : boolean;
begin
digit := (ord(c) >= ord('0')) and (ord(c) <= ord('9'))
end;
{ convert to lower case }
function lcase(c : char) : char;
begin
if (ord(c) >= ord('A')) and (ord(c) <= ord('Z')) then
c := chr(ord(c) - ord('A') + ord('a'));
lcase := c
end;
{ check alphabetical }
function alpha(c : char) : boolean;
begin
alpha := (ord(lcase(c)) >= ord('a')) and
(ord(c) <= ord('z'))
end;
{ parse leading integer }
function lint(var str : string80) : integer;
var i, v: integer;
b: boolean;
begin
v := 0;
i := 1;
while (i < 80) and (str[i] = ' ') do i := i + 1;
repeat
if digit(str[i]) then begin
v := v*10 + (ord(str[i]) - ord('0'));
if i <> 80 then begin
i := i + 1;
b := false
end else b := true
end else b := true
until b;
lint := v
end;
{ search label }
function schlab(lab : integer):integer;
var i: integer;
begin
i := 1;
while (lab <> lint(prgm[i])) and (i <= maxpgm) do i := i + 1;
if lab <> lint(prgm[i]) then prterr(elabnf);
schlab := i
end;
{ input string }
procedure inpstr(var str : string80);
var i: integer;
begin
for i := 1 to 80 do str[i] := ' ';
i := 1;
while (i <= 80) and not eoln do begin
read(str[i]);
i := i + 1
end;
readln;
if (i > 80) then prterr(eiovf)
end;
{ parse variable reference }
function getvar : char;
begin
if not alpha(chkchr) then prterr(evare);
getvar := lcase(getchr)
end;
{ enter line to store }
procedure enter(var str : string80);
var line, i, j, k: integer;
f: boolean;
begin
line := lint(str);
if line > maxlin then prterr(elintl); { input line number to large }
i := 1;
f := false;
repeat
if null(prgm[i]) then f := true
else if lint(prgm[i]) < line then begin
i := i + 1;
if i > maxpgm then f := true
end else f := true
until f;
if i > maxpgm then prterr(epbful);
if null(prgm[i]) then prgm[i] := str
else if lint(prgm[i]) = line then begin
j := 1;
while (str[j] = ' ') and (j < 80) do j := j + 1;
while digit(str[j]) and (j < 80) do j := j + 1;
while (str[j] = ' ') and (j < 80) do j := j + 1;
if j = 80 then begin
for k := i to maxpgm - 1 do prgm[k] := prgm[k + 1];
for j := 1 to 80 do prgm[maxpgm][j] := ' '
end else prgm[i] := str
end else if not null(prgm[maxpgm]) then prterr(epbful)
else begin
for k := maxpgm downto i + 1 do prgm[k] := prgm[k - 1];
prgm[i] := str
end
end;
{ compress keys }
procedure keycom(var str : string80);
var ts: string80;
k, i1, i2: integer;
f: boolean;
c: char;
function matstr(var stra: string80; var i: integer;
var strb: string10): boolean;
var i1, i2: integer;
f: boolean;
begin { matstr }
i1 := i;
i2 := 1;
repeat
if strb[i2] = ' ' then f := false
else if lcase(stra[i1]) = lcase(strb[i2]) then begin
f := true;
i1 := i1 + 1;
i2 := i2 + 1
end
else f := false
until not f or (i1 > 80) or (i2 > 10);
if i2 > 10 then begin f := true; i := i1 end
else if strb[i2] = ' ' then begin f := true; i := i1 end
else f := false;
matstr := f
end; { matstr }
{}
begin { keycom }
for i2 := 1 to 80 do ts[i2] := ' ';
i1 := 1;
i2 := 1;
repeat
if str[i1] = '"' then begin
ts[i2] := '"';
i1 := i1 + 1;
i2 := i2 + 1;
c := ' ';
while (i1 <= 80) and (c <> '"') do begin
c := str[i1];
ts[i2] := str[i1];
i1 := i1 + 1;
i2 := i2 + 1
end
end else if str[i1] = ' ' then begin
ts[i2] := str[i1];
i1 := i1 + 1;
i2 := i2 + 1
end else begin
k := 1;
f := false;
while (k <= maxkey) and not f do
begin
f := matstr(str, i1, keywd[k]);
k := k + 1
end;
if f then ts[i2] := chr(k - 1)
else begin ts[i2] := str[i1]; i1 := i1 + 1 end;
i2 := i2 + 1
end
until i1 > 80;
for i1 := 1 to 80 do str[i1] := ts[i1]
{ this diagnostic prints the resulting tolken sequence }
{;for i1 := 1 to 80 do write(ord(str[i1]), ' ');}
end; { keycom }
{ get integer }
function getint: integer;
var v: integer;
begin
v := 0;
skpspc;
if not digit(chkchr) then prterr(einte);
repeat v := v*10 + (ord(getchr) - ord('0'))
until not digit(chkchr);
getint := v
end;
{ get integer from string }
function getval(var str: string80): integer;
var i: integer;
begin
i := 1;
while (i <= 80) and (str[i] = ' ') do i := i + 1;
if not digit(str[i]) then prterr(einte);
getval := lint(str);
while (i < 80) and digit(str[i]) do i := i + 1;
while (i < 80) and (str[i] = ' ') do i := i + 1;
if i <> 80 then prterr(econv)
end;
{ get integer from basic string }
function getbval(var str: bstring80): integer;
var i, v: integer;
begin
i := 1;
while (i <= str.len) and (str.str[i] = ' ') do i := i + 1; { skip spaces }
if not digit(str.str[i]) then prterr(einte); { number not present }
v := 0; { clear result }
while (i <= str.len) and digit(str.str[i]) do begin { parse digit }
v := v*10+ord(str.str[i])-ord('0'); { scale, convert and add in digit }
i := i+1 { next character }
end;
while (i <= str.len) and (str.str[i] = ' ') do i := i + 1;
if i <= str.len then prterr(econv);
getbval := v { return result }
end;
{ place integer to string }
procedure putbval(var str: bstring80; v: integer);
var p: integer; { power holder }
i: integer; { string index }
begin
str.len := 0; { clear result string }
p := 10000; { set maximum power }
i := 1; { set 1st character }
if v < 0 then begin { negative }
str.str[i] := '-'; { place minus sign }
i := i + 1; { next character }
v := -v { negate number }
end;
while p <> 0 do begin { fit powers }
str.str[i] := chr(v div p+ord('0')); { place digit }
if str.str[1] = '-' then begin { negative }
if (str.str[2] <> '0') or (p = 1) then i := i + 1; { next digit }
end else { positive }
if (str.str[1] <> '0') or (p = 1) then i := i + 1; { next digit }
v := v mod p; { remove from value }
p := p div 10 { find next power }
end;
str.len := i-1 { set length of string }
end;
{ print basic string }
procedure prtbstr(var bstr: bstring80);
var i: integer;
begin
for i := 1 to bstr.len do write(bstr.str[i]);
end;
{ input basic string }
procedure inpbstr(var bstr: bstring80);
var i: integer;
begin
for i := 1 to 80 do bstr.str[i] := ' ';
i := 1;
while (i < 80) and not eoln do begin
read(bstr.str[i]);
i := i + 1
end;
if (i > 80) and not eoln then prterr(eiovf);
readln;
bstr.len := i
end;
{ concatenate basic strings }
procedure cat(var bstra, bstrb: bstring80);
var i: integer; { index for string }
begin
if (bstra.len + bstrb.len) > 80 then prterr(estrovf); { string overflow }
{ copy source after destination }
for i := 1 to bstrb.len do bstra.str[bstra.len+i] := bstrb.str[i];
bstra.len := bstra.len + bstrb.len { set new length }
end;
{ check stack items equal }
function chkequ : boolean;
begin
if (temp[top].typ <> tint) or (temp[top - 1].typ <> tint) then
prterr(ewtyp);
chkequ := temp[top - 1].int = temp[top].int
end;
{ check stack items less than }
function chkltn: boolean;
begin
if (temp[top].typ <> tint) or (temp[top - 1].typ <> tint)
then prterr(ewtyp);
chkltn := temp[top - 1].int < temp[top].int
end;
{ check stack items greater than }
function chkgtn: boolean;
begin
if (temp[top].typ <> tint) or (temp[top - 1].typ <> tint)
then prterr(ewtyp);
chkgtn := temp[top - 1].int > temp[top].int
end;
{ set tos true }
procedure settrue;
begin
temp[top].typ := tint;
temp[top].int := 1
end;
{ set tos false }
procedure setfalse;
begin
temp[top].typ := tint;
temp[top].int := 0
end;
{ clear program store }
procedure clear;
var x, y: integer;
c: char;
begin
for x := 1 to maxpgm do
for y := 1 to 80 do prgm[x][y] := ' ';
for c := 'a' to 'z' do strs[c].len := 0;
for c := 'a' to 'z' do ints[c] := 0;
prgmc := 0;
linec := 1;
top := 1
end;
{ clear variable store }
procedure clrvar;
var c: char;
begin
for c := 'a' to 'z' do strs[c].len := 0;
for c := 'a' to 'z' do ints[c] := 0;
prgmc := 0;
linec := 1;
top := 1
end;
{ execute string }
procedure exec;
label 1; { exit procedure }
var c: char;
{ execute statement }
procedure stat;
var x, y: integer;
c: char;
s: string80;
b: boolean;
{ parse expression }
procedure expr;
{ parse simple expression }
procedure sexpr;
{ parse term }
procedure term;
{ parse factor }
procedure factor;
var i: integer;
c: char;
begin { factor }
skpspc;
c := chkchr; { save starting character }
if chknxt('(') then begin
expr;
if not chknxt(')') then prterr(erpe)
end else if chknxt(chr(cadd)) then begin
factor;
if temp[top].typ <> tint then prterr(ewtyp)
end else if chknxt(chr(csub)) then begin
factor;
if temp[top].typ <> tint then prterr(ewtyp);
temp[top].int := - temp[top].int
end else if chknxt('"') then begin
top := top + 1;
if top > maxstk then prterr(eexc);
temp[top].typ := tstr;
i := 1;
while (i <= 80) and (chkchr <> '"') do begin
temp[top].bstr.str[i] := getchr;
i := i + 1
end;
if not chknxt('"') then prterr(emqu);
temp[top].bstr.len := i - 1
end else if digit(chkchr) then begin
top := top + 1;
if top > maxstk then prterr(eexc);
temp[top].typ := tint;
temp[top].int := getint
end else if alpha(chkchr) then begin
top := top + 1;
if top > maxstk then prterr(eexc);
c := getvar;
if chknxt('$') then begin
temp[top].typ := tstr;
temp[top].bstr := strs[c]
end else begin
temp[top].typ := tint;
temp[top].int := ints[c]
end
end else if chknxt(chr(cleft)) or chknxt(chr(cright)) or
chknxt(chr(cmid)) then begin
{ left$, right$ }
skpspc; { skip spaces }
if not chknxt('(') then prterr(elpe); { '(' expected }
expr; { parse expression }
if temp[top].typ <> tstr then prterr(estre); { string expected }
skpspc; { skip spaces }
if not chknxt(',') then prterr(ecmaexp); { ',' expected }
expr; { parse expression }
if temp[top].typ <> tint then prterr(einte); { integer expected }
skpspc; { skip spaces }
if c <> chr(cmid) then begin { left$ or right$ }
if not chknxt(')') then prterr(erpe); { ')' expected }
if temp[top].int > temp[top-1].bstr.len then prterr(estrinx);
if c = chr(cright) then { right$ }
for i := 1 to temp[top].int do { move string left }
temp[top-1].bstr.str[i] :=
temp[top-1].bstr.str[i+temp[top-1].bstr.len-temp[top].int];
temp[top-1].bstr.len := temp[top].int; { set new length left }
top := top-1 { clean stack }
end else begin { mid$ }
if not chknxt(',') then prterr(ecmaexp); { ',' expected }
expr; { parse end expression }
if temp[top].typ <> tint then prterr(einte); { integer expected }
skpspc; { skip spaces }
if not chknxt(')') then prterr(erpe); { ')' expected }
{ check requested length > string length }
if temp[top].int+temp[top-1].int-1 > temp[top-2].bstr.len then
prterr(estrinx);
for i := 1 to temp[top].int do { move string left }
temp[top-2].bstr.str[i] := temp[top-2].bstr.str[i+temp[top-1].int-1];
temp[top-2].bstr.len := temp[top].int; { set new length left }
top := top-2 { clean stack }
end
end else if chknxt(chr(cchr)) then begin { chr }
if not chknxt('(') then prterr(elpe); { '(' expected }
expr; { parse expression }
if temp[top].typ <> tstr then prterr(estre); { string expected }
skpspc; { skip spaces }
if not chknxt(')') then prterr(erpe); { ')' expected }
if temp[top].bstr.len < 1 then prterr(estrinx); { check valid }
c := temp[top].bstr.str[1]; { get the 1st character }
temp[top].typ := tint; { change to integer }
temp[top].int := ord(c) { place result }
end else if chknxt(chr(cval)) then begin { val }
if not chknxt('(') then prterr(elpe); { '(' expected }
expr; { parse expression }
if temp[top].typ <> tstr then prterr(estre); { string expected }
skpspc; { skip spaces }
if not chknxt(')') then prterr(erpe); { ')' expected }
i := getbval(temp[top].bstr); { get string value }
temp[top].typ := tint; { change to integer }
temp[top].int := i { place result }
end else if chknxt(chr(cstr)) then begin { str$ }
if not chknxt('(') then prterr(elpe); { '(' expected }
expr; { parse expression }
if temp[top].typ <> tint then prterr(einte); { integer expected }
skpspc; { skip spaces }
if not chknxt(')') then prterr(erpe); { ')' expected }
i := temp[top].int; { get value }
temp[top].typ := tstr; { change to string }
putbval(temp[top].bstr, i) { place value in ascii }
end else prterr(eifact)
end; { factor }
begin { term }
factor;
skpspc;
while ord(chkchr) in [cmult, cdiv, cmod] do begin
case ord(getchr) of { tolken }
cmult: begin { * }
factor;
if (temp[top].typ <> tint) or
(temp[top - 1].typ <> tint) then prterr(ewtyp);
temp[top - 1].int := temp[top - 1].int * temp[top].int;
top := top - 1
end;
cdiv: begin { / }
factor;
if (temp[top].typ <> tint) or
(temp[top - 1].typ <> tint) then prterr(ewtyp);
temp[top - 1].int := temp[top - 1].int div temp[top].int;
top := top - 1
end;
cmod: begin { mod }
factor;
if (temp[top].typ <> tint) or
(temp[top - 1].typ <> tint) then prterr(ewtyp);
temp[top - 1].int := temp[top - 1].int mod
temp[top].int;
top := top - 1
end
end;
skpspc { skip spaces }
end
end; { term }
begin { sexpr }
term;
skpspc;
while ord(chkchr) in [cadd, csub] do begin
case ord(getchr) of { tolken }
cadd: begin
term;
if temp[top].typ = tstr then begin
if temp[top - 1].typ <> tstr then prterr(estyp);
cat(temp[top - 1].bstr, temp[top].bstr);
top := top - 1
end else begin
if temp[top - 1].typ <> tint then prterr(estyp);
temp[top - 1].int :=
temp[top - 1].int + temp[top].int;
top := top - 1;
end
end;
csub: begin { - }
term;
if (temp[top].typ <> tint) or
(temp[top - 1].typ <> tint) then prterr(ewtyp);
temp[top - 1].int := temp[top - 1].int - temp[top].int;
top := top - 1
end
end;
skpspc { skip spaces }
end
end; { sexpr }
begin { expr }
sexpr; { parse simple expression }
skpspc; { skip spaces }
while ord(chkchr) in [cequ, cnequ, cltn, cgtn, clequ, cgequ] do begin
case ord(getchr) of { tolken }
cequ: begin
sexpr;
if chkequ then begin top := top - 1; settrue end
else begin top := top - 1; setfalse end
end;
cnequ: begin
sexpr;
if chkequ then begin top := top - 1; setfalse end
else begin top := top - 1; settrue end
end;
cltn: begin
sexpr;
if chkltn then begin top := top - 1; settrue end
else begin top := top - 1; setfalse end
end;
cgtn: begin
sexpr;
if chkgtn then begin top := top - 1; settrue end
else begin top := top - 1; setfalse end
end;
clequ: begin
sexpr;
if chkgtn then begin top := top - 1; setfalse end
else begin top := top - 1; settrue end
end;
cgequ: begin
sexpr;
if chkltn then begin top := top - 1; setfalse end
else begin top := top - 1; settrue end
end
end;
skpspc { skip spaces }
end
end; { expr }
{ process "let" function }
procedure let;
begin
skpspc;
c := getvar;
if chknxt('$') then begin
skpspc;
if not chknxt(chr(cequ)) then
prterr(eeque);
expr;
if temp[top].typ <> tstr then
prterr(estyp);
strs[c] := temp[top].bstr;
top := top - 1
end else begin
skpspc;
if not chknxt(chr(cequ)) then
prterr(eeque);
expr;
if temp[top].typ <> tint then
prterr(estyp);
ints[c] := temp[top].int;
top := top - 1
end
end;
begin { stat }
skpspc;
if ord(chkchr) < ord(' ') then begin
if ord(chkchr) > cbye then prterr(estate);
case ord(getchr) of { statement }
cinput: begin
skpspc;
c := getvar;
if chknxt('$') then inpbstr(strs[c])
else begin
inpstr(s);
ints[c] := getval(s)
end
end;
cprint: begin
repeat { list items }
expr;
if temp[top].typ = tstr then prtbstr(temp[top].bstr)
else write(temp[top].int);
top := top - 1;
skpspc
until not chknxt(','); { until not ',' }
if not chknxt(';') then writeln
end;
cgoto: begin
prgmc := schlab(getint);
goto 1
end;
cif: begin
expr;
if temp[top].typ <> tint then
prterr(eexmi);
if temp[top].int = 0 then begin
top := top - 1;
{ go next line }
if prgmc > 0 then prgmc := prgmc + 1;
goto 1
end;
top := top - 1;
b := chknxt(chr(cthen));
stat
end;
crem: begin
if prgmc > 0 then prgmc := prgmc + 1; { go next line }
goto 1 { exit line executive }
end;
cstop: goto 88;
crun: begin clrvar; prgmc := 1; goto 1 end;
clist: begin
x := 1; { set default list swath }
y := maxpgm;
if not chksend then begin { list swath is specified }
x := schlab(getint);
skpspc;
{ check if end line is specified }
if chknxt(',') then y := schlab(getint)
end;
for x := x to y do { print specified lines }
if not null(prgm[x]) then { line exists in buffer }
prtlin(prgm[x]) { print }
end;
cnew: begin clear; goto 88 end;
clet: let;
cbye: goto 99
end
end else let { default let }
end; { stat }
begin { exec }
linec := 1;
while digit(chkchr) do c := getchr; { skip label }
repeat stat until getchr <> ':';
skpspc;
if not chkend then prterr(eedlexp); { should be at line end }
if prgmc > 0 then prgmc := prgmc + 1;
1:
end; { exec }
begin { executive }
clear;
{ initalize keys }
keywd[cinput] := 'input '; keywd[cprint] := 'print ';
keywd[cgoto] := 'goto '; keywd[cif] := 'if ';
keywd[crem] := 'rem '; keywd[cstop] := 'stop ';
keywd[crun] := 'run '; keywd[clist] := 'list ';
keywd[cnew] := 'new '; keywd[clet] := 'let ';
keywd[cbye] := 'bye '; keywd[clequ] := '<= ';
keywd[cgequ] := '>= '; keywd[cequ] := '= ';
keywd[cnequ] := '<> '; keywd[cltn] := '< ';
keywd[cgtn] := '> '; keywd[cadd] := '+ ';
keywd[csub] := '- '; keywd[cmult] := '* ';
keywd[cdiv] := '/ '; keywd[cmod] := 'mod ';
keywd[cleft] := 'left$ '; keywd[cright] := 'right$ ';
keywd[cmid] := 'mid$ '; keywd[cthen] := 'then ';
keywd[cstr] := 'str$ '; keywd[cval] := 'val ';
keywd[cchr] := 'chr ';
writeln;
writeln('Tiny basic interpreter vs. 0.1 Copyright (C) 1994 S. A. Moore');
writeln;
88: while true do begin
writeln('Ready');
77: prgmc := 0;
linec := 1;
top := 0;
{ get user lines until non-blank }
repeat inpstr(prgm[0]) until not null(prgm[0]);
keycom(prgm[0]);
if lint(prgm[0]) > 0 then begin
enter(prgm[0]);
goto 77
end else repeat
exec;
if (prgmc > maxpgm) then prgmc := 0
else if null(prgm[prgmc]) then prgmc := 0
until prgmc = 0
end;
99: writeln('Bye...')
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
unit RN_RecastContourHelper;
interface
uses
RN_Helper, RN_Recast;
type
//struct rcContourHole
{
rcContour* contour;
int minx, minz, leftmost;
}
PrcContourHole = ^TrcContourHole;
TrcContourHole = record
contour: PrcContour;
minx, minz, leftmost: Integer;
end;
//struct rcContourRegion
{
rcContour* outline;
rcContourHole* holes;
int nholes;
}
PrcContourRegion = ^TrcContourRegion;
TrcContourRegion = record
outline: PrcContour;
holes: PrcContourHole;
nholes: Integer;
end;
//struct rcPotentialDiagonal
{
int vert;
int dist;
}
PrcPotentialDiagonal = ^TrcPotentialDiagonal;
TrcPotentialDiagonal = record
vert: Integer;
dist: Integer;
end;
implementation
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1997,99 Inprise Corporation }
{ }
{*******************************************************}
unit WebConst;
interface
resourcestring
sInvalidActionRegistration = 'Invalid Action registration';
sDuplicateActionName = 'Duplicate action name';
sOnlyOneDispatcher = 'Only one WebDispatcher per form/data module';
sHTTPItemName = 'Name';
sHTTPItemURI = 'PathInfo';
sHTTPItemEnabled = 'Enabled';
sHTTPItemDefault = 'Default';
sHTTPItemProducer = 'Producer';
sResNotFound = 'Resource %s not found';
sTooManyColumns = 'Too many table columns';
sFieldNameColumn = 'Field Name';
sFieldTypeColumn = 'Field Type';
implementation
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: TypesMDC<p>
Types for Return to Castle Wolfenstein's MDC file format.<p>
Original code by Osman Turan (osmanturancom@yahoo.com)<p>
<b>History :</b><font size=-1><ul>
<li>16/10/08 - UweR - Compatibility fix for Delphi 2009
<li>18/12/04 - PhP - fixed constants, improve performance
<li>11/05/04 - SG - Added to CVS
<li>07/02/04 - OT - Creation (Osman Turan)
</ul></font>
}
unit TypesMDC;
interface
uses
GLVectorTypes;
const
MDCFILE_IDENTITY = 'IDPC';
MDCFILE_VERSION = 2;
MDC_BASEVERTEX_FACTOR = 0.015625; // 1/64;
MDC_COMPVERTEX_FACTOR = 0.046875; // 3/64;
type
TMDCPoint = array[0..2] of Single;
TMDCAngle = TMDCPoint;
TMDCFileHeader = packed record
Ident : array[0..3] of AnsiChar;
Version : Cardinal;
Name : array[0..63] of AnsiChar;
Flags : Cardinal;
NumFrames : Cardinal;
NumTags : Cardinal;
NumSurfaces : Cardinal;
NumSkins : Cardinal;
OffsetBorderFrames : Cardinal;
OffsetTagNames : Cardinal;
OffsetTagFrames : Cardinal;
OffsetSurfaces : Cardinal;
OffsetEnd : Cardinal;
end;
TMDCBorderFrame = packed record
BBMin, BBMax : TMDCPoint;
LocalOrigin : TMDCPoint;
Radius : Single;
Name : array[0..15] of AnsiChar;
end;
PMDCTagName = ^TMDCTagName;
TMDCTagName = packed record
Name: array[0..63] of AnsiChar;
end;
PMDCTagFrame = ^TMDCTagFrame;
TMDCTagFrame = packed record
TagPosition: array[0..2] of Word; //or ShortInt?
TagAngle: array[0..2] of Word; //or ShortInt?
end;
TMDCTag = packed record
TagName: PMDCTagName;
TagFrame: PMDCTagFrame;
end;
TMDCSurfaceHeader = packed record
Ident : array[0..3] of AnsiChar;
Name : array[0..63] of AnsiChar;
Flags : Cardinal;
NumCompFrames : Cardinal;
NumBaseFrames : Cardinal;
NumSkins : Cardinal;
NumVertices : Cardinal;
NumTriangles : Cardinal;
OffsetTriangles : Cardinal;
OffsetSkins : Cardinal;
OffsetTexCoords : Cardinal;
OffsetBaseVerts : Cardinal;
OffsetCompVerts : Cardinal;
OffsetFrameBaseFrames : Cardinal;
OffsetFrameCompFrames : Cardinal;
OffsetEnd : Cardinal;
end;
TMDCTriangle = array[0..2] of Cardinal;
TMDCSkin = packed record
Shader : array[0..63] of AnsiChar;
Flags : Cardinal;
end;
TMDCTexCoord = array[0..1] of Single;
TMDCBaseVertex = array[0..3] of SmallInt;
TMDCCompVertex = array[0..3] of Byte;
TMDCBaseFrame = packed record
BaseVertices: array of TMDCBaseVertex;
end;
TMDCCompFrame = packed record
CompVertices: array of TMDCCompVertex;
end;
implementation
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXClassRegistry;
interface
uses
System.Classes,
System.Generics.Collections,
System.SysUtils
;
type
// TObject constructor is not virtual, so allow for virtual constructor
// for registered Objects.
//
TClassRegistryObject = class
public
constructor Create; virtual;
end;
EClassRegistryError = class(Exception);
TClassRegistryPackageItem = class
private
FPackageName: string;
{$IFNDEF NEXTGEN}
FPackageHandle: HMODULE;
{$ENDIF !NEXTGEN}
constructor Create(PackageName: string);
public
destructor Destroy; override;
end;
TClassRegistry = class
private
FLock: TThreadList;
FClasses: TDictionary<string, TClass>;
FPackages: TDictionary<string, TClassRegistryPackageItem>;
FCanDestroy: Boolean;
class var
ClassRegistry: TClassRegistry;
public
constructor Create;
destructor Destroy; override;
class function GetClassRegistry: TClassRegistry;
procedure RegisterPackageClass(ClassName: string;
PackageName: string);
procedure RegisterClass(ClassName: string; ObjectClass: TClass);
procedure RegisterRegistryClass(ClassName: string;
RegistryClass: TClass);
procedure UnregisterClass(ClassName: string);
function HasClass(ClassName: string): Boolean;
function CreateInstance(ClassName: string): TObject;
end;
implementation
uses
Data.DBXCommonResStrs, System.Generics.Defaults;
{ TClassRegistry }
constructor TClassRegistry.Create;
begin
inherited Create;
FLock := TThreadList.Create;
FClasses := TDictionary<string, TClass>.Create(TIStringComparer.Ordinal);
FPackages := TObjectDictionary<string, TClassRegistryPackageItem>.Create([doOwnsValues], TIStringComparer.Ordinal);
FCanDestroy := true;
end;
destructor TClassRegistry.Destroy;
begin
if not FCanDestroy then
raise EClassRegistryError.Create(SCannotFreeClassRegistry);
FreeAndNil(FLock);
FClasses.Free;
FPackages.Free;
end;
function TClassRegistry.CreateInstance(ClassName: string): TObject;
begin
FLock.LockList;
try
if not FClasses.ContainsKey(ClassName) then
raise EClassRegistryError.Create(Format(SNotRegistered, [ClassName]));
finally
FLock.UnlockList;
end;
// To improve performance, create the instance out of the critical section.
//
Result := FClasses.Items[ClassName].Create;
end;
class function TClassRegistry.GetClassRegistry: TClassRegistry;
begin
if TClassRegistry.ClassRegistry = nil then
begin
TClassRegistry.ClassRegistry := TClassRegistry.Create;
TClassRegistry.ClassRegistry.FCanDestroy := false;
end;
Result := ClassRegistry;
end;
function TClassRegistry.HasClass(ClassName: string): Boolean;
begin
Result := FClasses.ContainsKey(ClassName);
end;
procedure TClassRegistry.RegisterClass(ClassName: string;
ObjectClass: TClass);
begin
if ObjectClass = nil then
raise EClassRegistryError.Create(Format(SInvalidClassRegister, [ClassName]));
FLock.LockList;
try
if FClasses.ContainsKey(ClassName) then
begin
// Subtle. Get here on .net if RegisterPackageClass was called first
// and then the initialization section is consequently invoked
// and calls RegisterClass. The initial RegisterPackageClass did
// not have the class reference, so it is nil. Corner case resulting
// from a general system for static and dynamic linkage across native
// and managed code.
//
if FClasses.Items[ClassName] <> nil then
raise EClassRegistryError.Create(Format(SAlreadyRegistered, [ClassName]));
FClasses.Items[ClassName] := ObjectClass;
end
else
FClasses.Add(ClassName, ObjectClass);
finally
FLock.UnlockList;
end;
end;
procedure TClassRegistry.RegisterRegistryClass(ClassName: string;
RegistryClass: TClass);
begin
if RegistryClass = nil then
raise EClassRegistryError.Create(Format(SInvalidClassRegister, [ClassName]));
FLock.LockList;
try
if FClasses.ContainsKey(ClassName) then
begin
// Subtle. Get here on .net if RegisterPackageClass was called first
// and then the initialization section is consequently invoked
// and calls RegisterClass. The initial RegisterPackageClass did
// not have the class reference, so it is nil. Corner case resulting
// from a general system for static and dynamic linkage across native
// and managed code.
//
if FClasses.Items[ClassName] <> nil then
raise EClassRegistryError.Create(Format(SAlreadyRegistered, [ClassName]));
end
else
FClasses.Add(ClassName, RegistryClass);
finally
FLock.UnlockList;
end;
end;
procedure TClassRegistry.RegisterPackageClass(ClassName,
PackageName: string);
var
PackageItem: TClassRegistryPackageItem;
begin
FLock.LockList;
try
if FClasses.ContainsKey(ClassName) then
raise EClassRegistryError.Create(Format(SAlreadyRegistered, [ClassName]));
// native unit initialization section is invoked when the package was loaded.
//
if not FPackages.ContainsKey(PackageName) then
begin
PackageItem := TClassRegistryPackageItem.Create(PackageName);
try
FPackages.Add(PackageName, PackageItem);
except
PackageItem.Free;
raise;
end;
end;
if not FClasses.ContainsKey(ClassName) then
FClasses.Add(ClassName, nil);
finally
FLock.UnlockList;
end;
end;
procedure TClassRegistry.UnregisterClass(ClassName: string);
begin
FLock.LockList;
try
if FClasses.ContainsKey(ClassName) then
FClasses.Remove(ClassName);
finally
FLock.UnlockList;
end;
end;
{ TClassRegistryPackageItem }
constructor TClassRegistryPackageItem.Create(PackageName: string);
begin
inherited Create;
FPackageName := PackageName;
{$IFNDEF NEXTGEN}
FPackageHandle := LoadPackage(PackageName);
{$ENDIF !NEXTGEN}
end;
destructor TClassRegistryPackageItem.Destroy;
begin
{$IFNDEF NEXTGEN}
if FPackageHandle <> 0 then
UnloadPackage(FPackageHandle);
{$ENDIF !NEXTGEN}
inherited;
end;
{ TClassRegistryObject }
constructor TClassRegistryObject.Create;
begin
inherited Create;
end;
initialization
finalization
if TClassRegistry.ClassRegistry <> nil then
begin
TClassRegistry.ClassRegistry.FCanDestroy := true;
FreeAndNil(TClassRegistry.ClassRegistry);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC InterBase/Firebird metadata }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.IBMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Consts, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator;
const
csIDNone = 0;
csIDOctets = 1;
csIDUnicodeFSS = 3;
csIDFBUtf8 = 4;
csIDUnicodeBE = 8;
csIDIBUtf8 = 59;
csIDUnicodeLE = 64;
type
TFDPhysIBBrand = (ibInterbase, ibFirebird, ibYaffil);
IFDPhysIBConnectionMetadata = interface (IUnknown)
['{898D228C-56E3-4D34-9AA4-B1DC613CE57A}']
// private
function GetBrand: TFDPhysIBBrand;
function GetDialect: Integer;
// public
property Brand: TFDPhysIBBrand read GetBrand;
property Dialect: Integer read GetDialect;
end;
TFDPhysIBMetadata = class (TFDPhysConnectionMetadata, IFDPhysIBConnectionMetadata)
private
FBrand: TFDPhysIBBrand;
FDialect: Integer;
protected
// IFDPhysConnectionMetadata
function GetKind: TFDRDBMSKind; override;
function GetTxMultiple: Boolean; override;
function GetTxSavepoints: Boolean; override;
function GetEventSupported: Boolean; override;
function GetEventKinds: String; override;
function GetGeneratorSupported: Boolean; override;
function GetTruncateSupported: Boolean; override;
function GetIdentitySupported: Boolean; override;
function GetIdentityInsertSupported: Boolean; override;
function GetParamNameMaxLength: Integer; override;
function GetNameParts: TFDPhysNameParts; override;
function GetNameQuotedCaseSensParts: TFDPhysNameParts; override;
function GetNameCaseSensParts: TFDPhysNameParts; override;
function GetNameDefLowCaseParts: TFDPhysNameParts; override;
function GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; override;
function GetInlineRefresh: Boolean; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function GetAsyncAbortSupported: Boolean; override;
function GetLineSeparator: TFDTextEndOfLine; override;
function GetLockNoWait: Boolean; override;
function GetDefValuesSupported: TFDPhysDefaultValues; override;
function GetArrayExecMode: TFDPhysArrayExecMode; override;
function GetLimitOptions: TFDPhysLimitOptions; override;
function GetNullLocations: TFDPhysNullLocations; override;
procedure DefineMetadataStructure(ATable: TFDDatSTable; AKind: TFDPhysMetaInfoKind); override;
function GetResultSetFields(const ASQLKey: String): TFDDatSView; override;
function InternalEscapeBoolean(const AStr: String): String; override;
function InternalEscapeDate(const AStr: String): String; override;
function InternalEscapeDateTime(const AStr: String): String; override;
function InternalEscapeFloat(const AStr: String): String; override;
function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override;
function InternalEscapeTime(const AStr: String): String; override;
function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
// IFDPhysIBConnectionMetadata
function GetBrand: TFDPhysIBBrand;
function GetDialect: Integer;
public
constructor Create(const AConnection: TFDPhysConnection;
ABrand: TFDPhysIBBrand; AServerVersion, AClientVersion: TFDVersion;
ADialect: Integer; AIsUnicode: Boolean);
end;
TFDPhysIBCommandGenerator = class(TFDPhysCommandGenerator)
private
FIDUTF8: Integer;
FEncoding: TFDEncoding;
protected
function GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String; override;
function GetPessimisticLock: String; override;
function GetSavepoint(const AName: String): String; override;
function GetRollbackToSavepoint(const AName: String): String; override;
function GetCommitSavepoint(const AName: String): String; override;
function GetReadGenerator(const AName, AAlias: String;
ANextValue, AFullSelect: Boolean): String; override;
function GetSingleRowTable: String; override;
function GetRowId(var AAlias: String): String; override;
function GetCall(const AName: String): String; override;
function GetStoredProcCall(const ACatalog, ASchema, APackage, AProc: String;
AOverload: Word; ASPUsage: TFDPhysCommandKind): String; override;
function GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String; override;
function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer;
var AOptions: TFDPhysLimitOptions): String; override;
function GetCountSelect(const ASQL: String): String; override;
function GetColumnType(AColumn: TFDDatSColumn): String; override;
function GetCreateGenerator(const AName: String): String; override;
function GetDropGenerator(const AName: String): String; override;
function GetCreateIdentityTrigger: String; override;
function GetMerge(AAction: TFDPhysMergeAction): String; override;
public
constructor Create(const ACommand: IFDPhysCommand; AIDUTF8: Integer;
AEncoding: TFDEncoding); overload;
constructor Create(const AConnection: IFDPhysConnection; AIDUTF8: Integer;
AEncoding: TFDEncoding); overload;
end;
implementation
uses
System.SysUtils, Data.DB,
FireDAC.Stan.Util, FireDAC.Stan.Param, FireDAC.Stan.Error;
{-------------------------------------------------------------------------------}
{ TFDPhysIBMetadata }
{-------------------------------------------------------------------------------}
constructor TFDPhysIBMetadata.Create(const AConnection: TFDPhysConnection;
ABrand: TFDPhysIBBrand; AServerVersion, AClientVersion: TFDVersion;
ADialect: Integer; AIsUnicode: Boolean);
var
sKwds: String;
begin
inherited Create(AConnection, AServerVersion, AClientVersion, AIsUnicode);
FBrand := ABrand;
FDialect := ADialect;
// IB 2007
sKwds :=
'ACTION,ACTIVE,ADD,ADMIN,' +
'AFTER,ALL,ALTER,AND,' +
'ANY,AS,ASC,ASCENDING,' +
'AT,AUTO,AUTODDL,AVG,' +
'BASED,BASENAME,BASE_NAME,BEFORE,' +
'BEGIN,BETWEEN,BLOB,BLOBEDIT,' +
'BOOLEAN,BUFFER,BY,CACHE,' +
'CASCADE,CAST,CHAR,CHARACTER,' +
'CHARACTER_LENGTH,CHAR_LENGTH,CHECK,CHECK_POINT_LEN,' +
'CHECK_POINT_LENGTH,COLLATE,COLLATION,COLUMN,' +
'COMMIT,COMMITTED,COMPILETIME,COMPUTED,' +
'CLOSE,CONDITIONAL,CONNECT,CONSTRAINT,' +
'CONTAINING,CONTINUE,COUNT,CREATE,' +
'CSTRING,CURRENT,CURRENT_DATE,CURRENT_TIME,' +
'CURRENT_TIMESTAMP,CURSOR,DATABASE,DATE,' +
'DAY,DEBUG,DEC,' +
'DECIMAL,DECLARE,DEFAULT,DELETE,' +
'DESC,DESCENDING,DESCRIBE,DESCRIPTOR,' +
'DISCONNECT,DISPLAY,DISTINCT,DO,' +
'DOMAIN,DOUBLE,DROP,ECHO,' +
'EDIT,ELSE,END,ENTRY_POINT,' +
'ESCAPE,EVENT,EXCEPTION,EXECUTE,' +
'EXISTS,EXIT,EXTERN,EXTERNAL,' +
'EXTRACT,FALSE,FETCH,FILE,' +
'FILTER,FLOAT,FOR,FOREIGN,' +
'FOUND,FREE_IT,FROM,FULL,' +
'FUNCTION,GDSCODE,GENERATOR,GEN_ID,' +
'GLOBAL,GOTO,GRANT,GROUP,' +
'GROUP_COMMIT_WAIT,GROUP_COMMIT_WAIT_TIME,HAVING,HELP,' +
'HOUR,IF,IMMEDIATE,IN,' +
'INACTIVE,INDEX,INDICATOR,INIT,' +
'INNER,INPUT,INPUT_TYPE,INSERT,' +
'INT,INTEGER,INTO,IS,' +
'ISOLATION,ISQL,JOIN,KEY,' +
'LC_MESSAGES,LC_TYPE,LEFT,LENGTH,' +
'LEV,LEVEL,LIKE,LOGFILE,' +
'LOG_BUFFER_SIZE,LOG_BUF_SIZE,LONG,MANUAL,' +
'MAX,MAXIMUM,MAXIMUM_SEGMENT,MAX_SEGMENT,' +
'MERGE,MESSAGE,MIN,MINIMUM,' +
'MINUTE,MODULE_NAME,MONTH,NAMES,' +
'NATIONAL,NATURAL,NCHAR,NO,' +
'NOAUTO,NOT,NULL,NUMERIC,' +
'NUM_LOG_BUFS,NUM_LOG_BUFFERS,OCTET_LENGTH,OF,' +
'ON,ONLY,OPEN,OPTION,' +
'OR,ORDER,OUTER,OUTPUT,' +
'OUTPUT_TYPE,OVERFLOW,PAGE,PAGELENGTH,' +
'PAGES,PAGE_SIZE,PARAMETER,PASSWORD,' +
'PERCENT,PLAN,POSITION,POST_EVENT,' +
'PRECISION,PREPARE,PRESERVE,PROCEDURE,' +
'PROTECTED,PRIMARY,PRIVILEGES,PUBLIC,' +
'QUIT,RAW_PARTITIONS,READ,' +
'REAL,RECORD_VERSION,REFERENCES,RELEASE,' +
'RESERV,RESERVING,RESTRICT,RETAIN,' +
'RETURN,RETURNING_VALUES,RETURNS,REVOKE,' +
'RIGHT,ROLE,ROLLBACK,ROWS,' +
'RUNTIME,SCHEMA,SECOND,SEGMENT,' +
'SELECT,SET,SHADOW,SHARED,' +
'SHELL,SHOW,SINGULAR,SIZE,' +
'SMALLINT,SNAPSHOT,SOME,SORT,' +
'SQLCODE,SQLERROR,SQLWARNING,STABILITY,' +
'STARTING,STARTS,STATEMENT,STATIC,' +
'STATISTICS,SUB_TYPE,SUM,SUSPEND,' +
'TABLE,TEMPORARY,TERMINATOR,THEN,' +
'TIES,TIME,TIMESTAMP,TO,' +
'TRANSACTION,TRANSLATE,TRANSLATION,TRIGGER,' +
'TRIM,TRUE,TYPE,UNCOMMITTED,' +
'UNION,UNIQUE,UNKNOWN,UPDATE,' +
'UPPER,USER,USING,VALUE,' +
'VALUES,VARCHAR,VARIABLE,VARYING,' +
'VERSION,VIEW,WAIT,WEEKDAY,' +
'WHEN,WHENEVER,WHERE,WHILE,' +
'WITH,WORK,WRITE,YEAR,' +
'WEEKDAY,YEARDAY';
if FBrand = ibFirebird then begin
sKwds := sKwds + ',' +
// Firebird 1.0
'CURRENT_USER,CURRENT_ROLE,BREAK,DESCRIPTOR,FIRST,RECREATE,SKIP,' +
'SUBSTRING,' +
// Firebird 1.5
'CURRENT_CONNECTION,CURRENT_TRANSACTION,BIGINT,CASE,RELEASE,' +
'ROW_COUNT,SAVEPOINT,COALESCE,DELETING,INSERTING,LAST,LEAVE,' +
'LOCK,NULLIF,NULLS,STATEMENT,UPDATING,USING,BREAK,DESCRIPTOR,' +
'FIRST,SKIP,SUBSTRING,' +
// Firebird 2.0
'BIT_LENGTH,BOTH,CHAR_LENGTH,CHARACTER_LENGTH,CLOSE,CROSS,FETCH,' +
'LEADING,LOWER,OCTET_LENGTH,OPEN,ROWS,TRAILING,TRIM,USING,BACKUP,' +
'BLOCK,COLLATION,COMMENT,DIFFERENCE,IIF,NEXT,SCALAR_ARRAY,SEQUENCE,' +
'RESTART,RETURNING,ACTION,CASCADE,FREE_IT,RESTRICT,ROLE,TYPE,' +
'WEEKDAY,YEARDAY,BASENAME,CACHE,CHECK_POINT_LEN,GROUP_COMMIT_WAIT,' +
'LOGFILE,LOG_BUF_SIZE,NUM_LOG_BUFS,RAW_PARTITIONS,' +
// Firebird 2.1
'CONNECT,DISCONNECT,GLOBAL,INSENSITIVE,RECURSIVE,SENSITIVE,START,' +
'ABS,ACCENT,ACOS,ALWAYS,ASCII_CHAR,ASCII_VAL,ASIN,ATAN,ATAN2,BIN_AND,' +
'BIN_OR,BIN_SHL,BIN_SHR,BIN_XOR,CEIL,CEILING,COS,COSH,COT,DATEADD,' +
'DATEDIFF,DECODE,EXP,FLOOR,GEN_UUID,GENERATED,HASH,LIST,LN,LOG,LOG10,' +
'LPAD,MATCHED,MATCHING,MAXVALUE,MILLISECOND,MINVALUE,MOD,OVERLAY,PFD,' +
'PI,PLACING,POWER,PRESERVE,RAND,REPLACE,REVERSE,ROUND,RPAD,SIGN,SIN,' +
'SINH,SPACE,SQRT,TAN,TANH,TEMPORARY,TRUNC,WEEK,' +
// Firebird 2.5
'SIMILAR,AUTONOMOUS,BIN_NOT,CALLER,CHAR_TO_UUID,COMMON,DATA,FIRSTNAME,' +
'GRANTED,LASTNAME,MIDDLENAME,MAPPING,OS_NAME,SOURCE,TWO_PHASE,UUID_TO_CHAR';
end;
FKeywords.CommaText := sKwds;
ConfigQuoteChars;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetKind: TFDRDBMSKind;
begin
if FBrand = ibFirebird then
Result := TFDRDBMSKinds.Firebird
else
Result := TFDRDBMSKinds.Interbase;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetNameCaseSensParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetParamNameMaxLength: Integer;
begin
Result := 256;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetNameParts: TFDPhysNameParts;
begin
Result := [npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts;
begin
if FDialect >= 3 then
Result := [npBaseObject, npObject]
else
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel;
ASide: TFDPhysNameQuoteSide): Char;
begin
if (FDialect >= 3) and (AQuote = ncDefault) then
Result := '"'
else
Result := #0;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetTxMultiple: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetTxSavepoints: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetEventSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetEventKinds: String;
begin
Result := S_FD_EventKind_IB_Events;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetGeneratorSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetTruncateSupported: Boolean;
begin
Result := (FBrand = ibInterbase) and (GetServerVersion >= ivIB130000);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetIdentitySupported: Boolean;
begin
Result := (FBrand = ibFirebird) and
(FConnectionObj.ConnectionDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata] or
(GetServerVersion >= ivFB030000));
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetIdentityInsertSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetInlineRefresh: Boolean;
begin
Result := (FBrand = ibFirebird) and (GetServerVersion >= ivFB020100);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
if (FBrand = ibFirebird) or
(FBrand = ibInterbase) and (GetServerVersion >= ivIB120100) then
Result := [soInlineView]
else
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetLockNoWait: Boolean;
begin
Result := True;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysIBMetadata.GetAsyncAbortSupported: Boolean;
begin
Result :=
(FBrand = ibInterbase) and (GetServerVersion >= ivIB070000) or
(FBrand = ibFirebird) and (GetServerVersion >= ivFB020500);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetLineSeparator: TFDTextEndOfLine;
begin
Result := elPosix;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
if (FBrand = ibFirebird) and (GetServerVersion >= ivFB020100) then
Result := dvDefVals
else
Result := dvNone;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetArrayExecMode: TFDPhysArrayExecMode;
begin
if (FBrand = ibFirebird) and (GetServerVersion >= ivFB020100) then
Result := aeOnErrorUndoAll
else
Result := aeUpToFirstError;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetLimitOptions: TFDPhysLimitOptions;
begin
if (FBrand in [ibFirebird, ibYaffil]) and (GetServerVersion >= ivFB020000) or
(FBrand = ibInterbase) then
Result := [loSkip, loRows]
else
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetNullLocations: TFDPhysNullLocations;
begin
case FBrand of
ibYaffil:
Result := [nlAscLast, nlDescLast];
ibFirebird:
if GetServerVersion < ivFB020000 then
Result := [nlAscLast, nlDescLast]
else
Result := [nlAscFirst, nlDescLast];
ibInterbase:
if GetServerVersion < ivIB070500 then
Result := [nlAscLast, nlDescLast]
else
Result := [nlAscFirst, nlDescLast];
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetBrand: TFDPhysIBBrand;
begin
Result := FBrand;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetDialect: Integer;
begin
Result := FDialect;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysIBMetadata.DefineMetadataStructure(ATable: TFDDatSTable;
AKind: TFDPhysMetaInfoKind);
begin
inherited DefineMetadataStructure(ATable, AKind);
case AKind of
mkResultSetFields:
begin
AddMetadataCol(ATable, 'TABLE_NAME', dtWideString);
AddMetadataCol(ATable, 'COLUMN_NAME', dtWideString);
AddMetadataCol(ATable, 'DOMAIN_NAME', dtWideString);
AddMetadataCol(ATable, 'IN_PKEY', dtInt16);
AddMetadataCol(ATable, 'GENERATOR_NAME', dtWideString);
AddMetadataCol(ATable, 'ISCOMPUTED', dtInt16);
AddMetadataCol(ATable, 'HASDEFAULT', dtInt16);
if (FBrand = ibFirebird) and (GetServerVersion >= ivFB030000) then
AddMetadataCol(ATable, 'IDENT_TYPE', dtInt16);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.GetResultSetFields(const ASQLKey: String): TFDDatSView;
begin
Result := inherited GetResultSetFields(ASQLKey);
Result.Mechanisms.AddSort('TABLE_NAME;COLUMN_NAME');
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.InternalEscapeBoolean(const AStr: String): String;
begin
if CompareText(AStr, S_FD_True) = 0 then
Result := '1'
else
Result := '0';
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.InternalEscapeDate(const AStr: String): String;
begin
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS DATE)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS TIMESTAMP)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.InternalEscapeTime(const AStr: String): String;
begin
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS TIME)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.InternalEscapeFloat(const AStr: String): String;
begin
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS NUMERIC(18,6))';
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String;
var
sName, A1, A2, A3, A4: String;
function AddArgs: string;
begin
Result := '(';
if Length(ASeq.FArgs) > 0 then
Result := Result + AddEscapeSequenceArgs(ASeq);
Result := Result + ')';
end;
procedure DoFB21;
var
i: Integer;
begin
case ASeq.FFunc of
// numeric
efDEGREES: Result := '(180 * (' + A1 + ') / PI())';
efLOG: Result := 'LN' + AddArgs;
efRADIANS: Result := '((' + A1 + ') / 180 * PI())';
efRANDOM:
begin
Result := 'RAND()';
if Length(ASeq.FArgs) = 1 then
Result := '(' + Result + ' * (' + A1 + '))';
end;
efROUND:
begin
Result := sName + '(' + A1;
if Length(ASeq.FArgs) = 1 then
Result := Result + ', 0'
else
Result := Result + ', ' + A2;
Result := Result + ')';
end;
efTRUNCATE: Result := 'TRUNC' + AddArgs;
efABS,
efACOS,
efASIN,
efATAN,
efATAN2,
efCEILING,
efCOS,
efCOT,
efEXP,
efFLOOR,
efLOG10,
efMOD,
efPI,
efPOWER,
efSIGN,
efSIN,
efSQRT,
efTAN: Result := sName + AddArgs;
// character
efASCII: Result := 'ASCII_VAL' + AddArgs;
efCHAR: Result := 'ASCII_CHAR' + AddArgs;
efCONCAT: Result := '(' + A1 + ' || ' + A2 + ')';
efINSERT: Result := '(SUBSTRING(' + A1 + ' FROM 1 FOR (' + A2 + ') - 1) || ' + A4 +
' || SUBSTRING(' + A1 + ' FROM (' + A2 + ' + ' + A3 + ')))';
efLCASE: Result := 'LOWER' + AddArgs;
efLENGTH: Result := 'CHAR_LENGTH(' + A1 + ')';
efLOCATE,
efPOSITION:
begin
if Length(ASeq.FArgs) >= 3 then
UnsupportedEscape(ASeq);
Result := 'POSITION(' + A1 + ' IN ' + A2 + ')';
end;
efLTRIM: Result := 'TRIM(LEADING '' '' FROM ' + A1 + ')';
efREPEAT: Result := 'RPAD(' + A1 + ', (' + A2 + ') * CHAR_LENGTH(' + A1 + '), ' + A1 + ')';
efRTRIM: Result := 'TRIM(TRAILING '' '' FROM ' + A1 + ')';
efSPACE: Result := 'RPAD('' '', ' + A1 + ')';
efUCASE: Result := 'UPPER' + AddArgs;
efBIT_LENGTH,
efCHAR_LENGTH,
efLEFT,
efOCTET_LENGTH,
efREPLACE,
efRIGHT: Result := sName + AddArgs;
efSUBSTRING:
begin
Result := sName + '(' + A1 + ' FROM ' + A2;
if Length(ASeq.FArgs) >= 3 then
Result := Result + ' FOR ' + A3;
Result := Result + ')';
end;
// system
efCATALOG: Result := '''''';
efSCHEMA: Result := '''''';
efIFNULL: Result := 'COALESCE(' + A1 + ', ' + A2 + ')';
efIF: Result := 'IIF' + AddArgs;
efDECODE: Result := sName + AddArgs;
// convert
efCONVERT:
begin
A2 := UpperCase(Trim(A2));
if A2 = 'DATETIME' then
A2 := 'TIMESTAMP'
else if Copy(A2, 1, 9) = 'VARBINARY' then
A2 := 'VARCHAR' + Copy(A2, 10, MAXINT) + ' CHARACTER SET OCTETS'
else if Copy(A2, 1, 6) = 'BINARY' then
A2 := 'CHAR' + Copy(A2, 7, MAXINT) + ' CHARACTER SET OCTETS';
Result := 'CAST(' + A1 + ' AS ' + A2 + ')';
end;
// date and time
efCURDATE: Result := 'CURRENT_DATE';
efCURTIME: Result := 'CURRENT_TIME';
efNOW: Result := 'CURRENT_TIMESTAMP';
efDAYNAME:
begin
Result := 'TRIM(TRAILING FROM CASE EXTRACT(WEEKDAY FROM ' + A1 + ')';
for i := 1 to 7 do
Result := Result + ' WHEN ' + IntToStr(i - 1) + ' THEN ''' +
AnsiUpperCase(FormatSettings.LongDayNames[i]) + '''';
Result := Result + ' END)';
end;
efDAYOFMONTH: Result := 'EXTRACT(DAY FROM ' + A1 + ')';
efDAYOFWEEK: Result := '(EXTRACT(WEEKDAY FROM ' + A1 + ') + 1)';
efDAYOFYEAR: Result := '(EXTRACT(YEARDAY FROM ' + A1 + ') + 1)';
efEXTRACT: Result := sName + '(' + FDUnquote(A1, '''') + ' FROM ' + A2 + ')';
efHOUR: Result := 'EXTRACT(HOUR FROM ' + A1 + ')';
efMINUTE: Result := 'EXTRACT(MINUTE FROM ' + A1 + ')';
efMONTH: Result := 'EXTRACT(MONTH FROM ' + A1 + ')';
efMONTHNAME:
begin
Result := 'TRIM(TRAILING FROM CASE EXTRACT(MONTH FROM ' + A1 + ')';
for i := 1 to 12 do
Result := Result + ' WHEN ' + IntToStr(i) + ' THEN ''' +
AnsiUpperCase(FormatSettings.LongMonthNames[i]) + '''';
Result := Result + ' END)';
end;
efQUARTER: Result := '(TRUNC((EXTRACT(MONTH FROM ' + A1 + ') - 1) / 3) + 1)';
efSECOND: Result := 'EXTRACT(SECOND FROM ' + A1 + ')';
efTIMESTAMPADD:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'FRAC_SECOND' then
Result := 'DATEADD(MILLISECOND, (' + A2 + ') / 1000, ' + A3 + ')'
else if A1 = 'WEEK' then
Result := 'DATEADD(DAY, 7 * (' + A2 + '), ' + A3 + ')'
else if A1 = 'QUARTER' then
Result := 'DATEADD(MONTH, 3 * (' + A2 + '), ' + A3 + ')'
else
Result := 'DATEADD(' + A1 + ', ' + A2 + ', ' + A3 + ')';
end;
efTIMESTAMPDIFF:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'FRAC_SECOND' then
Result := 'TRUNC(DATEDIFF(MILLISECOND, ' + A2 + ', ' + A3 + ') * 1000)'
else if A1 = 'WEEK' then
Result := 'TRUNC(DATEDIFF(DAY, ' + A2 + ', ' + A3 + ') / 7)'
else if A1 = 'QUARTER' then
Result := 'TRUNC(DATEDIFF(MONTH, ' + A2 + ', ' + A3 + ') / 3)'
else
Result := 'DATEDIFF(' + A1 + ', ' + A2 + ', ' + A3 + ')';
end;
efWEEK: Result := 'TRUNC((EXTRACT(YEARDAY FROM ' + A1 +
') - EXTRACT(WEEKDAY FROM ' + A1 + ' - 1) + 7) / 7) + 1';
efYEAR: Result := 'EXTRACT(YEAR FROM ' + A1 + ')';
else
UnsupportedEscape(ASeq);
end;
end;
procedure DoIB;
var
i: Integer;
s1, s2: String;
begin
case ASeq.FFunc of
// numeric
efDEGREES: Result := '(180 * (' + A1 + ') / PI())';
efLOG: Result := 'LN' + AddArgs;
efRADIANS: Result := '((' + A1 + ') / 180 * PI())';
efRANDOM: Result := 'RAND';
efROUND: Result := 'CASE WHEN ABS(CEILING(' + A1 + ') - FLOOR(' + A1 + ')) <= 0.5 THEN FLOOR(' + A1 + ') ELSE CEILING(' + A1 + ') END';
efTRUNCATE: Result := 'FLOOR' + AddArgs;
efABS,
efACOS,
efASIN,
efATAN,
efATAN2,
efCEILING,
efCOS,
efCOT,
efFLOOR,
efLOG10,
efMOD,
efPI,
efSIGN,
efSIN,
efSQRT,
efTAN: Result := sName + AddArgs;
// character
efASCII: Result := 'ASCII_VAL' + AddArgs;
efBIT_LENGTH: Result := '(STRLEN(' + A1 + ') * 8)';
efCHAR: Result := 'ASCII_CHAR' + AddArgs;
efCONCAT: Result := '(' + A1 + ' || ' + A2 + ')';
efINSERT:
begin
s1 := 'SUBSTR(' + A1 + ', 1, ' + A2 + ' - 1)';
s1 := 'CASE WHEN ' + s1 + ' IS NULL THEN CAST('''' AS VARCHAR(1)) ELSE ' + s1 + ' END';
s2 := 'SUBSTR(' + A1 + ', ' + A2 + ' + ' + A3 + ', STRLEN(' + A1 + '))';
s2 := 'CASE WHEN ' + s2 + ' IS NULL THEN CAST('''' AS VARCHAR(1)) ELSE ' + s2 + ' END';
Result := '(' + s1 + ' || ' + A4 + ' || ' + s2 + ')';
end;
efLCASE: Result := 'LOWER' + AddArgs;
efLEFT: Result := 'SUBSTR(' + A1 + ', 1, ' + A2 + ')';
efLENGTH,
efCHAR_LENGTH,
efOCTET_LENGTH: Result := 'STRLEN(' + A1 + ')';
efLOCATE,
efPOSITION:
begin
if Length(ASeq.FArgs) >= 3 then
UnsupportedEscape(ASeq);
Result := 'LOCATE(' + A1 + ', ' + A2 + ')';
end;
efRIGHT: Result := 'SUBSTR(' + A1 + ', STRLEN(' + A1 + ') + 1 - ' + A2 + ', STRLEN(' + A1 + '))';
efSPACE: Result := 'CAST('' '' AS NCHAR(' + A1 + '))';
efSUBSTRING: Result := 'SUBSTR(' + A1 + ', ' + A2 + ', ' + A2 + ' + ' + A3 + ' - 1)';
efLTRIM,
efRTRIM: Result := sName + AddArgs;
efUCASE: Result := 'UPPER' + AddArgs;
// system
efCATALOG: Result := '''''';
efSCHEMA: Result := '''''';
efIFNULL: Result := 'COALESCE(' + A1 + ', ' + A2 + ')';
efIF: Result := 'CASE WHEN ' + A1 + ' THEN ' + A2 + ' ELSE ' + A3 + ' END';
efDECODE:
begin
Result := 'CASE ' + ASeq.FArgs[0];
i := 1;
while i < Length(ASeq.FArgs) - 1 do begin
Result := Result + ' WHEN ' + ASeq.FArgs[i] + ' THEN ' + ASeq.FArgs[i + 1];
Inc(i, 2);
end;
if i = Length(ASeq.FArgs) - 1 then
Result := Result + ' ELSE ' + ASeq.FArgs[i];
Result := Result + ' END';
end;
// convert
efCONVERT:
begin
A2 := UpperCase(Trim(A2));
if A2 = 'DATETIME' then
A2 := 'TIMESTAMP'
else if Copy(A2, 1, 9) = 'VARBINARY' then
A2 := 'VARCHAR' + Copy(A2, 10, MAXINT) + ' CHARACTER SET OCTETS'
else if Copy(A2, 1, 6) = 'BINARY' then
A2 := 'CHAR' + Copy(A2, 7, MAXINT) + ' CHARACTER SET OCTETS';
Result := 'CAST(' + A1 + ' AS ' + A2 + ')';
end;
// date and time
efCURDATE: Result := 'CURRENT_DATE';
efCURTIME: Result := 'CURRENT_TIME';
efNOW: Result := 'CURRENT_TIMESTAMP';
efDAYNAME:
begin
Result := 'CASE EXTRACT(WEEKDAY FROM ' + A1 + ')';
for i := 1 to 7 do
Result := Result + ' WHEN ' + IntToStr(i - 1) + ' THEN ''' +
AnsiUpperCase(FormatSettings.LongDayNames[i]) + '''';
Result := Result + ' ELSE '''' END';
end;
efDAYOFMONTH: Result := 'EXTRACT(DAY FROM ' + A1 + ')';
efDAYOFWEEK: Result := '(EXTRACT(WEEKDAY FROM ' + A1 + ') + 1)';
efDAYOFYEAR: Result := '(EXTRACT(YEARDAY FROM ' + A1 + ') + 1)';
efEXTRACT: Result := sName + '(' + FDUnquote(A1, '''') + ' FROM ' + A2 + ')';
efHOUR: Result := 'EXTRACT(HOUR FROM ' + A1 + ')';
efMINUTE: Result := 'EXTRACT(MINUTE FROM ' + A1 + ')';
efMONTH: Result := 'EXTRACT(MONTH FROM ' + A1 + ')';
efMONTHNAME:
begin
Result := 'CASE EXTRACT(MONTH FROM ' + A1 + ')';
for i := 1 to 12 do
Result := Result + ' WHEN ' + IntToStr(i) + ' THEN ''' +
AnsiUpperCase(FormatSettings.LongMonthNames[i]) + '''';
Result := Result + ' ELSE '''' END';
end;
efQUARTER: Result := '(FLOOR((EXTRACT(MONTH FROM ' + A1 + ') - 1) / 3) + 1)';
efSECOND: Result := 'EXTRACT(SECOND FROM ' + A1 + ')';
efTIMESTAMPADD:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'WEEK' then
Result := '(' + A3 + ' + 7 * (' + A2 + '))'
else if A1 = 'DAY' then
Result := '(' + A3 + ' + ' + A2 + ')'
else if A1 = 'HOUR' then
Result := '(' + A3 + ' + (' + A2 + ') / 24.0)'
else if A1 = 'MINUTE' then
Result := '(' + A3 + ' + (' + A2 + ') / (24.0 * 60.0))'
else if A1 = 'SECOND' then
Result := '(' + A3 + ' + (' + A2 + ') / (24.0 * 60.0 * 60.0))'
else if A1 = 'FRAC_SECOND' then
Result := '(' + A3 + ' + (' + A2 + ') / (24.0 * 60.0 * 60.0 * 1000000))'
else
// YEAR, MONTH
UnsupportedEscape(ASeq);
end;
efTIMESTAMPDIFF:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'WEEK' then
Result := 'FLOOR(((' + A3 + ') - (' + A2 + ')) / 7)'
else if A1 = 'DAY' then
Result := 'FLOOR((' + A3 + ') - (' + A2 + '))'
else if A1 = 'HOUR' then
Result := 'FLOOR(((' + A3 + ') - (' + A2 + ')) * 24.0)'
else if A1 = 'MINUTE' then
Result := 'FLOOR(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0))'
else if A1 = 'SECOND' then
Result := 'FLOOR(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0 * 60.0))'
else if A1 = 'FRAC_SECOND' then
Result := 'FLOOR(((' + A3 + ') - (' + A2 + ')) * (24.0 * 60.0 * 60.0 * 1000000.0))'
else
// YEAR, MONTH
UnsupportedEscape(ASeq);
end;
efWEEK: Result := 'FLOOR((EXTRACT(YEARDAY FROM ' + A1 +
') - EXTRACT(WEEKDAY FROM ' + A1 + ' - 1) + 7) / 7) + 1';
efYEAR: Result := 'EXTRACT(YEAR FROM ' + A1 + ')';
else
// Numeric: efEXP, efPOWER
// String: efREPEAT, efREPLACE
UnsupportedEscape(ASeq);
end;
end;
begin
sName := ASeq.FName;
if Length(ASeq.FArgs) >= 1 then begin
A1 := ASeq.FArgs[0];
if Length(ASeq.FArgs) >= 2 then begin
A2 := ASeq.FArgs[1];
if Length(ASeq.FArgs) >= 3 then begin
A3 := ASeq.FArgs[2];
if Length(ASeq.FArgs) >= 4 then
A4 := ASeq.FArgs[3];
end;
end;
end;
if (FBrand = ibFirebird) and (GetServerVersion >= ivFB020100) then
DoFB21
else
DoIB;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBMetadata.InternalGetSQLCommandKind(
const ATokens: TStrings): TFDPhysCommandKind;
var
sToken: String;
begin
sToken := ATokens[0];
if sToken = 'EXECUTE' then
Result := skExecute
else if sToken = 'SET' then
if ATokens.Count = 1 then
Result := skNotResolved
else if ATokens[1] = 'TRANSACTION' then
Result := skStartTransaction
else
Result := skSet
else if sToken = 'DECLARE' then
Result := skCreate
else if sToken = 'UPDATE' then
if ATokens.Count < 3 then
Result := skNotResolved
else if (ATokens[1] = 'OR') and (ATokens[2] = 'INSERT') then
Result := skMerge
else
Result := skUpdate
else
Result := inherited InternalGetSQLCommandKind(ATokens);
if (Result in [skInsert, skMerge, skUpdate, skDelete]) and (ATokens.Count = 2) and
(ATokens[1] = 'RETURNING') then
Result := skSelectForLock;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysIBCommandGenerator }
{-------------------------------------------------------------------------------}
constructor TFDPhysIBCommandGenerator.Create(const ACommand: IFDPhysCommand;
AIDUTF8: Integer; AEncoding: TFDEncoding);
begin
inherited Create(ACommand);
FIDUTF8 := AIDUTF8;
FEncoding := AEncoding;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysIBCommandGenerator.Create(const AConnection: IFDPhysConnection;
AIDUTF8: Integer; AEncoding: TFDEncoding);
begin
inherited Create(AConnection);
FIDUTF8 := AIDUTF8;
FEncoding := AEncoding;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String;
var
sRet: String;
begin
Result := AStmt;
sRet := GetReturning(ARequest, False);
if sRet <> '' then begin
Result := Result + sRet;
FCommandKind := skSelectForLock;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetPessimisticLock: String;
var
lNeedFrom: Boolean;
oIBConnMeta: IFDPhysIBConnectionMetadata;
begin
lNeedFrom := False;
Result := 'SELECT ' + GetSelectList(True, False, lNeedFrom) + BRK +
'FROM ' + GetFrom + BRK + 'WHERE ' + GetWhere(False, True, False) + BRK +
'FOR UPDATE';
Supports(FConnMeta, IFDPhysIBConnectionMetadata, oIBConnMeta);
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB010500) then
Result := Result + ' WITH LOCK';
FCommandKind := skSelectForLock;
ASSERT(lNeedFrom);
// WAIT / NOWAIT is controlled through transaction
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetSavepoint(const AName: String): String;
begin
Result := 'SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetRollbackToSavepoint(const AName: String): String;
begin
Result := 'ROLLBACK TO SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetCommitSavepoint(const AName: String): String;
begin
Result := 'RELEASE SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetReadGenerator(const AName, AAlias: String;
ANextValue, AFullSelect: Boolean): String;
begin
if ANextValue then
Result := 'GEN_ID(' + AName + ', 1)'
else
Result := 'GEN_ID(' + AName + ', 0)';
if AAlias <> '' then
Result := Result + ' ' + AAlias;
if AFullSelect then
Result := 'SELECT ' + Result + BRK + 'FROM ' + GetSingleRowTable;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetSingleRowTable: String;
begin
Result := 'RDB$DATABASE';
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetRowId(var AAlias: String): String;
begin
Result := 'RDB$DB_KEY';
AAlias := 'DB_KEY';
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetCall(const AName: String): String;
begin
Result := 'EXECUTE PROCEDURE ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetStoredProcCall(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
var
i: Integer;
sInPar: String;
oParam: TFDParam;
lHasOutput: Boolean;
lIsFunc: Boolean;
rName: TFDPhysParsedName;
sProc: String;
begin
sInPar := '';
lHasOutput := False;
lIsFunc := False;
if FParams.Count > 0 then begin
for i := 0 to FParams.Count - 1 do begin
oParam := FParams[i];
if oParam.ParamType in [ptUnknown, ptInput, ptInputOutput] then begin
if sInPar <> '' then
sInPar := sInPar + ', ';
sInPar := sInPar + '?';
end;
if oParam.ParamType in [ptOutput, ptInputOutput, ptResult] then
lHasOutput := True;
if oParam.ParamType = ptResult then
lIsFunc := True;
end;
end;
if FCommandKind = skStoredProc then
if (ASPUsage = skStoredProcWithCrs) and lHasOutput then
FCommandKind := skStoredProcWithCrs
else
FCommandKind := skStoredProcNoCrs;
rName.FCatalog := ACatalog;
rName.FSchema := ASchema;
rName.FBaseObject := APackage;
rName.FObject := AProc;
sProc := FConnMeta.EncodeObjName(rName, FCommand, [eoQuote, eoNormalize]);
if lIsFunc then begin
Result := 'SELECT ' + sProc;
if sInPar <> '' then
Result := Result + '(' + sInPar + ')';
Result := Result + ' AS Result FROM RDB$DATABASE';
end
else if FCommandKind = skStoredProcWithCrs then begin
Result := 'SELECT * FROM ' + sProc;
if sInPar <> '' then
Result := Result + '(' + sInPar + ')';
end
else begin
Result := 'EXECUTE PROCEDURE ' + sProc;
if sInPar <> '' then begin
Result := Result + ' ' + sInPar;
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String;
var
lWasWhere: Boolean;
sScope, sKinds: String;
oIBConnMeta: IFDPhysIBConnectionMetadata;
function NVL(const AField, AValue: String; AIntField: Boolean): String;
begin
if (oIBConnMeta.Brand = ibInterbase) and ((FConnMeta.ServerVersion < ivIB070500) or not AIntField) then
Result := AField
else
Result := 'COALESCE(' + AField + ', ' + AValue + ')';
end;
procedure AddWhere(const ACond: String; const AParam: String = '');
var
oParam: TFDParam;
begin
if lWasWhere then
Result := Result + ' AND ' + ACond
else begin
Result := Result + ' WHERE ' + ACond;
lWasWhere := True;
end;
if AParam <> '' then begin
oParam := GetParams.Add;
oParam.Name := AParam;
oParam.DataType := ftString;
oParam.Size := 70;
end;
end;
procedure AddTopScope(AWithOwner: Boolean);
begin
if AObjectScopes <> [osMy, osSystem, osOther] then begin
sScope := '';
if osMy in AObjectScopes then begin
sScope := sScope + '(RDB$SYSTEM_FLAG IS NULL OR RDB$SYSTEM_FLAG = 0) ';
if AWithOwner then
sScope := sScope + 'AND ' + NVL('RDB$OWNER_NAME', '''''', False) + ' = USER ';
sScope := sScope + 'OR ';
end;
if osSystem in AObjectScopes then
sScope := sScope + '(RDB$SYSTEM_FLAG IS NOT NULL AND RDB$SYSTEM_FLAG > 0) OR ';
if (osOther in AObjectScopes) and (AWithOwner or not (osMy in AObjectScopes)) then begin
sScope := sScope + '(RDB$SYSTEM_FLAG IS NULL OR RDB$SYSTEM_FLAG = 0) ';
if AWithOwner then
sScope := sScope + 'AND ' + NVL('RDB$OWNER_NAME', '''''', False) + ' <> USER ';
sScope := sScope + 'OR ';
end;
if sScope <> '' then
AddWhere('(' + Copy(sScope, 1, Length(sScope) - 4) + ')');
end;
end;
function EncodeDataType(const AField, ASubField, AScaleField, ACharsetField,
ADomainField: String): String;
function DT2Str(AType: TFDDataType): String;
begin
Result := IntToStr(Integer(AType));
end;
function EncodeScale(AType: TFDDataType; ACurrency: Boolean): String;
begin
if ACurrency then
Result :=
'CASE' +
' WHEN ' + AScaleField + ' < -4 THEN ' + DT2Str(dtFmtBCD) +
' WHEN ' + AScaleField + ' < 0 THEN ' + DT2Str(dtBCD) +
' ELSE ' + DT2Str(AType) +
' END'
else
Result :=
'CASE' +
' WHEN ' + AScaleField + ' < 0 THEN ' + DT2Str(dtFmtBCD) +
' ELSE ' + DT2Str(AType) +
' END';
end;
function EncodeStrType: String;
begin
Result :=
'CASE ' + ACharsetField +
' WHEN ' + IntToStr(csIDNone) + ' THEN ' + DT2Str(dtAnsiString) +
' WHEN ' + IntToStr(csIDOctets) + ' THEN ' + DT2Str(dtByteString) +
' WHEN ' + IntToStr(csIDUnicodeFSS) + ' THEN ' + DT2Str(dtWideString);
if oIBConnMeta.Brand = ibInterbase then
Result := Result +
' WHEN ' + IntToStr(csIDUnicodeBE) + ' THEN ' + DT2Str(dtWideString) +
' WHEN ' + IntToStr(csIDUnicodeLE) + ' THEN ' + DT2Str(dtWideString);
if FIDUTF8 <> 0 then
Result := Result +
' WHEN ' + IntToStr(FIDUTF8) + ' THEN ' + DT2Str(dtWideString);
Result := Result +
' ELSE ' + DT2Str(dtAnsiString) +
' END';
end;
begin
Result :=
'CASE WHEN ' + ADomainField + ' LIKE ''%BOOL%'' THEN ' + DT2Str(dtBoolean) +
' ELSE ' +
'CASE ' + AField +
' WHEN 7 THEN ' + EncodeScale(dtInt16, True) +
' WHEN 8 THEN ' + EncodeScale(dtInt32, True) +
' WHEN 9 THEN ' + EncodeScale(dtInt64, False) +
' WHEN 10 THEN ' + DT2Str(dtSingle) +
' WHEN 11 THEN ' + DT2Str(dtDouble) +
' WHEN 12 THEN ' + DT2Str(dtDate) +
' WHEN 13 THEN ' + DT2Str(dtTime) +
' WHEN 14 THEN ' + EncodeStrType() +
' WHEN 16 THEN ' + EncodeScale(dtInt64, False) +
' WHEN 17 THEN ' + DT2Str(dtBoolean) +
' WHEN 23 THEN ' + DT2Str(dtBoolean) +
' WHEN 27 THEN ' + DT2Str(dtDouble) +
' WHEN 35 THEN ' + DT2Str(dtDateTimeStamp) +
' WHEN 37 THEN ' + EncodeStrType() +
' WHEN 40 THEN ' + EncodeStrType() +
' WHEN 45 THEN ' + DT2Str(dtBlob) +
' WHEN 261 THEN ' +
'CASE ' + ASubField;
if FEncoding = ecUTF8 then
Result := Result +
' WHEN 1 THEN ' + DT2Str(dtWideMemo)
else
Result := Result +
' WHEN 1 THEN ' + DT2Str(dtMemo);
Result := Result +
' ELSE ' + DT2Str(dtBlob) +
' END ' +
' ELSE ' + DT2Str(dtUnknown) +
' END' +
' END';
end;
function EncodeTypeName(const AField, ASubField, AScaleField, ADomainField,
AIdentField: String): String;
function EncodeNumType(const AIntType: String): String;
begin
Result :=
'CASE' +
' WHEN ' + AScaleField + ' = 0 THEN ''' + AIntType + '''' +
' WHEN ' + AScaleField + ' < 0 THEN ''DECIMAL''' +
' END';
end;
begin
Result :=
'CASE WHEN ' + ADomainField + ' LIKE ''%BOOL%'' THEN ''BOOLEAN''' +
' ELSE ' +
'CASE ' + AField +
' WHEN 7 THEN ' + EncodeNumType('SMALLINT') +
' WHEN 8 THEN ' + EncodeNumType('INTEGER') +
' WHEN 9 THEN ' + EncodeNumType('NUMERIC') +
' WHEN 10 THEN ''FLOAT''' +
' WHEN 11 THEN ''DOUBLE PRECISION''' +
' WHEN 12 THEN ''DATE''' +
' WHEN 13 THEN ''TIME''' +
' WHEN 14 THEN ''CHAR''' +
' WHEN 16 THEN ''NUMERIC''' +
' WHEN 17 THEN ''BOOLEAN''' +
' WHEN 23 THEN ''BOOLEAN''' +
' WHEN 27 THEN ''DOUBLE PRECISION''' +
' WHEN 35 THEN ''TIMESTAMP''' +
' WHEN 37 THEN ''VARCHAR''' +
' WHEN 40 THEN ''VARCHAR''' +
' WHEN 45 THEN ''BLOB''' +
' WHEN 261 THEN ''BLOB SUB_TYPE '' || CAST(' + ASubField + ' AS INTEGER)' +
' END' +
' END';
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then begin
if AIdentField <> '' then
Result := Result +
' || CASE' +
' WHEN ' + AIdentField + ' >= 1 THEN '' GENERATED BY DEFAULT AS IDENTITY''' +
' ELSE ''''' +
' END';
Result := 'TRIM(TRAILING '' '' FROM ' + Result + ')';
end;
end;
function EncodeScope(const ASysFlagName, AOwnerName: String): String;
begin
Result :=
'CASE ' + ASysFlagName;
if (oIBConnMeta.Brand = ibInterbase) or (AOwnerName = '') then
Result := Result +
' WHEN 0 THEN ' + IntToStr(Integer(osMy)) +
' ELSE ' + IntToStr(Integer(osSystem))
else
Result := Result +
' WHEN 0 THEN ' +
'CASE ' + AOwnerName +
' WHEN USER THEN ' + IntToStr(Integer(osMy)) +
' ELSE ' + IntToStr(Integer(osOther)) +
' END' +
' ELSE ' + IntToStr(Integer(osSystem));
Result := Result +
' END';
end;
function EncodeAttrs(const ATypeFieldName, ACompFieldName, ADefFieldName,
ANullFieldName, AIdentField: String): String;
function Attrs2Str(AAttrs: TFDDataAttributes): String;
begin
if AKind <> mkTableFields then
Exclude(AAttrs, caBase);
Result := IntToStr(PWord(@AAttrs)^);
end;
begin
Result :=
'(CASE ' + ATypeFieldName +
' WHEN 7 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 8 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 9 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 10 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 11 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 12 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 13 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 14 THEN ' + Attrs2Str([caBase, caSearchable, caFixedLen]) +
' WHEN 16 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 17 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 23 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 27 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 35 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 37 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 40 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 45 THEN ' + Attrs2Str([caBase, caSearchable]) +
' WHEN 261 THEN ' + Attrs2Str([caBase, caBlobData]) +
' END + ' +
'CASE ' +
' WHEN ' + ACompFieldName + ' IS NOT NULL THEN ' + Attrs2Str([caCalculated, caReadOnly]) +
' ELSE 0' +
' END + ' +
'CASE ' +
' WHEN ' + ADefFieldName + ' IS NOT NULL THEN ' + Attrs2Str([caDefault]) +
' ELSE 0' +
' END + ' +
'CASE ' +
' WHEN ' + ANullFieldName + ' IS NULL THEN ' + Attrs2Str([caAllowNull]) +
' ELSE 0' +
' END';
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) and
(AIdentField <> '') then
Result := Result +
' + CASE' +
' WHEN ' + AIdentField + ' >= 1 THEN ' + Attrs2Str([caAutoInc]) +
' ELSE 0' +
' END';
Result := Result + ')';
end;
function EncodeRTrim(const AValue: String): String;
begin
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB020100) then
Result := 'TRIM(TRAILING '' '' FROM ' + AValue + ')'
else
Result := 'RTRIM(' + AValue + ')';
end;
function EncodeTabFlags(const AValue: String): String;
begin
Result := NVL(AValue, '0', True);
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB020100) then
Result := 'BIN_AND(' + Result + ', 31)'
else if oIBConnMeta.Brand = ibInterbase then
Result :=
'CASE' +
' WHEN ' + Result + ' >= 32 THEN 1' +
' ELSE ' + Result +
' END';
end;
begin
Result := '';
lWasWhere := False;
Supports(FConnMeta, IFDPhysIBConnectionMetadata, oIBConnMeta);
case AKind of
mkCatalogs:
;
mkSchemas:
;
mkTables:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'RDB$RELATION_NAME AS TABLE_NAME, ';
if (oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion < ivIB070500) then
Result := Result +
'RDB$VIEW_BLR AS TABLE_TYPE, ' +
'RDB$SYSTEM_FLAG AS TABLE_SCOPE '
else
Result := Result +
'CASE' +
' WHEN RDB$VIEW_BLR IS NULL THEN ' +
'CASE ' + EncodeTabFlags('RDB$FLAGS') +
' WHEN 0 THEN ' + IntToStr(Integer(tkTable)) +
' WHEN 1 THEN ' + IntToStr(Integer(tkTable)) +
' WHEN 2 THEN ' + IntToStr(Integer(tkTempTable)) +
' WHEN 8 THEN ' + IntToStr(Integer(tkTempTable)) +
' WHEN 16 THEN ' + IntToStr(Integer(tkTempTable)) +
' END' +
' ELSE ' + IntToStr(Integer(tkView)) +
' END AS TABLE_TYPE, ' +
EncodeScope(NVL('RDB$SYSTEM_FLAG', '0', True), NVL('RDB$OWNER_NAME', '''''', False)) + ' AS TABLE_SCOPE ';
Result := Result +
'FROM RDB$RELATIONS';
sKinds := '';
if tkTable in ATableKinds then
sKinds := sKinds + EncodeTabFlags('RDB$FLAGS') + ' IN (0, 1) AND RDB$VIEW_BLR IS NULL OR ';
if tkView in ATableKinds then
sKinds := sKinds + 'RDB$VIEW_BLR IS NOT NULL OR ';
if tkTempTable in ATableKinds then
sKinds := sKinds + EncodeTabFlags('RDB$FLAGS') + ' IN (2, 8, 16) AND RDB$VIEW_BLR IS NULL OR ';
if sKinds <> '' then
AddWhere('(' + Copy(sKinds, 1, Length(sKinds) - 4) + ')');
if AWildcard <> '' then
AddWhere(EncodeRTrim('RDB$RELATION_NAME') + ' LIKE ?', 'WIL');
AddTopScope(True);
Result := Result + ' ORDER BY 4';
end;
mkTableFields:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'RF.RDB$RELATION_NAME AS TABLE_NAME, ' +
'RF.RDB$FIELD_NAME AS COLUMN_NAME, ' +
'RF.RDB$FIELD_POSITION + 1 AS COLUMN_POSITION, ';
if (oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion < ivIB070500) then
Result := Result +
'F.RDB$FIELD_TYPE AS COLUMN_DATATYPE, ' +
''''' AS COLUMN_TYPENAME, ' +
'1 AS COLUMN_ATTRIBUTES, '
else
Result := Result +
EncodeDataType('F.RDB$FIELD_TYPE', 'F.RDB$FIELD_SUB_TYPE', 'F.RDB$FIELD_SCALE',
'F.RDB$CHARACTER_SET_ID', 'RF.RDB$FIELD_SOURCE') + ' AS COLUMN_DATATYPE, ' +
EncodeTypeName('F.RDB$FIELD_TYPE', 'F.RDB$FIELD_SUB_TYPE', 'F.RDB$FIELD_SCALE',
'RF.RDB$FIELD_SOURCE', 'RF.RDB$IDENTITY_TYPE') + ' AS COLUMN_TYPENAME, ' +
EncodeAttrs('F.RDB$FIELD_TYPE', 'F.RDB$COMPUTED_BLR', 'RF.RDB$DEFAULT_VALUE',
'RF.RDB$NULL_FLAG', 'RF.RDB$IDENTITY_TYPE') + ' AS COLUMN_ATTRIBUTES, ';
Result := Result +
'F.RDB$FIELD_PRECISION AS COLUMN_PRECISION, ' +
'- F.RDB$FIELD_SCALE AS COLUMN_SCALE, ' +
'F.RDB$CHARACTER_LENGTH AS COLUMN_LENGTH ' +
'FROM RDB$RELATION_FIELDS RF LEFT JOIN RDB$FIELDS F ON RF.RDB$FIELD_SOURCE = F.RDB$FIELD_NAME';
AddWhere('RF.RDB$RELATION_NAME = ?', 'OBJ');
if AWildcard <> '' then
AddWhere(EncodeRTrim('RF.RDB$FIELD_NAME') + ' LIKE ?', 'WIL');
Result := Result + ' ORDER BY 6';
end;
mkIndexes:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'I.RDB$RELATION_NAME AS TABLE_NAME, ' +
'I.RDB$INDEX_NAME AS INDEX_NAME, ' +
'C.RDB$CONSTRAINT_NAME AS CONSTRAINT_NAME, ';
if (oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion < ivIB070500) then
Result := Result +
'I.RDB$UNIQUE_FLAG AS INDEX_TYPE '
else
Result := Result +
'CASE' +
' WHEN I.RDB$UNIQUE_FLAG IS NULL OR I.RDB$UNIQUE_FLAG = 0 THEN ' + IntToStr(Integer(ikNonUnique)) +
' WHEN I.RDB$UNIQUE_FLAG = 1 THEN ' +
'CASE ' +
' WHEN C.RDB$CONSTRAINT_TYPE = ''PRIMARY KEY'' THEN ' + IntToStr(Integer(ikPrimaryKey)) +
' ELSE ' + IntToStr(Integer(ikUnique)) +
' END' +
' END AS INDEX_TYPE ';
Result := Result +
'FROM RDB$INDICES I LEFT OUTER JOIN RDB$RELATION_CONSTRAINTS C ON ' +
' I.RDB$RELATION_NAME = C.RDB$RELATION_NAME AND I.RDB$INDEX_NAME = C.RDB$INDEX_NAME';
if (oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion < ivIB070500) then
Result := Result +
' AND C.RDB$CONSTRAINT_TYPE = ''PRIMARY KEY''';
AddWhere('I.RDB$RELATION_NAME = ?', 'OBJ');
if AWildcard <> '' then
AddWhere(EncodeRTrim('I.RDB$INDEX_NAME') + ' LIKE ?', 'WIL');
Result := Result + ' ORDER BY 7 DESC, 5 ASC';
end;
mkIndexFields:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'I.RDB$RELATION_NAME AS TABLE_NAME, ' +
'I.RDB$INDEX_NAME AS INDEX_NAME, ' +
'S.RDB$FIELD_NAME AS COLUMN_NAME, ' +
'S.RDB$FIELD_POSITION + 1 AS COLUMN_POSITION, ' +
'CASE WHEN I.RDB$INDEX_TYPE = 1 THEN ''D'' ELSE ''A'' END AS SORT_ORDER, ' +
'CAST(NULL AS VARCHAR(67)) AS FILTER_ ' +
'FROM RDB$INDICES I LEFT JOIN RDB$INDEX_SEGMENTS S ON I.RDB$INDEX_NAME = S.RDB$INDEX_NAME';
AddWhere('I.RDB$RELATION_NAME = ?', 'BAS');
AddWhere('I.RDB$INDEX_NAME = ?', 'OBJ');
if AWildcard <> '' then
AddWhere(EncodeRTrim('S.RDB$FIELD_NAME') + ' LIKE ?', 'WIL');
Result := Result + ' ORDER BY 7';
end;
mkPrimaryKey:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'RDB$RELATION_NAME AS TABLE_NAME, ' +
'RDB$INDEX_NAME AS INDEX_NAME, ' +
'RDB$CONSTRAINT_NAME AS CONSTRAINT_NAME, ' +
IntToStr(Integer(ikPrimaryKey)) + ' AS INDEX_TYPE ' +
'FROM RDB$RELATION_CONSTRAINTS';
AddWhere('RDB$CONSTRAINT_TYPE = ''PRIMARY KEY''');
AddWhere('RDB$RELATION_NAME = ?', 'OBJ');
if AWildcard <> '' then
AddWhere(EncodeRTrim('RDB$INDEX_NAME') + ' LIKE ?', 'WIL');
Result := Result + ' ORDER BY 5';
end;
mkPrimaryKeyFields:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'C.RDB$RELATION_NAME AS TABLE_NAME, ' +
'C.RDB$INDEX_NAME AS INDEX_NAME, ' +
'S.RDB$FIELD_NAME AS COLUMN_NAME, ' +
'S.RDB$FIELD_POSITION + 1 AS COLUMN_POSITION, ' +
'''A'' AS SORT_ORDER, ' +
'CAST(NULL AS VARCHAR(67)) AS FILTER_ ' +
'FROM RDB$RELATION_CONSTRAINTS C LEFT JOIN RDB$INDEX_SEGMENTS S ON C.RDB$INDEX_NAME = S.RDB$INDEX_NAME';
AddWhere('C.RDB$CONSTRAINT_TYPE = ''PRIMARY KEY''');
AddWhere('C.RDB$RELATION_NAME = ?', 'BAS');
if AWildcard <> '' then
AddWhere(EncodeRTrim('S.RDB$FIELD_NAME') + ' LIKE ?', 'WIL');
Result := Result + ' ORDER BY 7';
end;
mkForeignKeys:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'FK.RDB$RELATION_NAME AS TABLE_NAME, ' +
'FK.RDB$CONSTRAINT_NAME AS FKEY_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS PKEY_CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS PKEY_SCHEMA_NAME, ' +
'PK.RDB$RELATION_NAME AS PKEY_TABLE_NAME, ';
if (oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion < ivIB070500) then
Result := Result +
'R.RDB$DELETE_RULE AS DELETE_RULE, ' +
'R.RDB$UPDATE_RULE AS UPDATE_RULE '
else
Result := Result +
'CASE R.RDB$DELETE_RULE'+
' WHEN ''RESTRICT'' THEN ' + IntToStr(Integer(ckRestrict)) +
' WHEN ''NO ACTION'' THEN ' + IntToStr(Integer(ckNone)) +
' WHEN ''CASCADE'' THEN ' + IntToStr(Integer(ckCascade)) +
' WHEN ''SET NULL'' THEN ' + IntToStr(Integer(ckSetNull)) +
' WHEN ''SET DEFAULT'' THEN ' + IntToStr(Integer(ckSetDefault)) +
' END AS DELETE_RULE, ' +
'CASE R.RDB$UPDATE_RULE' +
' WHEN ''RESTRICT'' THEN ' + IntToStr(Integer(ckRestrict)) +
' WHEN ''NO ACTION'' THEN ' + IntToStr(Integer(ckNone)) +
' WHEN ''CASCADE'' THEN ' + IntToStr(Integer(ckCascade)) +
' WHEN ''SET NULL'' THEN ' + IntToStr(Integer(ckSetNull)) +
' WHEN ''SET DEFAULT'' THEN ' + IntToStr(Integer(ckSetDefault)) +
' END AS UPDATE_RULE ';
Result := Result +
'FROM RDB$RELATION_CONSTRAINTS FK LEFT JOIN RDB$REF_CONSTRAINTS R ON FK.RDB$CONSTRAINT_NAME = R.RDB$CONSTRAINT_NAME ' +
'LEFT JOIN RDB$RELATION_CONSTRAINTS PK ON R.RDB$CONST_NAME_UQ = PK.RDB$CONSTRAINT_NAME';
AddWhere('FK.RDB$CONSTRAINT_TYPE = ''FOREIGN KEY''');
AddWhere('FK.RDB$RELATION_NAME = ?', 'OBJ');
if AWildcard <> '' then
AddWhere(EncodeRTrim('FK.RDB$CONSTRAINT_NAME') + ' LIKE ?', 'WIL');
Result := Result + ' ORDER BY 5';
end;
mkForeignKeyFields:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'FK.RDB$RELATION_NAME AS TABLE_NAME, ' +
'FK.RDB$CONSTRAINT_NAME AS FKEY_NAME, ' +
'FK_F.RDB$FIELD_NAME AS COLUMN_NAME, ' +
'PK_F.RDB$FIELD_NAME AS PKEY_COLUMN_NAME, ' +
'FK_F.RDB$FIELD_POSITION + 1 AS COLUMN_POSITION ' +
'FROM RDB$RELATION_CONSTRAINTS FK LEFT JOIN RDB$REF_CONSTRAINTS R ON FK.RDB$CONSTRAINT_NAME = R.RDB$CONSTRAINT_NAME ' +
'LEFT JOIN RDB$RELATION_CONSTRAINTS PK ON R.RDB$CONST_NAME_UQ = PK.RDB$CONSTRAINT_NAME ' +
'LEFT JOIN RDB$INDEX_SEGMENTS FK_F ON FK.RDB$INDEX_NAME = FK_F.RDB$INDEX_NAME ' +
'LEFT JOIN RDB$INDEX_SEGMENTS PK_F ON PK.RDB$INDEX_NAME = PK_F.RDB$INDEX_NAME AND' +
' FK_F.RDB$FIELD_POSITION = PK_F.RDB$FIELD_POSITION';
AddWhere('FK.RDB$RELATION_NAME = ?', 'BAS');
AddWhere('FK.RDB$CONSTRAINT_NAME = ?', 'OBJ');
if AWildcard <> '' then
AddWhere(EncodeRTrim('FK_F.RDB$FIELD_NAME') + ' LIKE ?', 'WIL');
Result := Result + ' ORDER BY 8';
end;
mkPackages:
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'RDB$PACKAGE_NAME AS PACKAGE_NAME, ' +
EncodeScope(NVL('RDB$SYSTEM_FLAG', '0', True), NVL('RDB$OWNER_NAME', '''''', False)) + ' AS PACKAGE_SCOPE ' +
'FROM RDB$PACKAGES';
AddTopScope(True);
if AWildcard <> '' then
AddWhere(EncodeRTrim('RDB$PACKAGE_NAME') + ' LIKE ?', 'WIL');
Result := Result + ' ORDER BY 4';
end
else
Result := '';
mkProcs:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ';
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then
Result := Result +
'RDB$PACKAGE_NAME AS PACK_NAME, '
else
Result := Result +
'CAST(NULL AS VARCHAR(67)) AS PACK_NAME, ';
Result := Result +
'RDB$PROCEDURE_NAME AS PROC_NAME, ' +
'CAST(NULL AS NUMERIC) AS OVERLOAD, ' +
IntToStr(Integer(pkProcedure)) + ' AS PROC_TYPE, ';
if (oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion < ivIB070500) then
Result := Result +
'RDB$SYSTEM_FLAG AS PROC_SCOPE, '
else
Result := Result +
EncodeScope(NVL('RDB$SYSTEM_FLAG', '0', True), NVL('RDB$OWNER_NAME', '''''', False)) + ' AS PROC_SCOPE, ';
Result := Result +
'RDB$PROCEDURE_INPUTS AS IN_PARAMS, ' +
'RDB$PROCEDURE_OUTPUTS AS OUT_PARAMS ' +
'FROM RDB$PROCEDURES';
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then
if ABaseObject <> '' then
AddWhere('RDB$PACKAGE_NAME = ?', 'BAS')
else
AddWhere('RDB$PACKAGE_NAME IS NULL');
AddTopScope(True);
if AWildcard <> '' then
AddWhere(EncodeRTrim('RDB$PROCEDURE_NAME') + ' LIKE ?', 'WIL');
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then begin
lWasWhere := False;
Result := Result + ' UNION ALL ' +
'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'RDB$PACKAGE_NAME AS PACK_NAME, ' +
'RDB$FUNCTION_NAME AS PROC_NAME, ' +
'CAST(NULL AS NUMERIC) AS OVERLOAD, ' +
IntToStr(Integer(pkFunction)) + ' AS PROC_TYPE, ' +
EncodeScope(NVL('RDB$SYSTEM_FLAG', '0', True), NVL('RDB$OWNER_NAME', '''''', False)) + ' AS PROC_SCOPE, ' +
'CAST(NULL AS NUMERIC) AS IN_PARAMS, ' +
'CAST(NULL AS NUMERIC) AS OUT_PARAMS ' +
'FROM RDB$FUNCTIONS';
if ABaseObject <> '' then
AddWhere('RDB$PACKAGE_NAME = ?', 'BAS')
else
AddWhere('RDB$PACKAGE_NAME IS NULL');
AddTopScope(True);
if AWildcard <> '' then
AddWhere(EncodeRTrim('RDB$FUNCTION_NAME') + ' LIKE ?', 'WIL');
end;
Result := Result + ' ORDER BY 5';
end;
mkProcArgs:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ';
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then
Result := Result +
'P.RDB$PACKAGE_NAME AS PACK_NAME, '
else
Result := Result +
'CAST(NULL AS VARCHAR(67)) AS PACK_NAME, ';
Result := Result +
'P.RDB$PROCEDURE_NAME AS PROC_NAME, ' +
'CAST(NULL AS NUMERIC) AS OVERLOAD, ' +
'P.RDB$PARAMETER_NAME AS PARAM_NAME, ' +
'P.RDB$PARAMETER_NUMBER + 1 AS PARAM_POSITION, ' +
'P.RDB$PARAMETER_TYPE + 1 AS PARAM_TYPE, ';
if (oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion < ivIB070500) then
Result := Result +
'F.RDB$FIELD_TYPE AS PARAM_DATATYPE, ' +
''''' AS PARAM_TYPENAME, ' +
'1 AS PARAM_ATTRIBUTES, '
else
Result := Result +
EncodeDataType('F.RDB$FIELD_TYPE', 'F.RDB$FIELD_SUB_TYPE', 'F.RDB$FIELD_SCALE',
'F.RDB$CHARACTER_SET_ID', 'P.RDB$FIELD_SOURCE') + ' AS PARAM_DATATYPE, ' +
EncodeTypeName('F.RDB$FIELD_TYPE', 'F.RDB$FIELD_SUB_TYPE', 'F.RDB$FIELD_SCALE',
'P.RDB$FIELD_SOURCE', '') + ' AS PARAM_TYPENAME, ' +
EncodeAttrs('F.RDB$FIELD_TYPE', 'F.RDB$COMPUTED_SOURCE', 'F.RDB$DEFAULT_SOURCE',
'F.RDB$NULL_FLAG', '') + ' AS PARAM_ATTRIBUTES, ';
Result := Result +
'F.RDB$FIELD_PRECISION AS PARAM_PRECISION, ' +
'- F.RDB$FIELD_SCALE AS PARAM_SCALE, ' +
'F.RDB$CHARACTER_LENGTH AS PARAM_LENGTH ' +
'FROM RDB$PROCEDURE_PARAMETERS P LEFT JOIN RDB$FIELDS F ON P.RDB$FIELD_SOURCE = F.RDB$FIELD_NAME';
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then
if ABaseObject <> '' then
AddWhere('P.RDB$PACKAGE_NAME = ?', 'BAS')
else
AddWhere('P.RDB$PACKAGE_NAME IS NULL');
AddWhere('P.RDB$PROCEDURE_NAME = ?', 'OBJ');
if AWildcard <> '' then
AddWhere(EncodeRTrim('P.RDB$PARAMETER_NAME') + ' LIKE ?', 'WIL');
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then begin
lWasWhere := False;
Result := Result + ' UNION ALL ' +
'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'P.RDB$PACKAGE_NAME AS PACK_NAME, ' +
'P.RDB$FUNCTION_NAME AS PROC_NAME, ' +
'CAST(NULL AS NUMERIC) AS OVERLOAD, ' +
'CASE WHEN P.RDB$ARGUMENT_POSITION = 0 THEN ''Result'' ELSE P.RDB$ARGUMENT_NAME END AS PARAM_NAME, ' +
'P.RDB$ARGUMENT_POSITION + 1 AS PARAM_POSITION, ' +
'CASE WHEN P.RDB$ARGUMENT_POSITION = 0 THEN 4 ELSE 1 END AS PARAM_TYPE, ' +
EncodeDataType('F.RDB$FIELD_TYPE', 'F.RDB$FIELD_SUB_TYPE', 'F.RDB$FIELD_SCALE',
'F.RDB$CHARACTER_SET_ID', 'P.RDB$FIELD_SOURCE') + ' AS PARAM_DATATYPE, ' +
EncodeTypeName('F.RDB$FIELD_TYPE', 'F.RDB$FIELD_SUB_TYPE', 'F.RDB$FIELD_SCALE',
'P.RDB$FIELD_SOURCE', '') + ' AS PARAM_TYPENAME, ' +
EncodeAttrs('F.RDB$FIELD_TYPE', 'F.RDB$COMPUTED_SOURCE', 'F.RDB$DEFAULT_SOURCE',
'F.RDB$NULL_FLAG', '') + ' AS PARAM_ATTRIBUTES, ' +
'F.RDB$FIELD_PRECISION AS PARAM_PRECISION, ' +
'- F.RDB$FIELD_SCALE AS PARAM_SCALE, ' +
'F.RDB$CHARACTER_LENGTH AS PARAM_LENGTH ' +
'FROM RDB$FUNCTION_ARGUMENTS P LEFT JOIN RDB$FIELDS F ON P.RDB$FIELD_SOURCE = F.RDB$FIELD_NAME';
if ABaseObject <> '' then
AddWhere('P.RDB$PACKAGE_NAME = ?', 'BAS')
else
AddWhere('P.RDB$PACKAGE_NAME IS NULL');
AddWhere('P.RDB$FUNCTION_NAME = ?', 'OBJ');
if AWildcard <> '' then
AddWhere(EncodeRTrim('P.RDB$ARGUMENT_NAME') + ' LIKE ?', 'WIL');
end;
Result := Result + ' ORDER BY 9, 8';
end;
mkGenerators:
begin
Result := 'SELECT CAST(NULL AS NUMERIC) AS RECNO, ' +
'CAST(NULL AS VARCHAR(67)) AS CATALOG_NAME, ' +
'CAST(NULL AS VARCHAR(67)) AS SCHEMA_NAME, ' +
'RDB$GENERATOR_NAME AS GENERATOR_NAME, ';
if (oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion < ivIB070500) then
Result := Result +
'RDB$SYSTEM_FLAG AS GENERATOR_SCOPE '
else
Result := Result +
EncodeScope(NVL('RDB$SYSTEM_FLAG', '0', True), '') + ' AS GENERATOR_SCOPE ';
Result := Result +
'FROM RDB$GENERATORS';
AddTopScope(False);
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then
AddWhere('RDB$SYSTEM_FLAG <> 6');
if AWildcard <> '' then
AddWhere(EncodeRTrim('RDB$GENERATOR_NAME') + ' LIKE ?', 'WIL');
Result := Result + ' ORDER BY 4';
end;
mkResultSetFields:
begin
Result :=
'SELECT CAST(NULL AS NUMERIC) AS RECNO, CAST(' + QuotedStr(AObject) + ' AS VARCHAR(1024)) AS RESULTSET_KEY, ' +
'RF.RDB$RELATION_NAME AS TABLE_NAME, RF.RDB$FIELD_NAME AS COLUMN_NAME, RF.RDB$FIELD_SOURCE AS DOMAIN_NAME, ' +
'S.RDB$FIELD_POSITION AS IN_PKEY, G1.RDB$DEPENDED_ON_NAME AS GENERATOR_NAME, ';
if (oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion < ivIB070500) then
Result := Result +
'F.RDB$COMPUTED_SOURCE AS ISCOMPUTED, ' +
'RF.RDB$DEFAULT_SOURCE AS HASDEFAULT'
else
Result := Result +
'CASE WHEN F.RDB$COMPUTED_SOURCE IS NULL THEN 0 ELSE 1 END AS ISCOMPUTED, ' +
'CASE WHEN RF.RDB$DEFAULT_SOURCE IS NULL THEN 0 ELSE 1 END AS HASDEFAULT';
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then
Result := Result +
', RF.RDB$IDENTITY_TYPE AS IDENT_TYPE';
Result := Result +
' FROM RDB$RELATION_FIELDS RF ' +
'LEFT JOIN RDB$FIELDS F ON ' +
'RF.RDB$FIELD_SOURCE = F.RDB$FIELD_NAME ' +
'LEFT OUTER JOIN RDB$RELATION_CONSTRAINTS C ON ' +
'RF.RDB$RELATION_NAME = C.RDB$RELATION_NAME AND C.RDB$CONSTRAINT_TYPE = ''PRIMARY KEY'' ' +
'LEFT OUTER JOIN RDB$INDEX_SEGMENTS S ON ' +
'RF.RDB$FIELD_NAME = S.RDB$FIELD_NAME AND C.RDB$INDEX_NAME = S.RDB$INDEX_NAME ' +
'LEFT OUTER JOIN RDB$DEPENDENCIES C1 ON ' +
'C1.RDB$DEPENDED_ON_NAME = RF.RDB$RELATION_NAME AND C1.RDB$FIELD_NAME = RF.RDB$FIELD_NAME AND ' +
'C1.RDB$DEPENDENT_TYPE = 2 AND C1.RDB$DEPENDED_ON_TYPE = 0 AND EXISTS ( ' +
'SELECT 1 ' +
'FROM RDB$TRIGGERS T ' +
'WHERE T.RDB$RELATION_NAME = RF.RDB$RELATION_NAME AND T.RDB$TRIGGER_NAME = C1.RDB$DEPENDENT_NAME AND ' +
'T.RDB$FLAGS = 1 AND T.RDB$TRIGGER_TYPE = 1 ' +
') ' +
'LEFT OUTER JOIN RDB$DEPENDENCIES G1 ON G1.RDB$DEPENDENT_NAME = C1.RDB$DEPENDENT_NAME AND EXISTS ( ' +
'SELECT 1 ' +
'FROM RDB$DEPENDENCIES G ' +
'WHERE G.RDB$DEPENDENT_NAME = G1.RDB$DEPENDENT_NAME ' +
'GROUP BY G.RDB$DEPENDENT_NAME, G.RDB$DEPENDENT_TYPE ' +
'HAVING COUNT(*) = 2 ' +
') AND G1.RDB$DEPENDENT_TYPE = 2 AND G1.RDB$DEPENDED_ON_TYPE = ';
if oIBConnMeta.Brand = ibInterbase then
Result := Result + '11'
else
Result := Result + '14';
if Pos(',', AObject) = 0 then
AddWhere('RF.RDB$RELATION_NAME = ?', 'OBJ')
else
AddWhere('RF.RDB$RELATION_NAME IN (' + AObject + ')');
end;
mkTableTypeFields:
;
else
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetLimitSelect(const ASQL: String;
ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String;
var
oIBConnMeta: IFDPhysIBConnectionMetadata;
begin
if Supports(FConnMeta, IFDPhysIBConnectionMetadata, oIBConnMeta) and
(oIBConnMeta.Brand in [ibFirebird, ibYaffil]) and (FConnMeta.ServerVersion >= ivFB020000) or
(oIBConnMeta.Brand = ibInterbase) then
if ASkip > 0 then
Result := ASQL + BRK + 'ROWS ' + IntToStr(ASkip + 1) + ' TO ' + IntToStr(ASkip + ARows)
else if ARows >= 0 then
Result := ASQL + BRK + 'ROWS ' + IntToStr(ARows)
else begin
Result := ASQL;
AOptions := [];
end
else begin
Result := ASQL;
AOptions := [];
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetCountSelect(const ASQL: String): String;
var
oIBConnMeta: IFDPhysIBConnectionMetadata;
begin
Supports(FConnMeta, IFDPhysIBConnectionMetadata, oIBConnMeta);
if not ((oIBConnMeta.Brand = ibFirebird) or
(oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion >= ivIB120100)) then
FDCapabilityNotSupported(Self, [S_FD_LPhys, S_FD_IBId]);
Result := inherited GetCountSelect(ASQL);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String;
var
oIBConnMeta: IFDPhysIBConnectionMetadata;
begin
case AColumn.DataType of
dtBoolean:
begin
Supports(FConnMeta, IFDPhysIBConnectionMetadata, oIBConnMeta);
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) or
(oIBConnMeta.Brand = ibInterbase) and (FConnMeta.ServerVersion >= ivIB090000) then
Result := 'BOOLEAN'
else
Result := 'SMALLINT';
end;
dtSByte,
dtInt16,
dtByte:
Result := 'SMALLINT';
dtInt32,
dtUInt16:
Result := 'INTEGER';
dtInt64,
dtUInt32,
dtUInt64:
begin
Supports(FConnMeta, IFDPhysIBConnectionMetadata, oIBConnMeta);
if oIBConnMeta.Brand = ibFirebird then
Result := 'BIGINT'
else
Result := 'INT64';
end;
dtSingle:
Result := 'FLOAT';
dtDouble,
dtExtended:
Result := 'DOUBLE PRECISION';
dtCurrency:
Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1, 18, 4);
dtBCD,
dtFmtBCD:
Result := 'DECIMAL' + GetColumnDim(-1, AColumn.Precision, AColumn.Scale, -1,
FOptions.FormatOptions.MaxBcdPrecision, 0);
dtDateTime,
dtDateTimeStamp:
Result := 'TIMESTAMP';
dtTime:
Result := 'TIME';
dtDate:
Result := 'DATE';
dtAnsiString,
dtWideString,
dtByteString:
begin
if caFixedLen in AColumn.ActualAttributes then
Result := 'CHAR'
else
Result := 'VARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
case AColumn.DataType of
dtWideString: Result := Result + ' CHARACTER SET UNICODE_FSS';
dtByteString: Result := Result + ' CHARACTER SET OCTETS';
end;
end;
dtBlob,
dtHBlob,
dtHBFile:
Result := 'BLOB(2000,0)';
dtMemo,
dtWideMemo,
dtXML,
dtHMemo,
dtWideHMemo:
Result := 'BLOB(2000,1)';
dtGUID:
Result := 'CHAR(38)';
dtUnknown,
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef,
dtParentRowRef,
dtObject:
Result := '';
end;
if Result <> '' then
if caAutoInc in AColumn.ActualAttributes then begin
Supports(FConnMeta, IFDPhysIBConnectionMetadata, oIBConnMeta);
if (oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB030000) then
Result := Result + ' GENERATED BY DEFAULT AS IDENTITY'
else
FFlags := FFlags + [gfCreateIdentityTrigger, gfCreateIdentityGenerator];
end
else if caExpr in AColumn.ActualAttributes then
Result := Result + ' COMPUTED BY (' + AColumn.Expression + ')';
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetCreateGenerator(const AName: String): String;
var
rName: TFDPhysParsedName;
begin
rName.FCatalog := '';
rName.FSchema := '';
rName.FBaseObject := '';
rName.FObject := AName;
Result := 'CREATE GENERATOR ' + FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetDropGenerator(const AName: String): String;
var
rName: TFDPhysParsedName;
begin
rName.FCatalog := '';
rName.FSchema := '';
rName.FBaseObject := '';
rName.FObject := AName;
Result := 'DROP GENERATOR ' + FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetCreateIdentityTrigger: String;
var
i: Integer;
oCols: TFDDatSColumnList;
oCol: TFDDatSColumn;
sGen, sCol, sTab: String;
rName: TFDPhysParsedName;
begin
oCols := FTable.Columns;
for i := 0 to oCols.Count - 1 do begin
oCol := oCols[i];
if ColumnStorable(oCol) and (caAutoInc in oCol.ActualAttributes) then begin
sGen := ColumnGenerator(oCol);
if sGen <> '' then begin
rName.FCatalog := '';
rName.FSchema := '';
rName.FBaseObject := '';
rName.FObject := sGen;
sGen := FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]);
sCol := GetColumn('', -1, oCol);
Result := IND + 'IF (NEW.' + sCol + ' IS NULL) THEN' + BRK +
IND + 'BEGIN' + BRK +
IND + IND + 'NEW.' + sCol + ' = GEN_ID(' + sGen + ', 1);' + BRK +
IND + 'END' + BRK;
end;
end;
end;
if Result <> '' then begin
sTab := GetFrom;
FConnMeta.DecodeObjName(sTab, rName, nil, [doUnquote]);
rName.FObject := 'TR_' + rName.FObject + '_BI';
Result := 'CREATE TRIGGER ' + FConnMeta.EncodeObjName(rName, nil, [eoQuote, eoNormalize]) + ' FOR ' + sTab + BRK +
'ACTIVE BEFORE INSERT POSITION 0' + BRK +
'AS' + BRK +
'BEGIN' + BRK +
Result +
'END' + BRK;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysIBCommandGenerator.GetMerge(AAction: TFDPhysMergeAction): String;
var
oIBConnMeta: IFDPhysIBConnectionMetadata;
begin
Supports(FConnMeta, IFDPhysIBConnectionMetadata, oIBConnMeta);
if not ((oIBConnMeta.Brand = ibFirebird) and (FConnMeta.ServerVersion >= ivFB020100)) then
FDCapabilityNotSupported(Self, [S_FD_LPhys]);
Result := inherited GetMerge(AAction);
end;
{-------------------------------------------------------------------------------}
initialization
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.Interbase, S_FD_IB_RDBMS);
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.Firebird, S_FD_FB_RDBMS);
end.
|
{####################################################################################################################
TINJECT - Componente de comunicação (Não Oficial)
www.tinject.com.br
Novembro de 2019
####################################################################################################################
Owner.....: Daniel Oliveira Rodrigues - Dor_poa@hotmail.com - +55 51 9.9155-9228
Developer.: Joathan Theiller - jtheiller@hotmail.com -
Mike W. Lustosa - mikelustosa@gmail.com - +55 81 9.9630-2385
Robson André de Morais - robinhodemorais@gmail.com
####################################################################################################################
Obs:
- Código aberto a comunidade Delphi, desde que mantenha os dados dos autores e mantendo sempre o nome do IDEALIZADOR
Mike W. Lustosa;
- Colocar na evolução as Modificação juntamente com as informaçoes do colaborador: Data, Nova Versao, Autor;
- Mantenha sempre a versao mais atual acima das demais;
- Todo Commit ao repositório deverá ser declarado as mudança na UNIT e ainda o Incremento da Versão de
compilação (último digito);
####################################################################################################################
Evolução do Código
####################################################################################################################
Autor........:
Email........:
Data.........:
Identificador:
Modificação..:
####################################################################################################################
}
unit uTInject.languages;
interface
uses uTInject.Constant, Winapi.Windows, System.Classes;
Type
TTranslatorInject = Class(TPersistent)
Private
Procedure LanguageDefault;
procedure LanguageEnglish;
class procedure SetResourceString(xOldResourceString: PResStringRec; xValueChanged: PChar);
procedure LanguageFarsi;
procedure LanguageEspanol;
Public
Procedure SetTranslator(Const PLanguage: TLanguageInject);
End;
implementation
{ LTranslatorInject }
class procedure TTranslatorInject.SetResourceString(
xOldResourceString: PResStringRec; xValueChanged: PChar);
var
POldProtect: DWORD;
begin
VirtualProtect(xOldResourceString, SizeOf(xOldResourceString^), PAGE_EXECUTE_READWRITE, @POldProtect);
xOldResourceString^.Identifier := Integer(xValueChanged);
VirtualProtect(xOldResourceString,SizeOf(xOldResourceString^),POldProtect, @POldProtect);
end;
procedure TTranslatorInject.LanguageDefault;
begin
SetResourceString(@MSG_ConfigCEF_ExceptNotFoundPATH , 'Não é possível realizar essa operação após a inicialização do componente');
SetResourceString(@MSG_ConfigCEF_ExceptConnection , 'Erro ao conectar com componente');
SetResourceString(@MSG_ConfigCEF_ExceptBrowse , 'Erro ao criar browser no CEF');
SetResourceString(@MSG_ConfigCEF_ExceptConnetServ , 'Você não está conectado ao Servidor de serviço');
SetResourceString(@MSG_ConfigCEF_ExceptConsoleNaoPronto , 'Console ainda não obteve os comandos de INJECT JS');
SetResourceString(@MSG_ConfigCEF_ExceptVersaoErrada , 'Sua versão do CEF4 não é compatível, por favor, atualize suas biblioteca em https://github.com/salvadordf/CEF4Delphi' + slinebreak + 'Versão requerida: %s' + slinebreak + 'Versão identificada: %s');
SetResourceString(@MSG_ExceptSetBatteryLow , 'O valor deve estar entre 5 e 90');
SetResourceString(@MSG_ExceptOnAlterQrCodeStyle , 'Não é possível realizar essa operação após a inicialização do componente');
SetResourceString(@MSG_ExceptConfigVersaoCompInvalida , 'Sua versão do componente TInject não é compatível com o novo JavaScript, por favor, atualize suas biblioteca em http://www.TInject.com.br/');
SetResourceString(@MSG_ExceptUpdate , 'Erro de servidor WEB. Não foi possível receber a atualização do JS.ABR');
SetResourceString(@MSG_WarningDuplicityDetected , 'Enviando o mesmo comando em um intervalo pequeno');
SetResourceString(@MSG_ExceptJS_ABRUnknown , 'Retorno JS.ABR não conhecido');
SetResourceString(@MSG_ExceptNotAssignedOnGetQrCode , 'OnGetQrCode não foi definido');
SetResourceString(@Text_FrmClose_Caption , 'Aguarde.. Finalizando o serviço..');
SetResourceString(@Text_FrmClose_Label , 'Finalizando todas as threads com segurança');
SetResourceString(@Text_FrmClose_WarningClose , 'Deseja Finalizar a aplicação?');
SetResourceString(@Text_FrmQRCode_CaptionStart , 'Carregando QR Code...');
SetResourceString(@Text_FrmQRCode_CaptionSucess , 'Aponte seu celular agora!');
SetResourceString(@Text_FrmQRCode_OnCLose , 'Cancelar entrada ao Servidor de serviço?');
SetResourceString(@MSG_ExceptPhoneNumberError , 'Número inválido');
SetResourceString(@MSG_ExceptAlterDesigner , 'Não é possível modificar em Modo Designer');
SetResourceString(@MSG_ExceptAlterInicialized , 'Método não pode ser modificado após TInject Inicializado');
SetResourceString(@MSG_ExceptCOntactNotFound , 'Não existem contatos a serem exportados');
SetResourceString(@MSG_ExceptCOntactSaveFile , 'Não foi possivel salvar os contatos em %s');
SetResourceString(@MSG_ExceptErrorLocateForm , 'Erro ao localizar FORM');
SetResourceString(@MSG_ExceptPath , 'O caminho %s é inválido');
SetResourceString(@MSG_ExceptGlobalCef , 'Classe GLOBALCEF não definida no DPR');
SetResourceString(@MSG_WarningClosing , 'Aguarde... Finalizando aplicação');
SetResourceString(@MSG_WarningErrorFile , 'Erro no arquivo repassado (%s)');
SetResourceString(@MSG_ExceptMisc , 'Erro Desconhecido');
SetResourceString(@Text_FrmConsole_Caption , 'Componente TInject Brasil');
SetResourceString(@Text_FrmConsole_LblMsg , 'Aguarde.. Inicializando comunicação');
SetResourceString(@MSG_WarningClassUnknown , 'Classe Desconhecida');
SetResourceString(@MSG_Exceptlibeay32dll , 'Seu computador não possui as DLLs "libeay32.dll" e "ssleay32.dll". Para continuar coloque as DLL na pasta system ou dentro do diretório da aplicação.');
SetResourceString(@Text_Vcard_Comments1 , 'Exportado do Componente TInject em' );
SetResourceString(@Text_Vcard_Comments2 , 'Contato Silenciado');
SetResourceString(@Text_Vcard_Comments3 , 'Capturado em:');
SetResourceString(@MSG_WarningQrCodeStart1 , 'A sessão anterior ainda está sendo finalizada, tente novamente mais tarde');
SetResourceString(@Text_Status_Serv_Initialized , 'Conectado com sucesso ao Servidor de serviço');
SetResourceString(@Text_Status_Serv_Initializing , 'Inicializando Servidor de serviço');
SetResourceString(@Text_Status_Serv_Disconnected , 'Não Conectado ao Servidor de serviço e TInject');
SetResourceString(@Text_Status_Serv_Disconnecting , 'Desconectado do Servidor de serviço e TInject ');
SetResourceString(@Text_Status_Serv_Connected , 'Servidor de serviço Conectado');
SetResourceString(@Text_Status_Serv_ConnectedDown , 'Sessão finalizada via Celular');
SetResourceString(@Text_Status_Serv_Connecting , 'Aguarde, Conectando ao Servidor de serviço');
SetResourceString(@Text_Status_Serv_ConnectingNoPhone , 'Erro ao conectar, Telefone desligado');
SetResourceString(@Text_Status_Serv_ConnectingReaderQR , 'Aguardando leitura QR Code');
SetResourceString(@Text_Status_Serv_TimeOut , 'Erro ao conectar (TimeOut)');
SetResourceString(@Text_Status_Serv_Destroying , 'Destruindo e fechando Tinject');
SetResourceString(@Text_Status_Serv_Destroy , 'TInject finalizado');
SetResourceString(@MSG_WarningNothingtoSend , 'Não existe nenhum conteúdo a ser enviado na mensagem');
SetResourceString(@MSG_Except_Data_TypeObj , 'Tipo de objeto não é compatível');
SetResourceString(@MSG_Except_DATA_ConnectRepass , 'Tipo de DataSet não possui Conexão com Banco de dados');
SetResourceString(@MSG_Except_DATA_ConnectionNull , 'Conexão Nao vinculada');
SetResourceString(@MSG_Except_AtribuicaoInvalida , 'Atribuição Inválida(já esta em uso por outro objeto)');
SetResourceString(@MSG_WarningDeveloper , 'Aviso ao Desenvolvedor VIA IDE');
SetResourceString(@Text_DefaultPathDown , 'TInjectAnexos');
SetResourceString(@Text_DefaultError , 'Erro ao criar diretório em ');
SetResourceString(@MSG_Except_SaveAttached , 'Erro ao salvar arquivo em anexo à mensagem');
SetResourceString(@MSG_Except_CefNull , 'Componente GlobalCEFApp não foi inicializado em seu .DPR (Verifique o .DPR da aplicação DEMO para melhor entendimento)');
SetResourceString(@Text_System_memUse , 'Memória usada pela Aplicação: ');
SetResourceString(@Text_System_memTot , 'Memória total: ');
SetResourceString(@Text_System_memFree , 'Memória física disponível: ');
SetResourceString(@Text_System_memLoad , 'Mémoria Carregada: ');
SetResourceString(@Text_FrmConfigNetWork_Caption , 'Configuração de LAN');
SetResourceString(@Text_FrmConfigNetWork_ProxyTypeLbl , 'Tipo:');
SetResourceString(@Text_FrmConfigNetWork_PrtocolLbl , 'Protocolo:');
SetResourceString(@Text_FrmConfigNetWork_ProxyServerLbl , 'Servidor:');
SetResourceString(@Text_FrmConfigNetWork_ProxyPortLbl , 'Porta:');
SetResourceString(@Text_FrmConfigNetWork_ProxyUsernameLbl , 'Usuário:');
SetResourceString(@Text_FrmConfigNetWork_ProxyPasswordLbl , 'Senha:');
SetResourceString(@Text_FrmConfigNetWork_ProxyScriptURLLbl , 'Script de Configuração Automática:');
SetResourceString(@Text_FrmConfigNetWork_ProxyByPassListLbl , 'Não usar proxy nos endereços: (use ponto-e-vírgula para separar entradas)');
SetResourceString(@Text_FrmConfigNetWork_MaxConnectionsPerProxyLbl , 'Número máximo de conexões por proxy:');
SetResourceString(@Text_FrmConfigNetWork_GroupBox2 , 'Personalização de Cabeçalhos:');
SetResourceString(@Text_FrmConfigNetWork_HeaderNameLbl , 'Nome "Variável":');
SetResourceString(@Text_FrmConfigNetWork_HeaderValueLbl , 'Valor "Variável":');
SetResourceString(@Text_FrmConfigNetWork_BntOK , 'Salvar');
SetResourceString(@Text_FrmConfigNetWork_BntCancel , 'Cancelar');
SetResourceString(@Text_FrmConfigNetWork_QuestionSave , 'Deseja realmente aplicar essas configurações?');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
// SetResourceString(@Text_FrmClose_WarningClose , '');
end;
procedure TTranslatorInject.LanguageEnglish;
begin
SetResourceString(@MSG_ConfigCEF_ExceptNotFoundPATH , 'It is not possible to perform this operation after the component has been initialized');
SetResourceString(@MSG_ConfigCEF_ExceptConnection , 'Error connecting with component');
SetResourceString(@MSG_ConfigCEF_ExceptBrowse , 'Error creating browser in CEF');
SetResourceString(@MSG_ConfigCEF_ExceptConnetServ , 'You are not connected to the service server');
SetResourceString(@MSG_ConfigCEF_ExceptConsoleNaoPronto , 'Console has not yet obtained the commands for INJECT JS');
SetResourceString(@MSG_ConfigCEF_ExceptVersaoErrada , 'Your CEF4 version is not compatible, please update your library at https://github.com/salvadordf/CEF4Delphi' + slinebreak + 'Required version: %s' + slinebreak + 'Identified version: %s');
SetResourceString(@MSG_ExceptSetBatteryLow , 'Value must be between 5 and 90');
SetResourceString(@MSG_ExceptOnAlterQrCodeStyle , 'It is not possible to perform this operation after the component has been initialized');
SetResourceString(@MSG_ExceptConfigVersaoCompInvalida , 'Your version of TInject component is not compatible with the latest JavaScript version, please update your library at http://www.TInject.com.br/');
SetResourceString(@MSG_ExceptUpdate , 'WEB server error. Unable to receive JS.ABR update');
SetResourceString(@MSG_WarningDuplicityDetected , 'Sending the same command within a short interval');
SetResourceString(@MSG_ExceptJS_ABRUnknown , 'Unknown JS.ABR return');
SetResourceString(@MSG_ExceptNotAssignedOnGetQrCode , 'OnGetQrCode has not been defined');
SetResourceString(@Text_FrmClose_Caption , 'Wait.. TInject is Terminating..');
SetResourceString(@Text_FrmClose_Label , 'Terminating all threads safely');
SetResourceString(@Text_FrmClose_WarningClose , 'Do you want to close the application?');
SetResourceString(@Text_FrmQRCode_CaptionStart , 'Loading QRCode...');
SetResourceString(@Text_FrmQRCode_CaptionSucess , 'Point your phone now!');
SetResourceString(@Text_FrmQRCode_OnCLose , 'Cancel service server? connection');
SetResourceString(@MSG_ExceptPhoneNumberError , 'Invalid Number');
SetResourceString(@MSG_ExceptAlterDesigner , 'It is not possible to modify in Designer Mode');
SetResourceString(@MSG_ExceptAlterInicialized , 'Method Cannot Be Modified After TInject has been Initialized');
SetResourceString(@MSG_ExceptCOntactNotFound , 'There are no contacts to export');
SetResourceString(@MSG_ExceptCOntactSaveFile , 'Unable to save contacts to %s');
SetResourceString(@MSG_ExceptErrorLocateForm , 'Error locating FORM');
SetResourceString(@MSG_ExceptPath , 'The path %s is invalid');
SetResourceString(@MSG_ExceptGlobalCef , 'GLOBALCEF class has not been defined in DPR');
SetResourceString(@MSG_WarningClosing , 'Wait... closing application');
SetResourceString(@MSG_WarningErrorFile , 'Error on selected file (%s)');
SetResourceString(@MSG_ExceptMisc , 'Unknown error');
SetResourceString(@Text_FrmConsole_Caption , 'Brazil TInject Component');
SetResourceString(@Text_FrmConsole_LblMsg , 'Wait .. Initializing TInject');
SetResourceString(@MSG_WarningClassUnknown , 'Unknown class');
SetResourceString(@MSG_Exceptlibeay32dll , 'Your computer does not have the "libeay32.dll" and "ssleay32.dll" DLLs. To continue place the DLLs in the system folder or in the application directory.');
SetResourceString(@Text_Vcard_Comments1 , 'Exported from TInject Component in: ' );
SetResourceString(@Text_Vcard_Comments2 , 'Contact has been silenced');
SetResourceString(@Text_Vcard_Comments3 , 'Captured in: ');
SetResourceString(@MSG_WarningQrCodeStart1 , 'A previous session is still running, please try again later');
SetResourceString(@Text_Status_Serv_Initialized , 'TInject connected successfully to the service server');
SetResourceString(@Text_Status_Serv_Initializing , 'Initializing TInject to service server');
SetResourceString(@Text_Status_Serv_Disconnected , 'Not connected to service server and TInject');
SetResourceString(@Text_Status_Serv_Disconnecting , 'Disconnected from service server and TInject ');
SetResourceString(@Text_Status_Serv_Connected , 'Connected to service server');
SetResourceString(@Text_Status_Serv_ConnectedDown , 'Session terminated via Mobile');
SetResourceString(@Text_Status_Serv_Connecting , 'Wait, connecting to service server');
SetResourceString(@Text_Status_Serv_ConnectingNoPhone , 'Error connecting, phone is turned off');
SetResourceString(@Text_Status_Serv_ConnectingReaderQR , 'Waiting QR code scan');
SetResourceString(@Text_Status_Serv_TimeOut , 'Unabke to connect (TimeOut)');
SetResourceString(@Text_Status_Serv_Destroying , 'Destroying and closing the TInject');
SetResourceString(@Text_Status_Serv_Destroy , 'TInject has been terminated');
SetResourceString(@MSG_WarningNothingtoSend , 'There is no content to send in this message');
SetResourceString(@MSG_Except_Data_TypeObj , 'Object type is not compatible');
SetResourceString(@MSG_Except_DATA_ConnectRepass , 'DataSet Type Does Not Have Database Connection');
SetResourceString(@MSG_Except_DATA_ConnectionNull , 'Unlinked connection');
SetResourceString(@MSG_Except_AtribuicaoInvalida , 'Invalid attribution (already in use by another object)');
SetResourceString(@MSG_WarningDeveloper , 'Developer notice (IDE)');
SetResourceString(@Text_DefaultPathDown , 'TInjectAttachment');
SetResourceString(@Text_DefaultError , 'Error creating directory in ');
SetResourceString(@MSG_Except_SaveAttached , 'Error saving file attached to message');
SetResourceString(@MSG_Except_CefNull , 'Component GlobalCEFApp has not been initialized in your application (Check DPR of DEMO app)');
SetResourceString(@Text_System_memUse , 'Total memory used by this application: ');
SetResourceString(@Text_System_memTot , 'Total system memory: ');
SetResourceString(@Text_System_memFree , 'Available physical memory: ');
SetResourceString(@Text_System_memLoad , 'Memory load: ');
SetResourceString(@Text_FrmConfigNetWork_Caption , 'LAN configuration');
SetResourceString(@Text_FrmConfigNetWork_ProxyTypeLbl , 'Type:');
SetResourceString(@Text_FrmConfigNetWork_ProxyServerLbl , 'Server:');
SetResourceString(@Text_FrmConfigNetWork_PrtocolLbl , 'Protocol:');
SetResourceString(@Text_FrmConfigNetWork_ProxyPortLbl , 'Port:');
SetResourceString(@Text_FrmConfigNetWork_ProxyUsernameLbl , 'Username:');
SetResourceString(@Text_FrmConfigNetWork_ProxyPasswordLbl , 'Password:');
SetResourceString(@Text_FrmConfigNetWork_ProxyScriptURLLbl , 'Automatic Configuration Script:');
SetResourceString(@Text_FrmConfigNetWork_ProxyByPassListLbl , 'Do not proxy addresses: (use semicolons to separate entries)');
SetResourceString(@Text_FrmConfigNetWork_MaxConnectionsPerProxyLbl , 'Maximum connections per proxy:');
SetResourceString(@Text_FrmConfigNetWork_GroupBox2 , ' Custom header: ');
SetResourceString(@Text_FrmConfigNetWork_HeaderNameLbl , 'Name "Variable":');
SetResourceString(@Text_FrmConfigNetWork_HeaderValueLbl , 'Value "Variable":');
SetResourceString(@Text_FrmConfigNetWork_BntOK , 'Save');
SetResourceString(@Text_FrmConfigNetWork_BntCancel , 'Cancel');
SetResourceString(@Text_FrmConfigNetWork_QuestionSave , 'Do you really want to apply these settings?');
end;
procedure TTranslatorInject.LanguageEspanol;
begin
//Revisado por:
// Daniel Serrano - darnaldo2005@gmail.com - Quito / Ecuador - 03/01/2020
SetResourceString(@MSG_ConfigCEF_ExceptNotFoundPATH , 'No se puede realizar esta operación después de la inicialización del componente');
SetResourceString(@MSG_ConfigCEF_ExceptConnection , 'Error al conectar con el componente');
SetResourceString(@MSG_ConfigCEF_ExceptBrowse , 'Error al crear el navegador en CEF');
SetResourceString(@MSG_ConfigCEF_ExceptConnetServ , 'No estás conectado al servidor de servicio');
SetResourceString(@MSG_ConfigCEF_ExceptConsoleNaoPronto , 'La consola aún no ha obtenido los comandos para INJECT JS');
SetResourceString(@MSG_ConfigCEF_ExceptVersaoErrada , 'Su versión de CEF4 no es compatible, actualice su biblioteca en https://github.com/salvadordf/CEF4Delphi' + slinebreak + 'Versión requerida: %s' + slinebreak + 'Versión identificada: %s');
SetResourceString(@MSG_ExceptSetBatteryLow , 'El valor debe estar entre 5 y 90');
SetResourceString(@MSG_ExceptOnAlterQrCodeStyle , 'No se puede realizar esta operación después de la inicialización del componente');
SetResourceString(@MSG_ExceptConfigVersaoCompInvalida , 'Su versión del componente TInject no es compatible con el nuevo JavaScript, actualice sus bibliotecas en http://www.TInject.com.br/');
SetResourceString(@MSG_ExceptUpdate , 'Error del servidor web. No se puede recibir la actualización JS.ABR');
SetResourceString(@MSG_WarningDuplicityDetected , 'Enviar el mismo comando en un intervalo pequeño');
SetResourceString(@MSG_ExceptJS_ABRUnknown , 'Devuelve JS.ABR desconocido');
SetResourceString(@MSG_ExceptNotAssignedOnGetQrCode , 'OnGetQrCode no se ha establecido');
SetResourceString(@Text_FrmClose_Caption , 'Espere... Terminando TInject..');
SetResourceString(@Text_FrmClose_Label , 'Terminar todos los threads de forma segura');
SetResourceString(@Text_FrmClose_WarningClose , '¿Quieres terminar la aplicación?');
SetResourceString(@Text_FrmQRCode_CaptionStart , 'Capturando QRCode...');
SetResourceString(@Text_FrmQRCode_CaptionSucess , '¡Apunte su teléfono ahora!');
SetResourceString(@Text_FrmQRCode_OnCLose , '¿Darse de baja del servidor de servicio?');
SetResourceString(@MSG_ExceptPhoneNumberError , 'Número inválido');
SetResourceString(@MSG_ExceptAlterDesigner , 'No se puede modificar en modo de desarrollo');
SetResourceString(@MSG_ExceptAlterInicialized , 'El método no se puede modificar después de que TInject se haya inicializado');
SetResourceString(@MSG_ExceptCOntactNotFound , 'No hay contactos para exportar');
SetResourceString(@MSG_ExceptCOntactSaveFile , 'No se pueden guardar contactos en %s');
SetResourceString(@MSG_ExceptErrorLocateForm , 'Error al localizar FORM');
SetResourceString(@MSG_ExceptPath , 'La ruta %s no es válida');
SetResourceString(@MSG_ExceptGlobalCef , 'Clase GLOBALCEF no definida en .DPR');
SetResourceString(@MSG_WarningClosing , 'Por favor espere... Finalizando la aplicación');
SetResourceString(@MSG_WarningErrorFile , 'Error de archivo aprobado (%s)');
SetResourceString(@MSG_ExceptMisc , 'Error desconocido');
SetResourceString(@Text_FrmConsole_Caption , 'Componente TInject Brasil');
SetResourceString(@Text_FrmConsole_LblMsg , 'Espera ... Inicializando TInject');
SetResourceString(@MSG_WarningClassUnknown , 'Clase desconocida');
SetResourceString(@MSG_Exceptlibeay32dll , 'Su computadora no tiene los archivos DLL "libeay32.dll" y "ssleay32.dll". Para continuar, coloque las DLL en la carpeta del sistema o dentro del directorio de la aplicación.');
SetResourceString(@Text_Vcard_Comments1 , 'Exportado desde TInject Component en' );
SetResourceString(@Text_Vcard_Comments2 , 'Contacto silenciado');
SetResourceString(@Text_Vcard_Comments3 , 'Capturado en:');
SetResourceString(@MSG_WarningQrCodeStart1 , 'La sesión anterior aún está terminando, intente nuevamente más tarde.');
SetResourceString(@Text_Status_Serv_Initialized , 'TInject se conectó correctamente al servidor de servicio');
SetResourceString(@Text_Status_Serv_Initializing , 'Inicializando TInject al servidor de servicio');
SetResourceString(@Text_Status_Serv_Disconnected , 'No conectado al servicio y al servidor TInject');
SetResourceString(@Text_Status_Serv_Disconnecting , 'Desconectado del servidor de servicio y TInject ');
SetResourceString(@Text_Status_Serv_Connected , 'Servidor de servicio conectado');
SetResourceString(@Text_Status_Serv_ConnectedDown , 'Sesión finalizada a través del teléfono');
SetResourceString(@Text_Status_Serv_Connecting , 'Espera, conectando al servidor de servicio');
SetResourceString(@Text_Status_Serv_ConnectingNoPhone , 'Error al conectar, teléfono apagado');
SetResourceString(@Text_Status_Serv_ConnectingReaderQR , 'En espera a leer el código QR');
SetResourceString(@Text_Status_Serv_TimeOut , 'Error al conectar (TimeOut)');
SetResourceString(@Text_Status_Serv_Destroying , 'Destruyendo y cerrando la aplicación');
SetResourceString(@Text_Status_Serv_Destroy , 'TInject terminado');
SetResourceString(@MSG_WarningNothingtoSend , 'No hay contenido para enviar en el mensaje');
SetResourceString(@MSG_Except_Data_TypeObj , 'El tipo de objeto no es compatible');
SetResourceString(@MSG_Except_DATA_ConnectRepass , 'El tipo de conjunto de datos no tiene conexión de base de datos');
SetResourceString(@MSG_Except_DATA_ConnectionNull , 'Conexión no transmitida');
SetResourceString(@MSG_Except_AtribuicaoInvalida , 'Atribución inválida (ya está en uso por otro objeto)');
SetResourceString(@MSG_WarningDeveloper , 'Aviso del desarrollador através de IDE');
SetResourceString(@Text_System_memUse , 'Memoria total utilizada por esta aplicación: ');
SetResourceString(@Text_System_memTot , 'Memoria total del sistema: ');
SetResourceString(@Text_System_memFree , 'Memoria física disponible: ');
SetResourceString(@Text_System_memLoad , 'Carga de memoria: ');
SetResourceString(@Text_FrmConfigNetWork_Caption , 'Configuración LAN');
SetResourceString(@Text_FrmConfigNetWork_ProxyTypeLbl , 'Tipo:');
SetResourceString(@Text_FrmConfigNetWork_ProxyServerLbl , 'Servidor:');
SetResourceString(@Text_FrmConfigNetWork_PrtocolLbl , 'Protocolo:');
SetResourceString(@Text_FrmConfigNetWork_ProxyPortLbl , 'Port:');
SetResourceString(@Text_FrmConfigNetWork_ProxyUsernameLbl , 'Nombre usuario:');
SetResourceString(@Text_FrmConfigNetWork_ProxyPasswordLbl , 'Contraseña:');
SetResourceString(@Text_FrmConfigNetWork_ProxyScriptURLLbl , 'Script de configuración automática:');
SetResourceString(@Text_FrmConfigNetWork_ProxyByPassListLbl , 'No proxy direcciones: (use punto y coma para separar las entradas)');
SetResourceString(@Text_FrmConfigNetWork_MaxConnectionsPerProxyLbl , 'Conexiones máximas por proxy:');
SetResourceString(@Text_FrmConfigNetWork_GroupBox2 , ' Cabeceras personalizadas: ');
SetResourceString(@Text_FrmConfigNetWork_HeaderNameLbl , 'Nombre "variable":');
SetResourceString(@Text_FrmConfigNetWork_HeaderValueLbl , 'Valor "Variable":');
SetResourceString(@Text_FrmConfigNetWork_BntOK , 'Guardar');
SetResourceString(@Text_FrmConfigNetWork_BntCancel , 'Cancelar');
SetResourceString(@Text_FrmConfigNetWork_QuestionSave , '¿Realmente quieres aplicar esta configuración?');
end;
procedure TTranslatorInject.LanguageFarsi;
begin
//
end;
{
procedure TTranslatorInject.LanguageAfrikaans;
begin
end;
}
procedure TTranslatorInject.SetTranslator(Const PLanguage: TLanguageInject);
begin
LanguageDefault;
case PLanguage of
Tl_English : LanguageEnglish;
TL_Farsi : LanguageFarsi;
Tl_Espanol : LanguageEspanol;
end;
end;
end.
|
unit uFuncionarioDAO;
interface
uses
System.Classes, SysUtils, Data.SqlExpr, uFuncionario, uDependente,
uDependenteDAO, uDM, uDMClient;
type
TFuncionarioDAO = class
private
FSQL: TSQLQuery;
procedure SalvarDependentes(const AFuncionario: TFuncionario;
const AEmTransacao: boolean = false);
public
procedure Salvar(const AFuncionario: TFuncionario;
const AEmTransacao: boolean = false);
end;
implementation
{ TFuncionarioDAO }
procedure TFuncionarioDAO.Salvar(const AFuncionario: TFuncionario;
const AEmTransacao: boolean = false);
var
iIdFuncionario: Integer;
bAbreTransacao: boolean;
begin
try
bAbreTransacao := false;
FSQL := TSQLQuery.Create(nil);
FSQL.SQLConnection := DM.SQLConnection;
FSQL.CommandText := '';
if not AEmTransacao then
begin
bAbreTransacao := true;
DM.IniciarTransacao;
end;
try
iIdFuncionario := DMClient.GerarIDTabela('FUNCIONARIO');
FSQL.SQL.Add
('Insert into FUNCIONARIO( ID_FUNCIONARIO, NOME, CPF, SALARIO)');
FSQL.SQL.Add('values(:id, :nome,:cpf, :salario)');
FSQL.Params.ParamByName('id').AsInteger := iIdFuncionario;
FSQL.Params.ParamByName('nome').AsString := AFuncionario.Nome;
FSQL.Params.ParamByName('cpf').AsString := AFuncionario.CPF;
FSQL.Params.ParamByName('salario').AsFloat := AFuncionario.Salario;;
FSQL.ExecSQL;
AFuncionario.Id_Funcionario := iIdFuncionario;
SalvarDependentes(AFuncionario, bAbreTransacao);
finally
FSQl.Free;
if not AEmTransacao then
DM.ConfirmarTransacao;
end;
except
on E: Exception do
if not AEmTransacao then
DM.CancelarTransacao;
end;
end;
procedure TFuncionarioDAO.SalvarDependentes(const AFuncionario: TFuncionario;
const AEmTransacao: boolean = false);
var
oDependenteDAO: TDependenteDAO;
oDependente: TDependente;
begin
oDependenteDAO := TDependenteDAO.Create;
try
for oDependente in AFuncionario.Dependentes do
begin
oDependente.Id_Funcionario := AFuncionario.Id_Funcionario;
oDependenteDAO.Salvar(oDependente, AEmTransacao);
end;
finally
oDependenteDAO.Free;
end;
end;
end.
|
unit LoanClient;
interface
uses
Employer, ClientLoan;
type
TLoanClient = class(TObject)
private
FId: string;
FName: string;
FEmployer: TEmployer;
FAddress: string;
FAge: integer;
FNetPay: currency;
FLoans: array of TClientLoan;
FValidIdentityDocs: integer;
FAvailablePromissoryNotes: array of string;
procedure AddLoan(const loan: TClientLoan);
procedure AddPromissoryNote(const AValue: string);
function GetLoan(const i: integer): TClientLoan;
function GetPromissoryNote(const i: integer): string;
function GetPromissoryNoteCount: integer;
public
procedure GetLoans;
procedure GetAvailablePromissoryNotes;
function GetLoanClassCount(const classId: integer): integer;
function GetLoanClassBalance(const classId: integer): real;
property Id: string read FId write FId;
property Name: string read FName write FName;
property Employer: TEmployer read FEmployer write FEmployer;
property Address: string read FAddress write FAddress;
property Age: integer read FAge write FAge;
property NetPay: currency read FNetPay write FNetPay;
property Loans[const i: integer]: TClientLoan read GetLoan;
property ValidIdentityDocs: integer read FValidIdentityDocs write FValidIdentityDocs;
property PromissoryNotes[const i: integer]: string read GetPromissoryNote;
property PromissoryNotesCount: integer read GetPromissoryNoteCount;
constructor Create; overload;
constructor Create(const id, name: string; emp: TEmployer; const addr: string); overload;
constructor Create(const id, name: string; emp: TEmployer; const addr: string;
const age: integer; const netPay: real; const idDocs: integer = 0); overload;
destructor Destroy; override;
end;
var
lnc: TLoanClient;
implementation
uses
LoanData;
constructor TLoanClient.Create;
begin
if lnc = nil then
lnc := self;
end;
constructor TLoanClient.Create(const id, name: string; emp: TEmployer; const addr: string);
begin
inherited Create;
FId := id;
FName := name;
FEmployer := emp;
FAddress := addr;
end;
procedure TLoanClient.AddPromissoryNote(const AValue: string);
begin
SetLength(FAvailablePromissoryNotes,Length(FAvailablePromissoryNotes) + 1);
FAvailablePromissoryNotes[Length(FAvailablePromissoryNotes) - 1] := AValue;
end;
constructor TLoanClient.Create(const id, name: string; emp: TEmployer; const addr: string;
const age: integer; const netPay: real; const idDocs: integer);
begin
inherited Create;
FId := id;
FName := name;
FEmployer := emp;
FAddress := addr;
FAge := age;
FNetPay := netPay;
FValidIdentityDocs := idDocs;
end;
destructor TLoanClient.Destroy;
begin
if lnc = self then
lnc := nil;
inherited;
end;
procedure TLoanClient.AddLoan(const loan: TClientLoan);
begin
SetLength(FLoans,Length(FLoans) + 1);
FLoans[Length(FLoans) - 1] := loan;
end;
procedure TLoanClient.GetLoans;
begin
// clear the loans
FLoans := [];
with dmLoan.dstClientLoans do
begin
try
Open;
while not Eof do
begin
AddLoan(TClientLoan.Create(FieldByName('loan_id').AsString,
FieldByName('class_id').AsInteger,
FieldByName('balance').AsCurrency));
Next;
end;
finally
Close;
end;
end;
end;
function TLoanClient.GetPromissoryNote(const i: integer): string;
begin
Result := FAvailablePromissoryNotes[i];
end;
function TLoanClient.GetPromissoryNoteCount: integer;
begin
Result := Length(FAvailablePromissoryNotes);
end;
procedure TLoanClient.GetAvailablePromissoryNotes;
begin
// clear the promissory notes
FAvailablePromissoryNotes := [];
with dmLoan.dstPromissoryNotes do
begin
try
Open;
while not Eof do
begin
AddPromissoryNote(FieldByName('pn_no').AsString);
Next;
end;
finally
Close;
end;
end;
end;
function TLoanClient.GetLoan(const i: Integer): TClientLoan;
begin
Result := FLoans[i];
end;
function TLoanClient.GetLoanClassCount(const classId: Integer): integer;
var
cnt: integer;
loan: TClientLoan;
begin
cnt := 0;
for loan in FLoans do
if loan.LoanClassId = classId then Inc(cnt);
Result := cnt;
end;
function TLoanClient.GetLoanClassBalance(const classId: integer): real;
var
balance: real;
loan: TClientLoan;
begin
balance := 0;
for loan in FLoans do
if loan.LoanClassId = classId then balance := balance + loan.Balance;
Result := balance;
end;
end.
|
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium Software
E-Mail: mshkolnik@scalabium.com
WEB: http://www.scalabium.com
This is a grid a-la MS Access grid for text file import
}
unit SMBreakGrid;
interface
{$I SMVersion.inc}
uses Classes, Controls, StdCtrls, ExtCtrls;
type
TSMBreakColumn = class(TCollectionItem)
private
{ Private declarations }
FPosition: Integer;
procedure SetPosition(Value: Integer);
protected
{ Protected declarations }
public
{ Public declarations }
procedure Assign(Source: TPersistent); override;
published
{ Published declarations }
property Position: Integer read FPosition write SetPosition;
end;
TSMBreakColumns = class(TCollection)
private
FBreakGrid: TComponent;
function GetColumn(Index: Integer): TSMBreakColumn;
procedure SetColumn(Index: Integer; Value: TSMBreakColumn);
protected
function GetOwner: TPersistent; override;
public
constructor Create(ABreakGrid: TComponent);
function Add: TSMBreakColumn;
function Insert(Index: Integer): TSMBreakColumn;
property BreakGrid: TComponent read FBreakGrid;
property Items[Index: Integer]: TSMBreakColumn read GetColumn write SetColumn; default;
end;
TSMScrollEvent = procedure(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer) of object;
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TSMBreakGrid = class(TPanel)
private
FColumns: TSMBreakColumns;
FRows: TStrings;
FReadonly: Boolean;
pbBreaks: TPaintBox;
sbBreakHorz: TScrollbar;
sbBreakVert: TScrollbar;
intBreakShiftX, intBreakShiftY: Integer;
InDownMouse: Integer;
MousePressed: Boolean;
FOnChangeColumns: TNotifyEvent;
FOnScrollHorizontal: TSMScrollEvent;
FOnScrollVertical: TSMScrollEvent;
function GetColumns: TSMBreakColumns;
procedure SetColumns(AValue: TSMBreakColumns);
function GetRows: TStrings;
procedure SetRows(AValue: TStrings);
protected
procedure CreateInternalControls;
function GetBreak(X: Integer; IsAdd: Boolean): Integer;
procedure pbBreaksMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure pbBreaksMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure pbBreaksMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure pbBreaksPaint(Sender: TObject);
procedure sbBreakHorzScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
procedure sbBreakVertScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Columns: TSMBreakColumns read GetColumns write SetColumns;
property Rows: TStrings read GetRows write SetRows;
property Readonly: Boolean read FReadonly write FReadonly default False;
property OnChangeColumns: TNotifyEvent read FOnChangeColumns write FOnChangeColumns;
property OnScrollHorizontal: TSMScrollEvent read FOnScrollHorizontal write FOnScrollHorizontal;
property OnScrollVertical: TSMScrollEvent read FOnScrollVertical write FOnScrollVertical;
end;
procedure Register;
implementation
uses Windows, Graphics, SysUtils, Forms;
procedure Register;
begin
RegisterComponents('SMComponents', [TSMBreakGrid]);
end;
{ TSMBreakColumn }
procedure TSMBreakColumn.SetPosition(Value: Integer);
begin
FPosition := Value;
if (Collection is TSMBreakColumns) then
(TSMBreakColumns(Collection).BreakGrid as TSMBreakGrid).Invalidate
end;
procedure TSMBreakColumn.Assign(Source: TPersistent);
begin
if Source is TSMBreakColumn then
begin
if Assigned(Collection) then
Collection.BeginUpdate;
try
Position := TSMBreakColumn(Source).Position;
finally
if Assigned(Collection) then
Collection.EndUpdate;
end;
end
else
inherited Assign(Source);
end;
{ TSMBreakColumns }
constructor TSMBreakColumns.Create(ABreakGrid: TComponent);
begin
inherited Create(TSMBreakColumn);
FBreakGrid := ABreakGrid;
end;
function TSMBreakColumns.Add: TSMBreakColumn;
begin
Result := TSMBreakColumn(inherited Add);
end;
function TSMBreakColumns.Insert(Index: Integer): TSMBreakColumn;
begin
Result := TSMBreakColumn(inherited Add);
while (Result.Index <= Index) and (Result.Index > 0) do
begin
Result.Assign(Items[Result.Index-1]);
Result := Items[Result.Index-1];
end;
end;
function TSMBreakColumns.GetOwner: TPersistent;
begin
Result := FBreakGrid;
end;
function TSMBreakColumns.GetColumn(Index: Integer): TSMBreakColumn;
begin
Result := TSMBreakColumn(inherited Items[Index]);
end;
procedure TSMBreakColumns.SetColumn(Index: Integer; Value: TSMBreakColumn);
begin
Items[Index].Assign(Value);
end;
{ TSMBreakGrid }
constructor TSMBreakGrid.Create(AOwner: TComponent);
begin
inherited;
FReadonly := False;
FColumns := TSMBreakColumns.Create(Self);
FRows := TStringList.Create;
Font.Name := 'Courier';
CreateInternalControls;
end;
destructor TSMBreakGrid.Destroy;
begin
FColumns.Free;
FRows.Free;
inherited
end;
procedure TSMBreakGrid.CreateInternalControls;
begin
{1. paintbox}
pbBreaks := TPaintBox.Create(Self);
pbBreaks.Parent := Self;
pbBreaks.Top := 2;
pbBreaks.Left := 2;
pbBreaks.OnMouseDown := pbBreaksMouseDown;
pbBreaks.OnMouseMove := pbBreaksMouseMove;
pbBreaks.OnMouseUp := pbBreaksMouseUp;
pbBreaks.OnPaint := pbBreaksPaint;
{2. hor.scrollbar}
sbBreakHorz := TScrollbar.Create(Self);
sbBreakHorz.Parent := Self;
sbBreakHorz.OnScroll := sbBreakHorzScroll;
{3. vert.scrollbar}
sbBreakVert := TScrollbar.Create(Self);
sbBreakVert.Parent := Self;
sbBreakVert.OnScroll := sbBreakVertScroll;
sbBreakVert.Kind := sbVertical;
intBreakShiftX := 0;
intBreakShiftY := 0;
sbBreakHorz.Position := 0;
sbBreakVert.Position := 0;
end;
function TSMBreakGrid.GetColumns: TSMBreakColumns;
begin
Result := FColumns
end;
procedure TSMBreakGrid.SetColumns(AValue: TSMBreakColumns);
begin
FColumns.Assign(AValue);
pbBreaks.Invalidate
end;
function TSMBreakGrid.GetRows: TStrings;
begin
Result := FRows
end;
procedure TSMBreakGrid.SetRows(AValue: TStrings);
var
i, intMax: Integer;
begin
FRows.Assign(AValue);
intMax := 10;
for i := 0 to FRows.Count-1 do
if intMax < Length(FRows[i]) then
intMax := Length(FRows[i]);
sbBreakHorz.Max := intMax;
pbBreaks.Invalidate
end;
{mouse processing}
procedure TSMBreakGrid.pbBreaksMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Readonly then exit;
InDownMouse := GetBreak(X, False);
MousePressed := True;
if (ssDouble in Shift) then
begin
if (InDownMouse > -1) then
begin
Columns[InDownMouse].Free;
pbBreaks.Repaint;
InDownMouse := -1;
if Assigned(OnChangeColumns) then
OnChangeColumns(Self);
end
end
else
if (InDownMouse < 0) then
GetBreak(X, True);
end;
procedure TSMBreakGrid.pbBreaksMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
MousePressed := False;
end;
procedure TSMBreakGrid.pbBreaksMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
intNew, intPos, intCharWidth: Integer;
begin
if ReadOnly then exit;
if MousePressed and (InDownMouse > -1) then
begin
intCharWidth := pbBreaks.Canvas.TextWidth('W');
intPos := X div intCharWidth;
if (intPos = 0) then exit;
intNew := intBreakShiftX + intPos;
if (Columns[InDownMouse].Position <> intNew) then
begin
Columns[InDownMouse].Position := intNew;
if Assigned(OnChangeColumns) then
OnChangeColumns(Self);
end;
end
end;
{draw the grid}
procedure TSMBreakGrid.pbBreaksPaint(Sender: TObject);
var
R: TRect;
i, j, k,
intCharWidth, intCharHeight,
intSampleWidth, intSampleHeight: Integer;
intBreak: LongInt;
s: string;
begin
with pbBreaks, Canvas do
begin
intCharWidth := TextWidth('W');
intCharHeight := TextHeight('Wg');
R := ClientRect;
R.Top := R.Top + intCharHeight + 15;
Brush.Color := clBlack;
FrameRect(R);
InflateRect(R, -1, -1);
intSampleWidth := (R.Right-R.Left) div intCharWidth;
intSampleHeight := 5;
Brush.Color := clWhite;
Pen.Color := clBlack;
FillRect(R);
{draw a text sample}
for i := 0 to intSampleHeight-1 do
begin
if i + intBreakShiftY < Rows.Count then
s := Rows[i + intBreakShiftY]
else
s := '';
s := Copy(s, intBreakShiftX+1, intSampleWidth);
TextOut(R.Left, R.Top + i*intCharHeight, s);
end;
{draw the ruler}
Brush.Color := Color;
MoveTo(R.Left, R.Top - 8);
LineTo(R.Right, R.Top - 8);
for i := 0 to intSampleWidth-1 do
begin
j := i*intCharWidth;
k := i + intBreakShiftX;
if k mod 5 = 0 then
begin
MoveTo(j, R.Top - 13);
LineTo(j, R.Top - 8);
if (k <> 0) and (k mod 10 = 0) then
begin
s := IntToStr(k);
k := TextWidth(s);
TextOut(j - k div 2, R.Top - intCharHeight - 15, s);
end
end
else
begin
MoveTo(j, R.Top - 10);
LineTo(j, R.Top - 8);
end
end;
{draw the arrows for breaks}
for i := 0 to Columns.Count-1 do
begin
intBreak := Columns[i].Position;
if (intBreakShiftX <= intBreak) and
(intBreak <= intBreakShiftX + intSampleWidth) then
begin
j := ((intBreak - intBreakShiftX) mod intSampleWidth)*intCharWidth;
if MousePressed and (i = InDownMouse) then
Pen.Style := psDot
else
Pen.Style := psSolid;
{arrow above}
Brush.Color := clBlack;
Polygon([Point(j, R.Top - 7),
Point(j - 3, R.Top - 3),
Point(j + 3, R.Top - 3)]);
{line}
MoveTo(j, R.Top - 3);
LineTo(j, R.Bottom);
Pen.Style := psSolid;
end;
end;
end;
end;
{ scrollbar processing }
procedure TSMBreakGrid.sbBreakHorzScroll(Sender: TObject;
ScrollCode: TScrollCode; var ScrollPos: Integer);
var
i, intCharWidth, intSampleWidth: Integer;
R: TRect;
begin
if Assigned(OnScrollHorizontal) then
OnScrollHorizontal(Sender, ScrollCode, ScrollPos);
with pbBreaks do
begin
R := ClientRect;
R.Top := R.Top + 20;
intCharWidth := Canvas.TextWidth('W');
end;
intSampleWidth := (R.Right-R.Left) div intCharWidth;
// sbBreakHorz.Max := 1000;
case ScrollCode of
scLineUp: i := intBreakShiftX - 1;
scLineDown: i := intBreakShiftX + 1;
scPageUp: i := intBreakShiftX - intSampleWidth;
scPageDown: i := intBreakShiftX + intSampleWidth;
scTop: i := 0;
scBottom: i := sbBreakHorz.Max;
scPosition,
scEndScroll,
scTrack: with sbBreakHorz do
begin
i := Min + ScrollPos;//(ScrollPos * (Max - Min)) div MaxShortInt;
// caption := Format('ScrollPos=%d, Min=%d, Max=%d, Cur=%d', [ScrollPos, Min, Max, Position])
end;
else
i := intBreakShiftX;
end;
if (i < 0) then
i := 0;
if (i > sbBreakHorz.Max) then
i := sbBreakHorz.Max;
if (i <> intBreakShiftX) then
begin
sbBreakHorz.Position := i;
intBreakShiftX := i;
pbBreaks.Invalidate
end;
end;
procedure TSMBreakGrid.sbBreakVertScroll(Sender: TObject;
ScrollCode: TScrollCode; var ScrollPos: Integer);
var
i, intSampleHeight: Integer;
begin
if Assigned(OnScrollvertical) then
OnScrollVertical(Sender, ScrollCode, ScrollPos);
intSampleHeight := 5;
sbBreakVert.Max := Rows.Count;
case ScrollCode of
scLineUp: i := intBreakShiftY - 1;
scLineDown: i := intBreakShiftY + 1;
scPageUp: i := intBreakShiftY - intSampleHeight;
scPageDown: i := intBreakShiftY + intSampleHeight;
scTop: i := 0;
scBottom: i := sbBreakVert.Max;
scPosition,
scEndScroll,
scTrack: with sbBreakVert do
begin
i := Min + ScrollPos;//(ScrollPos * (Max - Min)) div MaxShortInt;
// caption := Format('ScrollPos=%d, Min=%d, Max=%d, Cur=%d', [ScrollPos, Min, Max, Position])
end;
else
i := intBreakShiftY;
end;
if (i < 0) then
i := 0;
if (i > sbBreakVert.Max) then
i := sbBreakVert.Max;
if (i <> intBreakShiftY) then
begin
sbBreakVert.Position := i;
intBreakShiftY := i;
pbBreaks.Invalidate
end;
end;
function TSMBreakGrid.GetBreak(X: Integer; IsAdd: Boolean): Integer;
var
i, j, intPos, intCharWidth: Integer;
IsFound: Boolean;
begin
Result := -1;
intCharWidth := pbBreaks.Canvas.TextWidth('W');
intPos := X div intCharWidth;
if IsAdd and (intPos = 0) then exit;
IsFound := False;
for i := 0 to Columns.Count-1 do
begin
j := Columns[i].Position - intBreakShiftX;
if (j = intPos) then
begin
IsFound := True;
Result := i;
break
end;
end;
if IsAdd and not IsFound then
begin
if (Columns.Count = 0) then
i := 0;
with Columns.Insert(i) do
Position := intBreakShiftX + intPos;
if Assigned(OnChangeColumns) then
OnChangeColumns(Self);
end;
end;
procedure TSMBreakGrid.Resize;
begin
inherited;
{change position for scrollbars and paintbox}
sbBreakHorz.Top := ClientHeight - sbBreakHorz.Height - 2;
sbBreakVert.Height := sbBreakHorz.Top - sbBreakVert.Top;
pbBreaks.Height := ClientHeight - pbBreaks.Top - 2;
sbBreakVert.Left := ClientWidth - sbBreakVert.Width - 2;
sbBreakHorz.Width := sbBreakVert.Left-sbBreakHorz.Left;
pbBreaks.Width := sbBreakHorz.Width;
end;
end.
|
unit TelaConsultaRapidaCupom;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBTables, RxQuery, Grids, DBGrids, ExtCtrls, StdCtrls, CartaoCredito,
Buttons, Mask, ToolEdit, AdvGlowButton, DBClient, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, pcnConversaoNFe,
cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, UnitCheckoutLibrary,
cxClasses, cxControls, cxGridCustomView, cxGrid, Menus;
type
TFormTelaConsultaRapidaCupom = class(TForm)
DSSQLCupom: TDataSource;
SQLCupom: TRxQuery;
SQLCupomCUPOA13ID: TStringField;
SQLCupomCUPODEMIS: TDateTimeField;
SQLCupomCLIEA60RAZAOSOC: TStringField;
SQLCupomVENDA60NOME: TStringField;
SQLCupomPLRCA60DESCR: TStringField;
PanelDescricao: TPanel;
Panel2: TPanel;
Label1: TLabel;
edtDataInicial: TDateEdit;
SQLCupomCUPOINRO: TIntegerField;
SQLCupomVLRLIQ: TFloatField;
SQLCupomCLIENTECNPJ: TStringField;
btTransmite: TAdvGlowButton;
BtInutilizarNFCE: TAdvGlowButton;
SQLCupomCHAVEACESSO: TStringField;
edtDataFinal: TDateEdit;
Label2: TLabel;
btnAtualizar: TSpeedButton;
cdsCupom: TClientDataSet;
cdsCupomCUPOA13ID: TStringField;
cdsCupomCUPOINRO: TIntegerField;
cdsCupomVLRLIQ: TFloatField;
cdsCupomCUPODEMIS: TDateTimeField;
cdsCupomCLIEA60RAZAOSOC: TStringField;
cdsCupomVENDA60NOME: TStringField;
cdsCupomPLRCA60DESCR: TStringField;
cdsCupomCLIENTECNPJ: TStringField;
cdsCupomCHAVEACESSO: TStringField;
cdsCupomSelecionar: TBooleanField;
btnEnviarTodos: TAdvGlowButton;
cdsCupomMensagem: TStringField;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
cxGrid1DBTableView1CUPOA13ID: TcxGridDBColumn;
cxGrid1DBTableView1CUPOINRO: TcxGridDBColumn;
cxGrid1DBTableView1VLRLIQ: TcxGridDBColumn;
cxGrid1DBTableView1CUPODEMIS: TcxGridDBColumn;
cxGrid1DBTableView1CHAVEACESSO: TcxGridDBColumn;
cxGrid1DBTableView1Selecionar: TcxGridDBColumn;
cxGrid1DBTableView1Mensagem: TcxGridDBColumn;
lblTitulo: TLabel;
PopupMenu1: TPopupMenu;
Recalcular1: TMenuItem;
SQLCupomRecalc: TRxQuery;
SQLCupomItemRecalc: TRxQuery;
SQLCupomRecalcCUPOA13ID: TStringField;
SQLCupomRecalcCUPON2TOTITENS: TFloatField;
SQLCupomRecalcCUPON2DESC: TFloatField;
SQLCupomRecalcCUPON2ACRESC: TFloatField;
SQLCupomRecalcCUPON2TOTITENSRET: TFloatField;
SQLCupomRecalcCUPON2DESCITENS: TFloatField;
SQLCupomRecalcCUPON2BASEICMS: TFloatField;
SQLCupomRecalcCUPON2VLRICMS: TFloatField;
SQLCupomRecalcCUPON2VLRPIS: TFloatField;
SQLCupomRecalcCUPON2VLRCOFINS: TFloatField;
SQLCupomItemRecalcCUPOA13ID: TStringField;
SQLCupomItemRecalcCOITN2ICMSALIQ: TFloatField;
SQLCupomItemRecalcCPITN2BASEICMS: TFloatField;
SQLCupomItemRecalcCPITN2VLRICMS: TFloatField;
SQLCupomItemRecalcCPITN2VLRPIS: TFloatField;
SQLCupomItemRecalcCPITN2VLRCOFINS: TFloatField;
SQLCupomItemRecalcCPITN2IMPOSTOMED: TFloatField;
SQLCupomItemRecalcTOTAL_ITEM: TFloatField;
SQLCupomItemRecalcBASE_ST_RETIDO: TFloatField;
SQLCupomItemRecalcVALOR_ST_RETIDO: TFloatField;
SQLCupomItemRecalcALIQUOTA_PIS: TFloatField;
SQLCupomItemRecalcVLR_BASE_PIS: TFloatField;
SQLCupomItemRecalcALIQUOTA_COFINS: TFloatField;
SQLCupomItemRecalcVLR_BASE_COFINS: TFloatField;
SQLCupomItemRecalcPERC_REDUCAO_BASE_CALCULO: TFloatField;
SQLCupomItemRecalcPRODICOD: TIntegerField;
procedure BtInutilizarNFCEClick(Sender: TObject);
procedure btTransmiteClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
Procedure AbrirDadosCupom;
procedure btnAtualizarClick(Sender: TObject);
procedure SQLCupomAfterOpen(DataSet: TDataSet);
procedure btnEnviarTodosClick(Sender: TObject);
procedure cxGrid1DBTableView1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cxGrid1DBTableView1SelecionarHeaderClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edtDataInicialExit(Sender: TObject);
procedure edtDataFinalExit(Sender: TObject);
procedure Recalcular1Click(Sender: TObject);
private
{ Private declarations }
function Consulta_NFCe : Boolean;
procedure Inicia_NFe;
public
{ Public declarations }
ProvedorCartao, NomeNumerarioCartao : string;
TempoLimite, TempoIntervalo: Integer;
RetornoCartao : TInfoRetorno;
DadosImpressora : TInfoImpressao;
Cancelamento : Boolean;
end;
var
FormTelaConsultaRapidaCupom: TFormTelaConsultaRapidaCupom;
implementation
uses UnitLibrary, DataModulo, Principal, TelaItens, DataModuloTemplate;
{$R *.dfm}
procedure TFormTelaConsultaRapidaCupom.BtInutilizarNFCEClick(
Sender: TObject);
var ano, Modelo, Serie, Justificativa, NumeroInicial, NumeroFinal : string;
begin
if (copy(ECFAtual,1,4) = 'NFCE') then
begin
ano := FormatDateTime('yyyy',now);
Modelo := '65';
Serie := dm.SQLTerminalAtivoTERMICOD.AsString;
if not(InputQuery('WebServices Inutilização ', 'Modelo', Modelo)) then
exit;
if not(InputQuery('WebServices Inutilização ', 'Serie', Serie)) then
exit;
if Modelo = '' then
Modelo := '65';
if Serie = '' then
Serie := dm.SQLTerminalAtivoTERMICOD.AsString;
if not(InputQuery('WebServices Inutilização ', 'Justificativa', Justificativa)) then
exit;
if Justificativa = '' then
Justificativa := 'Falha no processo de geração desta NFCe!';
if not(InputQuery('WebServices Inutilização ', 'Número Inicial', NumeroInicial)) then
exit;
if not(InputQuery('WebServices Inutilização ', 'Número Final', NumeroFinal)) then
exit;
try
dm.ACBrNFe.WebServices.Inutiliza(dm.SQLEmpresaEMPRA14CGC.AsString,
Justificativa,
StrToInt(Ano),
StrToInt(Modelo),
StrToInt(Serie),
StrToInt(NumeroInicial),
StrToInt(NumeroFinal));
ShowMessage('Numeração Inutilizada.');
except
on e:Exception do
ShowMessage(e.message);
end;
end;
end;
procedure TFormTelaConsultaRapidaCupom.btTransmiteClick(
Sender: TObject);
begin
ModalResult := mrOk ;
end;
procedure TFormTelaConsultaRapidaCupom.FormCreate(Sender: TObject);
begin
edtDataInicial.Date := Now;
edtDataFinal.Date := Now;
AbrirDadosCupom;
end;
procedure TFormTelaConsultaRapidaCupom.AbrirDadosCupom;
begin
SQLCupom.Close;
SQLCupom.MacroByName('DataEmissao').Value := 'Cupom.CUPODEMIS BETWEEN ' + Quotedstr(FormatDateTime('mm/dd/yyyy',edtDataInicial.Date))
+ ' and '+ Quotedstr(FormatDateTime('mm/dd/yyyy',edtDataFinal.Date));
SQLCupom.MacroByName('Empresa').Value := 'Cupom.EMPRICOD = ' + EmpresaPadrao;
SQLCupom.Open;
end;
procedure TFormTelaConsultaRapidaCupom.btnAtualizarClick(Sender: TObject);
begin
AbrirDadosCupom;
end;
procedure TFormTelaConsultaRapidaCupom.SQLCupomAfterOpen(
DataSet: TDataSet);
begin
cdsCupom.close;
cdsCupom.CreateDataSet;
cdsCupom.DisableControls;
SQLCupom.DisableControls;
try
while not SQLCupom.eof do
begin
cdsCupom.Insert;
cdsCupomCUPOA13ID.Value := SQLCupomCUPOA13ID.Value;
cdsCupomCUPOINRO.Value := SQLCupomCUPOINRO.Value;
cdsCupomVLRLIQ.Value := SQLCupomVLRLIQ.Value;
cdsCupomCUPODEMIS.Value := SQLCupomCUPODEMIS.Value;
cdsCupomCLIEA60RAZAOSOC.Value := SQLCupomCLIEA60RAZAOSOC.Value;
cdsCupomVENDA60NOME.Value := SQLCupomVENDA60NOME.Value;
cdsCupomPLRCA60DESCR.Value := SQLCupomPLRCA60DESCR.Value;
cdsCupomCLIENTECNPJ.Value := SQLCupomCLIENTECNPJ.Value;
cdsCupomCHAVEACESSO.Value := SQLCupomCHAVEACESSO.Value;
cdsCupomSelecionar.Value := True;
cdsCupom.Post;
SQLCupom.next;
end;
finally
SQLCupom.EnableControls;
cdsCupom.EnableControls;
end;
end;
procedure TFormTelaConsultaRapidaCupom.btnEnviarTodosClick(
Sender: TObject);
var
vCupomOK, vCupomNaoOK:Integer;
begin
if not cdsCupom.Locate('Selecionar', true, []) then
raise Exception.Create('Nenhum cupom selecionado!');
vCupomOK := 0;
vCupomNaoOK := 0;
cdsCupom.First;
while not cdsCupom.eof do
begin
try
if cdsCupomSelecionar.Value then
begin
if Consulta_NFCe then
Inc(vCupomOK)
else
begin
Imprimir_Nfce := False;
FormTelaItens.Transmite_NFCe(cdsCupomCUPOA13ID.Value);
if cdsCupomMensagem.AsString = EmptyStr then
Inc(vCupomOK)
else
Inc(vCupomNaoOK);
end;
end;
except
on E: Exception do
begin
inc(vCupomNaoOK);
cdsCupom.Edit;
cdsCupomMensagem.Value := E.Message;
cdsCupom.Post;
end;
end;
cdsCupom.Next;
end;
Imprimir_Nfce := True;
ShowMessage('Cupom(s) Enviado(s): ' + FormatFloat('000', vCupomOK)
+ sLineBreak +'Cupom(s) não Enviado(s): '+ FormatFloat('000', vCupomNaoOK));
end;
procedure TFormTelaConsultaRapidaCupom.cxGrid1DBTableView1KeyDown(
Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
SQLCupom.locate('CUPOA13ID', cdsCupomCUPOA13ID.Value, []);
ModalResult := mrOk;
end;
if Key = VK_ESCAPE then ModalResult := mrCancel;
end;
procedure TFormTelaConsultaRapidaCupom.cxGrid1DBTableView1SelecionarHeaderClick(
Sender: TObject);
begin
try
cdsCupom.DisableControls;
cdsCupom.First;
while not cdsCupom.eof do
begin
cdsCupom.Edit;
cdsCupomSelecionar.Value := not cdsCupomSelecionar.Value;
cdsCupom.Post;
cdsCupom.Next;
end;
finally
cdsCupom.EnableControls;
end;
end;
procedure TFormTelaConsultaRapidaCupom.FormShow(Sender: TObject);
begin
btnEnviarTodos.Enabled := not Cancelamento;
btTransmite.Enabled := not Cancelamento;
BtInutilizarNFCE.Enabled := not Cancelamento;
cxGrid1.SetFocus;
end;
procedure TFormTelaConsultaRapidaCupom.edtDataInicialExit(Sender: TObject);
begin
AbrirDadosCupom;
end;
procedure TFormTelaConsultaRapidaCupom.edtDataFinalExit(Sender: TObject);
begin
AbrirDadosCupom;
end;
function TFormTelaConsultaRapidaCupom.Consulta_NFCe: Boolean;
var
Chave : String;
begin
Result := False;
Inicia_NFe;
dm.ACBrNFe.Consultar(cdsCupomCHAVEACESSO.AsString);
if (dm.ACBrNFe.WebServices.Consulta.cStat = 613) or (dm.ACBrNFe.WebServices.Consulta.cStat = 539) then
begin
if dm.ACBrNFe.WebServices.Consulta.XMotivo <> '' then
begin
if pos('NF-e [', dm.ACBrNFe.WebServices.Consulta.XMotivo) > 0 then
begin
Chave := Copy(dm.ACBrNFe.WebServices.Consulta.XMotivo, pos('NF-e [', dm.ACBrNFe.WebServices.Consulta.XMotivo), 200);
Chave := StringReplace(Chave, 'NF-e [', '', [rfReplaceAll, rfIgnoreCase]);
Chave := StringReplace(Chave, ']', '', [rfReplaceAll]);
if Chave <> '' then
begin
dm.SQLCupom.close;
dm.SQLCupom.macrobyname('MFiltro').Value := 'CUPOA13ID = ''' + cdsCupomCUPOA13ID.Value + '''';
dm.SQLCupom.Open;
dm.SQLCupom.RequestLive := True;
dm.SQLCupom.edit;
dm.SQLCupomCHAVEACESSO.AsString := Chave;
dm.SQLCupom.Post;
dm.ACBrNFe.Consultar(Chave);
if (dm.ACBrNFe.WebServices.Consulta.cStat = 100) then
begin
DM.SQLTemplate.Close;
DM.SQLTemplate.SQL.Clear;
DM.SQLTemplate.SQL.Add('Update CUPOM Set STNFE = ' + IntToStr(dm.ACBrNFe.WebServices.consulta.cStat));
DM.SQLTemplate.SQL.Add(', PROTOCOLO=''' + dm.ACBrNFe.WebServices.consulta.Protocolo + '''');
DM.SQLTemplate.SQL.Add(', PENDENTE=' + QuotedStr('S'));
DM.SQLTemplate.SQL.Add(' Where CUPOA13ID =''' + cdsCupomCUPOA13ID.Value + '''');
DM.SQLTemplate.ExecSQL;
Result := True;
end;
Result := True;
end;
// SQLCupom.Close;
// SQLCupom.Open;
// ConsultarDenovo := True;
end;
end
else if dm.ACBrNFe.WebServices.Consulta.protNFe.xMotivo <> '' then
begin
Chave := Copy(dm.ACBrNFe.WebServices.Consulta.XMotivo, pos('[chNFe:', dm.ACBrNFe.WebServices.Consulta.XMotivo), 200);
Chave := StringReplace(Chave, '[chNFe:', '', [rfReplaceAll, rfIgnoreCase]);
Chave := StringReplace(Chave, ']', '', [rfReplaceAll]);
if Chave <> '' then
begin
if dm.SQLCupom.IsEmpty then
begin
dm.SQLCupom.close;
dm.SQLCupom.macrobyname('MFiltro').Value := 'CUPOA13ID = ''' + cdsCupomCUPOA13ID.Value + '''';
dm.SQLCupom.Open;
end;
dm.SQLCupom.RequestLive := True;
dm.SQLCupom.edit;
dm.SQLCupomCHAVEACESSO.AsString := Chave;
dm.SQLCupom.Post;
Result := True;
end;
end;
end
else
if (dm.ACBrNFe.WebServices.Consulta.cStat = 100) then
begin
DM.SQLTemplate.Close;
DM.SQLTemplate.SQL.Clear;
DM.SQLTemplate.SQL.Add('Update CUPOM Set STNFE = ' + IntToStr(dm.ACBrNFe.WebServices.consulta.cStat));
DM.SQLTemplate.SQL.Add(', PROTOCOLO=''' + dm.ACBrNFe.WebServices.consulta.Protocolo + '''');
DM.SQLTemplate.SQL.Add(', PENDENTE=' + QuotedStr('S'));
DM.SQLTemplate.SQL.Add(' Where CUPOA13ID =''' + cdsCupomCUPOA13ID.Value + '''');
DM.SQLTemplate.ExecSQL;
Result := True;
end;
end;
procedure TFormTelaConsultaRapidaCupom.Inicia_NFe;
begin
{$IFDEF ACBrNFeOpenSSL}
dm.ACBrNFe.Configuracoes.Certificados.ArquivoPFX := dm.sqlEmpresa.FieldByName('EMPRA100CERTIFSERIE').AsString;
dm.ACBrNFe.Configuracoes.Certificados.Certificado := dm.sqlEmpresa.FieldByName('EMPRA100CERTIFSERIE').AsString;
dm.ACBrNFe.Configuracoes.Certificados.Senha := dm.sqlEmpresa.FieldByName('EMPRA35CERTIFSENHA').AsString;
{$ELSE}
dm.ACBrNFe.Configuracoes.Certificados.NumeroSerie := dm.sqlEmpresa.FieldByName('EMPRA100CERTIFSERIE').AsString;
dm.ACBrNFe.Configuracoes.Certificados.Senha := dm.sqlEmpresa.FieldByName('EMPRA35CERTIFSENHA').AsString;
{$ENDIF}
if dm.sqlEmpresa.FieldByName('VERSAO').AsString = '4' then
dm.ACBrNFe.Configuracoes.Geral.VersaoDF := ve400
else
dm.ACBrNFe.Configuracoes.Geral.VersaoDF := ve310;
dm.ACBrNFe.Configuracoes.Geral.IdCSC := dm.sqlEmpresa.FieldByName('idTOKEN').AsString;
dm.ACBrNFe.Configuracoes.Geral.CSC := dm.sqlEmpresa.FieldByName('TOKEN').AsString;
DM.ACBrNFe.Configuracoes.Geral.VersaoQRCode := veqr200;
dm.ACBrNFeDANFeESCPOS.ViaConsumidor := True;
dm.ACBrNFeDANFeESCPOS.ImprimeItens := True;
dm.ACBrNFeDANFeESCPOS.ViaConsumidor := True;
dm.ACBrNFeDANFeESCPOS.ImprimeItens := True;
end;
procedure TFormTelaConsultaRapidaCupom.Recalcular1Click(Sender: TObject);
var
vTotalBaseICMS, vTotalValorICMS, ReducaoICMS : Real;
begin
if MessageDlg('Recalcular Impostos?',mtConfirmation,[mbYes,mbNo],0) = mrNo then
Exit;
ReducaoICMS := 0;
SQLCupomRecalc.Close;
SQLCupomRecalc.ParamByName('CUPOA13ID').AsString := cdsCupomCUPOA13ID.AsString;
SQLCupomRecalc.Open;
if SQLCupomRecalc.IsEmpty then
exit;
SQLCupomItemRecalc.Close;
SQLCupomItemRecalc.ParamByName('CUPOA13ID').AsString := cdsCupomCUPOA13ID.AsString;
SQLCupomItemRecalc.Open;
while not SQLCupomItemRecalc.Eof do
begin
DM.sqlConsulta.SQL.Clear;
DM.sqlConsulta.SQL.Add('select P.PRODICOD, P.ICMSICOD, P.PRODIORIGEM, P.PRODCSUBSTRIB, P.PRODN2PIS, P.PRODISITTRIB, P.PRODN2PERCSUBST, ');
DM.sqlConsulta.SQL.Add('P.PRODCCOFINS, P.PRODA2CSTCOFINS, P.PRODA2CSTIPI, P.PRODA2CSTPIS, P.PRODN2ALIQCOFINS, P.PRODN2ALIQPIS, ');
DM.sqlConsulta.SQL.Add('P.VALOR_FRETE, P.VALOR_ICMSST, P.PERC_REDUCAO_BASE_CALCULO, P.PERC_REDUCAO_BASE_CALCULO_ST, P.VALOR_ICM_ST_RET, ');
DM.sqlConsulta.SQL.Add('P.BASE_ICM_ST_RET, P.VALOR_ICMS_SUBSTITUTO, I.ICMSN2ALIQUOTA, I.ICMSA60DESCR from PRODUTO P ');
DM.sqlConsulta.SQL.Add('inner join ICMS I on I.ICMSICOD = P.ICMSICOD ');
DM.sqlConsulta.SQL.Add('where PRODICOD = ' + IntToStr(SQLCupomItemRecalcPRODICOD.AsInteger));
DM.sqlConsulta.Open;
SQLCupomItemRecalc.Edit;
if (dm.sqlConsulta.FieldByName('PRODISITTRIB').AsString = '40') or
(dm.sqlConsulta.FieldByName('PRODISITTRIB').AsString = '41') or
(dm.sqlConsulta.FieldByName('PRODISITTRIB').AsString = '60') or
(dm.sqlConsulta.FieldByName('PRODISITTRIB').AsString = '400') or
(dm.sqlConsulta.FieldByName('PRODISITTRIB').AsString = '500') then
begin
SQLCupomItemRecalcCPITN2BASEICMS.AsFloat := 0;
SQLCupomItemRecalcCPITN2BASEICMS.AsFloat := 0;
SQLCupomItemRecalcCOITN2ICMSALIQ.asFloat := 0;
SQLCupomItemRecalcCPITN2VLRICMS.AsFloat := 0;
SQLCupomItemRecalcPERC_REDUCAO_BASE_CALCULO.AsFloat := 0;
end
else
begin
SQLCupomItemRecalcCPITN2BASEICMS.AsFloat := SQLCupomItemRecalcTOTAL_ITEM.AsFloat;
SQLCupomItemRecalcCOITN2ICMSALIQ.asFloat := RetornaAliquotaICMSProduto(DM.sqlConsulta.FieldByName('ICMSICOD').AsInteger);
SQLCupomItemRecalcCPITN2VLRICMS.AsFloat := SQLCupomItemRecalcCOITN2ICMSALIQ.asFloat * RetornaAliquotaICMSProduto(DM.sqlConsulta.FieldByName('ICMSICOD').AsInteger);
if DM.sqlConsulta.FieldByName('PERC_REDUCAO_BASE_CALCULO').AsFloat > 0 then
begin
ReducaoICMS := 100 - DM.sqlConsulta.FieldByName('PERC_REDUCAO_BASE_CALCULO').AsFloat;
SQLCupomItemRecalcCPITN2BASEICMS.AsFloat := SQLCupomItemRecalcTOTAL_ITEM.AsFloat * (ReducaoICMS / 100);
SQLCupomItemRecalcPERC_REDUCAO_BASE_CALCULO.AsFloat := ReducaoICMS;
end;
SQLCupomItemRecalcCPITN2VLRICMS.AsFloat := SQLCupomItemRecalcCPITN2BASEICMS.AsFloat * (SQLCupomItemRecalcCOITN2ICMSALIQ.asFloat / 100);
vTotalBaseICMS := vTotalBaseICMS + SQLCupomItemRecalcCPITN2BASEICMS.AsFloat;
vTotalValorICMS := vTotalValorICMS + SQLCupomItemRecalcCPITN2VLRICMS.AsFloat;
SQLCupomItemRecalc.Post;
end;
SQLCupomItemRecalc.Next;
end;
SQLCupomRecalc.Edit;
SQLCupomRecalcCUPON2BASEICMS.AsFloat := vTotalBaseICMS;
SQLCupomRecalcCUPON2VLRICMS.AsFloat := vTotalValorICMS;
SQLCupomRecalc.Post;
cdsCupom.Edit;
cdsCupomMensagem.AsString := '';
cdsCupom.Post;
end;
end.
|
unit record_props_0;
interface
implementation
type
TRec = record
function GetCnt: Int32;
property CNT: Int32 read GetCnt;
end;
function TRec.GetCnt: Int32;
begin
Result := 3;
end;
var G: Int32;
R: TRec;
procedure Test;
begin
G := R.CNT;
end;
initialization
Test();
finalization
Assert(G = 3);
end. |
unit Ths.Erp.Database.Table.AyarVergiOrani;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Constants,
Ths.Erp.Database.Singleton,
Ths.Erp.Database.Table,
Ths.Erp.Database.Table.HesapKarti;
type
TAyarVergiOrani = class(TTable)
private
FVergiOrani: TFieldDB;
FSatisVergiHesapKodu: TFieldDB;
FSatisIadeVergiHesapKodu: TFieldDB;
FAlisVergiHesapKodu: TFieldDB;
FAlisIadeVergiHesapKodu: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property VergiOrani: TFieldDB read FVergiOrani write FVergiOrani;
Property SatisVergiHesapKodu: TFieldDB read FSatisVergiHesapKodu write FSatisVergiHesapKodu;
Property SatisIadeVergiHesapKodu: TFieldDB read FSatisIadeVergiHesapKodu write FSatisIadeVergiHesapKodu;
Property AlisVergiHesapKodu: TFieldDB read FAlisVergiHesapKodu write FAlisVergiHesapKodu;
Property AlisIadeVergiHesapKodu: TFieldDB read FAlisIadeVergiHesapKodu write FAlisIadeVergiHesapKodu;
end;
implementation
constructor TAyarVergiOrani.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'ayar_vergi_orani';
SourceCode := '1000';
FVergiOrani := TFieldDB.Create('vergi_orani', ftFloat, 0, 2);
FSatisVergiHesapKodu := TFieldDB.Create('satis_vergi_hesap_kodu', ftString, '', 0, True, False);
FSatisVergiHesapKodu.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FSatisVergiHesapKodu.FK.FKCol := TFieldDB.Create(THesapKarti(FSatisVergiHesapKodu.FK.FKTable).HesapKodu.FieldName, THesapKarti(FSatisVergiHesapKodu.FK.FKTable).HesapKodu.FieldType, '');
FSatisIadeVergiHesapKodu := TFieldDB.Create('satis_iade_vergi_hesap_kodu', ftString, '', 0, True, False);
FSatisIadeVergiHesapKodu.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FSatisIadeVergiHesapKodu.FK.FKCol := TFieldDB.Create(THesapKarti(FSatisIadeVergiHesapKodu.FK.FKTable).HesapKodu.FieldName, THesapKarti(FSatisIadeVergiHesapKodu.FK.FKTable).HesapKodu.FieldType, '');
FAlisVergiHesapKodu := TFieldDB.Create('alis_vergi_hesap_kodu', ftString, '', 0, True, False);
FAlisVergiHesapKodu.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FAlisVergiHesapKodu.FK.FKCol := TFieldDB.Create(THesapKarti(FAlisVergiHesapKodu.FK.FKTable).HesapKodu.FieldName, THesapKarti(FAlisVergiHesapKodu.FK.FKTable).HesapKodu.FieldType, '');
FAlisIadeVergiHesapKodu := TFieldDB.Create('alis_iade_vergi_hesap_kodu', ftString, '', 0, True, False);
FAlisIadeVergiHesapKodu.FK.FKTable := THesapKarti.Create(OwnerDatabase);
FAlisIadeVergiHesapKodu.FK.FKCol := TFieldDB.Create(THesapKarti(FAlisIadeVergiHesapKodu.FK.FKTable).HesapKodu.FieldName, THesapKarti(FAlisIadeVergiHesapKodu.FK.FKTable).HesapKodu.FieldType, '');
end;
procedure TAyarVergiOrani.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FVergiOrani.FieldName,
TableName + '.' + FSatisVergiHesapKodu.FieldName,
TableName + '.' + FSatisIadeVergiHesapKodu.FieldName,
TableName + '.' + FAlisVergiHesapKodu.FieldName,
TableName + '.' + FAlisIadeVergiHesapKodu.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FVergiOrani.FieldName).DisplayLabel := 'Vergi Oranı';
Self.DataSource.DataSet.FindField(FSatisVergiHesapKodu.FieldName).DisplayLabel := 'Satış Vergi Hesap Kodu';
Self.DataSource.DataSet.FindField(FSatisIadeVergiHesapKodu.FieldName).DisplayLabel := 'Satış İade Vergi Hesap Kodu';
Self.DataSource.DataSet.FindField(FAlisVergiHesapKodu.FieldName).DisplayLabel := 'Alış Vergi Hesap Kodu';
Self.DataSource.DataSet.FindField(FAlisIadeVergiHesapKodu.FieldName).DisplayLabel := 'Alış İade Vergi Hesap Kodu';
end;
end;
end;
procedure TAyarVergiOrani.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FVergiOrani.FieldName,
TableName + '.' + FSatisVergiHesapKodu.FieldName,
TableName + '.' + FSatisIadeVergiHesapKodu.FieldName,
TableName + '.' + FAlisVergiHesapKodu.FieldName,
TableName + '.' + FAlisIadeVergiHesapKodu.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FVergiOrani.Value := FormatedVariantVal(FieldByName(FVergiOrani.FieldName).DataType, FieldByName(FVergiOrani.FieldName).Value);
FSatisVergiHesapKodu.Value := FormatedVariantVal(FieldByName(FSatisVergiHesapKodu.FieldName).DataType, FieldByName(FSatisVergiHesapKodu.FieldName).Value);
FSatisIadeVergiHesapKodu.Value := FormatedVariantVal(FieldByName(FSatisIadeVergiHesapKodu.FieldName).DataType, FieldByName(FSatisIadeVergiHesapKodu.FieldName).Value);
FAlisVergiHesapKodu.Value := FormatedVariantVal(FieldByName(FAlisVergiHesapKodu.FieldName).DataType, FieldByName(FAlisVergiHesapKodu.FieldName).Value);
FAlisIadeVergiHesapKodu.Value := FormatedVariantVal(FieldByName(FAlisIadeVergiHesapKodu.FieldName).DataType, FieldByName(FAlisIadeVergiHesapKodu.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TAyarVergiOrani.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FVergiOrani.FieldName,
FSatisVergiHesapKodu.FieldName,
FSatisIadeVergiHesapKodu.FieldName,
FAlisVergiHesapKodu.FieldName,
FAlisIadeVergiHesapKodu.FieldName
]);
NewParamForQuery(QueryOfInsert, FVergiOrani);
NewParamForQuery(QueryOfInsert, FSatisVergiHesapKodu);
NewParamForQuery(QueryOfInsert, FSatisIadeVergiHesapKodu);
NewParamForQuery(QueryOfInsert, FAlisVergiHesapKodu);
NewParamForQuery(QueryOfInsert, FAlisIadeVergiHesapKodu);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TAyarVergiOrani.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FVergiOrani.FieldName,
FSatisVergiHesapKodu.FieldName,
FSatisIadeVergiHesapKodu.FieldName,
FAlisVergiHesapKodu.FieldName,
FAlisIadeVergiHesapKodu.FieldName
]);
NewParamForQuery(QueryOfUpdate, FVergiOrani);
NewParamForQuery(QueryOfUpdate, FSatisVergiHesapKodu);
NewParamForQuery(QueryOfUpdate, FSatisIadeVergiHesapKodu);
NewParamForQuery(QueryOfUpdate, FAlisVergiHesapKodu);
NewParamForQuery(QueryOfUpdate, FAlisIadeVergiHesapKodu);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TAyarVergiOrani.Clone():TTable;
begin
Result := TAyarVergiOrani.Create(Database);
Self.Id.Clone(TAyarVergiOrani(Result).Id);
FVergiOrani.Clone(TAyarVergiOrani(Result).FVergiOrani);
FSatisVergiHesapKodu.Clone(TAyarVergiOrani(Result).FSatisVergiHesapKodu);
FSatisIadeVergiHesapKodu.Clone(TAyarVergiOrani(Result).FSatisIadeVergiHesapKodu);
FAlisVergiHesapKodu.Clone(TAyarVergiOrani(Result).FAlisVergiHesapKodu);
FAlisIadeVergiHesapKodu.Clone(TAyarVergiOrani(Result).FAlisIadeVergiHesapKodu);
end;
end.
|
{ Routines that work on CAN frames in isolation, and are independent of any
* CAN library use state or other external state.
}
module can_frame;
define can_frame_init;
define can_get_reset;
define can_add8;
define can_add16;
define can_add24;
define can_add32;
define can_add_fp32;
define can_add_fp32f;
define can_get_left;
define can_get_i8u;
define can_get_i8s;
define can_get_i16u;
define can_get_i16s;
define can_get_i24u;
define can_get_i24s;
define can_get_i32u;
define can_get_i32s;
define can_get_fp32;
define can_get_fp32f;
define can_get_err;
%include 'can2.ins.pas';
{
********************************************************************************
*
* Subroutine CAN_FRAME_INIT (FR)
*
* Initialize the CAN frame descriptor FR. All fields will be set and
* initialized to "off" or benign values to the extent possible. The CAN frame
* will be initialized to:
*
* - Standard, not extended.
*
* - Data, not remote request.
*
* - ID 0.
*
* - 0 data bytes.
*
* Applications should always use this routine to initialize CAN frame
* descriptors. If the fields are changed or new fields added, this routine
* will be updated.
}
procedure can_frame_init ( {init CAN frame descriptor}
out fr: can_frame_t); {all fields set, STD data frame, no bytes, ID 0}
val_param;
begin
fr.id := 0;
fr.ndat := 0;
fr.geti := 0;
fr.flags := [];
end;
{
********************************************************************************
*
* Subroutine CAN_GET_RESET (FR)
*
* Reset the data byte reading state of the CAN frame FR, so that the first
* data byte will be the next byte read.
}
procedure can_get_reset ( {reset to read first data byte next time}
in out fr: can_frame_t); {frame to reset read index of}
val_param;
begin
fr.geti := 0; {reset of index of next data byte to get}
end;
{
********************************************************************************
*
* Subroutine CAN_ADD8 (FRAME, B)
*
* Add the byte in the low bits of B as the next data byte in the CAN frame
* FRAME. Nothing is done if the CAN frame already contains the maximum number
* of data bytes.
}
procedure can_add8 ( {add one 8 bit byte to a CAN frame being built}
in out frame: can_frame_t; {the frame to add a byte to}
in b: sys_int_conv8_t); {byte value in the low bits}
val_param;
begin
if frame.ndat >= 8 then return; {CAN frame already full ?}
frame.dat[frame.ndat] := b & 255; {add the new byte to the list}
frame.ndat := frame.ndat + 1; {update number of bytes in the frame}
end;
{
********************************************************************************
*
* Subroutines CAN_ADDn (FRAME, W)
*
* Add the N bytes in the low bits of the word W to the CAN frame FRAME. The
* bytes are added in most to least significant order. No new bytes are added
* when the CAN frame already contains the maximum number of bytes.
}
procedure can_add16 ( {add a 16 bit word to a CAN frame being built}
in out frame: can_frame_t; {the frame to add a byte to}
in w: sys_int_conv16_t); {word value in the low bits, high to low byte order}
val_param;
begin
can_add8 (frame, rshft(w, 8));
can_add8 (frame, w);
end;
{
********************
}
procedure can_add24 ( {add a 24 bit word to a CAN frame being built}
in out frame: can_frame_t; {the frame to add a byte to}
in w: sys_int_conv24_t); {word value in the low bits, high to low byte order}
val_param;
begin
can_add8 (frame, rshft(w, 16));
can_add8 (frame, rshft(w, 8));
can_add8 (frame, w);
end;
{
********************
}
procedure can_add32 ( {add a 32 bit word to a CAN frame being built}
in out frame: can_frame_t; {the frame to add a byte to}
in w: sys_int_conv32_t); {word value in the low bits, high to low byte order}
val_param;
begin
can_add8 (frame, rshft(w, 24));
can_add8 (frame, rshft(w, 16));
can_add8 (frame, rshft(w, 8));
can_add8 (frame, w);
end;
{
********************************************************************************
*
* Subroutine CAN_ADD_FP32 (FR, V)
*
* Add the value of V in IEEE 32 bit floating point format to the CAN frame.
* This will add 4 bytes (32 bits). The bytes are added in most to least
* significant order.
}
procedure can_add_fp32 ( {add IEEE 32 bit floating point to CAN frame}
in out fr: can_frame_t; {the frame to add the bytes to}
in v: double); {the value to add}
val_param;
var
fp32: sys_fp_ieee32_t; {the input value in IEEE 32 bit FP format}
begin
fp32 := sys_fp_to_ieee32 (v); {convert the value to IEEE 32 bit FP format}
can_add32 (fr, integer32(fp32)); {add the data bytes to the CAN frame}
end;
{
********************************************************************************
*
* Subroutine CAN_ADD_FP32F (FR, V)
*
* Add the value of V in Embed dsPIC 32 bit fast floating point format to the
* CAN frame. This will add 4 bytes (32 bits). The bytes are added in most to
* least significant order.
}
procedure can_add_fp32f ( {add Embed dsPIC 32 bit fast FP to CAN frame}
in out fr: can_frame_t; {the frame to add the bytes to}
in v: double); {the value to add}
val_param;
var
fp32f: pic_fp32f_t; {V in Embed dsPIC fast 32 bit FP format}
begin
fp32f := pic_fp32f_f_real (v); {convert to the target FP format}
can_add16 (fr, fp32f.w1); {add the high bytes to the CAN frame}
can_add16 (fr, fp32f.w0); {add the low bytes to the CAN frame}
end;
{
********************************************************************************
*
* Function CAN_GET_LEFT (FR)
*
* Returns the number of unread data bytes left in the CAN frame.
}
function can_get_left ( {get number of unread data bytes left}
in out fr: can_frame_t) {CAN frame to check}
:sys_int_machine_t; {unread bytes, always 0-8 range}
val_param;
begin
can_get_left := max(0, fr.ndat - fr.geti);
end;
{
********************************************************************************
*
* Function CAN_GET_I8U (FR)
*
* Gets the next unread data from the CAN frame FR. The unsigned 0-255 value
* of the byte is returned.
*
* Successive calls to this function return the data bytes of the CAN frame in
* sequence. After all data bytes have been read, this function returns 0
* indefinitely.
}
function can_get_i8u ( {get next 8 bit unsigned integer from CAN frame}
in out fr: can_frame_t) {frame to get data from}
:sys_int_machine_t; {0 to 255 value}
val_param;
begin
can_get_i8u := 0; {init to the value for no byte available}
if fr.geti >= fr.ndat then begin {no more data bytes ?}
fr.geti := fr.ndat + 1; {remember attempt to read past end of data}
return;
end;
can_get_i8u := fr.dat[fr.geti]; {fetch the data byte}
fr.geti := fr.geti + 1; {update read index for next time}
end;
{
********************************************************************************
*
* Functions CAN_GET_Inx (FR)
*
* These function all get sequential unread data from the CAN frame FR. They
* are all layered on CAN_GET_I8U, above. In the function names:
*
* N - Is the width of the data read in bits. Multi-byte data is assumed
* to be in high to low byte order.
*
* X - Is either U to indicate unsigned, or S to indicate signed.
}
function can_get_i8s (
in out fr: can_frame_t)
:sys_int_machine_t;
val_param;
var
ii: sys_int_machine_t;
begin
ii := can_get_i8u (fr);
if (ii >= 16#80) then ii := ii - 16#100;
can_get_i8s := ii;
end;
function can_get_i16u (
in out fr: can_frame_t)
:sys_int_machine_t;
val_param;
var
ii: sys_int_machine_t;
begin
ii := can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
can_get_i16u := ii;
end;
function can_get_i16s (
in out fr: can_frame_t)
:sys_int_machine_t;
val_param;
var
ii: sys_int_machine_t;
begin
ii := can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
if (ii >= 16#8000) then ii := ii - 16#10000;
can_get_i16s := ii;
end;
function can_get_i24u (
in out fr: can_frame_t)
:sys_int_machine_t;
val_param;
var
ii: sys_int_machine_t;
begin
ii := can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
can_get_i24u := ii;
end;
function can_get_i24s (
in out fr: can_frame_t)
:sys_int_machine_t;
val_param;
var
ii: sys_int_machine_t;
begin
ii := can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
if (ii >= 16#800000) then ii := ii - 16#1000000;
can_get_i24s := ii;
end;
function can_get_i32u (
in out fr: can_frame_t)
:sys_int_machine_t;
val_param;
var
ii: sys_int_machine_t;
begin
ii := can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
can_get_i32u := ii;
end;
function can_get_i32s (
in out fr: can_frame_t)
:sys_int_machine_t;
val_param;
var
ii: sys_int_machine_t;
begin
ii := can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
ii := lshft(ii, 8) ! can_get_i8u (fr);
can_get_i32s := ii;
end;
{
********************************************************************************
*
* Function CAN_GET_FP32 (FR)
*
* Return the next 4 CAN frame data bytes interpreted as a IEEE 32 bit floating
* point value. The bytes are assumed to be stored in most to least
* significant order.
}
function can_get_fp32 ( {get IEEE 32 bit FP from CAN frame}
in out fr: can_frame_t) {the CAN frame to get the data from}
:double;
val_param;
begin
can_get_fp32 :=
sys_fp_from_ieee32( sys_fp_ieee32_t(can_get_i32u(fr)) );
end;
{
********************************************************************************
*
* Function CAN_GET_FP32F (FR)
*
* Return the next 4 CAN frame data bytes interpreted as a Embed dsPIC 32 bit
* fast floating point value. The bytes are assumed to be stored in most to
* least significant order.
}
function can_get_fp32f ( {get Embed 32 bit dsPIC fast FP value}
in out fr: can_frame_t) {the CAN frame to get the data from}
:double;
val_param;
var
fp32f: pic_fp32f_t; {value in dsPIC fast FP format}
begin
fp32f.w1 := can_get_i16u (fr); {get the high 16 bit word}
fp32f.w0 := can_get_i16u (fr); {get the low 16 bit word}
can_get_fp32f := {convert to internal format, return value}
pic_fp32f_t_real (fp32f);
end;
{
********************************************************************************
*
* Function CAN_GET_ERR (FR, STAT)
*
* Check for error after all the data bytes of the CAN frame are supposed to
* have been read. The funtion returns FALSE with STAT set to no error if all
* the data bytes were read, but no attempt was made to read past the end of
* the data. Otherwise, the function returns TRUE with STAT set to indicate
* a appropriate error.
}
function can_get_err ( {check for data bytes exactly used up}
in fr: can_frame_t; {CAN frame to check reading state of}
out stat: sys_err_t) {error status if data not exactly used up}
:boolean; {FALSE for data exactly used up}
val_param;
begin
can_get_err := false; {init to no error}
sys_error_none (stat);
if fr.geti = fr.ndat then return; {data bytes exactly used up ?}
if fr.geti < fr.ndat
then begin {some bytes not read}
sys_stat_set (can_subsys_k, can_stat_unread_k, stat);
sys_stat_parm_int (fr.ndat, stat); {number of available bytes}
sys_stat_parm_int (fr.ndat - fr.geti, stat); {number of bytes read}
end
else begin {read past end of data bytes}
sys_stat_set (can_subsys_k, can_stat_ovread_k, stat);
sys_stat_parm_int (fr.ndat, stat); {number of available bytes}
end
;
can_get_err := true; {indicate returning with error}
end;
|
unit uDBTesteUsuario;
interface
uses uDbObject, Data.DB;
type TDbUsuario = class(TDbObject)
private
Fcodigo: TDbField;
Fsenha: TDbField;
FnomeUsuario: TDbField;
Flogin: TDbField;
Fvalor: TDbField;
FdataCadastro: TDbField;
procedure Setcodigo(const Value: TDbField);
procedure Setlogin(const Value: TDbField);
procedure SetnomeUsuario(const Value: TDbField);
procedure Setsenha(const Value: TDbField);
procedure Setvalor(const Value: TDbField);
procedure SetdataCadastro(const Value: TDbField);
public
property codigo : TDbField read Fcodigo write Setcodigo;
property nomeUsuario: TDbField read FnomeUsuario write SetnomeUsuario;
property login : TDbField read Flogin write Setlogin;
property senha : TDbField read Fsenha write Setsenha;
property valor : TDbField read Fvalor write Setvalor;
property dataCadastro: TDbField read FdataCadastro write SetdataCadastro;
function Insert: Boolean;
constructor create;
end;
implementation
{ TDbUsuario }
constructor TDbUsuario.create;
begin
inherited create(Self);
Fcodigo := CreateDbField('CODIGO', ftInteger, True, True, False, True, '');
FnomeUsuario := CreateDbField('NOMEUSUARIO', ftString, True, False, False, True, '');
Flogin := CreateDbField('LOGIN', ftString, True, False, False, True, '');
Fsenha := CreateDbField('SENHA', ftString, True, False, False, True, '');
Fvalor := CreateDbField('VALOR', ftFloat, True, False, False, True, '');
FdataCadastro := CreateDbField('DATACADASTRO', ftDateTime, True, False, False, True, '', -1, True);
TableName := 'USUARIO';
end;
function TDbUsuario.Insert: Boolean;
begin
Fcodigo.AsInteger := GetSequence(TableName, Fcodigo.ColumName);
result := inherited Insert;
end;
procedure TDbUsuario.Setcodigo(const Value: TDbField);
begin
Fcodigo := Value;
end;
procedure TDbUsuario.SetdataCadastro(const Value: TDbField);
begin
FdataCadastro := Value;
end;
procedure TDbUsuario.Setlogin(const Value: TDbField);
begin
Flogin := Value;
end;
procedure TDbUsuario.SetnomeUsuario(const Value: TDbField);
begin
FnomeUsuario := Value;
end;
procedure TDbUsuario.Setsenha(const Value: TDbField);
begin
Fsenha := Value;
end;
procedure TDbUsuario.Setvalor(const Value: TDbField);
begin
Fvalor := Value;
end;
end.
|
unit upublicvar;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, upublictype;
var
gTongXinChaJianList:TStrings;
procedure InitTongXinChaJianList;
procedure FinalizTongXinChaJianList;
function GetTongXinChaJian(const AChaJianMing:string):TPublicFunctionType; overload;
function GetTongXinChaJian(const AIndex:NativeInt):TPublicFunctionType; overload;
function JiaZaiTongXinChaJian(AChaJianMingList:TStrings):Boolean;
implementation
uses upublicconst;
procedure InitTongXinChaJianList;
begin
gTongXinChaJianList:=TStringList.Create;
end;
procedure FinalizTongXinChaJianList;
var
i:Integer;
begin
for i:=gTongXinChaJianList.Count-1 downto 0 do
begin
TPublicFunctionType(gTongXinChaJianList.Objects[i]).Free;
end;
FreeAndNil(gTongXinChaJianList);
end;
function GetTongXinChaJian(const AChaJianMing: string): TPublicFunctionType;
var
LIndex:NativeInt;
begin
LIndex:=gTongXinChaJianList.IndexOf(AChaJianMing);
Result:=GetTongXinChaJian(LIndex);
end;
function GetTongXinChaJian(const AIndex: NativeInt): TPublicFunctionType;
begin
if AIndex<0 then
begin
Result:=nil;
end
else
begin
Result:=TPublicFunctionType(gTongXinChaJianList.Objects[AIndex]);
end;
end;
function JiaZaiTongXinChaJian(AChaJianMingList:TStrings):Boolean;
var
i:Integer;
LChaJianMing:PChar;
LChaJian:string;
LTempTongXinChaJian:TPublicFunctionType;
begin
try
for i:=0 to AChaJianMingList.Count-1 do
begin
LChaJian:=AChaJianMingList[i];
{$IFDEF UNIX}
LChaJianMing:=PChar(ExtractFilePath(ParamStr(0))+so_quanzhui+LChaJian+so_houzhui);
{$ELSE}
LChaJianMing:=PChar(ExtractFilePath(ParamStr(0))+LChaJian+dll_houzhui);
{$ENDIF}
LTempTongXinChaJian:=TPublicFunctionType.Create(LChaJianMing);
gTongXinChaJianList.AddObject(LChaJian,LTempTongXinChaJian);
end;
Result:=True;
except
Result:=False;
end;
end;
end.
|
unit Vigilante.ChangeSetItem.Model;
{$M+}
interface
uses
System.Classes, System.SysUtils;
type
TChangeSetItem = class
private
FAutor: string;
FDescricao: string;
FArquivosAlterados: TStringList;
public
constructor Create(const AAutor, ADescricao: string;
const AArquivosAlterados: TArray<TFileName>);
destructor Destroy; override;
published
property Autor: string read FAutor;
property ArquivosAlterados: TStringList read FArquivosAlterados;
property Descricao: String read FDescricao;
end;
implementation
constructor TChangeSetItem.Create(const AAutor, ADescricao: string;
const AArquivosAlterados: TArray<TFileName>);
var
i: Integer;
begin
FAutor := AAutor;
FDescricao := ADescricao;
FArquivosAlterados := TStringList.Create;
for i := Low(AArquivosAlterados) to High(AArquivosAlterados) do
FArquivosAlterados.Add(AArquivosAlterados[i]);
end;
destructor TChangeSetItem.Destroy;
begin
FArquivosAlterados.Free;
inherited;
end;
end.
|
unit UnitFormDelay;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ToolWin,
Vcl.ExtCtrls,
Vcl.StdCtrls, System.ImageList, Vcl.ImgList, Vcl.Imaging.pngimage;
type
TDelayInfo = record
Delay: boolean;
DurationMillis: int64;
What: string;
end;
TFormDelay = class(TForm)
ImageList4: TImageList;
TimerDelay: TTimer;
ImageInfo: TImage;
Panel1: TPanel;
Panel2: TPanel;
LabelDelayElepsedTime: TLabel;
LabelProgress: TLabel;
Label1: TLabel;
ProgressBar1: TProgressBar;
Panel3: TPanel;
Panel4: TPanel;
ToolBar6: TToolBar;
ToolButtonStop: TToolButton;
procedure TimerDelayTimer(Sender: TObject);
procedure ToolButtonStopClick(Sender: TObject);
private
{ Private declarations }
FStart:int64;
public
{ Public declarations }
procedure Delay(x:TDelayInfo);
end;
var
FormDelay: TFormDelay;
implementation
uses math, dateutils, UnitApiClient;
{$R *.dfm}
procedure TFormDelay.Delay(x:TDelayInfo);
begin
Visible := x.Delay;
TimerDelay.Enabled := x.Delay;
ProgressBar1.Position := 0;
ProgressBar1.Max := x.DurationMillis;
Label1.Caption := x.What;
LabelDelayElepsedTime.Caption := '00:00:00';
LabelProgress.Caption := '';
FStart := GetTickCount64;
Top := 100500;
end;
procedure TFormDelay.TimerDelayTimer(Sender: TObject);
begin
LabelDelayElepsedTime.Caption := FormatDateTime('HH:mm:ss',
IncMilliSecond(0, GetTickCount64 - FStart));
ProgressBar1.Position := ProgressBar1.Position + TimerDelay.Interval;
if ProgressBar1.Max <> 0 then
LabelProgress.Caption :=
inttostr(ceil(ProgressBar1.Position * 100 / ProgressBar1.Max)) + '%';
if GetEnvironmentVariable('ATOOL_AUTO_SKIP_DELAY') = 'true' then
ToolButtonStop.Click;
end;
procedure TFormDelay.ToolButtonStopClick(Sender: TObject);
begin
RunWorkClient.interruptDelay;
end;
end.
|
unit FIToolkit.Reports.Parser.XMLOutputParser;
interface
uses
System.SysUtils, System.Generics.Collections, Xml.XMLIntf,
FIToolkit.Reports.Parser.Messages;
type
TFixInsightXMLParser = class sealed
strict private
FMessages : TFixInsightMessages;
private
procedure AppendMessagesFromXML(const XML : IXMLDocument; const ProjectDir : String);
public
constructor Create;
destructor Destroy; override;
procedure Parse(const ReportFile : TFileName; Append : Boolean); overload;
procedure Parse(const ReportFile, ProjectFile : TFileName; Append : Boolean); overload;
property Messages : TFixInsightMessages read FMessages;
end;
implementation
uses
Xml.XMLDoc, Winapi.ActiveX, System.IOUtils,
FIToolkit.Commons.Utils,
FIToolkit.Reports.Parser.Exceptions, FIToolkit.Reports.Parser.Types, FIToolkit.Reports.Parser.Consts;
{ TFixInsightXMLParser }
procedure TFixInsightXMLParser.AppendMessagesFromXML(const XML : IXMLDocument; const ProjectDir : String);
var
RootNode, FileNode, MessageNode : IXMLNode;
i, k : Integer;
sFileName, sFullFileName : TFileName;
begin
try
RootNode := XML.Node.ChildNodes[STR_FIXML_ROOT_NODE];
if Assigned(RootNode) then
for i := 0 to RootNode.ChildNodes.Count - 1 do
begin
FileNode := RootNode.ChildNodes.Get(i);
if SameText(FileNode.NodeName, STR_FIXML_FILE_NODE) then
begin
sFileName := FileNode.Attributes[STR_FIXML_NAME_ATTRIBUTE];
sFullFileName := Iff.Get<String>(ProjectDir.IsEmpty, String.Empty, TPath.Combine(ProjectDir, sFileName));
for k := 0 to FileNode.ChildNodes.Count - 1 do
begin
MessageNode := FileNode.ChildNodes.Get(k);
if SameText(MessageNode.NodeName, STR_FIXML_MESSAGE_NODE) then
begin
if sFullFileName.IsEmpty then
FMessages.Add(
TFixInsightMessage.Create(
sFileName,
MessageNode.Attributes[STR_FIXML_LINE_ATTRIBUTE],
MessageNode.Attributes[STR_FIXML_COL_ATTRIBUTE],
MessageNode.Attributes[STR_FIXML_ID_ATTRIBUTE],
MessageNode.Text))
else
FMessages.Add(
TFixInsightMessage.Create(
sFileName,
sFullFileName.Expand,
MessageNode.Attributes[STR_FIXML_LINE_ATTRIBUTE],
MessageNode.Attributes[STR_FIXML_COL_ATTRIBUTE],
MessageNode.Attributes[STR_FIXML_ID_ATTRIBUTE],
MessageNode.Text));
end;
end;
end;
end;
except
Exception.RaiseOuterException(EFixInsightXMLParseError.Create);
end;
end;
constructor TFixInsightXMLParser.Create;
begin
inherited Create;
FMessages := TFixInsightMessages.Create;
end;
destructor TFixInsightXMLParser.Destroy;
begin
FreeAndNil(FMessages);
inherited Destroy;
end;
procedure TFixInsightXMLParser.Parse(const ReportFile : TFileName; Append : Boolean);
begin
Parse(ReportFile, String.Empty, Append);
end;
procedure TFixInsightXMLParser.Parse(const ReportFile, ProjectFile : TFileName; Append : Boolean);
var
XML : IXMLDocument;
begin
if not Append then
FMessages.Clear;
try
XML := TXMLDocument.Create(ReportFile);
except
Exception.RaiseOuterException(EFixInsightXMLParseError.Create);
end;
AppendMessagesFromXML(XML, TPath.GetDirectoryName(ProjectFile, True));
end;
initialization
CoInitialize(nil);
finalization
CoUninitialize;
end.
|
unit ncCommandPacking;
/// ////////////////////////////////////////////////////////////////////////////
//
// TSocketList
//
// This unit declares a TncCommand which is used by ncSources to pass
// information from peer to peer.
// The TncCommand can be packed and unnpacked into and from a TBytes array
//
// This unit has been optimised to perform at maximum speed by checking the
// assembly the compiler generates.
//
// Written by Demos Bill
// 7/8/2020
// - Optimised code by checking assembly. The performance of executing 100000
// times a command with data: 'Hello from Client', and compression on, was
// before optimisation: 57532 msec
// after optimisation: 19383 msec
// performance gain: 2,97 times faster.
// With compression off we can execute 100000 command executions
// in 5438 msec
// This performance testing was made before ncSources were re-engineered.
// Please check ncSources to see what the new performance is after
// latest re-engineering.
// - Initial Creation: Ported code from ncSources
//
/// ////////////////////////////////////////////////////////////////////////////
interface
uses SysUtils;
type
ENetComImproperMessageEncoding = class(Exception);
TncCommandType = (ctInitiator, ctResponse);
PncCommandType = ^TncCommandType;
TncCommandUniqueID = UInt32;
PncCommandUniqueID = ^TncCommandUniqueID;
TncCommandCmd = UInt32;
PncCommandCmd = ^TncCommandCmd;
TncCommand = record
public
CommandType: TncCommandType;
UniqueID: TncCommandUniqueID;
Cmd: TncCommandCmd;
Data: TBytes;
RequiresResult: Boolean;
AsyncExecute: Boolean;
ResultIsErrorString: Boolean;
SourceComponentHandler: string;
PeerComponentHandler: string;
procedure FromBytes(const aBytes: TBytes);
function ToBytes: TBytes;
end;
resourcestring
ENetComImproperMessageEncodingMessage = 'Improper message encoding';
implementation
// /////////////////////////////////////////////////////////////////////////////
{ TncCommand }
// /////////////////////////////////////////////////////////////////////////////
procedure TncCommand.FromBytes(const aBytes: TBytes);
type
PBool = ^Boolean;
PInt32 = ^Int32;
PUInt64 = ^UInt64;
const
SigLen = SizeOf(Byte);
BytesLen = SizeOf(UInt64);
CommandTypeLen = SizeOf(TncCommandType);
UniqueIDLen = SizeOf(TncCommandUniqueID);
CmdLen = SizeOf(TncCommandCmd);
AsyncExecuteLen = SizeOf(Boolean);
RequiresResultLen = SizeOf(Boolean);
ResultIsErrorStringLen = SizeOf(Boolean);
var
AddrPtr: PByte;
DataBytesLen, SourceComponentBytesLen, PeerComponentBytesLen: UInt64;
StrBytes: TBytes;
begin
// Point to beginning of aBytes
AddrPtr := @aBytes[0];
// Read command type
CommandType := PncCommandType(AddrPtr)^;
inc(AddrPtr, CommandTypeLen);
// Read UniqueID
UniqueID := PncCommandUniqueID(AddrPtr)^;
inc(AddrPtr, UniqueIDLen);
// Read Cmd
Cmd := PncCommandCmd(AddrPtr)^;
inc(AddrPtr, CmdLen);
// Read AsyncExecute
AsyncExecute := PBool(AddrPtr)^;
inc(AddrPtr, AsyncExecuteLen);
// Read RequiresResult
RequiresResult := PBool(AddrPtr)^;
inc(AddrPtr, RequiresResultLen);
// Read ResultIsErrorString
ResultIsErrorString := PBool(AddrPtr)^;
inc(AddrPtr, ResultIsErrorStringLen);
// Read Signature
if PByte(AddrPtr)^ <> $AA then // 10101010 bin
raise ENetComImproperMessageEncoding.Create(ENetComImproperMessageEncodingMessage);
inc(AddrPtr, SigLen);
// Read DataLen
DataBytesLen := PUInt64(AddrPtr)^;
inc(AddrPtr, BytesLen);
// Read Signature
if PByte(AddrPtr)^ <> $AA then // 10101010 bin
raise ENetComImproperMessageEncoding.Create(ENetComImproperMessageEncodingMessage);
inc(AddrPtr, SigLen);
// Read SourceComponentHandlerBytesLen
SourceComponentBytesLen := PUInt64(AddrPtr)^;
inc(AddrPtr, BytesLen);
// Read Signature
if PByte(AddrPtr)^ <> $AA then // 10101010 bin
raise ENetComImproperMessageEncoding.Create(ENetComImproperMessageEncodingMessage);
inc(AddrPtr, SigLen);
// Read PeerComponentHandlerBytesLen
PeerComponentBytesLen := PUInt64(AddrPtr)^;
inc(AddrPtr, BytesLen);
// Read Data
if DataBytesLen > 0 then
begin
SetLength(Data, DataBytesLen);
move(AddrPtr^, Data[0], DataBytesLen);
inc(AddrPtr, DataBytesLen);
end;
// Read SourceComponentHandlerBytes
if SourceComponentBytesLen > 0 then
begin
SetLength(StrBytes, SourceComponentBytesLen);
move(AddrPtr^, StrBytes[0], SourceComponentBytesLen);
SourceComponentHandler := StringOf(StrBytes);
inc(AddrPtr, SourceComponentBytesLen);
end;
// Read PeerComponentHandlerBytes
if PeerComponentBytesLen > 0 then
begin
SetLength(StrBytes, PeerComponentBytesLen);
move(AddrPtr^, StrBytes[0], PeerComponentBytesLen);
PeerComponentHandler := StringOf(StrBytes);
end;
end;
function TncCommand.ToBytes: TBytes;
type
PBool = ^Boolean;
PInt32 = ^Int32;
PUInt64 = ^UInt64;
const
SigLen = SizeOf(Byte);
BytesLen = SizeOf(UInt64);
CommandTypeLen = SizeOf(TncCommandType);
UniqueIDLen = SizeOf(TncCommandUniqueID);
CmdLen = SizeOf(TncCommandCmd);
AsyncExecuteLen = SizeOf(Boolean);
RequiresResultLen = SizeOf(Boolean);
ResultIsErrorStringLen = SizeOf(Boolean);
StaticBufferLen =
UInt64(CommandTypeLen + UniqueIDLen + CmdLen + AsyncExecuteLen + RequiresResultLen + ResultIsErrorStringLen +
SigLen + BytesLen + SigLen + BytesLen + SigLen + BytesLen);
var
AddrPtr: PByte;
DataBytesLen, SourceComponentBytesLen, PeerComponentBytesLen: UInt64;
SourceComponentHandlerBytes, PeerComponentHandlerBytes: TBytes;
begin
SourceComponentHandlerBytes := BytesOf(SourceComponentHandler);
PeerComponentHandlerBytes := BytesOf(PeerComponentHandler);
DataBytesLen := Length(Data);
SourceComponentBytesLen := Length(SourceComponentHandlerBytes);
PeerComponentBytesLen := Length(PeerComponentHandlerBytes);
SetLength(Result, StaticBufferLen + DataBytesLen + SourceComponentBytesLen + PeerComponentBytesLen);
// Point to beginning of result buffer
AddrPtr := @Result[0];
// Write command type
PncCommandType(AddrPtr)^ := CommandType;
inc(AddrPtr, CommandTypeLen);
// Write UniqueID
PncCommandUniqueID(AddrPtr)^ := UniqueID;
inc(AddrPtr, UniqueIDLen);
// Write Cmd
PncCommandCmd(AddrPtr)^ := Cmd;
inc(AddrPtr, CmdLen);
// Write AnyncExecute
PBool(AddrPtr)^ := AsyncExecute;
inc(AddrPtr, AsyncExecuteLen);
// Write RequiresResult
PBool(AddrPtr)^ := RequiresResult;
inc(AddrPtr, RequiresResultLen);
// Write ResultIsErrorString
PBool(AddrPtr)^ := ResultIsErrorString;
inc(AddrPtr, ResultIsErrorStringLen);
// Write Signature
PByte(AddrPtr)^ := $AA; // 10101010 bin
inc(AddrPtr, SigLen);
// Write DataLen
PUInt64(AddrPtr)^ := DataBytesLen;
inc(AddrPtr, BytesLen);
// Write Signature
PByte(AddrPtr)^ := $AA; // 10101010 bin
inc(AddrPtr, SigLen);
// Write SourceComponentHandlerBytesLen
PUInt64(AddrPtr)^ := SourceComponentBytesLen;
inc(AddrPtr, BytesLen);
// Write Signature
PByte(AddrPtr)^ := $AA; // 10101010 bin
inc(AddrPtr, SigLen);
// Write PeerComponentHandlerBytesLen
PUInt64(AddrPtr)^ := PeerComponentBytesLen;
inc(AddrPtr, BytesLen);
// Write Data
if DataBytesLen > 0 then
begin
move(Data[0], AddrPtr^, DataBytesLen);
inc(AddrPtr, DataBytesLen);
end;
// Write SourceComponentHandlerBytes
if SourceComponentBytesLen > 0 then
begin
move(SourceComponentHandlerBytes[0], AddrPtr^, SourceComponentBytesLen);
inc(AddrPtr, SourceComponentBytesLen);
end;
// Write PeerComponentHandlerBytes
if PeerComponentBytesLen > 0 then
move(PeerComponentHandlerBytes[0], AddrPtr^, PeerComponentBytesLen);
end;
end.
|
unit Filters;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls;
type
TFilterDlg = class(TForm)
Label1: TLabel;
Description: TEdit;
Label2: TLabel;
Extension: TEdit;
Button1: TButton;
Button2: TButton;
private
{ Private declarations }
procedure SetFilter(const Value: string);
function GetFilter: string;
public
{ Public declarations }
property Filter: string read GetFilter write SetFilter;
end;
implementation
{$R *.DFM}
procedure TFilterDlg.SetFilter(const Value: string);
var
P: Integer;
begin
Description.Text := '';
Extension.Text := '';
if Value > '' then
begin
P := AnsiPos('|', Value);
if P = 0 then P := 256;
Description.Text := Copy(Value, 1, P - 1);
Extension.Text := Copy(Value, P + 1, 255);
end;
end;
function TFilterDlg.GetFilter: string;
begin
Result := Description.Text + '|' + Extension.Text;
end;
end.
|
unit ServerMethodsUnit;
interface
uses
SysUtils, Classes, DSServer, DBXInterBase, FMTBcd, SqlExpr, DB, Provider,
Dialogs;
type
TServerMethods1 = class(TDSServerModule)
SQLConnection_Server: TSQLConnection;
Table_Report: TSQLTable;
Query_Emp_treeInfo: TSQLQuery;
Table_Emp: TSQLTable;
DataSetProvider_report: TDataSetProvider;
DataSetProvider_Emp: TDataSetProvider;
DataSetProvider_Emp_TreeInfo: TDataSetProvider;
Query_Login_Info: TSQLQuery;
DataSetProvider_Login: TDataSetProvider;
Query_Login: TSQLQuery;
private
{ Private declarations }
public
{ Public declarations }
function Get_Reportt : TDataSet;
function Get_Emp_Info : TDataSet;
function Get_Emp_TreeInfo : TDataSet;
Function Get_Logined_info(Value: Integer) : TDataSet;
Procedure EhocMessage;
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
end;
implementation
{$R *.dfm}
uses StrUtils;
function TServerMethods1.EchoString(Value: string): string;
begin
Result := Value;
end;
// 직원 정보를 테이불 쨰로 넘긴다..
procedure TServerMethods1.EhocMessage;
begin
showmessage('');
end;
function TServerMethods1.Get_Emp_Info: TDataSet;
begin
if Table_Emp.State = dsInactive then
Table_Emp.Open;
Result := table_Emp;
end;
// 트리뷰에 나올 직원 정보를 가져온다
function TServerMethods1.Get_Emp_TreeInfo: TDataSet;
begin
with Query_Emp_treeInfo do
begin
Close;
open;
end;
Result := Query_Emp_treeInfo;
end;
// 사번, 민번을 가져온다..
function TServerMethods1.Get_Logined_info(Value: Integer) : TDataSet;
var
Data : TDataSource;
begin
Query_Login.Close;
Query_Login.Params[0].AsInteger := Value;
Query_Login.open;
Result := Query_Login;
end;
function TServerMethods1.Get_Reportt: TDataSet;
begin
if Table_Report.State = dsInactive then
Table_Report.Open;
Result := Table_Report;
end;
function TServerMethods1.ReverseString(Value: string): string;
begin
Result := StrUtils.ReverseString(Value);
end;
end.
|
unit UThreadPool;
interface
uses
Windows, SysUtils, Classes;
const
WT_EXECUTEDEFAULT = DWORD($00000000);
WT_EXECUTEINIOTHREAD = DWORD($00000001);
WT_EXECUTEINUITHREAD = DWORD($00000002);
WT_EXECUTEINWAITTHREAD = DWORD($00000004);
WT_EXECUTEONLYONCE = DWORD($00000008);
WT_EXECUTEINTIMERTHREAD = DWORD($00000020);
WT_EXECUTELONGFUNCTION = DWORD($00000010);
WT_EXECUTEINPERSISTENTIOTHREAD = DWORD($00000040);
WT_EXECUTEINPERSISTENTTHREAD = DWORD($00000080);
WT_TRANSFER_IMPERSONATION = DWORD($00000100);
function QueueUserWorkItem(ThreadFunc: TThreadStartRoutine; Context: Pointer; Flags: DWORD): BOOL; stdcall; external kernel32 name 'QueueUserWorkItem';
type
TThreadPool = class
private
fWorkingThreads: Integer;
fNumberOfThreads: Integer;
procedure QueueWorkItem(Parameters: Pointer; WorkerEvent: TNotifyEvent);
public
function CreateThreadLimitFlag(Limit: DWORD): DWORD;
function AreThreadsWorking: Boolean;
public
property AllTasksFinished: Boolean read AreThreadsWorking;
property NumberOfThreads: Integer read fNumberOfThreads write fNumberOfThreads;
constructor Create(NumberOfThreads: Integer);
procedure AddTask(CallbackFunction: TNotifyEvent; Parameters: Pointer);
end;
TUserWorkItem = class
ThreadBoss: TThreadPool;
Parameters: Pointer;
WorkerEvent: TNotifyEvent;
public
destructor Destroy; override;
end;
implementation
function InternalThreadFunction(lpThreadParameter: Pointer): Integer; stdcall;
begin
Result := 0;
Try
Try
With TUserWorkItem(lpThreadParameter) Do
begin
If Assigned(WorkerEvent) Then
begin
WorkerEvent(Parameters);
InterlockedDecrement(ThreadBoss.fWorkingThreads);
end;
end;
Finally
FreeAndNil(TUserWorkItem(lpThreadParameter));
end;
except
raise;
end;
end;
function TThreadPool.CreateThreadLimitFlag(Limit: DWORD): DWORD;
begin
Result := WT_EXECUTEDEFAULT;
If Not(Limit in [1 .. 255]) Then
Exit;
Result := Result Or (Limit SHL 16);
end;
procedure TThreadPool.QueueWorkItem(Parameters: Pointer; WorkerEvent: TNotifyEvent);
var
WorkItem: TUserWorkItem;
begin
If Assigned(WorkerEvent) Then
begin
IsMultiThread := True;
WorkItem := TUserWorkItem.Create;
Try
WorkItem.ThreadBoss := Self;
WorkItem.WorkerEvent := WorkerEvent;
WorkItem.Parameters := Parameters;
InterlockedIncrement(fWorkingThreads);
If Not(QueueUserWorkItem(InternalThreadFunction, WorkItem, CreateThreadLimitFlag(fNumberOfThreads))) Then
begin
InterlockedDecrement(fWorkingThreads);
RaiseLastOSError;
end;
Except
WorkItem.Free;
raise;
end;
end;
end;
function TThreadPool.AreThreadsWorking: Boolean;
begin
Result := (fWorkingThreads = 0);
end;
constructor TThreadPool.Create(NumberOfThreads: Integer);
begin
inherited Create;
fWorkingThreads := 0;
fNumberOfThreads := NumberOfThreads;
end;
procedure TThreadPool.AddTask(CallbackFunction: TNotifyEvent; Parameters: Pointer);
begin
QueueWorkItem(Parameters, CallbackFunction);
end;
destructor TUserWorkItem.Destroy;
begin
inherited;
end;
end.
|
unit ncListaEspera;
interface
uses
SysUtils,
DB,
MD5,
Classes,
Windows,
ClasseCS,
ncClassesBase;
type
TncItemListaEspera = class
private
function GetString: String;
procedure SetString(const Value: String);
published
public
ilID : Integer;
ilCliente : Integer;
ilNomeCliente : String;
ilDataHora : TDateTime;
ilPrevisao : TDateTime;
ilPrevMaq : Integer;
ilPrevSessao : Integer;
ilObs : String;
_Operacao : Byte;
procedure LoadFromStram(S: TStream);
procedure LoadFromDataset(D: TDataset);
procedure SaveToStream(S: TStream);
procedure SaveToDataset(D: TDataset; aPos: Integer);
procedure Limpa;
procedure AssignFrom(B: TncItemListaEspera);
function Igual(B: TncItemListaEspera): Boolean;
property AsString: String
read GetString write SetString;
end;
TncListaEspera = class
private
FItens : TList;
function GetItem(I: Integer): TncItemListaEspera;
function GetString: String;
procedure SetString(const Value: String);
public
constructor Create;
destructor Destroy; override;
procedure AjustaOperacao(B: TncListaEspera);
procedure Remove(IME: TncItemListaEspera);
procedure Delete(aIndex: Integer);
procedure Limpa;
function Count: Integer;
function NewItem: TncItemListaEspera;
function GetItemByID(aID: Integer): TncItemListaEspera;
function GetItemBySessao(aSessao: Integer): TncItemListaEspera;
property Itens[I: Integer]: TncItemListaEspera
read GetItem; Default;
property AsString: String
read GetString write SetString;
end;
implementation
{ TncItemListaEspera }
procedure TncItemListaEspera.AssignFrom(B: TncItemListaEspera);
begin
ilID := B.ilID;
ilCliente := B.ilCliente;
ilNomeCliente := B.ilNomeCliente;
ilDataHora := B.ilDataHora;
ilPrevisao := B.ilPrevisao;
ilPrevMaq := B.ilPrevMaq;
ilPrevSessao := B.ilPrevSessao;
ilObs := B.ilObs;
_Operacao := B._Operacao;
end;
function TncItemListaEspera.GetString: String;
begin
Result :=
IntToStr(ilID) + sFldDelim +
IntToStr(ilCliente) + sFlddelim +
ilNomeCliente + sFldDelim +
GetDTStr(ilDataHora) + sFldDelim +
GetDTStr(ilPrevisao) + sFldDelim +
IntToStr(ilPrevMaq) + sFldDelim +
IntToStr(ilPrevSessao) + sFldDelim +
ilObs + sFldDelim +
IntToStr(_Operacao) + sFldDelim;
end;
function TncItemListaEspera.Igual(B: TncItemListaEspera): Boolean;
begin
Result := False;
if ilID <> B.ilID then Exit;
if ilCliente <> B.ilCliente then Exit;
if ilNomeCliente <> B.ilNomeCliente then Exit;
if ilDataHora <> B.ilDataHora then Exit;
if ilPrevisao <> B.ilPrevisao then Exit;
if ilPrevMaq <> B.ilPrevMaq then Exit;
if ilPrevSessao <> B.ilPrevSessao then Exit;
if ilObs <> B.ilObs then Exit;
Result := True;
end;
procedure TncItemListaEspera.Limpa;
begin
ilID := -1;
ilCliente := 0;
ilNomeCliente := '';
ilDataHora := 0;
ilPrevisao := 0;
ilPrevMaq := 0;
ilPrevSessao := 0;
ilObs := '';
_Operacao := osNenhuma;
end;
procedure TncItemListaEspera.LoadFromDataset(D: TDataset);
begin
ilID := D.FieldByName('ID').AsInteger;
ilCliente := D.FieldByName('Cliente').AsInteger;
ilNomeCliente := D.FieldByName('NomeCliente').AsInteger;
ilDataHora := D.FieldByName('DataHora').AsDateTime;
ilPrevisao := D.FieldByName('Previsao').AsDateTime;
ilPrevMaq := D.FieldByName('PrevMaq').AsInteger;
ilPrevSessao := D.FieldByName('PrevSessao').AsInteger;
ilObs := D.FieldByName('Obs').AsString;
end;
procedure TncItemListaEspera.LoadFromStram(S: TStream);
var
I : Integer;
Str : String;
begin
S.Read(I, SizeOf(I));
if I>0 then begin
SetLength(Str, I);
S.Read(Str[1], I);
AsString := Str;
end else
Limpa;
end;
procedure TncItemListaEspera.SaveToDataset(D: TDataset; aPos: Integer);
begin
D.FieldByName('Cliente').AsInteger := ilCliente;
D.FieldByName('NomeCliente').AsInteger := ilNomeCliente;
D.FieldByName('DataHora').AsDateTime := ilDataHora;
D.FieldByName('Pos').AsInteger := aPos;
D.FieldByName('Previsao').AsDateTime := ilPrevisao;
D.FieldByName('PrevMaq').AsInteger := ilPrevMaq;
D.FieldByName('PrevSessao').AsInteger := ilPrevSessao;
D.FieldByName('Obs').AsString := ilObs;
end;
procedure TncItemListaEspera.SaveToStream(S: TStream);
var
Str: String;
I : Integer;
begin
Str := AsString;
I := Length(Str);
S.Write(I, SizeOf(I));
if I>0 then
S.Write(Str[1], I);
end;
procedure TncItemListaEspera.SetString(const Value: String);
var S: String;
function pCampo: String;
begin
Result := GetNextStrDelim(S);
end;
begin
S := Value;
ilID := StrToIntDef(pCampo, -1);
ilCliente := StrToIntDef(pCampo, 0);
ilNomeCliente := pCampo;
ilDataHora := DTFromStr(pCampo);
ilPrevisao := DTFromStr(pCampo);
ilPrevMaq := StrToIntDef(pCampo, 0);
ilPrevSessao := StrToIntDef(pCampo, 0);
ilObs := pCampo;
_Operacao := StrToIntDef(pCampo, osNenhuma);
end;
procedure TncListaEspera.AjustaOperacao(B: TncListaEspera);
var
I : Integer;
IL : TncItemListaEspera;
begin
for I := 0 to Count - 1 do with Itens[I] do
if (ilID<>-1) and (B.GetItemByID(ilID)=nil) then
_Operacao := osExcluir;
for I := 0 to B.Count - 1 do
if (B[I].ilID=-1) then begin
if B[I]._Operacao<>osCancelar then begin
B[I]._Operacao := osIncluir;
NewItem.AssignFrom(B[I]);
end;
end
else begin
IL := GetItemByID(B[I].ilID);
if IL<>nil then begin
if B[I]._Operacao=osCancelar then
IL._Operacao := osCancelar
else begin
IL.AssignFrom(B[I]);
IL._Operacao := osAlterar;
end;
end;
end;
for I := Count-1 downto 0 do
if Itens[I]._Operacao=osNenhuma then begin
Itens[I].Free;
FItens.Delete(I);
end;
end;
function TncListaEspera.Count: Integer;
begin
Result := FItens.Count;
end;
constructor TncListaEspera.Create;
begin
FItens := TList.Create;
end;
procedure TncListaEspera.Delete(aIndex: Integer);
begin
FItens.Delete(aIndex);
end;
destructor TncListaEspera.Destroy;
begin
Limpa;
FItens.Free;
inherited;
end;
function TncListaEspera.GetItem(I: Integer): TncItemListaEspera;
begin
Result := TncItemListaEspera(FItens[I]);
end;
function TncListaEspera.GetItemByID(aID: Integer): TncItemListaEspera;
var I : Integer;
begin
for I := 0 to Count - 1 do
if Itens[I].ilID=aID then begin
Result := Itens[I];
Exit;
end;
Result := nil;
end;
function TncListaEspera.GetItemBySessao(aSessao: Integer): TncItemListaEspera;
var I : Integer;
begin
for I := 0 to Count - 1 do
if Itens[I].ilPrevSessao=aSessao then begin
Result := Itens[I];
Exit;
end;
Result := nil;
end;
function TncListaEspera.GetString: String;
var I : Integer;
begin
Result := '';
for I := 0 to Count - 1 do begin
if I>0 then Result := Result + sLineBreak;
Result := Result + Itens[I].AsString;
end;
end;
procedure TncListaEspera.Limpa;
begin
while Count>0 do begin
Itens[0].Free;
FItens.Delete(0);
end;
end;
function TncListaEspera.NewItem: TncItemListaEspera;
begin
Result := TncItemListaEspera.Create;
FItens.Add(Result);
end;
procedure TncListaEspera.Remove(IME: TncItemListaEspera);
begin
FItens.Remove(IME);
end;
procedure TncListaEspera.SetString(const Value: String);
var
SL : TStrings;
I : Integer;
begin
Limpa;
SL := TStringList.Create;
try
SL.Text := Value;
for I := 0 to SL.Count - 1 do
NewItem.AsString := SL[I];
finally
SL.Free;
end;
end;
end.
|
Unit OpenREMDiskForm;
Interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, RemDiskDll,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls;
Type
TOpenREMDiskFrm = Class (TForm)
MainPanel: TPanel;
EncryptionGroupBox: TGroupBox;
GeneralGroupBox: TGroupBox;
FileNameEdit: TEdit;
BrowseButton: TButton;
LoadAsRAMDiskCheckBox: TCheckBox;
ReadOnlyCheckBox: TCheckBox;
EncryptedCheckBox: TCheckBox;
PasswordEdit: TEdit;
ShowCharactersCheckBox: TCheckBox;
StornoButton: TButton;
OkButton: TButton;
Label1: TLabel;
Label2: TLabel;
FileNameOpenDialog: TOpenDialog;
Procedure BrowseButtonClick(Sender: TObject);
Procedure StornoButtonClick(Sender: TObject);
Procedure OkButtonClick(Sender: TObject);
Procedure ShowCharactersCheckBoxClick(Sender: TObject);
Procedure EncryptedCheckBoxClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
Private
FCancelled : Boolean;
FFileName : WideString;
FFlags : Cardinal;
FDiskType : EREMDiskType;
FPassword : WideString;
Public
Property Cancelled : Boolean Read FCancelled;
Property FileName : WideString Read FFileName;
Property Flags : Cardinal Read FFlags;
Property DiskType : EREMDiskType Read FDiskType;
Property Password : WideString Read FPassword;
end;
Implementation
{$R *.dfm}
Procedure TOpenREMDiskFrm.BrowseButtonClick(Sender: TObject);
begin
If FileNameOpenDialog.Execute Then
FileNameEdit.Text := FileNameOpenDialog.FileName;
end;
Procedure TOpenREMDiskFrm.EncryptedCheckBoxClick(Sender: TObject);
begin
If EncryptedCheckBox.Checked Then
begin
ShowCharactersCheckBox.Enabled := True;
PasswordEdit.ReadOnly := False;
PasswordEdit.Color := clWindow;
end
Else begin
ShowCharactersCheckBox.Enabled := False;
PasswordEdit.ReadOnly := True;
PasswordEdit.Color := clBtnFace;
end;
end;
procedure TOpenREMDiskFrm.FormCreate(Sender: TObject);
begin
FCancelled := True;
EncryptedCheckBoxClick(EncryptedCheckBox);
ShowCharactersCheckBoxClick(ShowCharactersCheckBox);
end;
Procedure TOpenREMDiskFrm.OkButtonClick(Sender: TObject);
begin
If (FileNameEdit.Text <> '') And
((Not EncryptedCheckBox.Checked) Or (PasswordEdit.Text <> '')) Then
begin
FCancelled := False;
FFilename := FileNameEdit.Text;
FDiskType := rdtFileDisk;
If LoadASRAMDiskCheckBox.Checked Then
FDiskType := rdtRAMDisk;
FFlags := REMDISK_FLAG_FILE_SOURCE;
If Not ReadOnlyCheckBox.Checked Then
FFlags := (FFlags Or REMDISK_FLAG_WRITABLE);
If EncryptedCheckBox.Checked Then
FFlags := (FFlags Or REMDISK_FLAG_ENCRYPTED);
FPassword := PasswordEdit.Text;
Close;
end;
end;
Procedure TOpenREMDiskFrm.ShowCharactersCheckBoxClick(Sender: TObject);
begin
If ShowCharactersCheckBox.Checked Then
PasswordEdit.PasswordChar := #0
Else PasswordEdit.PasswordChar := '*';
end;
Procedure TOpenREMDiskFrm.StornoButtonClick(Sender: TObject);
begin
Close;
end;
End.
|
{
This unit is part of the Lua4Delphi Source Code
Copyright (C) 2009-2012, LaKraven Studios Ltd.
Copyright Protection Packet(s): L4D014
www.Lua4Delphi.com
www.LaKraven.com
--------------------------------------------------------------------
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.
--------------------------------------------------------------------
Unit: L4D.Lua.Common.pas
Released: 5th February 2012
Changelog:
12th March 2012:
- Fixed the "lua_pop" macro method
5th February 2012:
- Released
}
unit L4D.Lua.Common;
interface
{$I Lua4Delphi.inc}
uses
{$IFDEF DELPHIXE2}
System.Classes, System.SysUtils,
{$ELSE}
Classes, SysUtils,
{$ENDIF}
L4D.Lua.Intf;
type
{ Forward Declarations }
TLuaBase = class;
TLuaCommon = class;
TLuaBaseMember = class;
{ Class Ref }
TLuaBaseType = class of TLuaCommon;
{
TLuaBase
- All Common (Abstract) Methods (excluding Localizers)
}
{$REGION 'Base Lua Class (no Localizers)'}
TLuaBase = class(TInterfacedObject, ILuaLibCommonMacros, ILuaLibInterchange, ILuaLibCommon, ILuaAuxCommon, ILuaAuxCommonMacros, ILuaAuxInterchange)
protected
FLibBase,
FLibDebug,
FLibIO,
FLibMath,
FLibOS,
FLibPackage,
FLibString,
FLibTable: TLuaDelphiFunction;
function LoadLuaLibrary(const L: PLuaState; const ALibName: AnsiString; ALibFunc: TLuaDelphiFunction): Integer; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure SetLuaLibRefs; virtual; abstract;
{$REGION 'ILuaLibCommonMacros'}
function lua_isboolean(L: PLuaState; idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isfunction(L: PLuaState; idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_islightuserdata(L: PLuaState; idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isnil(L: PLuaState; idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isnone(L: PLuaState; idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isnoneornil(L: PLuaState; idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_istable(L: PLuaState; idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isthread(L: PLuaState; idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_newtable(L: PLuaState); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pop(L: PLuaState; n: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pushcfunction(L: PLuaState; f: TLuaDelphiFunction); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_pushliteral(L: PLuaState; s: PAnsiChar): PAnsiChar; overload; inline; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_pushlstring(L: PLuaState; const s: PAnsiChar; ls: Cardinal): PAnsiChar; overload; virtual; abstract;
procedure lua_register(L: PLuaState; name: PAnsiChar; f: TLuaDelphiFunction); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_tostring(L: PLuaState; idx: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
{$REGION 'ILuaLibInterchange'}
procedure lua_call(L: PLuaState; nargs, nresults: Integer); overload; virtual; abstract; // External "lua_call" in 5.1, External "lua_callk" in 5.2
procedure lua_callk(L: PLuaState; nargs, nresults, ctx: Integer; k: TLuaDelphiFunction); overload; virtual; abstract; // External "lua_call" in 5.1, External "lua_callk" in 5.2
function lua_compare(L: PLuaState; idx1, idx2, op: Integer): LongBool; overload; virtual; abstract; // "lua_equal" OR "lua_lessthan" in 5.1, External in 5.2
function lua_cpcall(L: PLuaState; func: TLuaDelphiFunction; ud: Pointer): Integer; overload; virtual; abstract; // External in 5.1, "lua_pcall" in 5.2
function lua_equal(L: PLuaState; idx1, idx2: Integer): LongBool; overload; virtual; abstract; // External in 5.1, "lua_compare" in 5.2
procedure lua_getfenv(L: PLuaState; idx: Integer); overload; virtual; abstract; // External in 5.1, "lua_getuservalue" in 5.2
procedure lua_getglobal(L: PLuaState; name: PAnsiChar); overload; virtual; abstract; // "lua_getfield" in 5.1, External in 5.2
procedure lua_getuservalue(L: PLuaState; idx: Integer); overload; virtual; abstract; // "lua_getfenv" in 5.1, External in 5.2
function lua_lessthan(L: PLuaState; idx1, idx2: Integer): LongBool; overload; virtual; abstract; // External in 5.1, "lua_compare" in 5.2
function lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; const chunkname: PAnsiChar): Integer; overload; virtual; abstract; // Extra parameter in 5.2 (mode)... 5.1 to pass "nil" to operate normally
function lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; Source, Mode: PAnsiChar): Integer; overload; virtual; abstract; // Extra parameter in 5.2 (mode)... 5.1 to pass "nil" to operate normally
function lua_objlen(L: PLuaState; idx: Integer): Cardinal; overload; virtual; abstract; // External in 5.1, "lua_rawlen" in 5.2
function lua_pcall(L: PLuaState; nargs, nresults, errfunc: Integer): Integer; overload; virtual; abstract; // External in 5.1, "lua_pcallk" in 5.2
function lua_pcallk(L: PLuaState; nargs, nresults, arrfunc, ctx: Integer; k: TLuaDelphiFunction): Integer; overload; virtual; abstract; // External in 5.1, "lua_pcallk" in 5.2
function lua_rawlen(L: PLuaState; idx: Integer): Cardinal; overload; virtual; abstract; // "lua_objlen" in 5.1, External in 5.2
function lua_resume(L: PLuaState; narg: Integer): Integer; overload; virtual; abstract; // 5.1 version // Commonized Externals
function lua_setfenv(L: PLuaState; idx: Integer): LongBool; overload; virtual; abstract; // External in 5.1, "lua_setuservalue" in 5.2
procedure lua_setglobal(L: PLuaState; name: PAnsiChar); overload; virtual; abstract; // "lua_setfield" in 5.1, External in 5.2
function lua_setmetatable(L: PLuaState; objindex: Integer): LongBool; overload; virtual; abstract; // Function in 5.1, Procedure in 5.2... using a Function for both (saves hardship)
procedure lua_setuservalue(L: PLuaState; idx: Integer); overload; virtual; abstract; // "lua_getfenv" & "lua_setfenv" in 5.1, External in 5.2
function lua_tointeger(L: PLuaState; idx: Integer): Integer; overload; virtual; abstract; // 5.1
function lua_tointegerx(L: PLuaState; idx: Integer; isnum: PInteger): Integer; overload; virtual; abstract; // 5.2
function lua_tonumber(L: PLuaState; idx: Integer): Double; overload; virtual; abstract; // 5.1
function lua_tonumberx(L: PLuaState; idx: Integer; isnum: PInteger): Double; overload; virtual; abstract; // 5.2
function lua_yield(L: PLuaState; nresults: Integer): Integer; overload; virtual; abstract; // "lua_yield" in 5.1, "lua_yieldk" in 5.2
function lua_yieldk(L: PLuaState; nresults, ctx: Integer; k: TLuaDelphiFunction): Integer; overload; virtual; abstract; // "lua_yield" in 5.1, "lua_yieldk" in 5.2
{$ENDREGION}
{$REGION 'ILuaLibCommon'}
function lua_atpanic(L: PLuaState; panicf: TLuaDelphiFunction): TLuaDelphiFunction; overload; virtual; abstract;
function lua_checkstack(L: PLuaState; sz: Integer): LongBool; overload; virtual; abstract;
procedure lua_close(L: PLuaState); overload; virtual; abstract;
procedure lua_concat(L: PLuaState; n: Integer); overload; virtual; abstract;
procedure lua_createtable(L: PLuaState; narr, nrec: Integer); overload; virtual; abstract;
function lua_dump(L: PLuaState; writer: TLuaWriterFunction; data: Pointer): Integer; overload; virtual; abstract;
function lua_error(L: PLuaState): Integer; overload; virtual; abstract;
function lua_gc(L: PLuaState; what, data: Integer): Integer; overload; virtual; abstract;
function lua_getallocf(L: PLuaState; ud: PPointer): TLuaAllocFunction; overload; virtual; abstract;
procedure lua_getfield(L: PLuaState; idx: Integer; k: PAnsiChar); overload; virtual; abstract;
function lua_gethook(L: PLuaState): TLuaHookFunction; overload; virtual; abstract;
function lua_gethookcount(L: PLuaState): Integer; overload; virtual; abstract;
function lua_gethookmask(L: PLuaState): Integer; overload; virtual; abstract;
function lua_getinfo(L: PLuaState; const what: PAnsiChar; ar: PLuaDebug): Integer; overload; virtual; abstract;
function lua_getlocal(L: PLuaState; ar: PLuaDebug; n: Integer): PAnsiChar; overload; virtual; abstract;
function lua_getmetatable(L: PLuaState; objindex: Integer): LongBool; overload; virtual; abstract;
function lua_getstack(L: PLuaState; level: Integer; ar: PLuaDebug): Integer; overload; virtual; abstract;
procedure lua_gettable(L: PLuaState ; idx: Integer); overload; virtual; abstract;
function lua_gettop(L: PLuaState): Integer; overload; virtual; abstract;
function lua_getupvalue(L: PLuaState; funcindex, n: Integer): PAnsiChar; overload; virtual; abstract;
procedure lua_insert(L: PLuaState; idx: Integer); overload; virtual; abstract;
function lua_iscfunction(L: PLuaState; idx: Integer): LongBool; overload; virtual; abstract;
function lua_isnumber(L: PLuaState; idx: Integer): LongBool; overload; virtual; abstract;
function lua_isstring(L: PLuaState; idx: Integer): LongBool; overload; virtual; abstract;
function lua_isuserdata(L: PLuaState; idx: Integer): LongBool; overload; virtual; abstract;
function lua_newthread(L: PLuaState): PLuaState; overload; virtual; abstract;
public
function lua_newstate(f: TLuaAllocFunction; ud: Pointer): PLuaState; virtual; abstract;
protected
function lua_newuserdata(L: PLuaState; sz: Cardinal): Pointer; overload; virtual; abstract;
function lua_next(L: PLuaState; idx: Integer): Integer; overload; virtual; abstract;
procedure lua_pushboolean(L: PLuaState; b: LongBool); overload; virtual; abstract;
procedure lua_pushcclosure(L: PLuaState; fn: TLuaDelphiFunction; n: Integer); overload; virtual; abstract;
function lua_pushfstring(L: PLuaState; const fmt: PAnsiChar): PAnsiChar; {varargs;} overload; virtual; abstract;
procedure lua_pushinteger(L: PLuaState; n: Integer); overload; virtual; abstract;
procedure lua_pushlightuserdata(L: PLuaState; p: Pointer); overload; virtual; abstract;
procedure lua_pushnil(L: PLuaState); overload; virtual; abstract;
procedure lua_pushnumber(L: PLuaState; n: Double); overload; virtual; abstract;
function lua_pushstring(L: PLuaState; const s: PAnsiChar): PAnsiChar; overload; virtual; abstract;
function lua_pushthread(L: PLuaState): LongBool; overload; virtual; abstract;
procedure lua_pushvalue(L: PLuaState; idx: Integer); overload; virtual; abstract;
function lua_pushvfstring(L: PLuaState; const fmt: PAnsiChar; argp: Pointer): PAnsiChar; overload; virtual; abstract;
function lua_rawequal(L: PLuaState; idx1, idx2: Integer): LongBool; overload; virtual; abstract;
procedure lua_rawget(L: PLuaState; idx: Integer); overload; virtual; abstract;
procedure lua_rawgeti(L: PLuaState; idx, n: Integer); overload; virtual; abstract;
procedure lua_rawset(L: PLuaState; idx: Integer); overload; virtual; abstract;
procedure lua_rawseti(L: PLuaState; idx , n: Integer); overload; virtual; abstract;
procedure lua_remove(L: PLuaState; idx: Integer); overload; virtual; abstract;
procedure lua_replace(L: PLuaState; idx: Integer); overload; virtual; abstract;
procedure lua_setallocf(L: PLuaState; f: TLuaAllocFunction; ud: Pointer); overload; virtual; abstract;
procedure lua_setfield(L: PLuaState; idx: Integer; const k: PAnsiChar); overload; virtual; abstract;
function lua_sethook(L: PLuaState; func: TLuaHookFunction; mask, count: Integer): Integer; overload; virtual; abstract;
function lua_setlocal(L: PLuaState; ar: PLuaDebug; n: Integer): PAnsiChar; overload; virtual; abstract;
procedure lua_settable(L: PLuaState; idx: Integer); overload; virtual; abstract;
procedure lua_settop(L: PLuaState; idx: Integer); overload; virtual; abstract;
function lua_setupvalue(L: PLuaState; funcindex, n: Integer): PAnsiChar; overload; virtual; abstract;
function lua_status(L: PLuaState): Integer; overload; virtual; abstract;
function lua_toboolean(L: PLuaState; idx: Integer): LongBool; overload; virtual; abstract;
function lua_tocfunction(L: PLuaState; idx: Integer): TLuaDelphiFunction; overload; virtual; abstract;
function lua_tolstring(L: PLuaState; idx: Integer; len: PCardinal): PAnsiChar; overload; virtual; abstract;
function lua_topointer(L: PLuaState; idx: Integer): Pointer; overload; virtual; abstract;
function lua_tothread(L: PLuaState; idx: Integer): PLuaState; overload; virtual; abstract;
function lua_touserdata(L: PLuaState; idx: Integer): Pointer; overload; virtual; abstract;
function lua_type(L: PLuaState; idx: Integer): Integer; overload; virtual; abstract;
function lua_typename(L: PLuaState; tp: Integer): PAnsiChar; overload; virtual; abstract;
procedure lua_xmove(src, dest: PLuaState; n: Integer); overload; virtual; abstract;
function luaopen_base(L: PLuaState): Integer; overload; virtual; abstract;
function luaopen_debug(L: PLuaState): Integer; overload; virtual; abstract;
function luaopen_io(L: PLuaState): Integer; overload; virtual; abstract;
function luaopen_math(L: PLuaState): Integer; overload; virtual; abstract;
function luaopen_os(L: PLuaState): Integer; overload; virtual; abstract;
function luaopen_package(L: PLuaState): Integer; overload; virtual; abstract;
function luaopen_string(L: PLuaState): Integer; overload; virtual; abstract;
function luaopen_table(L: PLuaState): Integer; overload; virtual; abstract;
{$ENDREGION}
{$REGION 'ILuaAuxCommon'}
procedure luaL_addlstring(B: PLuaLBuffer; const s: PAnsiChar; ls: Cardinal); overload; virtual; abstract;
procedure luaL_addstring(B: PLuaLBuffer; const s: PAnsiChar); overload; virtual; abstract;
procedure luaL_addvalue(B: PLuaLBuffer); overload; virtual; abstract;
function luaL_argerror(L: PLuaState; numarg: Integer; const extramsg: PAnsiChar): Integer; overload; virtual; abstract;
procedure luaL_buffinit(L: PLuaState; B: PLuaLBuffer); overload; virtual; abstract;
function luaL_callmeta(L: PLuaState; obj: Integer; const e: PAnsiChar): Integer; overload; virtual; abstract;
procedure luaL_checkany(L: PLuaState; narg: Integer); overload; virtual; abstract;
function luaL_checkinteger(L: PLuaState; numArg: Integer): Integer; overload; virtual; abstract;
function luaL_checklstring(L: PLuaState; numArg: Integer; ls: PCardinal): PAnsiChar; overload; virtual; abstract;
function luaL_checknumber(L: PLuaState; numArg: Integer): Double; overload; virtual; abstract;
function luaL_checkoption(L: PLuaState; narg: Integer; const def: PAnsiChar; const lst: array of PAnsiChar): Integer; overload; virtual; abstract;
procedure luaL_checkstack(L: PLuaState; sz: Integer; const msg: PAnsiChar); overload; virtual; abstract;
procedure luaL_checktype(L: PLuaState; narg, t: Integer); overload; virtual; abstract;
function luaL_checkudata(L: PLuaState; ud: Integer; const tname: PAnsiChar): Pointer; overload; virtual; abstract;
function luaL_error(L: PLuaState; const fmt: PAnsiChar): Integer; {varargs;} overload; virtual; abstract;
function luaL_getmetafield(L: PLuaState; obj: Integer; const e: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_gsub(L: PLuaState; const s, p, r: PAnsiChar): PAnsiChar; overload; virtual; abstract;
function luaL_loadstring(L: PLuaState; const s: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_newmetatable(L: PLuaState; const tname: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_newstate: PLuaState; overload; virtual; abstract;
procedure luaL_openlibs(L: PLuaState); overload; virtual; abstract;
function luaL_optinteger(L: PLuaState; nArg: Integer; def: Integer): Integer; overload; virtual; abstract;
function luaL_optlstring(L: PLuaState; numArg: Integer; const def: PAnsiChar; ls: PCardinal): PAnsiChar; overload; virtual; abstract;
function luaL_optnumber(L: PLuaState; nArg: Integer; def: Double): Double; overload; virtual; abstract;
procedure luaL_pushresult(B: PLuaLBuffer); overload; virtual; abstract;
function luaL_ref(L: PLuaState; t: Integer): Integer; overload; virtual; abstract;
procedure luaL_unref(L: PLuaState; t, ref: Integer); overload; virtual; abstract;
procedure luaL_where(L: PLuaState; lvl: Integer); overload; virtual; abstract;
{$ENDREGION}
{$REGION 'ILuaAuxCommonMacros'}
function luaL_checkint(L: PLuaState; narg: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_checklong(L: PLuaState; narg: Cardinal): Cardinal; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_checkstring(L: PLuaState; narg: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_dofile(L: PLuaState; filename: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_dostring(L: PLuaState; str: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_getmetatable(L: PLuaState; tname: PAnsiChar); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_optint(L: PLuaState; narg, d: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_optlong(L: PLuaState; narg: Integer; d: Cardinal): Cardinal; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_optstring(L: PLuaState; narg: Integer; d: PAnsiChar): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_typename(L: PLuaState; index: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
{$REGION 'ILuaAuxInterchange'}
function luaL_loadbuffer(L: PLuaState; buff: PAnsiChar; sz: Cardinal; name: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_loadbufferx(L: PLuaState; buff: PAnsiChar; sz: Cardinal; name, mode: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_loadfile(L: PLuaState; filename: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_loadfilex(L: PLuaState; filename, mode: PAnsiChar): Integer; overload; virtual; abstract;
function luaL_prepbuffer(B: TLuaLBuffer): PAnsiChar; overload; virtual; abstract;
function luaL_prepbuffsize(B: TLuaLBuffer; sz: Cardinal): PAnsiChar; overload; virtual; abstract;
procedure luaL_register(L: PLuaState; libname: PAnsiChar; lib: PluaLReg); overload; virtual; abstract;
{$ENDREGION}
end;
{$ENDREGION}
{
TLuaCommon
- A Base Class (Abstract) for all Lua Classes.
}
{$REGION 'Base Class (Abstract) for all Lua Classes.'}
TLuaCommon = class(TLuaBase, ILuaLibCommonMacrosLocal, ILuaLibInterchangeLocal, ILuaLibCommonLocal, ILuaCommonAuxLocal, ILuaAuxCommonMacrosLocal, ILuaAuxInterchangeLocal)
protected
FLuaState: PLuaState;
function GetLinkType: TLuaBaseType; virtual; abstract;
public
{$REGION 'ILuaLibCommonMacrosLocal'}
function lua_isboolean(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isfunction(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_islightuserdata(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isnil(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isnone(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isnoneornil(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_istable(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isthread(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_newtable; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pop(n: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pushcfunction(f: TLuaDelphiFunction); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_pushliteral(s: PAnsiChar): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_pushlstring(const s: PAnsiChar; ls: Cardinal): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_register(name: PAnsiChar; f: TLuaDelphiFunction); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_tostring(idx: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
{$REGION 'ILuaLibInterchangeLocal'}
procedure lua_call(nargs, nresults: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_callk(nargs, nresults, ctx: Integer; k: TLuaDelphiFunction); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_compare(idx1, idx2, op: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_cpcall(func: TLuaDelphiFunction; ud: Pointer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_equal(idx1, idx2: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_getfenv(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_getglobal(name: PAnsiChar); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_getuservalue(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_lessthan(idx1, idx2: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_load(reader: TLuaReaderFunction; dt: Pointer; const chunkname: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF} // 5.1 version
function lua_load(reader: TLuaReaderFunction; dt: Pointer; Source, Mode: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF} // 5.2 version
function lua_objlen(idx: Integer): Cardinal; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_pcall(nargs, nresults, errfunc: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_pcallk(nargs, nresults, errfunc, ctx: Integer; k: TLuaDelphiFunction): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_rawlen(idx: Integer): Cardinal; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_resume(narg: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF} // 5.1 version
function lua_setfenv(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_setglobal(name: PAnsiChar); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_setmetatable(objindex: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_setuservalue(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_tointeger(idx: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_tointegerx(idx: Integer; isnum: PInteger): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_tonumber(idx: Integer): Double; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_tonumberx(idx: Integer; isnum: PInteger): Double; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_yield(nresults: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_yieldk(nresults, ctx: Integer; k: TLuaDelphiFunction): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
{$REGION 'ILuaLibCommonLocal'}
function lua_atpanic(panicf: TLuaDelphiFunction): TLuaDelphiFunction; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_checkstack(sz: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_close; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_concat(n: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_createtable(narr, nrec: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_dump(writer: TLuaWriterFunction; data: Pointer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_error: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_gc(what, data: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_getallocf(ud: PPointer): TLuaAllocFunction; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_getfield(idx: Integer; k: PAnsiChar); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_gethook: TLuaHookFunction; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_gethookcount: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_gethookmask: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_getinfo(const what: PAnsiChar; ar: PLuaDebug): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_getlocal(ar: PLuaDebug; n: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_getmetatable(objindex: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_getstack(level: Integer; ar: PLuaDebug): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_gettable( idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_gettop: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_getupvalue(funcindex, n: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_insert(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_iscfunction(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isnumber(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isstring(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_isuserdata(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_newthread: PLuaState; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_newuserdata(sz: Cardinal): Pointer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_next(idx: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pushboolean(b: LongBool); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pushcclosure(fn: TLuaDelphiFunction; n: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_pushfstring(const fmt: PAnsiChar): PAnsiChar; {varargs;} overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pushinteger(n: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pushlightuserdata(p: Pointer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pushnil; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pushnumber(n: Double); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_pushstring(const s: PAnsiChar): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_pushthread: LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_pushvalue(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_pushvfstring(const fmt: PAnsiChar; argp: Pointer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_rawequal(idx1, idx2: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_rawget(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_rawgeti(idx, n: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_rawset(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_rawseti(idx , n: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_remove(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_replace(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_setallocf(f: TLuaAllocFunction; ud: Pointer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_setfield(idx: Integer; const k: PAnsiChar); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_sethook(func: TLuaHookFunction; mask, count: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_setlocal(ar: PLuaDebug; n: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_settable(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_settop(idx: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_setupvalue(funcindex, n: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_status: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_toboolean(idx: Integer): LongBool; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_tocfunction(idx: Integer): TLuaDelphiFunction; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_tolstring(idx: Integer; len: PCardinal): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_topointer(idx: Integer): Pointer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_tothread(idx: Integer): PLuaState; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_touserdata(idx: Integer): Pointer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_type(idx: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function lua_typename(tp: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure lua_xmove(dest: PLuaState; n: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaopen_base: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaopen_debug: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaopen_io: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaopen_math: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaopen_os: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaopen_package: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaopen_string: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaopen_table: Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
{$REGION 'ILuaAuxCommonLocal'}
function luaL_argerror(numarg: Integer; const extramsg: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_buffinit(B: PLuaLBuffer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_callmeta(obj: Integer; const e: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_checkany(narg: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_checkinteger(numArg: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_checklstring(numArg: Integer; ls: PCardinal): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_checknumber(numArg: Integer): Double; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_checkoption(narg: Integer; const def: PAnsiChar; const lst: array of PAnsiChar): Integer; overload;
procedure luaL_checkstack(sz: Integer; const msg: PAnsiChar); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_checktype(narg, t: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_checkudata(ud: Integer; const tname: PAnsiChar): Pointer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_error(const fmt: PAnsiChar): Integer; {varargs;} overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_getmetafield(obj: Integer; const e: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_gsub(const s, p, r: PAnsiChar): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_loadstring(const s: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_newmetatable(const tname: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_openlibs; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_optinteger(nArg: Integer; def: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_optnumber(nArg: Integer; def: Double): Double; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_optlstring(numArg: Integer; const def: PAnsiChar; ls: PCardinal): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_ref(t: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_unref(t, ref: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_where(lvl: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
{$REGION 'ILuaAuxCommonMacrosLocal'}
function luaL_checkint(narg: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_checklong(narg: Cardinal): Cardinal; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_checkstring(narg: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_dofile(filename: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_dostring(str: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_getmetatable(tname: PAnsiChar); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_optint(narg, d: Integer): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_optlong(narg: Integer; d: Cardinal): Cardinal; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_optstring(narg: Integer; d: PAnsiChar): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_typename(index: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
{$REGION 'ILuaAuxInterchangeLocal'}
function luaL_loadbuffer(buff: PAnsiChar; sz: Cardinal; name: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_loadbufferx(buff: PAnsiChar; sz: Cardinal; name, mode: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_loadfile(filename: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_loadfilex(filename, mode: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_register(libname: PAnsiChar; lib: PluaLReg); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
constructor Create; overload;
constructor Create(const ALuaState: PLuaState); overload;
property LuaState: PLuaState read FLuaState;
end;
{$ENDREGION}
{
TLuaBaseMember
- A Base Class for all those linking back to TLuaBase!
}
{$REGION 'Base Class for all those linking back to TLuaCommon!'}
TLuaBaseMember = class(TPersistent)
protected
FLua: TLuaCommon;
public
constructor Create(const ALua: TLuaCommon);
end;
{$ENDREGION}
var
LuaLinkType: TLuaBaseType;
implementation
{$REGION 'TLuaBase - Lua Base Type (no Localizers)'}
{ TLuaBase }
function TLuaBase.LoadLuaLibrary(const L: PLuaState; const ALibName: AnsiString; ALibFunc: TLuaDelphiFunction): Integer;
begin
lua_pushcfunction(L, ALibFunc);
lua_pushstring(L, PAnsiChar(ALibName));
Result := (lua_pcall(L, 1, 0, 0));
lua_pop(L, 1);
end;
function TLuaBase.luaL_checkint(L: PLuaState; narg: Integer): Integer;
begin
Result := luaL_checkinteger(L, narg);
end;
function TLuaBase.luaL_checklong(L: PLuaState; narg: Cardinal): Cardinal;
begin
Result := Cardinal(luaL_checkinteger(L, narg));
end;
function TLuaBase.luaL_checkstring(L: PLuaState; narg: Integer): PAnsiChar;
begin
Result := luaL_checklstring(L, narg, nil);
end;
function TLuaBase.luaL_dofile(L: PLuaState; filename: PAnsiChar): Integer;
begin
luaL_loadfile(L, filename);
Result := lua_pcall(L, 0, 0, 0);
end;
function TLuaBase.luaL_dostring(L: PLuaState; str: PAnsiChar): Integer;
begin
luaL_loadstring(L, str);
Result := lua_pcall(L, 0, 0, 0);
end;
procedure TLuaBase.luaL_getmetatable(L: PLuaState; tname: PAnsiChar);
begin
lua_getfield(L, LUA_REGISTRYINDEX, tname);
end;
function TLuaBase.luaL_optint(L: PLuaState; narg, d: Integer): Integer;
begin
Result := luaL_optinteger(L, narg, d);
end;
function TLuaBase.luaL_optlong(L: PLuaState; narg: Integer; d: Cardinal): Cardinal;
begin
Result := Cardinal(luaL_optinteger(L, narg, d));
end;
function TLuaBase.luaL_optstring(L: PLuaState; narg: Integer; d: PAnsiChar): PAnsiChar;
begin
Result := luaL_optlstring(L, narg, d, nil);
end;
function TLuaBase.luaL_typename(L: PLuaState; index: Integer): PAnsiChar;
begin
Result := lua_typename(L, lua_type(L, index));
end;
function TLuaBase.lua_isboolean(L: PLuaState; idx: Integer): LongBool;
begin
Result := (lua_type(L, idx) = LUA_TBOOLEAN);
end;
function TLuaBase.lua_isfunction(L: PLuaState; idx: Integer): LongBool;
begin
Result := (lua_type(L, idx) = LUA_TFUNCTION);
end;
function TLuaBase.lua_islightuserdata(L: PLuaState; idx: Integer): LongBool;
begin
Result := (lua_type(L, idx) = LUA_TLIGHTUSERDATA);
end;
function TLuaBase.lua_isnil(L: PLuaState; idx: Integer): LongBool;
begin
Result := (lua_type(L, idx) = LUA_TNIL);
end;
function TLuaBase.lua_isnone(L: PLuaState; idx: Integer): LongBool;
begin
Result := (lua_type(L, idx) = LUA_TNONE);
end;
function TLuaBase.lua_isnoneornil(L: PLuaState; idx: Integer): LongBool;
begin
Result := (lua_isnone(L, idx) or lua_isnil(L, idx));
end;
function TLuaBase.lua_istable(L: PLuaState; idx: Integer): LongBool;
begin
Result := (lua_type(L, idx) = LUA_TTABLE);
end;
function TLuaBase.lua_isthread(L: PLuaState; idx: Integer): LongBool;
begin
Result := (lua_type(L, idx) = LUA_TTHREAD);
end;
procedure TLuaBase.lua_newtable(L: PLuaState);
begin
lua_createtable(L, 0, 0);
end;
procedure TLuaBase.lua_pop(L: PLuaState; n: Integer);
begin
lua_settop(L, (-n)-1);
end;
procedure TLuaBase.lua_pushcfunction(L: PLuaState; f: TLuaDelphiFunction);
begin
lua_pushcclosure(L, f, 0);
end;
function TLuaBase.lua_pushliteral(L: PLuaState; s: PAnsiChar): PAnsiChar;
begin
Result := lua_pushlstring(L, s, Length(s));
end;
procedure TLuaBase.lua_register(L: PLuaState; name: PAnsiChar; f: TLuaDelphiFunction);
begin
lua_pushcfunction(L, f);
lua_setglobal(L, name);
end;
function TLuaBase.lua_tostring(L: PLuaState; idx: Integer): PAnsiChar;
begin
Result := lua_tolstring(L, idx, nil);
end;
{$ENDREGION}
{$REGION 'TLuaCommon - Lua Common Type (with Localizers)'}
{ TLuaCommon }
constructor TLuaCommon.Create;
begin
inherited;
SetLuaLibRefs;
FLuaState := luaL_newstate;
lua_settop(0);
lua_pop(lua_gettop);
end;
constructor TLuaCommon.Create(const ALuaState: PLuaState);
begin
inherited Create;
SetLuaLibRefs;
FLuaState := ALuaState;
end;
function TLuaCommon.luaL_argerror(numarg: Integer; const extramsg: PAnsiChar): Integer;
begin
Result := luaL_argerror(FLuaState, numarg, extramsg);
end;
procedure TLuaCommon.luaL_buffinit(B: PLuaLBuffer);
begin
luaL_buffinit(FLuaState, B);
end;
function TLuaCommon.luaL_callmeta(obj: Integer; const e: PAnsiChar): Integer;
begin
Result := luaL_callmeta(FLuaState, obj, e);
end;
procedure TLuaCommon.luaL_checkany(narg: Integer);
begin
luaL_checkany(FLuaState, narg);
end;
function TLuaCommon.luaL_checkint(narg: Integer): Integer;
begin
Result := luaL_checkint(FLuaState, narg);
end;
function TLuaCommon.luaL_checkinteger(numArg: Integer): Integer;
begin
Result := luaL_checkinteger(FLuaState, numArg);
end;
function TLuaCommon.luaL_checklong(narg: Cardinal): Cardinal;
begin
Result := luaL_checklong(FLuaState, narg);
end;
function TLuaCommon.luaL_checklstring(numArg: Integer; ls: PCardinal): PAnsiChar;
begin
Result := luaL_checklstring(FLuaState, numArg, ls);
end;
function TLuaCommon.luaL_checknumber(numArg: Integer): Double;
begin
Result := luaL_checknumber(FLuaState, numArg);
end;
function TLuaCommon.luaL_checkoption(narg: Integer; const def: PAnsiChar; const lst: array of PAnsiChar): Integer;
begin
Result := luaL_checkoption(FLuaState, narg, def, lst);
end;
procedure TLuaCommon.luaL_checkstack(sz: Integer; const msg: PAnsiChar);
begin
luaL_checkstack(FLuaState, sz, msg);
end;
function TLuaCommon.luaL_checkstring(narg: Integer): PAnsiChar;
begin
Result := luaL_checkstring(FLuaState, narg);
end;
procedure TLuaCommon.luaL_checktype(narg, t: Integer);
begin
luaL_checktype(FLuaState, narg, t);
end;
function TLuaCommon.luaL_checkudata(ud: Integer; const tname: PAnsiChar): Pointer;
begin
Result := luaL_checkudata(FLuaState, ud, tname);
end;
function TLuaCommon.luaL_dofile(filename: PAnsiChar): Integer;
begin
Result := luaL_dofile(FLuaState, filename);
end;
function TLuaCommon.luaL_dostring(str: PAnsiChar): Integer;
begin
Result := luaL_dostring(FLuaState, str);
end;
function TLuaCommon.luaL_error(const fmt: PAnsiChar): Integer;
begin
Result := luaL_error(FLuaState, fmt);
end;
function TLuaCommon.luaL_getmetafield(obj: Integer; const e: PAnsiChar): Integer;
begin
Result := luaL_getmetafield(FLuaState, obj, e);
end;
procedure TLuaCommon.luaL_getmetatable(tname: PAnsiChar);
begin
luaL_getmetatable(FLuaState, tname);
end;
function TLuaCommon.luaL_gsub(const s, p, r: PAnsiChar): PAnsiChar;
begin
Result := luaL_gsub(FLuaState, s, p, r);
end;
function TLuaCommon.luaL_loadbuffer(buff: PAnsiChar; sz: Cardinal; name: PAnsiChar): Integer;
begin
Result := luaL_loadbuffer(FLuaState, buff, sz, name);
end;
function TLuaCommon.luaL_loadbufferx(buff: PAnsiChar; sz: Cardinal; name, mode: PAnsiChar): Integer;
begin
Result := luaL_loadbufferx(FLuaState, buff, sz, name, mode);
end;
function TLuaCommon.luaL_loadfile(filename: PAnsiChar): Integer;
begin
Result := luaL_loadfile(FLuaState, filename);
end;
function TLuaCommon.luaL_loadfilex(filename, mode: PAnsiChar): Integer;
begin
Result := luaL_loadfilex(FLuaState, filename, mode);
end;
function TLuaCommon.luaL_loadstring(const s: PAnsiChar): Integer;
begin
Result := luaL_loadstring(FLuaState, s);
end;
function TLuaCommon.luaL_newmetatable(const tname: PAnsiChar): Integer;
begin
Result := luaL_newmetatable(FLuaState, tname);
end;
procedure TLuaCommon.luaL_openlibs;
begin
luaL_openlibs(FLuaState);
end;
function TLuaCommon.luaL_optint(narg, d: Integer): Integer;
begin
Result := luaL_optint(FLuaState, narg, d);
end;
function TLuaCommon.luaL_optinteger(nArg, def: Integer): Integer;
begin
Result := luaL_optinteger(FLuaState, nArg, def);
end;
function TLuaCommon.luaL_optlong(narg: Integer; d: Cardinal): Cardinal;
begin
Result := luaL_optlong(FLuaState, narg, d);
end;
function TLuaCommon.luaL_optlstring(numArg: Integer; const def: PAnsiChar; ls: PCardinal): PAnsiChar;
begin
Result := luaL_optlstring(FLuaState, numArg, def, ls);
end;
function TLuaCommon.luaL_optnumber(nArg: Integer; def: Double): Double;
begin
Result := luaL_optnumber(FLuaState, nArg, def);
end;
function TLuaCommon.luaL_optstring(narg: Integer; d: PAnsiChar): PAnsiChar;
begin
Result := luaL_optstring(FLuaState, narg, d);
end;
function TLuaCommon.luaL_ref(t: Integer): Integer;
begin
Result := luaL_ref(FLuaState, t);
end;
procedure TLuaCommon.luaL_register(libname: PAnsiChar; lib: PluaLReg);
begin
luaL_register(FLuaState, libname, lib);
end;
function TLuaCommon.luaL_typename(index: Integer): PAnsiChar;
begin
Result := luaL_typename(FLuaState, index);
end;
procedure TLuaCommon.luaL_unref(t, ref: Integer);
begin
luaL_unref(FLuaState, t, ref);
end;
procedure TLuaCommon.luaL_where(lvl: Integer);
begin
luaL_where(FLuaState, lvl);
end;
function TLuaCommon.luaopen_base: Integer;
begin
Result := luaopen_base(FLuaState);
end;
function TLuaCommon.luaopen_debug: Integer;
begin
Result := luaopen_debug(FLuaState);
end;
function TLuaCommon.luaopen_io: Integer;
begin
Result := luaopen_io(FLuaState);
end;
function TLuaCommon.luaopen_math: Integer;
begin
Result := luaopen_math(FLuaState);
end;
function TLuaCommon.luaopen_os: Integer;
begin
Result := luaopen_os(FLuaState);
end;
function TLuaCommon.luaopen_package: Integer;
begin
Result := luaopen_package(FLuaState);
end;
function TLuaCommon.luaopen_string: Integer;
begin
Result := luaopen_string(FLuaState);
end;
function TLuaCommon.luaopen_table: Integer;
begin
Result := luaopen_table(FLuaState);
end;
function TLuaCommon.lua_atpanic(panicf: TLuaDelphiFunction): TLuaDelphiFunction;
begin
Result := lua_atpanic(FLuaState, panicf);
end;
procedure TLuaCommon.lua_call(nargs, nresults: Integer);
begin
lua_call(FLuaState, nargs, nresults);
end;
procedure TLuaCommon.lua_callk(nargs, nresults, ctx: Integer; k: TLuaDelphiFunction);
begin
lua_callk(FLuastate, nargs, nresults, ctx, k);
end;
function TLuaCommon.lua_checkstack(sz: Integer): LongBool;
begin
Result := lua_checkstack(FLuaState, sz);
end;
procedure TLuaCommon.lua_close;
begin
lua_close(FLuaState);
end;
function TLuaCommon.lua_compare(idx1, idx2, op: Integer): LongBool;
begin
Result := lua_compare(FLuastate, idx1, idx2, op);
end;
procedure TLuaCommon.lua_concat(n: Integer);
begin
lua_concat(FLuaState, n);
end;
function TLuaCommon.lua_cpcall(func: TLuaDelphiFunction; ud: Pointer): Integer;
begin
Result := lua_cpcall(FLuaState, func, ud);
end;
procedure TLuaCommon.lua_createtable(narr, nrec: Integer);
begin
lua_createtable(FLuaState, narr, nrec);
end;
function TLuaCommon.lua_dump(writer: TLuaWriterFunction; data: Pointer): Integer;
begin
Result := lua_dump(FLuaState, writer, data);
end;
function TLuaCommon.lua_equal(idx1, idx2: Integer): LongBool;
begin
Result := lua_equal(FLuaState, idx1, idx2);
end;
function TLuaCommon.lua_error: Integer;
begin
Result := lua_error(FLuaState);
end;
function TLuaCommon.lua_gc(what, data: Integer): Integer;
begin
Result := lua_gc(FLuaState, what, data);
end;
function TLuaCommon.lua_getallocf(ud: PPointer): TLuaAllocFunction;
begin
Result := lua_getallocf(FLuaState, ud);
end;
procedure TLuaCommon.lua_getfenv(idx: Integer);
begin
lua_getfenv(FLuaState, idx);
end;
procedure TLuaCommon.lua_getfield(idx: Integer; k: PAnsiChar);
begin
lua_getfield(FLuaState, idx, k);
end;
procedure TLuaCommon.lua_getglobal(name: PAnsiChar);
begin
lua_getglobal(FLuaState, name);
end;
function TLuaCommon.lua_gethook: TLuaHookFunction;
begin
Result := lua_gethook(FLuaState);
end;
function TLuaCommon.lua_gethookcount: Integer;
begin
Result := lua_gethookcount(FLuaState);
end;
function TLuaCommon.lua_gethookmask: Integer;
begin
Result := lua_gethookmask(FLuaState);
end;
function TLuaCommon.lua_getinfo(const what: PAnsiChar; ar: PLuaDebug): Integer;
begin
Result := lua_getinfo(FLuaState, what, ar);
end;
function TLuaCommon.lua_getlocal(ar: PLuaDebug; n: Integer): PAnsiChar;
begin
Result := lua_getlocal(FLuaState, ar, n);
end;
function TLuaCommon.lua_getmetatable(objindex: Integer): LongBool;
begin
Result := lua_getmetatable(FLuaState, objindex);
end;
function TLuaCommon.lua_getstack(level: Integer; ar: PLuaDebug): Integer;
begin
Result := lua_getstack(FLuaState, level, ar);
end;
procedure TLuaCommon.lua_gettable(idx: Integer);
begin
lua_gettable(FLuaState, idx);
end;
function TLuaCommon.lua_gettop: Integer;
begin
Result := lua_gettop(FLuaState);
end;
function TLuaCommon.lua_getupvalue(funcindex, n: Integer): PAnsiChar;
begin
Result := lua_getupvalue(FLuaState, funcindex, n);
end;
procedure TLuaCommon.lua_getuservalue(idx: Integer);
begin
lua_getuservalue(FLuaState, idx);
end;
procedure TLuaCommon.lua_insert(idx: Integer);
begin
lua_insert(FLuaState, idx);
end;
function TLuaCommon.lua_isboolean(idx: Integer): LongBool;
begin
Result := lua_isboolean(FLuaState, idx);
end;
function TLuaCommon.lua_iscfunction(idx: Integer): LongBool;
begin
Result := lua_iscfunction(FLuaState, idx);
end;
function TLuaCommon.lua_isfunction(idx: Integer): LongBool;
begin
Result := lua_isfunction(FLuaState, idx);
end;
function TLuaCommon.lua_islightuserdata(idx: Integer): LongBool;
begin
Result := lua_islightuserdata(FLuaState, idx);
end;
function TLuaCommon.lua_isnil(idx: Integer): LongBool;
begin
Result := lua_isnil(FLuastate, idx);
end;
function TLuaCommon.lua_isnone(idx: Integer): LongBool;
begin
Result := lua_isnone(FLuaState, idx);
end;
function TLuaCommon.lua_isnoneornil(idx: Integer): LongBool;
begin
Result := lua_isnoneornil(FLuaState, idx);
end;
function TLuaCommon.lua_isnumber(idx: Integer): LongBool;
begin
Result := lua_isnumber(FLuaState, idx);
end;
function TLuaCommon.lua_isstring(idx: Integer): LongBool;
begin
Result := lua_isstring(FLuaState, idx);
end;
function TLuaCommon.lua_istable(idx: Integer): LongBool;
begin
Result := lua_istable(FLuaState, idx);
end;
function TLuaCommon.lua_isthread(idx: Integer): LongBool;
begin
Result := lua_isthread(FLuaState, idx);
end;
function TLuaCommon.lua_isuserdata(idx: Integer): LongBool;
begin
Result := lua_isuserdata(FLuaState, idx);
end;
function TLuaCommon.lua_lessthan(idx1, idx2: Integer): LongBool;
begin
Result := lua_lessthan(FLuaState, idx1, idx2);
end;
function TLuaCommon.lua_load(reader: TLuaReaderFunction; dt: Pointer; Source, Mode: PAnsiChar): Integer;
begin
Result := lua_load(FLuaState, reader, dt, source, mode);
end;
function TLuaCommon.lua_load(reader: TLuaReaderFunction; dt: Pointer; const chunkname: PAnsiChar): Integer;
begin
Result := lua_load(FLuaState, reader, dt, chunkname, nil);
end;
procedure TLuaCommon.lua_newtable;
begin
lua_newtable(FLuaState);
end;
function TLuaCommon.lua_newthread: PLuaState;
begin
Result := lua_newthread(FLuaState);
end;
function TLuaCommon.lua_newuserdata(sz: Cardinal): Pointer;
begin
Result := lua_newuserdata(FLuaState, sz);
end;
function TLuaCommon.lua_next(idx: Integer): Integer;
begin
Result := lua_next(FLuaState, idx);
end;
function TLuaCommon.lua_objlen(idx: Integer): Cardinal;
begin
Result := lua_objlen(FLuaState, idx);
end;
function TLuaCommon.lua_pcall(nargs, nresults, errfunc: Integer): Integer;
begin
Result := lua_pcall(FLuaState, nargs, nresults, errfunc);
end;
function TLuaCommon.lua_pcallk(nargs, nresults, errfunc, ctx: Integer; k: TLuaDelphiFunction): Integer;
begin
Result := lua_pcallk(FLuaState, nargs, nresults, errfunc, ctx, k);
end;
procedure TLuaCommon.lua_pop(n: Integer);
begin
lua_pop(FLuaState, n);
end;
procedure TLuaCommon.lua_pushboolean(b: LongBool);
begin
lua_pushboolean(FLuaState, b);
end;
procedure TLuaCommon.lua_pushcclosure(fn: TLuaDelphiFunction; n: Integer);
begin
lua_pushcclosure(FLuaState, fn, n);
end;
procedure TLuaCommon.lua_pushcfunction(f: TLuaDelphiFunction);
begin
lua_pushcfunction(FLuaState, f);
end;
function TLuaCommon.lua_pushfstring(const fmt: PAnsiChar): PAnsiChar;
begin
Result := lua_pushfstring(FLuaState, fmt);
end;
procedure TLuaCommon.lua_pushinteger(n: Integer);
begin
lua_pushinteger(FLuaState, n);
end;
procedure TLuaCommon.lua_pushlightuserdata(p: Pointer);
begin
lua_pushlightuserdata(FLuaState, p);
end;
function TLuaCommon.lua_pushliteral(s: PAnsiChar): PAnsiChar;
begin
Result := lua_pushliteral(FLuaState, s);
end;
function TLuaCommon.lua_pushlstring(const s: PAnsiChar; ls: Cardinal): PAnsiChar;
begin
Result := lua_pushlstring(FLuaState, s, ls);
end;
procedure TLuaCommon.lua_pushnil;
begin
lua_pushnil(FLuaState);
end;
procedure TLuaCommon.lua_pushnumber(n: Double);
begin
lua_pushnumber(FLuaState, n);
end;
function TLuaCommon.lua_pushstring(const s: PAnsiChar): PAnsiChar;
begin
Result := lua_pushstring(FLuaState, s);
end;
function TLuaCommon.lua_pushthread: LongBool;
begin
Result := lua_pushthread(FLuaState);
end;
procedure TLuaCommon.lua_pushvalue(idx: Integer);
begin
lua_pushvalue(FLuaState, idx);
end;
function TLuaCommon.lua_pushvfstring(const fmt: PAnsiChar; argp: Pointer): PAnsiChar;
begin
Result := lua_pushvfstring(FLuaState, fmt, argp);
end;
function TLuaCommon.lua_rawequal(idx1, idx2: Integer): LongBool;
begin
Result := lua_rawequal(FLuaState, idx1, idx2);
end;
procedure TLuaCommon.lua_rawget(idx: Integer);
begin
lua_rawget(FLuaState, idx);
end;
procedure TLuaCommon.lua_rawgeti(idx, n: Integer);
begin
lua_rawgeti(FLuaState, idx, n);
end;
function TLuaCommon.lua_rawlen(idx: Integer): Cardinal;
begin
Result := lua_rawlen(FLuaState, idx);
end;
procedure TLuaCommon.lua_rawset(idx: Integer);
begin
lua_rawset(FLuaState, idx);
end;
procedure TLuaCommon.lua_rawseti(idx, n: Integer);
begin
lua_rawseti(FLuaState, idx, n);
end;
procedure TLuaCommon.lua_register(name: PAnsiChar; f: TLuaDelphiFunction);
begin
lua_register(FLuaState, name, f);
end;
procedure TLuaCommon.lua_remove(idx: Integer);
begin
lua_remove(FLuaState, idx);
end;
procedure TLuaCommon.lua_replace(idx: Integer);
begin
lua_replace(FLuaState, idx);
end;
function TLuaCommon.lua_resume(narg: Integer): Integer;
begin
Result := lua_resume(FLuaState, narg);
end;
procedure TLuaCommon.lua_setallocf(f: TLuaAllocFunction; ud: Pointer);
begin
lua_setallocf(FLuaState, f, ud);
end;
function TLuaCommon.lua_setfenv(idx: Integer): LongBool;
begin
Result := lua_setfenv(FLuaState, idx);
end;
procedure TLuaCommon.lua_setfield(idx: Integer; const k: PAnsiChar);
begin
lua_setfield(FLuaState, idx, k);
end;
procedure TLuaCommon.lua_setglobal(name: PAnsiChar);
begin
lua_setglobal(FLuaState, name);
end;
function TLuaCommon.lua_sethook(func: TLuaHookFunction; mask, count: Integer): Integer;
begin
Result := lua_Sethook(FLuaState, func, mask, count);
end;
function TLuaCommon.lua_setlocal(ar: PLuaDebug; n: Integer): PAnsiChar;
begin
Result := lua_setlocal(FLuaState, ar, n);
end;
function TLuaCommon.lua_setmetatable(objindex: Integer): LongBool;
begin
Result := lua_setmetatable(FLuaState, objindex);
end;
procedure TLuaCommon.lua_settable(idx: Integer);
begin
lua_settable(FLuaState, idx);
end;
procedure TLuaCommon.lua_settop(idx: Integer);
begin
lua_settop(FLuaState, idx);
end;
function TLuaCommon.lua_setupvalue(funcindex, n: Integer): PAnsiChar;
begin
Result := lua_setupvalue(FLuaState, funcindex, n);
end;
procedure TLuaCommon.lua_setuservalue(idx: Integer);
begin
lua_setuservalue(FLuaState, idx);
end;
function TLuaCommon.lua_status: Integer;
begin
Result := lua_status(FLuaState);
end;
function TLuaCommon.lua_toboolean(idx: Integer): LongBool;
begin
Result := lua_toboolean(FLuaState, idx);
end;
function TLuaCommon.lua_tocfunction(idx: Integer): TLuaDelphiFunction;
begin
Result := lua_tocfunction(FLuaState, idx);
end;
function TLuaCommon.lua_tointeger(idx: Integer): Integer;
begin
Result := lua_tointeger(FLuaState, idx);
end;
function TLuaCommon.lua_tointegerx(idx: Integer; isnum: PInteger): Integer;
begin
Result := lua_tointegerx(FLuaState, idx, isnum);
end;
function TLuaCommon.lua_tolstring(idx: Integer; len: PCardinal): PAnsiChar;
begin
Result := lua_tolstring(FLuaState, idx, len);
end;
function TLuaCommon.lua_tonumber(idx: Integer): Double;
begin
Result := lua_tonumber(FLuaState, idx);
end;
function TLuaCommon.lua_tonumberx(idx: Integer; isnum: PInteger): Double;
begin
Result := lua_tonumberx(FLuaState, idx, isnum);
end;
function TLuaCommon.lua_topointer(idx: Integer): Pointer;
begin
Result := lua_topointer(FLuaState, idx);
end;
function TLuaCommon.lua_tostring(idx: Integer): PAnsiChar;
begin
Result := lua_tostring(FLuaState, idx);
end;
function TLuaCommon.lua_tothread(idx: Integer): PLuaState;
begin
Result := lua_tothread(FLuaState, idx);
end;
function TLuaCommon.lua_touserdata(idx: Integer): Pointer;
begin
Result := lua_touserdata(FLuaState, idx);
end;
function TLuaCommon.lua_type(idx: Integer): Integer;
begin
Result := lua_type(FLuaState, idx);
end;
function TLuaCommon.lua_typename(tp: Integer): PAnsiChar;
begin
Result := lua_typename(FLuaState, tp);
end;
procedure TLuaCommon.lua_xmove(dest: PLuaState; n: Integer);
begin
lua_xmove(FLuaState, dest, n);
end;
function TLuaCommon.lua_yield(nresults: Integer): Integer;
begin
Result := lua_yield(FLuaState, nresults);
end;
function TLuaCommon.lua_yieldk(nresults, ctx: Integer; k: TLuaDelphiFunction): Integer;
begin
Result := lua_yieldk(FLuaState, nresults, ctx, k);
end;
{$ENDREGION}
{$REGION 'TLuaBaseMember - Lua Base Member Type'}
{ TLuaBaseMember }
constructor TLuaBaseMember.Create(const ALua: TLuaCommon);
begin
inherited Create;
FLua := ALua;
end;
{$ENDREGION}
end.
|
unit MainForm;
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.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB,
FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client,
Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, System.RegularExpressions;
type
TForm1 = class(TForm)
FDConnection1: TFDConnection;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
edtUserName: TEdit;
edtPassword: TEdit;
LoginButton: TButton;
Label1: TLabel;
Label2: TLabel;
Button1: TButton;
Memo1: TMemo;
ButtonLoginWithStrings: TButton;
Memo2: TMemo;
Memo3: TMemo;
Memo4: TMemo;
Memo5: TMemo;
SpeedButton1: TSpeedButton;
Memo6: TMemo;
ButtonLoginQuoted: TButton;
FDQuery1: TFDQuery;
ButtonLoginWithParams: TButton;
ButtonLoginRegExp: TButton;
Memo7: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure LoginButtonClick(Sender: TObject);
procedure ButtonLoginWithStringsClick(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure ButtonLoginQuotedClick(Sender: TObject);
procedure ButtonLoginWithParamsClick(Sender: TObject);
procedure ButtonLoginRegExpClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.ButtonLoginWithStringsClick(Sender: TObject);
var
Query :string;
begin
Query := 'SELECT FULL_NAME FROM USERS WHERE USER_NAME = ''' + edtUserName.Text + ''' AND PASSWORD = ''' + edtPassword.Text + ''' ';
Memo1.Text := VarToStr(FDConnection1.ExecSQLScalar(Query));
end;
procedure TForm1.LoginButtonClick(Sender: TObject);
const
QueryTpl = 'SELECT FULL_NAME FROM USERS WHERE USER_NAME = ''%s'' AND PASSWORD = ''%s'' ';
begin
Memo1.Text := VarToStr(FDConnection1.ExecSQLScalar(Format(QueryTpl, [edtUserName.Text, edtPassword.Text])));
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
if ActiveControl is TMemo then
edtPassword.Text := StringReplace(StringReplace(TMemo(ActiveControl).Text, #13, '', [rfReplaceAll]), #10, '', [rfReplaceAll]);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if edtPassword.PasswordChar = #0 then
edtPassword.PasswordChar := '*'
else
edtPassword.PasswordChar := #0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
PageControl1.ActivePageIndex := 0;
FDConnection1.Connected := True;
end;
////////////////////////////
////////////////////////////
procedure TForm1.ButtonLoginQuotedClick(Sender: TObject);
const
QueryTpl = 'SELECT FULL_NAME FROM USERS WHERE USER_NAME = %s AND PASSWORD = %s ';
begin
Memo1.Text := VarToStr(FDConnection1.ExecSQLScalar(Format(QueryTpl, [QuotedStr(edtUserName.Text), QuotedStr(edtPassword.Text)])));
end;
procedure TForm1.ButtonLoginWithParamsClick(Sender: TObject);
begin
FDQuery1.ParamByName('USER_NAME').AsString := edtUserName.Text;
FDQuery1.ParamByName('PASSWORD').AsString := edtPassword.Text;
FDQuery1.Open;
if not FDQuery1.IsEmpty then
Memo1.Text := FDQuery1.FieldByName('FULL_NAME').AsString
else
Memo1.Text := '';
FDQuery1.Close;
end;
procedure TForm1.ButtonLoginRegExpClick(Sender: TObject);
const
QueryTpl = 'SELECT FULL_NAME FROM USERS WHERE USER_NAME = %s AND PASSWORD = %s ';
var
UserPattern :TRegEx;
begin
UserPattern := TRegEx.Create('^[0-9A-Z_-]+$');
if not UserPattern.Match(edtUserName.Text).Success then
raise Exception.Create('Invalid user name');
if not UserPattern.Match(edtPassword.Text).Success then
raise Exception.Create('Invalid password');
Memo1.Text := VarToStr(FDConnection1.ExecSQLScalar(Format(QueryTpl, [QuotedStr(edtUserName.Text), QuotedStr(edtPassword.Text)])));
end;
end.
|
unit PSVClass;
interface
uses
classes, ComCtrls, sysUtils, Dialogs, Controls, strUtils;
type
TPSVFile = class
private
psvFile : TMemoryStream;
fileList : Tlist;
mainDirName : string;
PS2File : boolean;
function listFiles : boolean;
procedure PS2Buttons(enabled : boolean);
public
procedure Clear;
function loadFile(filename : string): boolean;
function extractAFile(item : integer; destination : string): boolean;
function extractAllFiles(destination : string): boolean;
function getDirName : string;
function extractPS1Save(destination: string): boolean;
function cleanString (input : AnsiString): AnsiString;
function CleanFileName(const InputString: AnsiString): AnsiString;
constructor Create;
Destructor Destroy;
end;
implementation
uses PSVFormat, main;
{ PSVFile }
procedure TPSVFile.Clear;
var
x : integer;
fileInfo : PTPS2FileInfo;
ps1Info : PTPS1Header;
begin
psvFile.Clear;
if PS2File then begin
for x := fileList.Count -1 downto 0 do begin
fileInfo := fileList.Items[x];
dispose(fileInfo);
fileList.Delete(x);
end;
end else begin
for x := fileList.Count -1 downto 0 do begin
ps1Info := fileList.Items[x];
dispose(ps1Info);
fileList.Delete(x);
end;
end;
fileList.Clear;
end;
constructor TPSVFile.Create;
begin
psvFile := TMemoryStream.Create;
fileList := Tlist.Create;
end;
destructor TPSVFile.Destroy;
begin
Clear;
psvFile.Free;
fileList.Free;
end;
function TPSVFile.extractAFile(item: integer; destination: string): boolean;
var
FS : TMemoryStream;
fileInfo : PTPS2FileInfo;
dialogResult : integer;
begin
FS := TMemoryStream.Create;
fileInfo := fileList.Items[item];
FS.SetSize(fileInfo^.filesize);
PSVFile.Position := fileInfo^.positionInFile;
//stream copying hates 0 size so skip if filesize := 0
if fileInfo.filesize > 0 then begin
FS.CopyFrom(PSVFile, FS.Size);
end;
if fileExists(destination) then begin
dialogResult := MessageDlg('File already exists, overwrite?', mtConfirmation, [mbYes, mbNo], 0, mbYes);
if (dialogResult = mrCancel) or (dialogResult = mrNo) then begin
Result := False;
FS.Free;
Exit;
end;
end;
FS.SaveToFile(destination);
FS.Free;
result := True;
end;
function TPSVFile.extractAllFiles(destination: string): boolean;
var
FS : TMemoryStream;
fileInfo : PTPS2FileInfo;
x : integer;
dialogResult : integer;
begin
FS := TMemoryStream.Create;
for x := 0 to fileList.Count - 1 do begin
fileInfo := fileList.Items[x];
FS.SetSize(fileInfo^.filesize);
PSVFile.Position := fileInfo^.positionInFile;
//stream copying hates 0 size so skip if filesize := 0
if fileInfo.filesize > 0 then begin
FS.CopyFrom(PSVFile, FS.Size);
end;
if not DirectoryExists(destination + '\' + CleanFileName(mainDirName)) then begin
CreateDir(destination + '\' + CleanFileName(mainDirName));
end;
if fileExists(destination + '\' + CleanFileName(mainDirName) + '\' + CleanFileName(fileInfo^.filename)) then begin
dialogResult := MessageDlg(destination + '\' + CleanFileName(mainDirName) + '\' + CleanFileName(fileInfo^.filename) + sLineBreak + 'already exists, overwrite?', mtConfirmation, [mbYes, mbNo], 0, mbYes);
if (dialogResult = mrCancel) or (dialogResult = mrNo) then begin
Result := False;
FS.Free;
Continue;
end;
end;
FS.SaveToFile(destination + '\' + CleanFileName(mainDirName) + '\' + CleanFileName(fileInfo^.filename));
FS.Clear;
end;
FS.Free;
result := True;
end;
function TPSVFile.extractPS1Save(destination: string): boolean;
var
FS : TMemoryStream;
PS1Header : PTPS1Header;
MCSHeader : PTPS1MCSHeader;
xorByte, xorResult : byte;
i : integer;
dialogResult : integer;
begin
PS1Header := fileList.Items[0];
new(MCSHeader);
MCSHeader^.magic := 81;
MCSHeader^.dataSize := PS1Header^.saveSize;
MCSHeader^.positionInCard := $FFFF;
MCSHeader^.prodCode := PS1Header^.prodCode;
FillChar(MCSHeader^.filler, SizeOf(MCSHeader^.filler), 0);
FS := TMemoryStream.Create;
if lowerCase(ExtractFileExt(destination)) = '.mcs' then begin
FS.Write(MCSHeader^, sizeof(MCSHeader^));
FS.Position := 0;
xorResult := 0;
for I := 0 to 126 do begin
FS.Read(xorByte, sizeof(xorByte));
xorResult := xorResult xor xorByte;
end;
FS.Write(xorResult, sizeof(xorResult));
end;
PSVFile.Position := PS1Header^.startOfSaveData;
FS.CopyFrom(PSVFile, PS1Header^.saveSize);
if fileExists(destination) then begin
dialogResult := MessageDlg(destination + sLineBreak + 'already exists, overwrite?', mtConfirmation, [mbYes, mbNo], 0, mbYes);
if (dialogResult = mrCancel) or (dialogResult = mrNo) then begin
Result := False;
FS.Free;
dispose(MCSHeader);
exit;
end;
end;
FS.SaveToFile(destination);
FS.Free;
dispose(MCSHeader);
Result := True;
end;
function TPSVFile.getDirName: string;
begin
result := mainDirName;
end;
function TPSVFile.listFiles : boolean;
var
header : PTHeader;
PS2Header : PTPS2Header;
PS1Header : PTPS1Header;
mainDirInfo : PTPS2MainDirInfo;
fileInfo : PTPS2FileInfo;
ps1FileInfo : PTPS1FileInfo;
magicString : String;
x : integer;
NewItem : TListItem;
created : string;
modified : string;
begin
psvFile.position := 0;
new(header);
psvFile.Read(header^, sizeof(header^));
magicString := header^.magic[3] + header^.magic[2] + header^.magic[1];
//exit if not PSV file
if magicString <> 'PSV' then begin
dispose(header);
result := False;
Exit;
end;
if header.saveType = 2 then begin
//PS2 file
PS2File := True;
PS2Buttons(True);
//get PS2 header
new(PS2Header);
psvFile.Read(PS2Header^, sizeof(PS2Header^));
//get maindirinfo
new(mainDirInfo);
psvFile.Read(mainDirInfo^, sizeof(MainDirInfo^));
mainDirName := mainDirInfo^.filename;
//add files to the list
for x := 0 to PS2header^.numberOfFiles -1 do begin
fileInfo := new(PTPS2FileInfo);
psvFile.Read(fileInfo^, sizeOf(fileInfo^));
fileList.Add(fileInfo);
newItem := nil;
newItem := form1.ListView1.Items.Add;
newItem.Caption := fileInfo^.filename;
newItem.SubItems.Add(intToStr(fileInfo^.filesize));
//Creation date
created := '';
if fileInfo^.CreateHours < 10 then begin
created := created + '0';
end;
created := created + intToStr(fileInfo^.CreateHours) + ':';
if fileInfo^.CreateMinutes < 10 then begin
created := created + '0';
end;
created := created + intToStr(fileInfo^.CreateMinutes)
{+ ':' + intToStr(fileInfo^.CreateSeconds)} + ' ' + intToStr(fileInfo^.CreateDays)
+ '/' + intToStr(fileInfo^.CreateMonths) + '/' + intToStr(fileInfo^.CreateYear);
newItem.SubItems.Add(created);
//modifed date
modified := '';
if fileInfo^.ModHours < 10 then begin
modified := modified + '0';
end;
modified := modified + intToStr(fileInfo^.ModHours) + ':';
if fileInfo^.ModMinutes < 10 then begin
modified := modified + '0';
end;
modified := modified + intToStr(fileInfo^.ModMinutes)
{+ ':' + intToStr(fileInfo^.ModSeconds)} + ' ' + intToStr(fileInfo^.ModDays)
+ '/' + intToStr(fileInfo^.ModMonths) + '/' + intToStr(fileInfo^.ModYear);
newItem.SubItems.Add(modified);
end;
dispose(mainDirInfo);
//showmessage(intToStr(header^.unknown6));
dispose(header);
dispose(PS2Header);
result := True;
end else begin
//PS1 file
PS2File := False;
PS2Buttons(False);
new(PS1Header);
psvFile.Read(PS1Header^, sizeof(PS1Header^));
//new(PS1FileInfo);
//psvFile.Read(PS1FileInfo^, sizeof(PS1FileInfo^));
newItem := nil;
newItem := form1.ListView1.Items.Add;
newItem.Caption := PS1Header^.prodCode;
//newItem.Caption := WideStringtoString(PS1FileInfo.title, 1252);
newItem.SubItems.Add(intToStr(PS1Header.saveSize div 8192) + ' block(s)');
fileList.Add(PS1header);
dispose(header);
Result := True;
end;
end;
function TPSVFile.loadFile(filename: string): boolean;
begin
Clear;
psvFile.LoadFromFile(fileName);
if listFiles then begin
result := True;
end else begin
result := False;
end;
end;
procedure TPSVFile.PS2Buttons(enabled: boolean);
begin
if enabled then begin
//PS2 only
Form1.btnSaveFile.Enabled := True;
Form1.btnExtractAll.Enabled := True;
Form1.btnSavePS1.Enabled := False;
Form1.MainMenu1.Items[0].Items[1].Enabled := True;
Form1.MainMenu1.Items[0].Items[2].Enabled := True;
Form1.MainMenu1.Items[0].Items[3].Enabled := False;
Form1.PopupMenu1.Items[0].Visible := True;
Form1.PopupMenu1.Items[1].Visible := True;
Form1.PopupMenu1.Items[2].Visible := False;
end else begin
//PS1 only
Form1.btnSaveFile.Enabled := False;
Form1.btnExtractAll.Enabled := False;
Form1.btnSavePS1.Enabled := True;
Form1.MainMenu1.Items[0].Items[1].Enabled := False;
Form1.MainMenu1.Items[0].Items[2].Enabled := False;
Form1.MainMenu1.Items[0].Items[3].Enabled := True;
Form1.PopupMenu1.Items[0].Visible := False;
Form1.PopupMenu1.Items[1].Visible := False;
Form1.PopupMenu1.Items[2].Visible := True;
end;
end;
function TPSVFile.cleanString (input : Ansistring): Ansistring;
begin
//'*'(0x2a), '/'(0x2f), and '?'(0x3f)
while AnsiPos('*', input) > 0 do begin
AnsiReplaceStr(input,'*', ' ');
end;
while AnsiPos('/', input) > 0 do begin
AnsiReplaceStr(input,'/', ' ');
end;
while AnsiPos('?', input) > 0 do begin
AnsiReplaceStr(input,'?', ' ');
end;
while AnsiPos(':', input) > 0 do begin
AnsiReplaceStr(input,':', ' ');
end;
while AnsiPos('\', input) > 0 do begin
AnsiReplaceStr(input,'\', ' ');
end;
while AnsiPos('"', input) > 0 do begin
AnsiReplaceStr(input,'"', ' ');
end;
while AnsiPos('<', input) > 0 do begin
AnsiReplaceStr(input,'<', ' ');
end;
while AnsiPos('>', input) > 0 do begin
AnsiReplaceStr(input,'>', ' ');
end;
while AnsiPos('|', input) > 0 do begin
AnsiReplaceStr(input,'|', ' ');
end;
result := input;
end;
function TPSVFile.CleanFileName(const InputString: AnsiString): Ansistring;
var
i: integer;
ResultWithSpaces: Ansistring;
begin
ResultWithSpaces := InputString;
for i := 1 to Length(ResultWithSpaces) do
begin
// These chars are invalid in file names.
case ResultWithSpaces[i] of
'/', '\', ':', '*', '?', '"', '|':
// Use a * to indicate a duplicate space so we can remove
// them at the end.
{$WARNINGS OFF} // W1047 Unsafe code 'String index to var param'
if (i > 1) and
((ResultWithSpaces[i - 1] = ' ') or (ResultWithSpaces[i - 1] = '*')) then
ResultWithSpaces[i] := '*'
else
ResultWithSpaces[i] := ' ';
{$WARNINGS ON}
end;
end;
// A * indicates duplicate spaces. Remove them.
result := ReplaceStr(ResultWithSpaces, '*', '');
// Also trim any leading or trailing spaces
result := Trim(Result);
if result = '' then
begin
raise(Exception.Create('Resulting FileName was empty Input string was: '
+ InputString));
end;
end;
end.
|
unit untGroupRightsOperate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, untEasyPlateDBBaseForm, ComCtrls, untEasyTreeView,
untEasyButtons, ExtCtrls, untEasyGroupBox, untEasyEdit, StdCtrls,
untEasyUtilConst, ImgList, DB, DBClient, untEasyLabel, untGroupRightsObjects,
Menus, untEasyMenus, untEasyMenuStylers, untEasyBallonControl;
type
TfrmGroupRightsOperate = class(TfrmEasyPlateDBBaseForm)
EasyPanel1: TEasyPanel;
EasyPanel3: TEasyPanel;
EasyPanel4: TEasyPanel;
EasyPanel5: TEasyPanel;
btnAssignAll: TEasyBitButton;
btnAssign: TEasyBitButton;
btnRevoke: TEasyBitButton;
btnRevokeAll: TEasyBitButton;
tvHaveRights: TEasyCheckTree;
tvNotHaveRights: TEasyCheckTree;
btnSave: TEasyBitButton;
btnCancel: TEasyBitButton;
edtRoleName: TEasyLabelEdit;
edtParentRole: TEasyButtonEdit;
imgRR: TImageList;
cdsResources: TClientDataSet;
EasyLabel1: TEasyLabel;
EasyLabel2: TEasyLabel;
cdsRoleResource: TClientDataSet;
pmNotHaveRights: TEasyPopupMenu;
EasyMenuOfficeStyler1: TEasyMenuOfficeStyler;
pmFullExpand2: TMenuItem;
pmFullCollapse2: TMenuItem;
pmHaveRights: TEasyPopupMenu;
pmFullExpand1: TMenuItem;
pmFullCollapse1: TMenuItem;
hintBall: TEasyHintBalloonForm;
procedure btnCancelClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure pmFullCollapse1Click(Sender: TObject);
procedure pmFullExpand1Click(Sender: TObject);
procedure pmFullExpand2Click(Sender: TObject);
procedure pmFullCollapse2Click(Sender: TObject);
procedure btnAssignAllClick(Sender: TObject);
procedure btnRevokeAllClick(Sender: TObject);
procedure btnAssignClick(Sender: TObject);
procedure btnRevokeClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure edtParentRoleButtonClick(Sender: TObject);
private
{ Private declarations }
FRoleResource,
FResource : TList;
function FindResourceParentNode(AParentRightGUID: string; ATree: TEasyCheckTree): TTreeNode;
procedure InitRoleResourcesTree(AClientDataSet: TClientDataSet);
procedure InitResourcesTree(AClientDataSet: TClientDataSet);
//权限分配 AType = 0分配权限 = 1移除权限
procedure AssignRight(ASrcTree, ADestTree: TEasyCheckTree; AType: Integer);
//分配权限时增加数据到ClietnDataSet
procedure AppendClientData(AClientDataSet: TClientDataSet; ARoleResource: TGroupRoleResource);
procedure DeleteClientData(AClientDataSet: TClientDataSet; ARoleResource: TGroupRoleResource);
procedure CreateParentNode(AParentNode: TTreeNode; ATree: TEasyCheckTree; AType: Integer);
public
{ Public declarations }
FOperateType: TEasyOperateType;
FRoleGUID : string;
end;
var
frmGroupRightsOperate: TfrmGroupRightsOperate;
implementation
{$R *.dfm}
uses
untEasyUtilMethod, untEasySelectParentRole;
procedure TfrmGroupRightsOperate.btnCancelClick(Sender: TObject);
begin
inherited;
ModalResult := mrCancel;
end;
procedure TfrmGroupRightsOperate.FormShow(Sender: TObject);
var
ARoleResourceSQL,
AResourceSQL: string;
ASQLOLE,
AResultData : OleVariant;
begin
inherited;
case FOperateType of
eotAdd:
Self.Caption := Self.Caption + '-[' + EASY_OPERATE_ADD + ']';
eotEdit:
Self.Caption := Self.Caption + '-[' + EASY_OPERATE_EDIT + ']';
end;
ASQLOLE := VarArrayCreate([0, 1], varVariant);
ARoleResourceSQL := ' SELECT * FROM vw_RoleResource WHERE RoleGUID = ' + QuotedStr(FRoleGUID);
ASQLOLE[0] := ARoleResourceSQL;
AResourceSQL := 'SELECT * FROM sysResource ORDER BY sParentResourceGUID, iOrder';
ASQLOLE[1] := AResourceSQL;
//
AResultData := EasyRDMDisp.EasyGetRDMDatas(ASQLOLE);
// cdsRoleResource.Data := ASQLOLE[0];
// cdsResources.Data := ASQLOLE[1];
cdsRoleResource.Data := EasyRDMDisp.EasyGetRDMData(ARoleResourceSQL);
cdsResources.Data := EasyRDMDisp.EasyGetRDMData(AResourceSQL);
//显示树
InitRoleResourcesTree(cdsRoleResource);
InitResourcesTree(cdsResources);
end;
procedure TfrmGroupRightsOperate.FormCreate(Sender: TObject);
begin
inherited;
FRoleResource := TList.Create;
FResource := TList.Create;
end;
procedure TfrmGroupRightsOperate.InitRoleResourcesTree(AClientDataSet: TClientDataSet);
var
I: Integer;
ATmpResourceNode: TTreeNode;
AGroupResource : TGroupRoleResource;
begin
if AClientDataSet.IsEmpty then Exit;
//先初始化模块
AClientDataSet.Filtered := False;
AClientDataSet.Filter := 'sParentResourceGUID = ' + QuotedStr('{00000000-0000-0000-0000-000000000003}');
AClientDataSet.Filtered := True;
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
AGroupResource := TGroupRoleResource.Create;
with AGroupResource do
begin
GUID := AClientDataSet.fieldbyname('GUID').AsString;
RoleGUID := AClientDataSet.fieldbyname('RoleGUID').AsString;
ResourceGUID := AClientDataSet.fieldbyname('ResourceGUID').AsString;
ResourceName := AClientDataSet.fieldbyname('sResourceName').AsString;
ParentResourceGUID := AClientDataSet.fieldbyname('sParentResourceGUID').AsString;
iOrder := AClientDataSet.fieldbyname('iOrder').AsInteger;
Checked := False;
end;
ATmpResourceNode := tvHaveRights.Items.AddChild(nil, AGroupResource.ResourceName);
ATmpResourceNode.Data := AGroupResource;
FRoleResource.Add(AGroupResource);
ATmpResourceNode.ImageIndex := 4;
ATmpResourceNode.SelectedIndex := 4;
AClientDataSet.Next;
end;
AClientDataSet.Filtered := False;
//挂靠可操作资源
AClientDataSet.Filtered := False;
AClientDataSet.Filter := 'sParentResourceGUID <> ' + QuotedStr('{00000000-0000-0000-0000-000000000003}');
AClientDataSet.Filtered := True;
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
AGroupResource := TGroupRoleResource.Create;
with AGroupResource do
begin
GUID := AClientDataSet.fieldbyname('GUID').AsString;
RoleGUID := AClientDataSet.fieldbyname('RoleGUID').AsString;
ResourceGUID := AClientDataSet.fieldbyname('ResourceGUID').AsString;
ResourceName := AClientDataSet.fieldbyname('sResourceName').AsString;
ParentResourceGUID := AClientDataSet.fieldbyname('sParentResourceGUID').AsString;
iOrder := AClientDataSet.fieldbyname('iOrder').AsInteger;
Checked := False;
end;
ATmpResourceNode := tvHaveRights.Items.AddChild(
FindResourceParentNode(AGroupResource.ParentResourceGUID, tvHaveRights),
AGroupResource.ResourceName);
ATmpResourceNode.Data := AGroupResource;
FRoleResource.Add(AGroupResource);
ATmpResourceNode.ImageIndex := 0;
ATmpResourceNode.SelectedIndex := ATmpResourceNode.ImageIndex + 1;
AClientDataSet.Next;
end;
AClientDataSet.Filtered := False;
end;
function TfrmGroupRightsOperate.FindResourceParentNode(
AParentRightGUID: string; ATree: TEasyCheckTree): TTreeNode;
var
I: Integer;
begin
Result := nil;
for I := 0 to ATree.Items.Count - 1 do
begin
if TGroupRoleResource(ATree.Items.Item[I].Data).ResourceGUID = AParentRightGUID then
begin
Result := ATree.Items.Item[I];
Break;
end;
end;
end;
procedure TfrmGroupRightsOperate.FormDestroy(Sender: TObject);
var
I: Integer;
begin
for I := FRoleResource.Count - 1 downto 0 do
TObject(FRoleResource.Items[I]).Free;
for I := FResource.Count - 1 downto 0 do
TObject(FResource.Items[I]).Free;
inherited;
end;
procedure TfrmGroupRightsOperate.InitResourcesTree(
AClientDataSet: TClientDataSet);
var
I: Integer;
ATmpResourceNode: TTreeNode;
AGroupResource : TGroupRoleResource;
begin
if AClientDataSet.IsEmpty then Exit;
//先初始化模块
AClientDataSet.Filtered := False;
AClientDataSet.Filter := 'sParentResourceGUID = ' + QuotedStr('{00000000-0000-0000-0000-000000000003}');
AClientDataSet.Filtered := True;
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
AGroupResource := TGroupRoleResource.Create;
with AGroupResource do
begin
GUID := AClientDataSet.fieldbyname('GUID').AsString;
RoleGUID := '';
ResourceGUID := AClientDataSet.fieldbyname('ResourceGUID').AsString;
ResourceName := AClientDataSet.fieldbyname('sResourceName').AsString;
ParentResourceGUID := AClientDataSet.fieldbyname('sParentResourceGUID').AsString;
iOrder := AClientDataSet.fieldbyname('iOrder').AsInteger;
Checked := False;
end;
ATmpResourceNode := tvNotHaveRights.Items.AddChild(nil, AGroupResource.ResourceName);
ATmpResourceNode.Data := AGroupResource;
FResource.Add(AGroupResource);
ATmpResourceNode.ImageIndex := 4;
ATmpResourceNode.SelectedIndex := 4;
AClientDataSet.Next;
end;
AClientDataSet.Filtered := False;
//挂靠可操作资源
AClientDataSet.Filtered := False;
AClientDataSet.Filter := 'sParentResourceGUID <> ' + QuotedStr('{00000000-0000-0000-0000-000000000003}');
AClientDataSet.Filtered := True;
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
//如果此权限已经分配就不会出现在待分配权限树中
//如果从已分配权限表移除时再显示在待分配权限树中
if FindResourceParentNode(AClientDataSet.fieldbyname('ResourceGUID').AsString,
tvHaveRights) = nil then
begin
AGroupResource := TGroupRoleResource.Create;
with AGroupResource do
begin
GUID := AClientDataSet.fieldbyname('GUID').AsString;
RoleGUID := '';
ResourceGUID := AClientDataSet.fieldbyname('ResourceGUID').AsString;
ResourceName := AClientDataSet.fieldbyname('sResourceName').AsString;
ParentResourceGUID := AClientDataSet.fieldbyname('sParentResourceGUID').AsString;
iOrder := AClientDataSet.fieldbyname('iOrder').AsInteger;
Checked := False;
end;
ATmpResourceNode := tvNotHaveRights.Items.AddChild(
FindResourceParentNode(AGroupResource.ParentResourceGUID, tvNotHaveRights),
AGroupResource.ResourceName);
ATmpResourceNode.Data := AGroupResource;
FResource.Add(AGroupResource);
ATmpResourceNode.ImageIndex := 0;
ATmpResourceNode.SelectedIndex := ATmpResourceNode.ImageIndex + 1;
end;
AClientDataSet.Next;
end;
AClientDataSet.Filtered := False;
//如果此权限是根节点、而且已经出现在已分配权限中、并且没有子节点
//则不应出现在待分配权限中
for I := tvNotHaveRights.Items.Count - 1 downto 0 do
begin
if (FindResourceParentNode(TGroupRoleResource(tvNotHaveRights.Items.Item[I].Data).ResourceGUID,
tvHaveRights) <> nil)
and (not tvNotHaveRights.Items.Item[I].HasChildren)
and (TGroupRoleResource(tvNotHaveRights.Items.Item[I].Data).ParentResourceGUID
= '{00000000-0000-0000-0000-000000000003}') then
begin
tvNotHaveRights.Items.Item[I].Delete;
end;
end;
end;
procedure TfrmGroupRightsOperate.pmFullCollapse1Click(Sender: TObject);
begin
inherited;
tvHaveRights.FullCollapse;
end;
procedure TfrmGroupRightsOperate.pmFullExpand1Click(Sender: TObject);
begin
inherited;
tvHaveRights.FullExpand;
end;
procedure TfrmGroupRightsOperate.pmFullExpand2Click(Sender: TObject);
begin
inherited;
tvNotHaveRights.FullExpand;
end;
procedure TfrmGroupRightsOperate.pmFullCollapse2Click(Sender: TObject);
begin
inherited;
tvNotHaveRights.FullCollapse;
end;
procedure TfrmGroupRightsOperate.AssignRight(ASrcTree,
ADestTree: TEasyCheckTree; AType: Integer);
var
I, J: Integer;
ATmpParentNode,
ATmpResourceNode,
ATmpNode : TTreeNode;
ATmpParentNodeGUID: TStrings;
begin
ASrcTree.Items.BeginUpdate;
ADestTree.Items.BeginUpdate;
ATmpParentNodeGUID := TStringList.Create;
for I := ASrcTree.Items.Count - 1 downto 0 do
begin
if ASrcTree.ItemState[I] = csChecked then
begin
ATmpResourceNode := ASrcTree.Items.Item[I];
ATmpParentNode := ATmpResourceNode.Parent;
if ATmpParentNode <> nil then
begin
CreateParentNode(ATmpParentNode, ADestTree, AType);
if ATmpParentNodeGUID.IndexOf(TGroupRoleResource(ATmpParentNode.Data).GUID) = -1 then
ATmpParentNodeGUID.Add(TGroupRoleResource(ATmpParentNode.Data).GUID);
end;
ATmpNode := ADestTree.Items.AddChild(
FindResourceParentNode(TGroupRoleResource(ATmpResourceNode.Data).ParentResourceGUID, ADestTree),
TGroupRoleResource(ATmpResourceNode.Data).ResourceName);
ATmpNode.Data := ATmpResourceNode.Data;
ATmpNode.ImageIndex := 0;
ATmpNode.SelectedIndex := ATmpNode.ImageIndex + 1;
if AType = 0 then
//生成数据集
AppendClientData(cdsRoleResource, TGroupRoleResource(ATmpNode.Data))
else
DeleteClientData(cdsRoleResource, TGroupRoleResource(ATmpNode.Data));
ASrcTree.Items.Item[I].Delete;
end;
end;
ASrcTree.Refresh;
ADestTree.Refresh;
ASrcTree.Items.EndUpdate;
ADestTree.Items.EndUpdate;
for J := ASrcTree.Items.Count - 1 downto 0 do
begin
if ATmpParentNodeGUID.IndexOf(TGroupRoleResource(ASrcTree.Items.Item[J].Data).GUID) <> -1 then
begin
if (not ASrcTree.Items.Item[J].HasChildren) then
ASrcTree.Items.Item[J].Delete;
end;
end;
ATmpParentNodeGUID.Free;
end;
procedure TfrmGroupRightsOperate.btnAssignAllClick(Sender: TObject);
begin
inherited;
if tvNotHaveRights.Items.Count = 0 then Exit;
tvNotHaveRights.SetAllNodes(csChecked);
AssignRight(tvNotHaveRights, tvHaveRights, 0);
end;
procedure TfrmGroupRightsOperate.btnRevokeAllClick(Sender: TObject);
begin
inherited;
if tvHaveRights.Items.Count = 0 then Exit;
tvHaveRights.SetAllNodes(csChecked);
AssignRight(tvHaveRights, tvNotHaveRights, 1);
end;
procedure TfrmGroupRightsOperate.btnAssignClick(Sender: TObject);
begin
inherited;
AssignRight(tvNotHaveRights, tvHaveRights, 0);
end;
procedure TfrmGroupRightsOperate.btnRevokeClick(Sender: TObject);
begin
inherited;
AssignRight(tvHaveRights, tvNotHaveRights, 1);
end;
procedure TfrmGroupRightsOperate.AppendClientData(
AClientDataSet: TClientDataSet; ARoleResource: TGroupRoleResource);
begin
with AClientDataSet do
begin
Append;
FieldByName('GUID').AsString := GenerateGUID;
FieldByName('RoleGUID').AsString := Trim(edtRoleName.EditLabel.Hint);
FieldByName('ResourceGUID').AsString := ARoleResource.ResourceGUID;
FieldByName('sResourceName').AsString := ARoleResource.ResourceName;
FieldByName('sParentResourceGUID').AsString := ARoleResource.ParentResourceGUID;
FieldByName('iOrder').AsInteger := ARoleResource.iOrder;
Post;
end;
end;
procedure TfrmGroupRightsOperate.DeleteClientData(
AClientDataSet: TClientDataSet; ARoleResource: TGroupRoleResource);
begin
if AClientDataSet.Locate('ResourceGUID', ARoleResource.ResourceGUID, [loCaseInsensitive]) then
AClientDataSet.Delete;
end;
procedure TfrmGroupRightsOperate.CreateParentNode(AParentNode: TTreeNode;
ATree: TEasyCheckTree; AType: Integer);
var
AATmpNode: TTreeNode;
begin
if FindResourceParentNode(TGroupRoleResource(AParentNode.Data).ResourceGUID,
ATree) = nil then
begin
AATmpNode := ATree.Items.AddChild(nil,
TGroupRoleResource(AParentNode.Data).ResourceName);
AATmpNode.Data := AParentNode.Data;
//生成数据集
if AType = 0 then
AppendClientData(cdsRoleResource, TGroupRoleResource(AParentNode.Data))
else
DeleteClientData(cdsRoleResource, TGroupRoleResource(AParentNode.Data));
end;
end;
procedure TfrmGroupRightsOperate.btnSaveClick(Sender: TObject);
var
AErrorCode: Integer;
AResultOLE: OleVariant;
begin
inherited;
if Trim(edtRoleName.Text) = '' then
begin
hintBall.ShowTextHintBalloon(bmtInfo, EASY_SYS_HINT, EASY_SYS_NOTNULL, 500, 200,
0, edtRoleName, bapBottomRight);
Exit;
end;
if Trim(edtParentRole.Text) = '' then
begin
hintBall.ShowTextHintBalloon(bmtInfo, EASY_SYS_HINT, EASY_SYS_NOTNULL, 500, 200,
0, edtParentRole, bapBottomRight);
Exit;
end;
if cdsRoleResource.ChangeCount = 0 then
begin
EasyHint(EASY_SYS_DATANOCHANGE);
Exit;
end;
try //sysRole_Resource
AResultOLE := EasyRDMDisp.EasySaveRDMData('sysRole_Resource', cdsRoleResource.Delta,
'GUID', AErrorCode);
EasyHint(EASY_SYS_SAVE_SUCCESS);
Self.ModalResult := mrOk;
except on e: Exception do
EasyHint(EASY_SYS_SAVE_FAILED + e.Message + IntToStr(AErrorCode));
end;
end;
procedure TfrmGroupRightsOperate.edtParentRoleButtonClick(Sender: TObject);
var
AList: TStrings;
begin
inherited;
AList := TStringList.Create;
if EasySelectParentRole(AList) then
begin
edtParentRole.EditLabel.Hint := AList.Values['ParentRoleGUID'];
edtParentRole.Text := AList.Values['ParentRoleName'];
end;
AList.Free;
end;
end.
|
unit ufrmSysLangDataContent;
interface
{$I ThsERP.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, StrUtils,
Vcl.AppEvnts, Vcl.Menus, Vcl.Samples.Spin,
Ths.Erp.Helper.Edit,
Ths.Erp.Helper.ComboBox,
Ths.Erp.Helper.Memo,
ufrmBase, ufrmBaseInputDB
;
type
TfrmSysLangDataContent = class(TfrmBaseInputDB)
lbllang: TLabel;
edtlang: TEdit;
lblval: TLabel;
edtval: TEdit;
procedure btnAcceptClick(Sender: TObject);override;
private
public
protected
procedure HelperProcess(Sender: TObject); override;
published
procedure FormShow(Sender: TObject); override;
end;
implementation
uses
Ths.Erp.Database.Singleton
, Ths.Erp.Database.Table.SysLangDataContent
, Ths.Erp.Database.Table.SysLang
, ufrmHelperSysLang
;
{$R *.dfm}
procedure TfrmSysLangDataContent.btnAcceptClick(Sender: TObject);
begin
if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then
begin
if (ValidateInput) then
begin
TSysLangDataContent(Table).Lang.Value := edtlang.Text;
TSysLangDataContent(Table).Value.Value := edtval.Text;
inherited;
end;
end
else
inherited;
end;
procedure TfrmSysLangDataContent.FormShow(Sender: TObject);
begin
inherited;
edtlang.CharCase := ecNormal;
end;
procedure TfrmSysLangDataContent.HelperProcess(Sender: TObject);
var
vHelperSysLang: TfrmHelperSysLang;
begin
if Sender.ClassType = TEdit then
begin
if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then
begin
if TEdit(Sender).Name = edtlang.Name then
begin
vHelperSysLang := TfrmHelperSysLang.Create(TEdit(Sender), Self, nil, True, ifmNone, fomNormal);
try
vHelperSysLang.ShowModal;
if Assigned(TSysLangDataContent(Table).Lang.FK.FKTable) then
TSysLangDataContent(Table).Lang.FK.FKTable.Free;
TSysLangDataContent(Table).Lang.FK.FKTable := vHelperSysLang.Table.Clone;
finally
vHelperSysLang.Free;
end;
end
end;
end;
end;
end.
|
Unit sysregs;
(***********************************************************)
(**) interface (**)
(***********************************************************)
uses ictrl;
const Ram_size_16MB = $00; //predefined value for 16Mb of ram.
Ram_size_04MB = $10; //predefined value for 4Mb of ram.
Ram_size_01MB = $20; //predefined value for 1Mb of ram.
Ram_size_08MB = $30; //predefined value for 8Mb of ram.
ROM_size_04MB = $C; //predefined value for 4Mb of rom.
ROM_size_02MB = $0; //predefined value for 2Mb of rom.
ROM_size_01MB = $8; //predefined value for 1Mb of rom.
ROM_size_512KB= $4; //predefined value for 512Kb of rom.
Flash_size_4MB= $0; //predefined value for 4Mb of Flash.
Flash_size_2MB= $1; //predefined value for 2Mb of Flash.
Flash_size_1MB= $2; //predefined value for 1Mb of Flash.
Flash_size_8MB= $3; //predefined value for 8Mb of Flash.
numzones = 15; //maxium number of memory zones.
Nomemory = 0;
R_able = 1;
W_able = 2;
RW_able = 3;
SaveFileName = '.\sav\sysregs.sav';
type c2500sysregs=class
(***********************************************************)
(**) private (**)
(***********************************************************)
registers : array[0..5] of word;
MemoryMAP : array [0..2,0..numzones] of longword;
MemoryMAPItems : byte;
intc : ^IntrCtrl;
maxram : ^longword;
interfInt : ^word;
(***********************************************************)
(**) public (**)
(***********************************************************)
function InterfaceRead8 (address:word): byte; //By this function cpu access in reading mode to 8 bit memory mapped registers.
procedure InterfaceWrite8 (address:word;data:byte); //By this function cpu access in Writing mode to 8 bit memory mapped registers.
function InterfaceRead16 (address:word): word; //By this function cpu access in reading mode to 16 bit memory mapped registers.
procedure InterfaceWrite16(address:word;data:word); //By this function cpu access in Writing mode to 16 bit memory mapped registers.
Procedure deepswitch (data:word);
procedure setint(addr:pointer);
procedure update_status; //Updates status of the device.
constructor create;
function validate(address:longword):byte; //Validate an adrres for the Busfault mechanism.
procedure SetInterruptController(ic:pointer); //Assigns an interrupt controller to the device.
procedure MemoryMapZone(Bp,Ep,mode:longword);
procedure reset;
procedure StatusSave;
procedure StatusRestore;
end;
(******************************************************************************)
(**) (**)
(**) implementation (**)
(**) (**)
(******************************************************************************)
procedure c2500sysregs.MemoryMapZone(Bp,Ep,mode:longword);
begin
MemoryMAP[0,MemoryMAPItems]:=bp;
MemoryMAP[1,MemoryMAPItems]:=ep;
MemoryMAP[2,MemoryMAPItems]:=mode;
inc(MemoryMAPItems);
end;
procedure c2500sysregs.update_status;
begin
if registers[0] and $c =$c then begin
registers[0]:=$c200;
intc^.irq($02); //hardware exception bus error
end;
case registers[1] and $30 of
$00: maxram^:=16*1024*1024;
$10: maxram^:= 4*1024*1024;
$20: maxram^:= 2*1024*1024;
$30: maxram^:= 8*1024*1024;
end;
end;
(******************************************************************************)
function c2500sysregs.validate(address:longword):byte;
var i:byte;
begin
result:=0;
for i:=0 to MemoryMAPItems do
begin
if (address>=memorymap[0,i]) and (address<memorymap[1,i]) then
begin
result:=memorymap[2,i];
if memorymap[2,i]=0 then begin
registers[0]:=registers[0] or $0100;
registers[0]:=registers[0] and $01ff;
end;
end;
end;
end;
(******************************************************************************)
function c2500sysregs.InterfaceRead8 (address:word): byte;
begin
if address and 1 = 0 then result:=registers[address shr 1] and $ff
else result:=(registers[address shr 1] and $ff00) shr 8;
end;
(******************************************************************************)
procedure c2500sysregs.InterfaceWrite8 (address:word;data:byte);
begin
end;
(******************************************************************************)
function c2500sysregs.InterfaceRead16 (address:word): word;
begin
result:=registers[address shr 1];
if address=0 then registers[0]:=registers[0]and $00ff;
if address=6 then result:=interfInt^;
end;
(******************************************************************************)
procedure c2500sysregs.InterfaceWrite16(address:word;data:word);
begin
registers[address shr 1]:=data;
registers[1]:=$300+ (registers[1]and $ff);
if address=6 then interfInt^:=data;
update_status;
end;
(******************************************************************************)
Procedure c2500sysregs.deepswitch(data:word);
begin
registers[1]:=data;
end;
(******************************************************************************)
constructor c2500sysregs.create;
var i:byte;
begin
//maxram:=16*1024*1024;
reset;
end;
(******************************************************************************)
procedure c2500sysregs.SetInterruptController(ic:pointer);
begin
intc:=ic;
end;
(******************************************************************************)
procedure c2500sysregs.reset;
begin
registers[0]:=0;registers[1]:=$0300;registers[2]:=0;registers[3]:=0;registers[4]:=0;
registers[5]:=$6f48;
// 0110 1101 0100 1000 >>6D48
// 0000 0110 0000 0000
// 0110 1111 0100 1000 >>6f48
//maxram:=16*1024*1024;
MemoryMAPItems:=0;
MemoryMapZone(0,16*1024*1024,RW_able);
maxram:=@memorymap[1,0];
end;
(******************************************************************************)
procedure c2500sysregs.setint(addr:pointer);
begin
interfInt:=addr;
end;
(******************************************************************************)
procedure c2500sysregs.StatusSave;
var f:file;
begin
assignfile(f,SaveFileName);
rewrite(f,1);
blockwrite(f,registers[0],13+3*(numzones+1)*4);
closefile(f);
end;
(******************************************************************************)
procedure c2500sysregs.StatusRestore;
var f:file;
begin
assignfile(f,SaveFileName);
system.Reset(f,1);
blockread(f,registers[0],13+3*(numzones+1)*4);
closefile(f);
end;
end.
|
unit PlayInfo;
{
Routines shared by all the Play objects. These are things
that everyone can do, or at least that can be done on more
than one device.
Status: Beta
Date: 5/16/93
Copyright (c) June 1993, by Charlie Calvert
Feel free to use this code as an adjunct to your own programs.
}
interface
uses
Strings,
MMSystem,
WinProcs,
WinTypes;
const
MsgLen = 200;
var
eroaremci:longint;
wDeviceID: Word;
PlayWindow: HWnd;
function Playfromto(mfrom,mto:longint): Boolean; export;
function Playfrom(mfrom:longint): Boolean; export;
function CloseMCI: Boolean; export;
function ErrorMsg(Error: LongInt; Msg: PChar): Boolean; export;
function GetDeviceID: Word; export;
function GetInfo(S: PChar): PChar; export;
function GetLen: Longint; export;
function GetLocation: LongInt; export;
function GetMode: Longint; export;
function OpenMCI(PWindow: HWnd; FileName, DeviceType: PChar): Boolean; export;
function PlayMCI: Boolean; export;
function SetTimeFormatMs: Boolean; export;
function StopMci: Boolean; export;
implementation
function CloseMci: Boolean;
var
Result: LongInt;
S1: array[0..MsgLen] of Char;
begin
CloseMci := True;
Result := mciSendCommand(wDeviceID, MCI_Close, 0, 0);
if Result <> 0 then begin
CloseMci := False;
ErrorMsg(Result, S1);
exit;
end;
wDeviceID := 0;
end;
function GetDeviceId: Word;
begin
GetDeviceId := wDeviceId;
end;
function GetErrorMessage(RC:LongInt; S: PChar): PChar;
begin
if not mciGetErrorString(RC, S, MsgLen) then
StrCopy(S, 'No message available');
GetErrorMessage := S;
end;
function ErrorMsg(Error: LongInt; Msg: PChar): Boolean;
var
S, S1: array[0..MsgLen] of Char;
begin
eroaremci:=error;
{ ErrorMsg := True;
StrCopy(S, 'Return Code: ');
Str(Error:5, S1);
StrCat(S, S1);
StrCat(S, Msg);
StrCat(S, GetErrorMessage(Error, S1));
if Error <> 0 then begin
MessageBox(0, S1, 'Information', mb_OK);
ErrorMsg := False;
end;}
end;
function GetInfo(S: PChar): PChar;
var
Info: TMci_Info_Parms;
Flags: LongInt;
S1: array[0..MsgLen] of Char;
Result: LongInt;
begin
Info.dwCallBack := 0;
Info.lpstrReturn := S;
Info.dwRetSize := MsgLen;
Flags := Mci_Info_Product;
Result := mciSendCommand(wDeviceID, Mci_Info, Flags, LongInt(@Info));
ErrorMsg(Result, S1);
GetInfo := S;
end;
function GetLen: Longint;
var
Info: TMci_Status_Parms;
Flags,
Result: LongInt;
S1: array [0..MsgLen] of Char;
begin
FillChar(Info, SizeOf(TMci_Status_Parms), 0);
Info.dwItem := Mci_Status_Length;
Flags := Mci_Status_Item;
Result := MciSendCommand(wDeviceID, Mci_Status, Flags, LongInt(@Info));
if Result <> 0 then begin
ErrorMsg(Result, S1);
exit;
end;
GetLen := Info.dwReturn;
end;
function GetLocation: LongInt;
var
Info: TMci_Status_Parms;
Flags: LongInt;
Result: LongInt;
S: array[0..MsgLen] of Char;
begin
Info.dwItem := Mci_Status_Position;
Flags := Mci_Status_Item;
Result := MciSendCommand(wDeviceID, Mci_Status, Flags, LongInt(@Info));
if Result <> 0 then begin
ErrorMsg(Result, S);
Exit;
end;
GetLocation := Info.dwReturn;
end;
function GetMode: Longint;
var
Info: TMci_Status_Parms;
Flags,
Result: LongInt;
S1: array [0..MsgLen] of Char;
begin
FillChar(Info, SizeOf(TMci_Status_Parms), 0);
Info.dwItem := Mci_Status_Mode;
Flags := Mci_Status_Item;
Result := MciSendCommand(wDeviceID, Mci_Status, Flags, LongInt(@Info));
if Result <> 0 then begin
ErrorMsg(Result, S1);
exit;
end;
GetMode := Info.dwReturn;
end;
function OpenMCI(PWindow: HWnd; FileName, DeviceType: PChar): Boolean;
var
OpenParms: TMci_Open_Parms;
Style: LongInt;
Result: LongInt;
S1: array [0..MsgLen] of Char;
begin
OpenMCI := True;
PlayWindow := PWindow;
OpenParms.lpstrDeviceType := DeviceType;
OpenParms.lpstrElementName := FileName;
Style := Mci_Open_Type or Mci_Open_Element;
Result := MciSendCommand(0, MCI_OPEN, Style, LongInt(@OpenParms));
if Result <> 0 then begin
OpenMCI := False;
ErrorMsg(Result, S1);
exit;
end;
wDeviceId := OpenParms.wDeviceID;
end;
function PlayMCI: Boolean;
var
Result: LongInt;
Info: TMci_Play_Parms;
S1: array[0..MsgLen] of Char;
begin
PlayMci := True;
Info.dwCallBack := PlayWindow;
Result := MciSendCommand(wDeviceID, Mci_Play, Mci_Notify, LongInt(@Info));
if Result <> 0 then begin
PlayMci := False;
ErrorMsg(Result, S1);
exit;
end;
end;
function Playfromto(mfrom,mto:longint): Boolean;
var
Result: LongInt;
Info: TMci_Play_Parms;
S1: array[0..MsgLen] of Char;
begin
Playfromto := True;
Info.dwCallBack := PlayWindow;
Info.dwFrom:=mfrom;
Info.dwto:=mto;
Result := MciSendCommand(wDeviceID, Mci_Play, Mci_Notify or Mci_From or Mci_to, LongInt(@Info));
if Result <> 0 then begin
Playfromto := False;
ErrorMsg(Result, S1);
exit;
end;
end;
function Playfrom(mfrom:longint): Boolean;
var
Result: LongInt;
Info: TMci_Play_Parms;
S1: array[0..MsgLen] of Char;
begin
Playfrom := True;
Info.dwCallBack := PlayWindow;
Info.dwFrom:=mfrom;
Result := MciSendCommand(wDeviceID, Mci_Play, Mci_Notify or Mci_From, LongInt(@Info));
if Result <> 0 then begin
Playfrom := False;
ErrorMsg(Result, S1);
exit;
end;
end;
function SetTimeFormatMS: Boolean;
var
Info: TMci_Set_Parms;
Flags,
Result: LongInt;
S1: array [0..MsgLen] of Char;
begin
SetTimeFormatMS := True;
Info.dwTimeFormat := Mci_Format_Milliseconds;
Flags := Mci_Set_Time_Format;
Result := MciSendCommand(wDeviceID, MCI_Set, Flags, LongInt(@Info));
if Result <> 0 then begin
ErrorMsg(Result, S1);
SetTimeFormatMS := False;
end;
end;
function StopMci: Boolean;
var
Result: LongInt;
Info: TMci_Generic_Parms;
S1: array[0..MsgLen] of Char;
begin
StopMci := True;
Info.dwCallBack := 0;
Result := MciSendCommand(wDeviceID, Mci_Stop, Mci_Notify, LongInt(@Info));
if Result <> 0 then begin
StopMci := False;
ErrorMsg(Result, S1);
exit;
end;
end;
begin
wDeviceId := 0;
end. |
{***************************************************************
*
* Project : MailDemo
* Unit Name: Setup
* Purpose : Sub form
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:28:54
* Author : Hadi Hari <hadi@pbe.com>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit Setup;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls,
{$ENDIF}
windows, messages, SysUtils, Classes;
type
TfmSetup = class(TForm)
BitBtn1: TBitBtn;
pcSetup: TPageControl;
tsPop3: TTabSheet;
tsSmtp: TTabSheet;
Label1: TLabel;
POPServer: TEdit;
Label2: TLabel;
POPPort: TEdit;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
lblAuthenticationType: TLabel;
cboAuthType: TComboBox;
lbAccount: TLabel;
edtAccount: TEdit;
lbPassword: TLabel;
edtPassword: TEdit;
Label11: TLabel;
Label12: TLabel;
SMTPServer: TEdit;
SMTPPort: TEdit;
Email: TEdit;
Account: TEdit;
Password: TEdit;
procedure bbtnAuthenticationClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
procedure UpdateServerLabel;
end;
var
fmSetup: TfmSetup;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
uses Main, smtpauth, IniFiles;
procedure TfmSetup.bbtnAuthenticationClick(Sender: TObject);
begin
frmSMTPAuthentication.ShowModal;
end;
procedure TfmSetup.UpdateServerLabel;
begin
frmMain.pnlServerName.caption := POPServer.Text;
end; (* *)
procedure TfmSetup.FormCreate(Sender: TObject);
begin
POPServer.Text := Pop3ServerName;
POPPort.Text := IntToStr(Pop3ServerPort);
Account.Text := Pop3ServerUser;
Password.Text := Pop3ServerPassword;
SMTPServer.Text := SmtpServerName;
SMTPPort.Text := IntToStr(SmtpServerPort);
edtAccount.Text := SmtpServerUser;
edtPassword.Text := SmtpServerPassword;
cboAuthType.ItemIndex := SmtpAuthType;
Email.Text := UserEmail;
UpdateServerLabel;
end;
procedure TfmSetup.FormHide(Sender: TObject);
begin
UpdateServerLabel;
end;
procedure TfmSetup.BitBtn1Click(Sender: TObject);
var
MailIni: TIniFile;
begin
MailIni := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Mail.ini');
with MailIni do
begin
WriteString('Pop3', 'ServerName', POPServer.Text);
Pop3ServerName := POPServer.Text;
WriteString('Pop3', 'ServerPort', POPPort.Text);
Pop3ServerPort := StrToIntDef(POPPort.Text, 110);
WriteString('Pop3', 'ServerUser', Account.Text);
Pop3ServerUser := Account.Text;
WriteString('Pop3', 'ServerPassword', Password.Text);
Pop3ServerPassword := Password.Text;
WriteString('Smtp', 'ServerName', SMTPServer.Text);
SmtpServerName := SMTPServer.Text;
WriteString('Smtp', 'ServerPort', SMTPPort.Text);
SmtpServerPort := StrToIntDef(SMTPPort.Text, 110);
WriteString('Smtp', 'ServerUser', edtAccount.Text);
SmtpServerUser := edtAccount.Text;
WriteString('Smtp', 'ServerPassword', edtPassword.Text);
SmtpServerPassword := edtPassword.Text;
WriteString('Email', 'PersonalEmail', Email.Text);
UserEmail := Email.Text;
WriteInteger('Smtp', 'SMTPAuthenticationType', cboAuthType.ItemIndex);
SmtpAuthType := cboAuthType.ItemIndex;
end;
MailIni.Free;
end;
procedure TfmSetup.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
end.
|
unit AIOUSB;
interface
uses
Windows;
const
diNone = $FFFFFFFF;
diFirst = $FFFFFFFE;
diOnly = $FFFFFFFD;
function GetDevices: LongWord; cdecl; external 'AIOUSB.dll';
function QueryDeviceInfo(DeviceIndex: LongWord; pPID: PLongWord; pNameSize: PLongWord; pName: PChar; pDIOBytes, pCounters: PLongWord): LongWord; cdecl; external 'AIOUSB.dll';
function AIOUSB_CloseDevice(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ClearDevices: LongWord; cdecl; external 'AIOUSB.dll';
function GetDeviceUniqueStr(DeviceIndex: LongWord; pIIDSize: PLongWord; pIID: PChar): LongWord; cdecl; external 'AIOUSB.dll';
function GetDeviceSerialNumber(DeviceIndex: LongWord; var pSerialNumber: Int64): LongWord; cdecl; external 'AIOUSB.dll';
function ResolveDeviceIndex(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function GetDeviceByEEPROMByte(Data: Byte): LongWord; cdecl; external 'AIOUSB.dll';
function GetDeviceByEEPROMData(StartAddress, DataSize: LongWord; pData: PByte): LongWord; cdecl; external 'AIOUSB.dll';
function GetDeviceBySerialNumber(const pSerialNumber: Int64): LongWord; cdecl; external 'AIOUSB.dll';
function AIOUSB_ClearFIFO(DeviceIndex: LongWord; TimeMethod: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function AIOUSB_SetStreamingBlockSize(DeviceIndex, BlockSize: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function CustomEEPROMRead(DeviceIndex: LongWord; StartAddress: LongWord; var DataSize: LongWord; Data: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function CustomEEPROMWrite(DeviceIndex: LongWord; StartAddress: LongWord; DataSize: LongWord; Data: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function AIOUSB_FlashRead(DeviceIndex: LongWord; StartAddress: LongWord; var DataSize: LongWord; Data: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function AIOUSB_FlashWrite(DeviceIndex: LongWord; StartAddress: LongWord; DataSize: LongWord; Data: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function AIOUSB_FlashEraseSector(DeviceIndex: LongWord; Sector: Integer): LongWord; cdecl; external 'AIOUSB.dll';
function GenericVendorRead(DeviceIndex: LongWord; Request: Byte; Value, Index: Word; var DataSize: LongWord; Data: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function GenericVendorWrite(DeviceIndex: LongWord; Request: Byte; Value, Index: Word; DataSize: LongWord; Data: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_GetScan(DeviceIndex: LongWord; pBuf: PWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_GetScanV(DeviceIndex: LongWord; pBuf: PDouble): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_GetChannelV(DeviceIndex, ChannelIndex: LongWord; pBuf: PDouble): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_GetCalRefV(DeviceIndex, CalRefIndex: LongWord; var pRef: Double): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_GetConfig(DeviceIndex: LongWord; pConfigBuf: Pointer; var ConfigBufSize: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_SetConfig(DeviceIndex: LongWord; pConfigBuf: Pointer; var ConfigBufSize: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_ADMode(DeviceIndex: LongWord; TriggerMode, CalMode: Byte): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_Range1(DeviceIndex, ADChannel: LongWord; GainCode: Byte; bDifferential: LongBool): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_RangeAll(DeviceIndex: LongWord; pGainCodes: PByte; bDifferential: LongBool): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_SetScanLimits(DeviceIndex, StartChannel, EndChannel: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_SetOversample(DeviceIndex: LongWord; Oversample: Byte): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_QueryCal(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_SetCal(DeviceIndex: LongWord; CalFileName: PChar): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_Initialize(DeviceIndex: LongWord; pConfigBuf: Pointer; var ConfigBufSize: LongWord; CalFileName: PChar): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_GetImmediate(DeviceIndex, Channel: LongWord; pBuf: PWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_BulkAcquire(DeviceIndex: LongWord; BufSize: LongWord; pBuf: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_BulkPoll(DeviceIndex: LongWord; var BytesLeft: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_BulkMode(DeviceIndex, BulkMode: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_BulkContinuousCallbackStart(DeviceIndex: LongWord; BufSize: LongWord; BaseBufCount: LongWord; Context: LongWord; pCallback: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_BulkContinuousEnd(DeviceIndex: LongWord; pIOStatus: PLongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_InitFastITScanV(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_ResetFastITScanV(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_SetFastITScanVChannels(DeviceIndex, NewChannels: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_GetFastITScanV(DeviceIndex: LongWord; pBuf: PDouble): LongWord; cdecl; external 'AIOUSB.dll';
function ADC_GetITScanV(DeviceIndex: LongWord; pBuf: PDouble): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_8254Load(DeviceIndex, BlockIndex, CounterIndex: LongWord; LoadValue: Word): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_8254Mode(DeviceIndex, BlockIndex, CounterIndex, Mode: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_8254ModeLoad(DeviceIndex, BlockIndex, CounterIndex, Mode: LongWord; LoadValue: Word): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_8254Read(DeviceIndex, BlockIndex, CounterIndex: LongWord; pReadValue: PWord): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_8254ReadStatus(DeviceIndex, BlockIndex, CounterIndex: LongWord; pReadValue: PWord; pStatus: PByte): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_8254ReadModeLoad(DeviceIndex, BlockIndex, CounterIndex, Mode: LongWord; LoadValue: Word; pReadValue: PWord): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_StartOutputFreq(DeviceIndex, BlockIndex: LongWord; pHz: PDouble): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_8254ReadAll(DeviceIndex: LongWord; pData: PWord): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_8254SelectGate(DeviceIndex, GateIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_8254ReadLatched(DeviceIndex: LongWord; pData: PWord): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_SetWaitGates(DeviceIndex: LongWord; A, B: Byte): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_EndWaitGates(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_WaitForGate(DeviceIndex: LongWord; GateIndex: Byte; var Content: Word): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_StartMeasuringPulseWidth(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_StopMeasuringPulseWidth(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function CTR_GetPulseWidthMeasurement(DeviceIndex, BlockIndex, CounterIndex: LongWord; pReadValue: PWord): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_Configure(DeviceIndex: LongWord; Tristate: ByteBool; pOutMask: Pointer; pData: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_ConfigureEx(DeviceIndex: LongWord; pOutMask: Pointer; pData: Pointer; pTristateMask: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_ConfigurationQuery(DeviceIndex: LongWord; pOutMask: Pointer; pTristateMask: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_Read1(DeviceIndex, BitIndex: LongWord; Buffer: PByte): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_Read8(DeviceIndex, ByteIndex: LongWord; Buffer: PByte): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_ReadAll(DeviceIndex: LongWord; pData: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_Write1(DeviceIndex, BitIndex: LongWord; Data: ByteBool): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_Write8(DeviceIndex, ByteIndex: LongWord; Data: Byte): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_WriteAll(DeviceIndex: LongWord; pData: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_StreamOpen(DeviceIndex: LongWord; bIsRead: LongBool): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_StreamClose(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_StreamFrame(DeviceIndex, FramePoints: LongWord; pFrameData: PWord; var BytesTransferred: DWord): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_StreamSetClocks(DeviceIndex: LongWord; var ReadClockHz, WriteClockHz: Double): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_SPI_Read(DeviceIndex: LongWord; Address, Reg: Byte; pValue: PByte): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_SPI_Write(DeviceIndex: LongWord; Address, Reg, Value: Byte): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_CSA_DoSync(DeviceIndex: LongWord; var BaseRateHz, DurAms, DurBms, DurCms: Double): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_CSA_DebounceSet(DeviceIndex, DebounceCounts: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function DIO_CSA_DebounceReadAll(DeviceIndex: LongWord; pData: Pointer): LongWord; cdecl; external 'AIOUSB.dll';
function DAC_CSA_SetRangeLimits(DeviceIndex: LongWord; pData: PByte): LongWord; cdecl; external 'AIOUSB.dll';
function DAC_CSA_ClearRangeLimits(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function DACDirect(DeviceIndex: LongWord; Channel: Word; Value: Word): LongWord; cdecl; external 'AIOUSB.dll';
function DACMultiDirect(DeviceIndex: LongWord; pDACData: PWord; DACDataCount: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function DACSetBoardRange(DeviceIndex: LongWord; RangeCode: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function DACSetChannelCal(DeviceIndex: LongWord; Channel: LongWord; CalFileName: PChar): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputProcess(DeviceIndex: LongWord; var ClockHz: Double; NumSamples: LongWord; pSampleData: PWord): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputOpen(DeviceIndex: LongWord; var ClockHz: Double): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputClose(DeviceIndex: LongWord; bWait: LongBool): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputCloseNoEnd(DeviceIndex: LongWord; bWait: LongBool): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputFrameRaw(DeviceIndex, FramePoints: LongWord; FrameData: PWord): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputFrame(DeviceIndex, FramePoints: LongWord; FrameData: PWord): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputSetCount(DeviceIndex, NewCount: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputSetInterlock(DeviceIndex: LongWord; bInterlock: LongBool): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputStart(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputAbort(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
function DACOutputStatus(DeviceIndex: LongWord): LongWord; cdecl; external 'AIOUSB.dll';
implementation
end. |
unit uclsAPI;
interface
uses REST.Types, REST.Client, System.StrUtils, uclsClasses, Rest.JSON;
type
IRestAPI = interface
['{EC7DAFE5-9724-401B-9CA1-A8912BA4F491}']
procedure GetDados(pCEP : string);
function GetCEP: TCEP;
property CEP: TCEP read GetCEP;
end;
TRESTAPI = class(TInterfacedObject, IRestAPI)
private
RESTRequest : TRESTRequest;
RESTClient : TRESTClient;
RESTResponse : TRESTResponse;
FEnderecoAPI : String;
FSufixoAPI: String;
FCEP: TCEP;
protected
function GetCEP: TCEP;
public
constructor Create(AEnderecoAPI: string; ASufixoAPI: String); reintroduce;
property CEP: TCEP read GetCEP;
procedure GetDados(pCEP : String);
destructor Destroy;override;
end;
implementation
uses
System.SysUtils, Vcl.Dialogs;
{ TRESTAPI }
constructor TRESTAPI.Create(AEnderecoAPI, ASufixoAPI: String);
begin
inherited Create;
FEnderecoAPI := AEnderecoAPI;
FSufixoAPI := ASufixoAPI;
RESTClient := TRESTClient.Create(nil);
RESTRequest := TRESTRequest.Create(nil);
RESTResponse := TRESTResponse.Create(nil);
RESTRequest.Client := RESTClient;
RESTRequest.Response := RESTResponse;
RESTRequest.Method := rmGET;
end;
destructor TRESTAPI.Destroy;
begin
if Assigned(RESTResponse) then
RESTResponse.Free;
if Assigned(RESTClient) then
RESTClient.Free;
if Assigned(RESTRequest) then
RESTRequest.Free;
inherited;
end;
function TRESTAPI.GetCEP: TCEP;
begin
Result := FCEP;
end;
procedure TRESTAPI.GetDados(pCEP: String);
begin
RESTClient.BaseURL := Format(FEnderecoAPI+'%s/'+FSufixoAPI, [pCEP]);
try
RESTRequest.Execute;
if RESTResponse.Content <> EmptyStr then
begin
FCEP := TJson.JsonToObject<TCEP>(RESTResponse.Content);
end;
finally
end;
end;
end.
|
{$mode objfpc}{$H+}{$J-}
program MyProgram;
procedure MyProcedure(const A: Integer);
begin
WriteLn('A + 10 составляет: ', A + 10);
end;
function MyFunction(const S: string): string;
begin
Result := S + 'строки управляются автоматически';
end;
var
X: Single;
begin
WriteLn(MyFunction('примечание: '));
MyProcedure(5);
// деление с помощью оператора "/" всегда даёт результат с плавающей запятой
// для целочисленного деления необходимо использовать "div"
X := 15 / 5;
WriteLn('X составляет: ', X); // отобразить в научном формате вида 3.0000000E+000
WriteLn('X составляет: ', X:1:2); // отобразить 2 знака после запятой
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Threads;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes, System.SysUtils, System.SyncObjs, System.Math,
{$ELSE}
Classes, SysUtils, SyncObjs,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT.Intf, ADAPT.Threadsafe,
ADAPT.Performance.Intf,
ADAPT.Threads.Intf;
{$I ADAPT_RTTI.inc}
type
{ Class Forward Declarations }
TADThread = class;
TADPrecisionThread = class;
/// <summary><c>Abstract Base Type for all Threads in the ADAPT codebase.</c></summary>
/// <remarks>
/// <para><c>ALL Threads in the codebase have a Threadsafe Lock.</c></para>
/// <para><c>ALL Threads in the codebase are Interfaced Types.</c></para>
/// </remarks>
TADThread = class abstract(TThread, IADInterface, IADThread, IADReadWriteLock)
private
FOwnerInterface: IInterface;
[volatile] FRefCount: Integer;
{ IInterface }
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
{ IADInterface }
function GetInstanceGUID: TGUID;
{ IADReadWriteLock }
function GetLock: IADReadWriteLock;
protected
FInstanceGUID: TGUID;
FLock: TADReadWriteLock;
public
constructor Create; reintroduce; overload; virtual;
constructor Create(const ACreateSuspended: Boolean); reintroduce; overload; virtual;
destructor Destroy; override;
procedure AfterConstruction; override;
{ IADInterface }
property InstanceGUID: TGUID read GetInstanceGUID;
{ IADReadWriteLock }
property Lock: IADReadWriteLock read GetLock implements IADReadWriteLock;
end;
/// <summary><c>Abstract Base Type for all Precision Threads in the ADAPT codebase.</c></summary>
/// <remarks>
/// <para><c>Provides extremely precise Delta Time between Ticks.</c></para>
/// <para><c>You can set a precise Tick Rate Limit.</c></para>
/// </remarks>
TADPrecisionThread = class abstract(TADThread, IADPrecisionThread)
private
FNextTickTime: ADFloat;
FPerformanceCounter: IADPerformanceCounter;
FThreadState: TADThreadState;
FTickRateDesired: ADFloat; // The DESIRED rate at which you want the Thread to Tick (minimum)
FTickRateLimit: ADFloat; // The current Tick Rate Limit (in "Ticks per Second"), 0 = no limit.
FThrottleInterval: Cardinal; // The current Throttling Interval (in Milliseconds)
FWakeUp: TEvent;
{ Internal Methods }
procedure AtomicIncrementNextTickTime(const AIncrementBy: ADFloat); inline;
procedure InitializeTickVariables(var ACurrentTime, ALastAverageCheckpoint, ANextAverageCheckpoint, ATickRate: ADFloat; var AAverageTicks: Integer);
procedure AtomicInitializeCycleValues(var ATickRateLimit, ATickRateDesired: ADFloat; var AThrottleInterval: Cardinal); inline;
{ Property Getters }
function GetNextTickTime: ADFloat;
function GetThreadState: TADThreadState;
function GetTickRate: ADFloat;
function GetTickRateAverage: ADFloat;
function GetTickRateAverageOver: Cardinal;
function GetTickRateDesired: ADFloat;
function GetTickRateLimit: ADFloat;
function GetThrottleInterval: Cardinal;
{ Property Setters }
procedure SetThreadState(const AThreadState: TADThreadState);
procedure SetTickRateAverageOver(const AAverageOver: Cardinal);
procedure SetTickRateDesired(const ADesiredRate: ADFloat);
procedure SetTickRateLimit(const ATickRateLimit: ADFloat);
procedure SetThrottleInterval(const AThrottleInterval: Cardinal);
protected
/// <summary><c>Override if you wish your inherited Type to enforce a Tick Rate Limit by Default.</c></summary>
/// <remarks>
/// <para>0 <c>= No Tick Rate Limit</c></para>
/// <para><c>Default = </c>0</para>
/// </remarks>
function GetDefaultTickRateLimit: ADFloat; virtual;
/// <summary><c>Override if you wish to change the default Tick Rate Averaging Sample Count.</c></summary>
/// <remarks>
/// <para><c>Value is in Samples</c></para>
/// <para><c>Default = </c>10</para>
/// </remarks>
function GetDefaultTickRateAverageOver: Cardinal; virtual;
/// <summary><c>Override if you wish your inherited Type to state a desired Tick Rate by Default.</c></summary>
/// <remarks>
/// <para>0 <c>= No Desired Rate</c></para>
/// <para><c>Default = </c>0</para>
/// </remarks>
function GetDefaultTickRateDesired: ADFloat; virtual;
/// <summary><c>Override if you wish to define a different Throttling Interval (period in which to rest the Thread when waiting between Ticks)</c></summary>
/// <remarks>
/// <para><c>Minimum Value = </c>1</para>
/// <para><c>Default = </c>1</para>
/// <para><c>Values are in </c>MILLISECONDS</para>
/// </remarks>
function GetDefaultThrottleInterval: Integer; virtual;
/// <summary><c>Defines whether the Thread should be Running or Paused upon Construction.</c></summary>
/// <remarks><c>Default = </c>tsRunning</remarks>
function GetInitialThreadState: TADThreadState; virtual;
/// <summary><c>Calculates how much "Extra Time" is available for the current Tick.</c></summary>
/// <remarks><c>Could be a negative number of the Thread is performing BELOW the desired rate!</c></remarks>
function CalculateExtraTime: ADFloat;
/// <summary><c>You must NOT override "Execute" on descendants. See </c><see DisplayName="Tick" cref="ADAPT.Threads|TADPrecisionThread.Tick"/><c> instead!</c></summary>
procedure Execute; override; final;
/// <summary><c>Override to implement code you need your Thread to perform on EVERY cycle (regardless of any Tick Rate Limit).</c></summary>
/// <param name="ADelta"><c>The time differential ("Delta") between the current Tick and the previous Tick.</c></param>
/// <param name="AStartTime"><c>The Reference Time at which the current Tick began.</c></param>
/// <remarks>
/// <para><c>Used extensively by the Event Engine.</c></para>
/// <para><c>Ignores any Tick Rate Limits.</c></para>
/// </remarks>
procedure PreTick(const ADelta, AStartTime: ADFloat); virtual;
/// <summary><c>Override to implement your Thread's operational code.</c></summary>
/// <param name="ADelta"><c>The time differential ("Delta") between the current Tick and the previous Tick.</c></param>
/// <param name="AStartTime"><c>The Reference Time at which the current Tick began.</c></param>
procedure Tick(const ADelta, AStartTime: ADFloat); virtual; abstract;
public
/// <summary><c>Puts a Thread to sleep ONLY if there's enough time!</c></summary>
class function SmartSleep(const ATimeToWait: ADFloat; const AThreshold: Cardinal): Boolean;
constructor Create(const ACreateSuspended: Boolean); override;
destructor Destroy; override;
procedure BeforeDestruction; override;
/// <summary><c>Forces the "Next Tick Time" to be bumped to RIGHT NOW. This will trigger the next Tick immediately regardless of any Rate Limit setting.</c></summary>
procedure Bump;
/// <summary><c>Places the Thread in an Inactive state, waiting for the signal to </c><see DisplayName="Wake" cref="ADAPT.Threads|TADPrecisionThread.Wake"/><c> the Thread.</c></summary>
procedure Rest;
/// <summary><c>Wakes the Thread if it is an Inactive state (see </c><see DisplayName="Rest" cref="ADAPT.Threads|TADPrecisionThread.Rest"/><c> for details)</c></summary>
procedure Wake;
/// <summary><c>The Absolute Reference Time at which the next Tick will occur.</c></summary>
property NextTickTime: ADFloat read GetNextTickTime;
/// <summary><c>The current State of the Thread (running or paused).</c></summary>
property ThreadState: TADThreadState read GetThreadState write SetThreadState;
/// <summary><c>The Absolute Rate (in Ticks Per Second [T/s]) at which the Thread is executing its Tick method.</c></summary>
property TickRate: ADFloat read GetTickRate;
/// <summary><c>The Running Average Rate (in Ticks Per Second [T/s]) at which the Thread is executing its Tick method.</c></summary>
property TickRateAverage: ADFloat read GetTickRateAverage;
/// <summary><c>The Time (in Seconds) over which to calculate the Running Average.</c></summary>
property TickRateAverageOver: Cardinal read GetTickRateAverageOver write SetTickRateAverageOver;
/// <summary><c>The number of Ticks Per Second [T/s] you would LIKE the Thread to operate at.</c></summary>
/// <remarks><c>This value is used to calculate how much "Extra Time" (if any) is available on the current Tick.</c></remarks>
property TickRateDesired: ADFloat read GetTickRateDesired write SetTickRateDesired;
/// <summary><c>The Absolute Tick Rate (in Ticks Per Second [T/s]) at which you wish the Thread to operate.</c></summary>
/// <remarks><c>There is no guarantee that the rate you specify here will be achievable. Slow hardware or an overloaded running environment may mean the thread operates below the specified rate.</c></remarks>
property TickRateLimit: ADFloat read GetTickRateLimit write SetTickRateLimit;
/// <summary><c>The minimum amount of time that must be available between Ticks in order to Rest the Thread.</c></summary>
/// <remarks>
/// <para><c>Value is in </c>MILLISECONDS<c> (1 = 0.001 seconds)</c></para>
/// <para><c>Minimum value = </c>1</para>
/// </remarks>
property ThrottleInterval: Cardinal read GetThrottleInterval write SetThrottleInterval;
end;
implementation
uses
ADAPT.Math.Delta,
ADAPT.Performance.Threadsafe;
{$I ADAPT_RTTI.inc}
{ TADThread }
constructor TADThread.Create;
begin
Create(False);
end;
constructor TADThread.Create(const ACreateSuspended: Boolean);
begin
inherited Create(ACreateSuspended);
CreateGUID(FInstanceGUID);
FLock := TADReadWriteLock.Create({$IFDEF ADAPT_THREADS_USEINTERFACES}IADThread{$ELSE}IADInterface{$ENDIF ADAPT_THREADS_USEINTERFACES}(Self));
end;
destructor TADThread.Destroy;
begin
FLock.{$IFDEF SUPPORTS_DISPOSEOF}DisposeOf{$ELSE}Free{$ENDIF SUPPORTS_DISPOSEOF};
inherited;
end;
function TADThread.GetInstanceGUID: TGUID;
begin
Result := FInstanceGUID;
end;
function TADThread.GetLock: IADReadWriteLock;
begin
Result := FLock;
end;
function TADThread.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function TADThread._AddRef: Integer;
begin
if FOwnerInterface <> nil then
Result := FOwnerInterface._AddRef
else
Result := AtomicIncrement(FRefCount);
end;
function TADThread._Release: Integer;
begin
if FOwnerInterface <> nil then
Result := FOwnerInterface._Release
else
Result := AtomicDecrement(FRefCount);
if Result = 0 then
begin
FLock.AcquireWrite;
// Terminate;
// WaitFor;
Free;
end;
end;
procedure TADThread.AfterConstruction;
begin
inherited;
GetInterface(IInterface, FOwnerInterface);
end;
{ TADThreadPrecision }
procedure TADPrecisionThread.AtomicIncrementNextTickTime(const AIncrementBy: ADFloat);
begin
FLock.AcquireWrite;
try
FNextTickTime := FNextTickTime + AIncrementBy;
finally
FLock.ReleaseWrite;
end;
end;
procedure TADPrecisionThread.AtomicInitializeCycleValues(var ATickRateLimit, ATickRateDesired: ADFloat; var AThrottleInterval: Cardinal);
begin
FLock.AcquireWrite;
try
ATickRateLimit := FTickRateLimit;
ATickRateDesired := FTickRateDesired;
AThrottleInterval := FThrottleInterval;
finally
FLock.ReleaseWrite;
end;
end;
procedure TADPrecisionThread.BeforeDestruction;
begin
inherited;
FWakeUp.SetEvent;
if not Terminated then
begin
Terminate;
WaitFor;
end;
end;
procedure TADPrecisionThread.Bump;
begin
FLock.AcquireWrite;
try
FNextTickTime := ADReferenceTime;
finally
FLock.ReleaseWrite;
end;
end;
function TADPrecisionThread.CalculateExtraTime: ADFloat;
begin
Result := NextTickTime - ADReferenceTime;
end;
constructor TADPrecisionThread.Create(const ACreateSuspended: Boolean);
const
THREAD_STATES: Array[TADThreadState] of Boolean = (True, False);
begin
inherited Create(ACreateSuspended);
FPerformanceCounter := TADPerformanceCounterTS.Create(GetDefaultTickRateAverageOver);
FThrottleInterval := GetDefaultThrottleInterval;
FreeOnTerminate := False;
FThreadState := GetInitialThreadState;
FTickRateLimit := GetDefaultTickRateLimit;
FTickRateDesired := GetDefaultTickRateDesired;
FWakeUp := TEvent.Create(nil, True, THREAD_STATES[FThreadState], '');
end;
destructor TADPrecisionThread.Destroy;
begin
FWakeUp.{$IFDEF SUPPORTS_DISPOSEOF}DisposeOf{$ELSE}Free{$ENDIF SUPPORTS_DISPOSEOF};
FPerformanceCounter := nil;
inherited;
end;
procedure TADPrecisionThread.Execute;
var
LDelta, LCurrentTime: ADFloat;
LTickRate, LTickRateLimit, LTickRateDesired: ADFloat;
LLastAverageCheckpoint, LNextAverageCheckpoint: ADFloat;
LAverageTicks: Integer;
LThrottleInterval: Cardinal;
begin
InitializeTickVariables(LCurrentTime, LLastAverageCheckpoint, LNextAverageCheckpoint, LTickRate, LAverageTicks);
while (not Terminated) do
begin
if ThreadState = tsRunning then
begin
LCurrentTime := ADReferenceTime;
AtomicInitializeCycleValues(LTickRateLimit, LTickRateDesired, LThrottleInterval);
LDelta := (LCurrentTime - FNextTickTime);
// Rate Limiter
if ((LTickRateLimit > 0)) and (LDelta < ( 1 / LTickRateLimit)) then
LDelta := (1 / LTickRateLimit);
// Calculate INSTANT Tick Rate
if LDelta > 0 then
begin
LTickRate := 1 / LDelta; // Calculate the current Tick Rate
FPerformanceCounter.RecordSample(LTickRate);
end;
// Call "PreTick"
PreTick(LDelta, LCurrentTime);
// Tick or Wait...
if ((LCurrentTime >= FNextTickTime) and (LTickRateLimit > 0)) or (LTickRateLimit = 0) then
begin
AtomicIncrementNextTickTime(LDelta);
Tick(LDelta, LCurrentTime);
end else
begin
if (FNextTickTime - ADReferenceTime >= LThrottleInterval / 1000) then
TThread.Sleep(LThrottleInterval);
end;
end else
FWakeUp.WaitFor(INFINITE);
end;
end;
function TADPrecisionThread.GetDefaultThrottleInterval: Integer;
begin
Result := 1;
end;
function TADPrecisionThread.GetDefaultTickRateAverageOver: Cardinal;
begin
Result := 10;
end;
function TADPrecisionThread.GetDefaultTickRateDesired: ADFloat;
begin
Result := 0;
end;
function TADPrecisionThread.GetDefaultTickRateLimit: ADFloat;
begin
Result := 0;
end;
function TADPrecisionThread.GetInitialThreadState: TADThreadState;
begin
Result := tsRunning;
end;
function TADPrecisionThread.GetNextTickTime: ADFloat;
begin
FLock.AcquireRead;
try
Result := FNextTickTime;
finally
FLock.ReleaseRead;
end;
end;
function TADPrecisionThread.GetThreadState: TADThreadState;
begin
FLock.AcquireRead;
try
Result := FThreadState;
finally
FLock.ReleaseRead;
end;
end;
function TADPrecisionThread.GetThrottleInterval: Cardinal;
begin
FLock.AcquireRead;
try
Result := FThrottleInterval;
finally
FLock.ReleaseRead;
end;
end;
function TADPrecisionThread.GetTickRate: ADFloat;
begin
Result := FPerformanceCounter.InstantRate;
end;
function TADPrecisionThread.GetTickRateAverage: ADFloat;
begin
Result := FPerformanceCounter.AverageRate;
end;
function TADPrecisionThread.GetTickRateAverageOver: Cardinal;
begin
Result := FPerformanceCounter.AverageOver;
end;
function TADPrecisionThread.GetTickRateDesired: ADFloat;
begin
FLock.AcquireRead;
try
Result := FTickRateDesired;
finally
FLock.ReleaseRead;
end
end;
function TADPrecisionThread.GetTickRateLimit: ADFloat;
begin
FLock.AcquireRead;
try
Result := FTickRateLimit;
finally
FLock.ReleaseRead;
end;
end;
procedure TADPrecisionThread.InitializeTickVariables(var ACurrentTime, ALastAverageCheckpoint, ANextAverageCheckpoint, ATickRate: ADFloat; var AAverageTicks: Integer);
begin
ACurrentTime := ADReferenceTime;
FLock.AcquireWrite;
try
FNextTickTime := ACurrentTime;
finally
FLock.ReleaseWrite;
end;
ALastAverageCheckpoint := 0;
ANextAverageCheckpoint := 0;
ATickRate := 0;
AAverageTicks := 0;
end;
procedure TADPrecisionThread.PreTick(const ADelta, AStartTime: ADFloat);
begin
// Do nothing by default
end;
procedure TADPrecisionThread.Rest;
begin
FLock.AcquireWrite;
try
FThreadState := tsPaused;
FWakeUp.ResetEvent;
finally
FLock.ReleaseWrite;
end;end;
procedure TADPrecisionThread.SetThreadState(const AThreadState: TADThreadState);
begin
FLock.AcquireWrite;
try
FThreadState := AThreadState;
case AThreadState of
tsRunning: FWakeUp.SetEvent;
tsPaused: FWakeUp.ResetEvent;
end;
finally
FLock.ReleaseWrite;
end;
end;
procedure TADPrecisionThread.SetThrottleInterval(const AThrottleInterval: Cardinal);
begin
FLock.AcquireWrite;
try
if AThrottleInterval > 0 then
FThrottleInterval := AThrottleInterval
else
FThrottleInterval := 1;
finally
FLock.ReleaseWrite;
end;
end;
procedure TADPrecisionThread.SetTickRateAverageOver(const AAverageOver: Cardinal);
begin
FPerformanceCounter.AverageOver := AAverageOver;
end;
procedure TADPrecisionThread.SetTickRateDesired(const ADesiredRate: ADFloat);
begin
FLock.AcquireWrite;
try
FTickRateDesired := ADesiredRate;
finally
FLock.ReleaseWrite;
end;
end;
procedure TADPrecisionThread.SetTickRateLimit(const ATickRateLimit: ADFloat);
begin
FLock.AcquireWrite;
try
FTickRateLimit := ATickRateLimit;
// If the Limit is LOWER than the defined "Desired" Rate, then we cannot desire MORE than the limit,
// so we match the two.
if (FTickRateLimit > 0) and (FTickRateLimit < FTickRateDesired) then
FTickRateDesired := FTickRateLimit;
finally
FLock.ReleaseWrite;
end;
end;
class function TADPrecisionThread.SmartSleep(const ATimeToWait: ADFloat; const AThreshold: Cardinal): Boolean;
begin
Result := False;
if (ATimeToWait >= AThreshold / 1000) then
begin
TThread.Sleep(AThreshold);
Result := True;
end;
end;
procedure TADPrecisionThread.Wake;
begin
FLock.AcquireWrite;
try
FThreadState := tsRunning;
FWakeUp.SetEvent;
finally
FLock.ReleaseWrite;
end;
end;
end.
|
{******************************************}
{ TeeChart XML DataSource }
{ Copyright (c) 2001-2004 by David Berneda }
{ All Rights Reserved }
{******************************************}
unit TeeXML;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QExtCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls,
{$ENDIF}
{$IFDEF CLR}
System.XML,
{$ENDIF}
TeEngine, TeeURL, Chart, Series, TeeSourceEdit, TeCanvas;
type
{$IFNDEF CLR}
XmlDocument=OleVariant;
XmlNode=OleVariant;
XmlNodeList=XmlNode;
XmlAttributeCollection=XmlNode;
{$ENDIF}
TTeeXMLSource=class(TTeeSeriesSourceFile)
private
FChart : TCustomChart;
FSeriesNode : String;
FValueSource : String;
FXML : TStrings;
FXMLDocument : XmlDocument;
Function CreateAndLoadXML:XmlDocument;
procedure CloseXML;
Procedure FillSeries(AItems:TStrings);
procedure LoadSeriesNode(ANode:XmlNode);
procedure SetSeriesNode(const Value: String);
procedure SetValueSource(const Value: String);
procedure XMLError(Const Reason:String);
procedure SetChart(const Value: TCustomChart);
procedure SetXML(const Value: TStrings);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure SetActive(const Value: Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
Procedure Close; override;
class Function Description:String; override;
class Function Editor:TComponentClass; override;
Procedure Load; override;
property XMLDocument:XmlDocument read FXMLDocument;
published
property Active;
property Chart:TCustomChart read FChart write SetChart;
property FileName;
property Series;
property SeriesNode:String read FSeriesNode write SetSeriesNode;
property ValueSource:String read FValueSource write SetValueSource;
property XML:TStrings read FXML write SetXML;
end;
TXMLSourceEditor = class(TBaseSourceEditor)
Label1: TLabel;
EFile: TEdit;
OpenDialog1: TOpenDialog;
SpeedButton1: TSpeedButton;
Label2: TLabel;
CBSeries: TComboFlat;
Label3: TLabel;
ESource: TEdit;
CBActive: TCheckBox;
procedure SpeedButton1Click(Sender: TObject);
procedure EFileChange(Sender: TObject);
procedure CBSeriesDropDown(Sender: TObject);
procedure CBSeriesChange(Sender: TObject);
procedure BApplyClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ESourceChange(Sender: TObject);
procedure CBActiveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
DataSource : TTeeXMLSource;
Procedure FillXMLSeries;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
uses {$IFNDEF LINUX}
ComObj,
{$ENDIF}
{$IFDEF D6}
Variants,
{$ENDIF}
TeeProcs, TeeProCo;
{$IFDEF CLR}
function VarIsClear(const V: XmlNode): Boolean; overload;
begin
result:=not Assigned(V);
end;
function VarIsClear(const V: XmlNodeList): Boolean; overload;
begin
result:=not Assigned(V);
end;
function VarIsClear(const V: XmlAttributeCollection): Boolean; overload;
begin
result:=not Assigned(V);
end;
type
XmlNodeHelper=class helper for XmlNode
public
function NodeValue:String;
end;
XmlNodeListHelper=class helper for XmlNodeList
public
function Length:Integer;
end;
function XmlNodeHelper.NodeValue:String;
begin
result:=Value;
end;
function XmlNodeListHelper.Length:Integer;
begin
result:=Count;
end;
{$ELSE}
{$IFNDEF D6}
function VarIsClear(const V: Variant): Boolean;
begin
with TVarData(V) do
result := (VType = varEmpty) or
(((VType = varDispatch) or (VType = varUnknown)) and
(VDispatch = nil))
end;
{$ENDIF}
{$ENDIF}
{ TTeeXMLSource }
procedure TTeeXMLSource.CloseXML;
begin
{$IFDEF CLR}
FreeAndNil(FXMLDocument);
{$ELSE}
if not VarIsEmpty(FXMLDocument) then
FXMLDocument:=UnAssigned;
{$ENDIF}
end;
procedure TTeeXMLSource.Close;
begin
CloseXML;
inherited;
end;
class function TTeeXMLSource.Description: String;
begin
result:=TeeMsg_XMLFile;
end;
class function TTeeXMLSource.Editor: TComponentClass;
begin
result:=TXMLSourceEditor;
end;
procedure TTeeXMLSource.XMLError(Const Reason:String);
Const TeeMsg_WrongXMLFormat='TeeChart XML: %s';
begin
raise ChartException.CreateFmt(TeeMsg_WrongXMLFormat,[Reason]);
end;
procedure TTeeXMLSource.LoadSeriesNode(ANode:XmlNode);
Function HexToColor(S:String):TColor;
begin
S:=Trim(S);
if Copy(s,1,1)='#' then
begin
result:=RGB(StrToInt('$'+Copy(s,2,2)),
StrToInt('$'+Copy(s,4,2)),
StrToInt('$'+Copy(s,6,2)));
end
else result:=clTeeColor;
end;
var tmpPoints : XmlNodeList;
tmpPoint : XmlNodeList;
t : Integer;
tt : Integer;
tmpValue : XmlNode;
tmpValueX : XmlNode;
tmpText : XmlNode;
tmpItem : XmlNode;
tmpPointItem : XmlAttributeCollection;
tmpColor : XmlNode;
tmpName : String;
tmpX : String;
tmpTex : String;
tmpList : String;
tmpCol : TColor;
tmpSeries : TChartSeries;
tmpClass : TChartSeriesClass;
begin
tmpSeries:=Series;
if Assigned(tmpSeries) then tmpSeries.Clear
else
begin
// Create a new Series...
tmpClass:=nil;
tmpItem:=ANode.Attributes.GetNamedItem('type');
if not VarIsClear(tmpItem) then
begin
tmpName:=UpperCase(tmpItem.NodeValue);
With TeeSeriesTypes do
for t:=0 to Count-1 do
if (Items[t].FunctionClass=nil) and
(UpperCase(Items[t].Description{$IFNDEF CLR}^{$ENDIF})=UpperCase(tmpName)) then
begin
tmpClass:=Items[t].SeriesClass;
break;
end;
end;
if not Assigned(tmpClass) then tmpClass:=TBarSeries;
tmpSeries:=Chart.AddSeries(tmpClass.Create(Self.Owner));
// Series Title
tmpItem:=ANode.Attributes.GetNamedItem('title');
if not VarIsClear(tmpItem) then
tmpSeries.Title:=tmpItem.NodeValue;
// Series Color
tmpColor:=ANode.Attributes.GetNamedItem('color');
if not VarIsClear(tmpColor) then
tmpSeries.Color:=HexToColor(tmpColor.NodeValue);
end;
{$IFDEF CLR}
tmpPoints:=ANode.SelectNodes('//points');
{$ELSE}
tmpPoints:=ANode.getElementsByTagName('points');
{$ENDIF}
if not VarIsClear(tmpPoints) then
begin
{$IFDEF CLR}
tmpPoint:=tmpPoints[0].SelectNodes('//point');
{$ELSE}
tmpPoint:=tmpPoints.Item[0].getElementsByTagName('point');
{$ENDIF}
if VarIsClear(tmpPoint) then XMLError('No <point> nodes.')
else
begin
tmpName:=tmpSeries.MandatoryValueList.ValueSource;
if tmpName='' then tmpName:=Self.ValueSource;
if tmpName='' then
tmpName:=tmpSeries.MandatoryValueList.Name;
tmpX:=tmpSeries.NotMandatoryValueList.ValueSource;
if tmpX='' then
tmpX:=tmpSeries.NotMandatoryValueList.Name;
for t:=0 to tmpPoint.Length-1 do
begin
tmpPointItem:=tmpPoint{$IFNDEF CLR}.Item{$ENDIF}[t].Attributes;
if VarIsClear(tmpPointItem) then
begin
XMLError('<point> node has no data.');
break;
end
else
begin
tmpText:=tmpPointItem.GetNamedItem('text');
if VarIsClear(tmpText) then tmpTex:=''
else tmpTex:=tmpText.NodeValue;
tmpColor:=tmpPointItem.GetNamedItem('color');
if VarIsClear(tmpColor) then tmpCol:=clTeeColor
else tmpCol:=HexToColor(tmpColor.NodeValue);
// Rest of values (if exist)
for tt:=2 to tmpSeries.ValuesList.Count-1 do
begin
tmpList:=tmpSeries.ValuesList[tt].ValueSource;
if tmpList='' then tmpList:=tmpSeries.ValuesList[tt].Name;
tmpValue:=tmpPointItem.GetNamedItem(tmpList);
if not VarIsClear(tmpValue) then
tmpSeries.ValuesList[tt].TempValue:={$IFDEF CLR}Convert.ToDouble{$ENDIF}(tmpValue.NodeValue);
end;
// Get X and Y values
if tmpName='' then {$IFDEF CLR}tmpValue:=nil{$ELSE}VarClear(tmpValue){$ENDIF} // 7.0
else tmpValue:=tmpPointItem.GetNamedItem(tmpName);
if tmpX='' then {$IFDEF CLR}tmpValueX:=nil{$ELSE}VarClear(tmpValueX){$ENDIF} // 7.0
else tmpValueX:=tmpPointItem.GetNamedItem(tmpX);
// Add point !
if VarIsClear(tmpValue) then
if VarIsClear(tmpValueX) then
tmpSeries.AddNull(tmpTex)
else
tmpSeries.AddNullXY({$IFDEF CLR}Convert.ToDouble{$ENDIF}(tmpValueX.NodeValue),0,tmpTex)
else
if VarIsClear(tmpValueX) then
tmpSeries.Add({$IFDEF CLR}Convert.ToDouble{$ENDIF}(tmpValue.NodeValue),tmpTex,tmpCol)
else
tmpSeries.AddXY({$IFDEF CLR}Convert.ToDouble{$ENDIF}(tmpValueX.NodeValue),
{$IFDEF CLR}Convert.ToDouble{$ENDIF}(tmpValue.NodeValue),tmpTex,tmpCol)
end;
end;
end;
end
else XMLError('No <points> node.');
end;
Function TTeeXMLSource.CreateAndLoadXML:XmlDocument;
begin
{$IFDEF LINUX}
result:=0;
{$ELSE}
{$IFDEF CLR}
result:=System.Xml.XmlDocument.Create;
{$ELSE}
result:=CreateOleObject('MSXML.DomDocument');
result.Async:=False;
{$ENDIF}
if FXML.Count>0 then
result.LoadXML(FXML.Text)
else
{$IFDEF CLR}
result.Load(FileName);
{$ELSE}
if not result.Load(FileName) then
XMLError('Cannot load '+FileName);
{$ENDIF}
{$ENDIF}
end;
procedure TTeeXMLSource.Load;
var tmpSeries : XmlNodeList;
t : Integer;
tmp : String;
tmpTitle : XmlNode;
tmpFound : Boolean;
begin
if not (csDesigning in ComponentState) then
if Assigned(Series) or Assigned(Chart) then
begin
CloseXML;
FXMLDocument:=CreateAndLoadXML;
tmpSeries:=FXMLDocument.getElementsByTagName('series');
if VarIsClear(tmpSeries) then XMLError('No <series> nodes.')
else
begin
if not Assigned(Series) then Chart.FreeAllSeries;
if SeriesNode='' then
begin
if tmpSeries.Length>0 then
for t:=0 to tmpSeries.Length-1 do
begin
LoadSeriesNode(tmpSeries{$IFNDEF CLR}.Item{$ENDIF}[t]);
if Assigned(Series) then break;
end
else
XMLError('Empty <series> node.');
end
else
begin
tmpFound:=False;
for t:=0 to tmpSeries.Length-1 do
begin
tmpTitle:=tmpSeries{$IFNDEF CLR}.Item{$ENDIF}[t].Attributes.GetNamedItem('title');
if not VarIsClear(tmpTitle) then // 6.01
begin
tmp:=tmpTitle.NodeValue;
if UpperCase(tmp)=UpperCase(SeriesNode) then
begin
LoadSeriesNode(tmpSeries{$IFNDEF CLR}.Item{$ENDIF}[t]);
tmpFound:=True;
break;
end;
end;
end;
if not tmpFound then XMLError('Series '+SeriesNode+' not found');
end;
end;
end;
end;
Procedure TTeeXMLSource.FillSeries(AItems:TStrings);
var t : Integer;
tmpSeries : XmlNodeList;
tmpXML : {$IFDEF CLR}System.Xml{$ELSE}TeeXML{$ENDIF}.XmlDocument;
tmpNode : XmlNode;
begin
tmpXML:=CreateAndLoadXML;
try
AItems.Clear;
tmpSeries:=tmpXML.getElementsByTagName('series');
if not VarIsClear(tmpSeries) then
for t:=0 to tmpSeries.Length-1 do
begin
tmpNode:=tmpSeries{$IFNDEF CLR}.Item{$ENDIF}[t].Attributes.GetNamedItem('title');
if not VarIsClear(tmpNode) then
AItems.Add(tmpNode.NodeValue);
end;
finally
tmpXML{$IFDEF CLR}.Free{$ELSE}:=UnAssigned{$ENDIF};
end;
end;
procedure TTeeXMLSource.SetSeriesNode(const Value: String);
begin
if FSeriesNode<>Value then
begin
Close;
FSeriesNode:=Value;
end;
end;
procedure TTeeXMLSource.SetValueSource(const Value: String);
begin
if FValueSource<>Value then
begin
Close;
FValueSource:=Value;
end;
end;
procedure TTeeXMLSource.SetChart(const Value: TCustomChart);
begin
if FChart<>Value then
begin
{$IFDEF D5}
if Assigned(FChart) then FChart.RemoveFreeNotification(Self);
{$ENDIF}
FChart:=Value;
if Assigned(FChart) then FChart.FreeNotification(Self);
end;
end;
procedure TTeeXMLSource.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation=opRemove) and Assigned(FChart) and (AComponent=FChart) then
Chart:=nil;
end;
constructor TTeeXMLSource.Create(AOwner: TComponent);
begin
inherited;
FXML:=TStringList.Create;
end;
destructor TTeeXMLSource.Destroy;
begin
FXML.Free;
inherited;
end;
procedure TTeeXMLSource.SetXML(const Value: TStrings);
begin
FXML.Assign(Value);
end;
procedure TTeeXMLSource.SetActive(const Value: Boolean);
begin
if Value<>Active then
begin
inherited;
if Active and (not Assigned(Series)) and (FileName<>'') then
if not (csLoading in ComponentState) then Load;
end;
end;
{ TXMLSourceEditor }
procedure TXMLSourceEditor.SpeedButton1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
EFile.Text:=OpenDialog1.FileName;
end;
procedure TXMLSourceEditor.EFileChange(Sender: TObject);
begin
CBSeries.Clear;
BApply.Enabled:=True;
end;
procedure TXMLSourceEditor.CBSeriesDropDown(Sender: TObject);
begin
if CBSeries.Items.Count=0 then
FillXMLSeries;
end;
Procedure TXMLSourceEditor.FillXMLSeries;
begin
Screen.Cursor:=crHourGlass;
try
if EFile.Text<>'' then
with TTeeXMLSource.Create(nil) do
try
FileName:=EFile.Text;
FillSeries(CBSeries.Items);
finally
Free;
end
else DataSource.FillSeries(CBSeries.Items);
finally
Screen.Cursor:=crDefault;
end;
end;
procedure TXMLSourceEditor.CBSeriesChange(Sender: TObject);
begin
BApply.Enabled:=True;
end;
procedure TXMLSourceEditor.BApplyClick(Sender: TObject);
begin
inherited;
CheckReplaceSource(DataSource);
DataSource.FileName:=EFile.Text;
with CBSeries do
if ItemIndex=-1 then DataSource.SeriesNode:=''
else DataSource.SeriesNode:=Items[ItemIndex];
DataSource.ValueSource:=ESource.Text;
BApply.Enabled:=False;
DataSource.Close;
DataSource.Open; // 6.0
end;
procedure TXMLSourceEditor.FormShow(Sender: TObject);
begin
inherited;
LLabel.Visible:=False;
CBSources.Visible:=False;
if not Assigned(TheSeries) then exit;
if TheSeries.DataSource is TTeeXMLSource then
DataSource:=TTeeXMLSource(TheSeries.DataSource)
else
begin
DataSource:=TTeeXMLSource.Create(TheSeries.Owner);
DataSource.Name:=TeeGetUniqueName(DataSource.Owner,'TeeXMLSource');
end;
with DataSource do
begin
EFile.Text:=FileName;
FillXMLSeries;
if SeriesNode<>'' then
with CBSeries do ItemIndex:=Items.IndexOf(SeriesNode);
ESource.Text:=ValueSource;
CBActive.Checked:=Active;
end;
BApply.Enabled:=Assigned(TheSeries) and (DataSource<>TheSeries.DataSource);
end;
procedure TXMLSourceEditor.FormDestroy(Sender: TObject);
begin
if Assigned(DataSource) and
(not Assigned(DataSource.Series)) then DataSource.Free;
inherited;
end;
procedure TXMLSourceEditor.ESourceChange(Sender: TObject);
begin
BApply.Enabled:=True;
end;
procedure TXMLSourceEditor.CBActiveClick(Sender: TObject);
begin
DataSource.Active:=CBActive.Checked;
end;
procedure TXMLSourceEditor.FormCreate(Sender: TObject);
begin
inherited;
OpenDialog1.Filter:=TeeMsg_XMLFile+'|*.xml';
{$IFDEF D6}
SpeedButton1.HelpContext:=1865;
{$ENDIF}
end;
initialization
RegisterClass(TTeeXMLSource);
TeeSources.Add({$IFDEF CLR}TObject{$ENDIF}(TTeeXMLSource));
finalization
TeeSources.Remove({$IFDEF CLR}TObject{$ENDIF}(TTeeXMLSource));
end.
|
unit frm_GetAliasPath;
interface
uses
Winapi.Windows, Winapi.Messages, Winapi.SHFolder,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
MSspecialFolders,
JvBaseDlg, JvSelectDirectory, Vcl.Buttons, JvComponentBase, JvFormPlacement;
type
TAliasPath = class(TForm)
lbl_Alias: TLabel;
lbl_theAlias: TLabel;
lbl_thePath: TLabel;
edt_Alias: TEdit;
edt_Path: TEdit;
jvslctdrctry_Folder: TJvSelectDirectory;
btn_BrowseFolder: TButton;
btn_Ok: TBitBtn;
btn_Cancel: TBitBtn;
procedure btn_BrowseFolderClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
fAlias : string;
fAliasPath : string;
GetSpecialFolders : TGEMSystemFolders;
function IsNx1FileInFolder(aAliasFolder: string): Boolean;
public
{ Public declarations }
DbFolderAliasMsg: string;
function Execute: Boolean;
property Alias: string read fAlias;
property theAliasPath: string read fAliasPath;
end;
var
AliasPath: TAliasPath;
implementation
uses
NxToolsMain,
GEMUseFullRoutines, Global;
{$R *.dfm}
procedure TAliasPath.btn_BrowseFolderClick(Sender: TObject);
begin
DbFolderAliasMsg := '';
edt_Alias.Text := StringReplace(edt_Alias.Text, ' ', '', [rfReplaceAll, rfIgnoreCase]);
if jvslctdrctry_Folder.Execute then begin
edt_Path.Text := jvslctdrctry_Folder.Directory;
if IsNx1FileInFolder(edt_Path.Text) then
begin
fAlias := edt_Alias.Text;
fAliasPath := jvslctdrctry_Folder.Directory;
// DbFolderAlias := edt_Alias.Text + '|'+ jvslctdrctry_Folder.Directory
end
else
DbFolderAliasMsg := 'Error: No ''nx1'' files in folder';
end;
end;
function TAliasPath.Execute: Boolean;
begin
Result := (ShowModal = mrOK);
end;
procedure TAliasPath.FormCreate(Sender: TObject);
begin
GetSpecialFolders := TGEMSystemFolders.Create;
DbFolderAliasMsg := '';
jvslctdrctry_Folder.InitialDir := GetSpecialFolders.Personal;
FreeAndNil(GetSpecialFolders);
end;
function TAliasPath.IsNx1FileInFolder(aAliasFolder: string): Boolean;
begin
result := False;
if DirectoryExists(aAliasFolder) then
begin
if CountFilesInFolder( ExtractFilePath(aAliasFolder), 'nx1' ) < 1 then
begin
if (MessageDlg('There are no files ending in ''nx1'' '+#10+#13+
' in the folder. Use the folder anyway?',
mtWarning, [mbOK, mbCancel], 0) in [mrOk, mrCancel, mrNone]) then
begin
result := true;
end;
end
else
Result := true;
end;
end;
end.
|
unit FilmManager;
interface
uses SysUtils, Graphics, FilmEditor, ExtCtrls, Controls;
{*
Функция киноленты, позволяет двигать ленту вправо или влево.
можно получить Editor. Editor является агрегатом Фильм - менеджера
*}
const
FILM_EDITOR_DONT_ASSIGNED = 'менеджер не связан с редактором';
EDITOR_NOT_ASSIGNED = 'не инициализирован реадктор';
type
TFrameSize = (fsSmall, fsMedium, fsBig);
TFilmManager = class
private
CurrentSelectFrame: Integer;
FEditor: TFilmEditor;
public
constructor Create; virtual; abstract;
// Рисовать на компоненте image интервал рисунков
procedure DrawByFrameInterval(aStartIndex: Integer; aEndIndex: Integer); virtual; abstract;
// Двигать ленту вправо
procedure MoveLentToRight; virtual; abstract;
// ДВигать ленту влево
procedure MoveLentToLeft; virtual; abstract;
procedure OnSelect(anXm, anY: Integer); virtual; abstract;
function GetEditor: TFilmEditor; virtual; abstract;
procedure Repaint; virtual; abstract;
end;
TImageBoxFilmManager = class(TFilmManager)
protected
const DrawFrameCount = 10; // Сколько кадров отображать по умолчанию
const DefaultImage = 0;
private
FImage: TImage;
FActiveFrame: Integer;
FCurrentStartFrame: Integer;
FImageList: TImageList;
procedure InitFilmEditor;
procedure SetActiveFrame(const Value: Integer);
public
constructor Create(); override;
procedure InitImage(anImage: TImage; anImageList: TImageList);
procedure DrawByFrameInterval(aStartIndex: Integer; aEndIndex: Integer); override;
// Двигать ленту вправо
procedure MoveLentToRight; override;
// ДВигать ленту влево
procedure MoveLentToLeft; override;
procedure OnSelect(anXm, anY: Integer); override;
function GetEditor: TFilmEditor; override;
procedure Repaint; override;
property ActiveFrame: Integer read FActiveFrame write SetActiveFrame;
end;
implementation
uses ImageUtils;
{ TImageBoxFilmManager }
constructor TImageBoxFilmManager.Create;
var
aFabric: TEditorFabrics;
begin
CurrentSelectFrame := -1;
FActiveFrame:= 0;
aFabric := TEditorFabrics.Create;
try
FEditor := aFabric.CreateFilmEditor(feBitmapFileEditor);
// Инициализируем меджер кадров
InitFilmEditor;
finally
aFabric.Free;
end;
end;
function TImageBoxFilmManager.GetEditor: TFilmEditor;
begin
if not Assigned(FEditor) then begin
raise Exception.Create(FILM_EDITOR_DONT_ASSIGNED);
end;
Result := FEditor;
end;
procedure TImageBoxFilmManager.DrawByFrameInterval(aStartIndex,
aEndIndex: Integer);
begin
{* Получить уменьшенные изображения рисунков и нарисовать их друг за другом *}
if not Assigned(FEditor) then begin
raise Exception.Create(FILM_EDITOR_DONT_ASSIGNED);
end;
//
end;
// Инициализация отображения раскадровки
procedure TImageBoxFilmManager.InitFilmEditor;
var
aBitmap: TBitmap;
i: Integer;
begin
aBitmap := TBitmap.Create;
try
// Добавляем первый кадр
aBitmap.SetSize(640, 480);
FEditor.AddFrame(aBitmap);
// Создаем 10 кадров копированием из первого
for i := 1 to DrawFrameCount do begin
FEditor.CopyFrame(0, i);
end;
finally
aBitmap.Free;
end;
end;
procedure TImageBoxFilmManager.InitImage(anImage: TImage; anImageList: TImageList);
begin
FImage := anImage;
FImageList := anImageList;
end;
// Процедура перерисовки кадров
procedure TImageBoxFilmManager.Repaint;
var
aBitmap: TBitmap;
aScaleImages: TBitmap;
i: Integer;
begin
aBitmap:= TBitmap.Create;
try
// Перебереаем картинки из начального состояние до (кадры который умещается в ленту.)
aScaleImages:= TBitmap.Create;
try
for I := FCurrentStartFrame to DrawFrameCount - 1 do begin
// Если кадр существует, то копируем его и пропорционально уменьшаем
if FEditor.FrameExist(i) then begin
FEditor.GetFrame(i, aBitmap);
ResizeImage(aBitmap, aScaleImages, 60, PROPRTIONAL_RESIZE);
end else begin
aScaleImages.SetSize(60,80);
end;
// Рисуем изображение пленки и на его фоне выводим изображение
FImageList.GetBitmap(DefaultImage, aBitmap);
FImage.Canvas.Draw(i*aBitmap.Width+10, 0, aBitmap);
FImage.Canvas.Draw(i*aBitmap.Width+12,20, aScaleImages);
end;
finally
aScaleImages.Free;
end;
// FImage.Canvas.Draw();
finally
aBitmap.Free;
end;
end;
procedure TImageBoxFilmManager.SetActiveFrame(const Value: Integer);
begin
FActiveFrame := Value;
end;
procedure TImageBoxFilmManager.MoveLentToLeft;
begin
end;
procedure TImageBoxFilmManager.MoveLentToRight;
begin
end;
procedure TImageBoxFilmManager.OnSelect(anXm, anY: Integer);
begin
end;
end.
|
{$i deltics.unicode.inc}
unit Deltics.Unicode.Escape.Json;
interface
uses
Deltics.Unicode.Types;
type
JsonEscape = class (UnicodeEscapeBase)
class function EscapedLength(const aChar: WideChar): Integer; override;
class function EscapedLength(const aCodepoint: Codepoint): Integer; override;
class procedure EscapeA(const aChar: WideChar; const aBuffer: PAnsiChar); override;
class procedure EscapeA(const aCodepoint: Codepoint; const aBuffer: PAnsiChar); override;
class procedure EscapeW(const aChar: WideChar; const aBuffer: PWideChar); override;
class procedure EscapeW(const aCodepoint: Codepoint; const aBuffer: PWideChar); override;
end;
implementation
uses
Deltics.Unicode,
Deltics.Unicode.Exceptions,
Deltics.Unicode.Utils;
{ JsonEscape }
class function JsonEscape.EscapedLength(const aChar: WideChar): Integer;
begin
result := 6;
end;
class function JsonEscape.EscapedLength(const aCodepoint: Codepoint): Integer;
begin
case aCodepoint of
$00000000..$0000ffff : result := 6;
$00010000..$0010ffff : result := 12;
else
raise EInvalidCodepoint.Create(aCodepoint);
end;
end;
class procedure JsonEscape.EscapeA(const aChar: WideChar; const aBuffer: PAnsiChar);
begin
SetBuffer(aBuffer, '\u' + AnsiHex(Word(aChar), 4, FALSE));
end;
class procedure JsonEscape.EscapeA(const aCodepoint: Codepoint; const aBuffer: PAnsiChar);
var
hi, lo: WideChar;
begin
case aCodepoint of
$00000000..$0000ffff : EscapeA(WideChar(aCodepoint), aBuffer);
$00010000..$0010ffff : begin
Unicode.CodepointToSurrogates(aCodepoint, hi, lo);
SetBuffer(aBuffer, '\u' + AnsiHex(Word(hi), 4, FALSE)
+ '\u' + AnsiHex(Word(lo), 4, FALSE));
end;
else
raise EInvalidCodepoint.Create(aCodepoint);
end;
end;
class procedure JsonEscape.EscapeW(const aChar: WideChar; const aBuffer: PWideChar);
begin
SetBuffer(aBuffer, '\u' + WideHex(Word(aChar), 4, FALSE));
end;
class procedure JsonEscape.EscapeW(const aCodepoint: Codepoint; const aBuffer: PWideChar);
var
hi, lo: WideChar;
begin
case aCodepoint of
$00000000..$0000ffff : EscapeW(WideChar(aCodepoint), aBuffer);
$00010000..$0010ffff : begin
Unicode.CodepointToSurrogates(aCodepoint, hi, lo);
SetBuffer(aBuffer, '\u' + WideHex(Word(hi), 4, FALSE)
+ '\u' + WideHex(Word(lo), 4, FALSE));
end;
else
raise EInvalidCodepoint.Create(aCodepoint);
end;
end;
end.
|
program SPLIT;
(* split a long text file into two pieces *)
uses DOS, fileops;
CONST
RecSize = 1;
InitBufSize : LONGINT = 16384;
VAR
ExitPtr : POINTER;
buf : POINTER;
PROCEDURE SplitFile;
VAR
infile, outfile : FILE;
Name, Name1, Name2 : String;
NumRead, NumWritten : Word;
BufSize,
SplitSize, RecCount : LONGINT;
err : INTEGER;
ByteCount,
CumCount : LONGINT;
{ ===================================================== }
FUNCTION MakeName(name : NameStr; count : INTEGER) : String;
VAR
ext : ExtStr;
BEGIN
str(count:1,ext);
IF count > 999 THEN
BEGIN
writeln('Max files is 999');
HALT;
END;
IF count < 100 THEN ext := '0' + ext;
IF count < 10 THEN ext := '0' + ext;
MakeName := name + '.' + ext;
END;
(* =================================================== *)
PROCEDURE ParseName(VAR FromName, ToName : String);
VAR
path : PathStr;
dir : DirStr;
name : NameStr;
ext : ExtStr;
count : INTEGER;
BEGIN
IF (ParamCount < 1) or (ParamStr(1) = '?') or
NOT exist(ParamStr(1)) THEN
BEGIN
WriteLn('usage: SPLIT FileName');
HALT;
END;
path := ParamStr(1);
FSplit(path,dir,name,ext);
FromName := path;
count := 0;
REPEAT
INC(count);
ToName := MakeName(name,count);
UNTIL NOT exist(ToName);
END (* ParseName *);
(* =================================================== *)
BEGIN
GetMem(buf,InitBufSize);
ParseName(Name, Name1);
Assign(infile, Name);
Reset(infile,RecSize);
SplitSize := FileSize(infile) DIV 2;
CumCount := 0;
IF (paramcount > 1) THEN
val(paramstr(2),SplitSize,err);
WriteLn('Copying ', SplitSize, ' of ', FileSize(infile),' bytes from ',name);
WHILE NOT eof(infile) DO
BEGIN
ParseName(Name, Name1);
Assign(outfile, Name1);
Rewrite(outfile,RecSize);
BufSize := InitBufSize;
ByteCount := 0;
Write('Writing ', Name1, ' using',BufSize:8,' Buffer');
REPEAT
{ shrink buffer as we approach split point }
IF (ByteCount + BufSize > SplitSize) THEN
BufSize := BufSize DIV 2;
BlockRead(infile,buf^, BufSize,NumRead);
BlockWrite(outfile,buf^,NumRead,NumWritten);
Write('.');
ByteCount := FilePos(outfile);
UNTIL (ByteCount > SplitSize) OR (NumRead = 0) or
(NumWritten <> NumRead);
Writeln;
Writeln('Wrote ',ByteCount,' Bytes');
CumCount := CumCount + ByteCount;
Close(outfile);
END {while};
close(infile);
Writeln(CumCount,' Total Bytes Written');
END (* SplitFile *);
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
{$F+} PROCEDURE CleanUp; {$F-}
{ restore original directory }
BEGIN
IF buf <> NIL THEN FreeMem(buf,InitBufSize);
buf := NIL;
ExitProc := ExitPtr;
END;
(* =================================================== *)
BEGIN
{ Install Termination Code }
ExitPtr := ExitProc;
ExitProc := @CleanUp;
SplitFile;
END (*SPLIT*). |
unit ABaixaParcialCotacao;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, StdCtrls, Buttons, Grids,
CGrades, UnDadosProduto,UnCotacao, UnProdutos, Localizacao, MPlayer,
Mask, numericos, SqlExpr;
type
TFBaixaParcialCotacao = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor2: TPanelColor;
BOk: TBitBtn;
BCancelar: TBitBtn;
BImprimir: TBitBtn;
BFechar: TBitBtn;
PUtilizarLeitor: TPanelColor;
Localiza: TConsultaPadrao;
Label8: TLabel;
SpeedButton2: TSpeedButton;
LNomProduto: TLabel;
EProduto: TEditLocaliza;
Som: TMediaPlayer;
PanelColor3: TPanelColor;
GProdutos: TRBStringGridColor;
PanelColor1: TPanelColor;
Label1: TLabel;
EPerDesconto: Tnumerico;
BEnviar: TBitBtn;
Label2: TLabel;
Label3: TLabel;
EPeso: Tnumerico;
EVolume: TEditColor;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BCancelarClick(Sender: TObject);
procedure BOkClick(Sender: TObject);
procedure GProdutosCarregaItemGrade(Sender: TObject;
VpaLinha: Integer);
procedure GProdutosKeyPress(Sender: TObject; var Key: Char);
procedure GProdutosMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
procedure GProdutosDadosValidos(Sender: TObject;
var VpaValidos: Boolean);
procedure BFecharClick(Sender: TObject);
procedure BImprimirClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure BEnviarClick(Sender: TObject);
procedure EProdutoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure GProdutosKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure GProdutosGetCellColor(Sender: TObject; ARow, ACol: Integer;
AState: TGridDrawState; ABrush: TBrush; AFont: TFont);
procedure FormShow(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
VprPressionadoR,
VprAcao,
VprFinanceiroGerado,
VprPermiteFechar,
VprIndConferindo : Boolean;
VprDCotacao : TRBDOrcamento;
VprDItemCotacao : TRBDOrcProduto;
VprSeqParcial,
VprProutoLiberado : Integer;
FunCotacao : TFuncoesCotacao;
procedure ConfiguraPermissaoUsuario;
procedure CarTituloGrade;
procedure AcertaQtdProdutosBaixarEstoque;
procedure EstadoBotoes(VpaEstado : Boolean);
procedure GeraFinanceiro;
function GravaBaixaParcial : String;
procedure AdicionaProduto(VpaSeqProduto : Integer);
function VerificaQtdABaixar : string;
public
{ Public declarations }
function GeraBaixaParcial(VpaDCotacao : TRBDOrcamento;VpaIndConferencia : Boolean) : Boolean;
end;
var
FBaixaParcialCotacao: TFBaixaParcialCotacao;
implementation
uses APrincipal, funString, ConstMsg, UnContasAreceber, Constantes, UnClientes,
FunValida, FunNumeros, dmRave;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFBaixaParcialCotacao.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
VprAcao := false;
VprPermiteFechar := false;
VprFinanceiroGerado := false;
VprIndConferindo := false;
ConfiguraPermissaoUsuario;
CarTituloGrade;
FunCotacao := TFuncoesCotacao.Cria(FPrincipal.BaseDados);
PUtilizarLeitor.Visible := config.UtilizarLeitorSeparacaoProduto;
if config.UtilizarLeitorSeparacaoProduto then
ActiveControl := EProduto;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFBaixaParcialCotacao.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
FunCotacao.free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFBaixaParcialCotacao.ConfiguraPermissaoUsuario;
begin
if not config.EstoquePorCor then
begin
GProdutos.ColWidths[6] := -1;
GProdutos.ColWidths[7] := -1;
GProdutos.ColWidths[5] := RetornaInteiro(GProdutos.ColWidths[5] *1.5);
end;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.CarTituloGrade;
begin
if VprIndConferindo then
begin
GProdutos.Cells[1,0] := 'Qtd Conferir';
PainelGradiente1.caption := ' Confere Produtos Baixados ';
caption := 'Confere Produtos Baixados';
end
else
begin
GProdutos.Cells[1,0] := 'Qtd Baixar';
end;
GProdutos.Cells[2,0] := 'Qtd Cotacao';
GProdutos.Cells[3,0] := 'Referencia';
GProdutos.Cells[4,0] := 'Codigo';
GProdutos.Cells[5,0] := 'Produto';
GProdutos.Cells[6,0] := 'Cor';
GProdutos.Cells[7,0] := 'Descrição';
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.AcertaQtdProdutosBaixarEstoque;
var
VpfLaco : Integer;
begin
for VpfLaco := 0 to VprDCotacao.Produtos.count - 1 do
begin
VprDItemCotacao := TRBDOrcProduto(VprDCotacao.Produtos.Items[VpfLaco]);
VprDItemCotacao.QtdProduto := VprDItemCotacao.QtdABaixar;
VprDItemCotacao.ValTotal := VprDItemCotacao.QtdProduto * VprDItemCotacao.ValUnitario;
end;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.EstadoBotoes(VpaEstado : Boolean);
begin
BImprimir.enabled := VpaEstado;
BEnviar.Enabled := VpaEstado;
BOk.Enabled := not VpaEstado;
BCancelar.Enabled := not VpaEstado;
BFechar.Enabled := VpaEstado;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.GeraFinanceiro;
var
VpfResultado : String;
VpfTransacao : TTransactionDesc;
begin
if VprSeqParcial = 0 then
aviso('ROMANEIO PARCIAL NÃO GRAVADO!!!'#13'Antes de gerar o finaneiro é necessário gravar o romaneio parcial.')
else
begin
if VprFinanceiroGerado then
if not confirmacao('FINANCEIRO JÁ FOI GERADO!!!'#13'O financeiro dessa baixa parcial já foi gerado, tem certeza que deseja gerar novamente?') then
exit;
VpfTransacao.IsolationLevel := xilREADCOMMITTED;
FPrincipal.BaseDados.StartTransaction(VpfTransacao);
if FunCotacao.GeraFinanceiroParcial(VprDCotacao,FunContasAReceber,VprSeqParcial, VpfResultado) then
begin
if VpfResultado ='' then
begin
VprDCotacao.ValTotal := FunCotacao.RValTotalOrcamento(VprDCotacao.CodEmpFil,VprDCotacao.LanOrcamento);
FunCotacao.SetaFinanceiroGerado(VprDCotacao);
VprDCotacao.FinanceiroGerado := true;
end;
if VpfResultado <> '' then
begin
FPrincipal.BaseDados.Rollback(VpfTransacao);
aviso(VpfResultado);
end
else
FPrincipal.BaseDados.Commit(VpfTransacao);
VprFinanceiroGerado := true;
end
else
FPrincipal.BaseDados.Rollback(VpfTransacao);
end;
end;
{******************************************************************************}
function TFBaixaParcialCotacao.GravaBaixaParcial : String;
begin
result := FunCotacao.GravaBaixaParcialCotacao(VprDCotacao,vprSeqParcial);
if result = '' then
begin
if not VprIndConferindo then
begin
FunCotacao.BaixaProdutosEtiquetadosSeparados(VprDCotacao);
AcertaQtdProdutosBaixarEstoque;
result := FunCotacao.GeraEstoqueProdutos(VprDCotacao,FunProdutos,false);
end;
if result = '' then
result := FunCotacao.BaixaProdutosParcialCotacao(VprDCotacao);
end;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.AdicionaProduto(VpaSeqProduto : Integer);
var
VpfLaco, VpfLinha : Integer;
VpfDProCotacao : TRBDOrcProduto;
VpfLocalizouProduto : Boolean;
begin
VprProutoLiberado := 0;
VpfLocalizouProduto := false;
VpfDProCotacao := nil;
for VpfLaco := 0 to VprDCotacao.Produtos.Count - 1 do
begin
if TRBDOrcProduto(VprDCotacao.Produtos.Items[VpfLaco]).SeqProduto = VpaSeqProduto then
begin
VpfDProCotacao := TRBDOrcProduto(VprDCotacao.Produtos.Items[VpfLaco]);
VpfLinha := VpfLaco + 1;
if VprIndConferindo then
begin
VpfLocalizouProduto := true;
break;
end
else
begin
VpfLocalizouProduto := true;
break;
end;
end;
end;
{ if not VpfLocalizouProduto and (VpfDProCotacao <> nil) then
begin
VpfDProCotacao.QtdABaixar := VpfDProCotacao.QtdABaixar + 1;
VpfLocalizouProduto := true;
end;}
if VpfLocalizouProduto then
begin
GProdutos.CarregaGrade;
ActiveControl := GProdutos;
GProdutos.Row := VpfLinha;
VprProutoLiberado := VpaSeqProduto;
end
else
begin
try
Som.play;
except
end;
if VpfDProCotacao <> nil then
aviso('PRODUTO BAIXADO A MAIS!!!'#13'O produto "'+ VpfDProCotacao.CodProduto+'-'+VpfDProCotacao.NomProduto+'" possui '+ FormatFloat('##0.00',VpfDProCotacao.QtdProduto)+' '+ VpfDProCotacao.UM+' no pedido')
else
Aviso('PRODUTO INVÁLIDO!!!!'#13'O produto selecionado não existe na cotação');
end;
end;
{******************************************************************************}
function TFBaixaParcialCotacao.VerificaQtdABaixar : string;
var
VpfLaco : Integer;
VpfDProCotacao : TRBDOrcProduto;
begin
result := '';
if (VARIA.CNPJFilial = CNPJ_MetalVidros) or (varia.CNPJFilial = CNPJ_VIDROMAX) then
begin
for VpfLaco := 0 to VprDCotacao.Produtos.Count - 1 do
begin
VpfDProCotacao := TRBDOrcProduto(VprDCotacao.Produtos.Items[VpfLaco]);
if VprIndConferindo then
begin
if VpfDProCotacao.QtdConferido < 0 then
begin
if (VpfDProCotacao.QtdConferidoSalvo + VpfDProCotacao.QtdConferido) < 0 then
result := #13+ 'A quantidade conferida a ser estornada do produto "'+VpfDProCotacao.CodProduto+'" é maior que a quantidade que foi conferida.';
end
else
if VpfDProCotacao.QtdConferido > 0 then
begin
if (VpfDProCotacao.QtdConferidoSalvo + VpfDProCotacao.QtdConferido) <> (VpfDProCotacao.QtdBaixadoNota) then
result := result + #13+VpfDProCotacao.CodProduto+'-'+VpfDProCotacao.NomProduto;
end;
end
else
begin
if VpfDProCotacao.QtdABaixar < 0 then
begin
if VpfDProCotacao.QtdConferidoSalvo > 0 then
result := #13+'Não é possivel estornar o produto "'+VpfDProCotacao.CodProduto+'" porque a quantidade já foi conferida. É necessário antes estornar a quantidade conferida.'
else
begin
if (VpfDProCotacao.QtdBaixadoNota + VpfDProCotacao.QtdABaixar) < 0 then
result :=#13+ 'A quantidade a ser estornada do produto "'+VpfDProCotacao.CodProduto+'" é maior que a quantidade que foi baixada.';
end;
end
else
if VpfDProCotacao.QtdABaixar > (VpfDProCotacao.QtdProduto - VpfDProCotacao.QtdBaixadoNota) then
result := result + #13+VpfDProCotacao.CodProduto+'-'+VpfDProCotacao.NomProduto;
end;
end;
end;
if result <> '' then
result := 'A quantidade baixada dos produtos abaixo é maior que a quantidade do pedido:'+result;
end;
{******************************************************************************}
function TFBaixaParcialCotacao.GeraBaixaParcial(VpaDCotacao : TRBDOrcamento;VpaIndConferencia : Boolean) : Boolean;
begin
VprIndConferindo := VpaIndConferencia;
CarTituloGrade;
VprDCotacao := VpaDCotacao;
EPeso.AValor:= VprDCotacao.PesLiquido;
EVolume.AInteiro:= VprDCotacao.QtdVolumesTransportadora;
GProdutos.ADados := VpaDCotacao.Produtos;
GProdutos.CarregaGrade;
EstadoBotoes(false);
Showmodal;
result := VprAcao;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.BCancelarClick(Sender: TObject);
var
VpfSenha : String;
begin
if config.SolicitarSenhaparaCancelarBaixaParcial then
if Entrada('Digite a senha para cancelar a baixa','Senha : ',VpfSenha,true,EProduto.Color,PanelColor2.Color) then
begin
if VpfSenha <> Descriptografa(Varia.senha) then
begin
aviso('SENHA INVÁLIDA!!!'#13'A senha digitada é diferente do usuario que começou a separação');
exit;
end;
end
else
exit;
VprAcao := false;
if varia.EstagioBaixaParcialCancelada <> 0 then
FunCotacao.AlteraEstagioCotacao(VprDCotacao.CodEmpFil,varia.CodigoUsuario,VprDCotacao.LanOrcamento,Varia.EstagioBaixaParcialCancelada,'');
VprPermiteFechar := true;
close;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.BOkClick(Sender: TObject);
var
VpfResultado : String;
VpfTransacao : TTransactionDesc;
begin
VpfTransacao.IsolationLevel := xilREADCOMMITTED;
FPrincipal.BaseDados.StartTransaction(VpfTransacao);
VpfResultado := VerificaQtdABaixar;
VprDCotacao.PerDesconto := EPerDesconto.AValor;
if EVolume.AInteiro <> VprDCotacao.QtdVolumesTransportadora then
VprDCotacao.QtdVolumesTransportadora:= EVolume.AInteiro;
if EPeso.AValor <> VprDCotacao.PesLiquido then
VprDCotacao.PesLiquido:= EPeso.AValor;
VprDCotacao.ValTotal:= FunCotacao.RValTotalCotacaoParcial(VprDCotacao);
if VprDCotacao.PerDesconto <> 0 then
VprDCotacao.ValTotal := VprDCotacao.ValTotal - ((VprDCotacao.ValTotal*VprDCotacao.PerDesconto)/100);
if VpfResultado = '' then
begin
VpfResultado := GravaBaixaParcial;
end;
if VpfResultado <> '' then
begin
FPrincipal.BaseDados.Rollback(VpfTransacao);
aviso(VpfResultado);
end
else
begin
VprAcao := true;
FPrincipal.BaseDados.Commit(VpfTransacao);
EstadoBotoes(true);
VprPermiteFechar := true;
end;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.GProdutosCarregaItemGrade(Sender: TObject;
VpaLinha: Integer);
begin
VprDItemCotacao := TRBDOrcProduto(VprDCotacao.Produtos.Items[GProdutos.ALinha - 1]);
if VprIndConferindo then
GProdutos.Cells[1,GProdutos.ALinha] := FormatFloat('#,###,##0.00',VprDItemCotacao.QtdConferido)
else
GProdutos.Cells[1,GProdutos.ALinha] := FormatFloat('#,###,##0.00',VprDItemCotacao.qtdaBaixar);
if (VARIA.CNPJFilial = CNPJ_MetalVidros) or (varia.CNPJFilial = CNPJ_VIDROMAX) then
GProdutos.Cells[2,GProdutos.ALinha] := FormatFloat('#,###,##0.00',VprDItemCotacao.QtdProduto - VprDItemCotacao.QtdBaixadoNota)
else
GProdutos.Cells[2,GProdutos.ALinha] := FormatFloat('#,###,##0.00',VprDItemCotacao.QtdProduto);
GProdutos.Cells[3,GProdutos.ALinha] := VprDItemCotacao.DesRefCliente;
GProdutos.Cells[4,GProdutos.ALinha] := VprDItemCotacao.CodProduto;
GProdutos.Cells[5,GProdutos.ALinha] := VprDItemCotacao.NomProduto;
GProdutos.Cells[6,GProdutos.ALinha] := IntTostr(VprDItemCotacao.CodCor);
GProdutos.Cells[7,GProdutos.ALinha] := VprDItemCotacao.DesCor;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.GProdutosKeyPress(Sender: TObject;
var Key: Char);
begin
if config.ControlarASeparacaodaCotacao then
begin
if not VprIndConferindo then
begin
if not VprDItemCotacao.IndPermiteAlterarQtdnaSeparacao then
begin
if VprDItemCotacao.SeqProduto <> VprProutoLiberado then
begin
aviso('PRODUTO INVÁLIDO!!!'#13'É necessário antes passar o produto no leitor de codigo de barras.');
key := #0;
end;
end;
end;
end;
if not(GProdutos.AColuna in [1]) then
key := #0
else
if key = '.' then
key := ',';
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.GProdutosMudouLinha(Sender: TObject;
VpaLinhaAtual, VpaLinhaAnterior: Integer);
begin
if VprDCotacao.Produtos.Count > 0 then
begin
VprDItemCotacao := TRBDOrcProduto(VprDCotacao.Produtos.Items[VpaLinhaAtual - 1]);
end;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.GProdutosDadosValidos(Sender: TObject;
var VpaValidos: Boolean);
begin
VpaValidos := true;
if VprIndConferindo then
VprDItemCotacao.QtdConferido := StrToFloat(DeletaChars(GProdutos.Cells[1,GProdutos.ALinha],'.'))
else
VprDItemCotacao.QtdABaixar := StrToFloat(DeletaChars(GProdutos.Cells[1,GProdutos.ALinha],'.'));
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.BImprimirClick(Sender: TObject);
begin
dtRave := TdtRave.create(self);
dtRave.ImprimePedidoParcial(VprDCotacao.CodEmpFil,VprDCotacao.LanOrcamento,VprSeqParcial);
dtRave.free;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = [ssCtrl,ssAlt]) then
begin
if (key = 82) then
VprPressionadoR := true
else
if VprPressionadoR then
if (key = 87) then
begin
GeraFinanceiro;
VprPressionadoR := false;
end
else
VprPressionadoR := false;
end;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.BEnviarClick(Sender: TObject);
begin
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.EProdutoKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if EProduto.AInteiro <> 0 then
if key = 13 then
begin
EProduto.Atualiza;
AdicionaProduto(EProduto.AInteiro);
EProduto.clear;
end;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.GProdutosKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if key = 13 then
begin
ActiveControl := EProduto;
end;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.GProdutosGetCellColor(Sender: TObject;
ARow, ACol: Integer; AState: TGridDrawState; ABrush: TBrush;
AFont: TFont);
var
VpfDItem : TRBDOrcProduto;
begin
if (ACol > 0) and (ARow > 0) and (VprDCotacao <> nil) then
begin
if VprDCotacao.Produtos.Count > 0 then
begin
VpfDItem := TRBDOrcProduto(VprDCotacao.Produtos.Items[Arow - 1]);
if VprIndConferindo then
begin
if VpfDItem.QtdBaixadoNota <= VpfDItem.QtdConferidoSalvo then
ABrush.Color := clGray;
end
else
begin
if VpfDItem.QtdProduto <= VpfDItem.QtdBaixadoNota then
ABrush.Color := clGray;
end;
end;
end;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.FormShow(Sender: TObject);
begin
try
Som.Open;
except
end;
end;
{******************************************************************************}
procedure TFBaixaParcialCotacao.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose := VprPermiteFechar;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFBaixaParcialCotacao]);
end.
|
unit uTravelManager;
interface
uses uTypes;
type
TTravelManger = class
private
fLevel : real; // текущая сложность путешествия. влияет на уровень
// параметров и эффектов объектов прри генерации путешествия
fLength : real; // длина уровня в пикселях в пересчете на количество и размер объектов приключения
fPosition : real; // текущее смещение уровня. значение от 0 до fLength.
// при достижении fLength живой командой, уровень считается успешно пройденным
fTravelArr : TTravelArr;
// массив всех объектов текущего приключения. рабочий массив
// по которому генерится визуал
public
procedure Init( point1, point2: integer; level: real );
/// по сочетанию вершин графа маршрутов находит нужные записи в базе
/// и генерит рабочий массив объектов с применением указанного уровня сложности.
///
/// возможно наличие нескольких маршрутов с данными точками, но ограничениями
/// на доступность по текущему уровню маршрута или установке каких-то флагов
/// (выполнен ли какой-то квест, к примеру)
end;
implementation
{ TTravelManger }
procedure TTravelManger.Init(point1, point2: integer; level: real);
begin
end;
end.
|
{ KOL MCK } // Do not remove this line!
{$DEFINE KOL_MCK}
unit MainForm;
interface
{$IFDEF KOL_MCK}
uses Windows, Messages, KOL, KOLadd {$IF Defined(KOL_MCK)}{$ELSE}, mirror, Classes, Controls, mckCtrls, mckObjs, Graphics {$IFEND},
Types, KOLHilightEdit, Gutter, Hilighter, InputDialog, SearchForm, OptionsForm, AboutForm;
{$ELSE}
{$I uses.inc}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
{$ENDIF}
type
PEditorPage = ^TEditorPage;
TEditorPage = object(TObj)
public
FileName: string;
Modified: Boolean;
Editor: PHilightMemo;
Gutter: PControl;
Hilighter: PCHilighter;
SearchOptions: TFindReplaceOptions;
SearchPoint: TPoint;
FindText, ReplaceText: string;
destructor Destroy; virtual;
procedure Change(Sender: PObj);
function NewLine(Sender: PControl; LineNo: Integer; var S: KOLString): Integer;
end;
{$IF Defined(KOL_MCK)}
{$DEFINE MCK_ACTIONS}
{$I MCKfakeClasses.inc}
{$IFDEF KOLCLASSES} {$I TFormMainclass.inc} {$ELSE OBJECTS} PFormMain = ^TFormMain; {$ENDIF CLASSES/OBJECTS}
{$IFDEF KOLCLASSES}{$I TFormMain.inc}{$ELSE} TFormMain = object(TObj) {$ENDIF}
Form: PControl;
{$ELSE not_KOL_MCK}
TFormMain = class(TForm)
{$IFEND KOL_MCK}
KOLProject: TKOLProject;
KOLForm: TKOLForm;
MainMenu: TKOLMainMenu;
ActionList: TKOLActionList;
Toolbar: TKOLToolbar;
ToolsTabs: TKOLTabControl;
ProjectSplitter: TKOLSplitter;
EditorPanel: TKOLPanel;
MessagesList: TKOLListBox;
MessagesSplitter: TKOLSplitter;
EditorTabs: TKOLTabControl;
ActionExit: TKOLAction;
KOLApplet: TKOLApplet;
PageSymbols: TKOLTabPage;
ActionOpen: TKOLAction;
ActionClose: TKOLAction;
ActionSave: TKOLAction;
ActionNew: TKOLAction;
ToolbarImageList: TKOLImageList;
SourceFileDialog: TKOLOpenSaveDialog;
ActionSaveAs: TKOLAction;
ActionUndo: TKOLAction;
ActionRedo: TKOLAction;
ActionCut: TKOLAction;
ActionCopy: TKOLAction;
ActionPaste: TKOLAction;
ActionSelectAll: TKOLAction;
EditorMenu: TKOLPopupMenu;
ActionCloseAll: TKOLAction;
ActionGoto: TKOLAction;
ActionIndent: TKOLAction;
ActionUnindent: TKOLAction;
PageProject: TKOLTabPage;
ActionSearch: TKOLAction;
ActionFindNext: TKOLAction;
ActionHilight: TKOLAction;
ActionOptions: TKOLAction;
ActionSaveAll: TKOLAction;
ProjectTree: TKOLTreeView;
ProjectTreeMenu: TKOLPopupMenu;
ActionNewProject: TKOLAction;
ProjectTreeImageList: TKOLImageList;
ActionProjectAdd: TKOLAction;
ActionProjectRemove: TKOLAction;
ActionCloseProject: TKOLAction;
ActionProjectOptions: TKOLAction;
ActionProjectProperties: TKOLAction;
ActionProjectBuild: TKOLAction;
ActionProjectRebuild: TKOLAction;
ActionProjectRun: TKOLAction;
ActionProjectClean: TKOLAction;
ActionAbout: TKOLAction;
procedure ActionExitExecute(Sender: PObj);
procedure KOLFormFormCreate(Sender: PObj);
procedure ActionNewExecute(Sender: PObj);
procedure ActionOpenExecute(Sender: PObj);
procedure ActionSaveExecute(Sender: PObj);
procedure ActionSaveAsExecute(Sender: PObj);
procedure ActionCloseExecute(Sender: PObj);
procedure EditorTabsMouseDblClk(Sender: PControl; var Mouse: TMouseEventData);
procedure ActionCopyExecute(Sender: PObj);
procedure ActionCutExecute(Sender: PObj);
procedure ActionPasteExecute(Sender: PObj);
procedure ActionSelectAllExecute(Sender: PObj);
procedure ActionUndoExecute(Sender: PObj);
procedure ActionRedoExecute(Sender: PObj);
procedure KOLFormClose(Sender: PObj; var Accept: Boolean);
procedure EditorMenuToggleBookmark(Sender: PMenu; Item: Integer);
procedure EditorMenuGotoBookmark(Sender: PMenu; Item: Integer);
procedure EditorMenuPopup(Sender: PObj);
procedure ActionCloseAllExecute(Sender: PObj);
procedure ActionGotoExecute(Sender: PObj);
procedure ActionIndentExecute(Sender: PObj);
procedure ActionUnindentExecute(Sender: PObj);
procedure ActionSearchExecute(Sender: PObj);
procedure ActionFindNextExecute(Sender: PObj);
procedure ActionHilightExecute(Sender: PObj);
procedure EditorTabsDropFiles(Sender: PControl; const FileList: KOL_String; const Pt: TPoint);
procedure ActionOptionsExecute(Sender: PObj);
procedure ActionSaveAllExecute(Sender: PObj);
procedure KOLFormShow(Sender: PObj);
procedure ProjectTreeMenuPopup(Sender: PObj);
procedure ActionNewProjectExecute(Sender: PObj);
procedure ActionProjectAddExecute(Sender: PObj);
procedure ActionListUpdateActions(Sender: PObj);
procedure ActionAboutExecute(Sender: PObj);
private
procedure CloseEditorTab(Tab: Integer);
function EditorPage(Tab: Integer): PEditorPage;
function NewEditorTab(const Caption: string): PEditorPage;
procedure OpenFile(const FileName: string);
procedure SaveFile(Tab: Integer);
procedure SetEditorOptions(Page: PEditorPage);
procedure ReadWriteFormPosition(Mode: TIniFileMode);
procedure SetHilighter(Page: PEditorPage);
public
destructor Destroy; virtual;
end;
var
FormMain {$IFDEF KOL_MCK} : PFormMain {$ELSE} : TFormMain {$ENDIF} ;
{$IFDEF KOL_MCK}
procedure NewFormMain( var Result: PFormMain; AParent: PControl );
{$ENDIF}
function SameText(const S1, S2: string): Boolean;
implementation
{$R Icons.res}
const
SSearchCompleted = 'Search completed';
SGotoLine = 'Go to line:';
SUnnamed = 'Unnamed';
SUnsavedFile = 'File "%s" has unsaved modifications. Save now?';
SUnsavedFiles = 'Some files has unsaved modifications. Save now?';
{$IF Defined(KOL_MCK)}{$ELSE}{$R *.DFM}{$IFEND}
{$IFDEF KOL_MCK}
{$I MainForm_1.inc}
{$ENDIF}
function SameText(const S1, S2: string): Boolean;
begin
Result := AnsiCompareTextA(S1, S2) = 0;
end;
function Token(var S: string; const Delim: string): string;
var
P: Integer;
begin
P := Pos(Delim, S);
if P = 0 then
P := Length(S) + 1;
Result := Copy(S, 1, P - 1);
Delete(S, 1, P + Length(Delim) - 1);
end;
function LastChar(const S: string): Char;
begin
if S <> '' then
Result := S[Length(S)]
else
Result := #0;
end;
{TEditorPage}
destructor TEditorPage.Destroy;
begin
FileName := '';
FindText := '';
ReplaceText := '';
inherited;
end;
procedure TEditorPage.Change(Sender: PObj);
var
i: Integer;
begin
if Modified then Exit;
Modified := true;
with FormMain.EditorTabs^ do
for i := 0 to Count - 1 do
if Pages[i].CustomObj = @Self then
TC_Items[i] := TC_Items[i] + '*';
end;
function TEditorPage.NewLine(Sender: PControl; LineNo: Integer; var S: KOLString): Integer;
var
i: Integer;
PrevLine, Prefix: string;
begin
Result := 0;
while (LineNo > 0) and (PHilightMemo(Sender).Edit.Lines[LineNo - 1] = '') do
Dec(LineNo);
if LineNo = 0 then Exit;
PrevLine := PHilightMemo(Sender).Edit.Lines[LineNo - 1];
Prefix := '';
for i := 1 to Length(PrevLine) do
if PrevLine[i] in [#9, #32] then
Prefix := Prefix + PrevLine[i]
else
Break;
if (LastChar(PrevLine) = '{') and (oeSmartTabs in PHilightMemo(Sender).Edit.Options) then
Prefix := Prefix + #9;
S := Prefix + S;
for i := 1 to Length(Prefix) do
if Prefix[i] = #9 then
Result := PHilightMemo(Sender).Edit.GiveNextTabPos(Result)
else
Inc(Result);
end;
{TFormMain}
destructor TFormMain.Destroy;
begin
inherited;
end;
procedure TFormMain.ActionExitExecute(Sender: PObj);
begin
Form.Close;
end;
procedure TFormMain.KOLFormFormCreate(Sender: PObj);
begin
ToolBar.Perform(TB_SETMAXTEXTROWS, 0, 0);
end;
function TFormMain.NewEditorTab(const Caption: string): PEditorPage;
var
Tab: PControl;
begin
Tab := EditorTabs.TC_Insert(EditorTabs.Count, Caption, 0);
EditorTabs.CurIndex := EditorTabs.Count - 1;
New(Result, Create);
Tab.CustomObj := Result;
New(Result.Hilighter, Create);
Result.Add2AutoFree(Result.Hilighter);
Result.Modified := false;
Result.Editor := NewHilightEdit(Tab);
with Result.Editor^ do
begin
Border := 0;
Align := caClient;
ExStyle := (ExStyle and not WS_EX_CLIENTEDGE) or WS_EX_STATICEDGE;
OnChange := Result.Change;
Edit.OnNewLine := Result.NewLine;
SetAutoPopupMenu(EditorMenu);
Edit.OnScanToken := Result.Hilighter.ScanToken;
Focused := true;
end;
Result.Gutter := NewGutter(Tab, Result.Editor).SetSize(32, 0).SetAlign(caLeft);
Result.Gutter.SetAutoPopupMenu(EditorMenu);
SetEditorOptions(Result);
end;
procedure TFormMain.ActionNewExecute(Sender: PObj);
begin
NewEditorTab(SUnnamed);
end;
procedure TFormMain.ActionOpenExecute(Sender: PObj);
var
Path, BasePath: string;
begin
SourceFileDialog.OpenDialog := true;
SourceFileDialog.Filename := '';
if not SourceFileDialog.Execute then Exit;
Path := SourceFileDialog.Filename;
if Pos(#13, Path) > 0 then
begin
BasePath := IncludeTrailingPathDelimiter(Token(Path, #13));
while Length(Path) > 0 do
OpenFile(BasePath + Token(Path, #13));
end
else OpenFile(Path);
end;
procedure TFormMain.ActionSaveExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
SaveFile(EditorTabs.CurIndex);
end;
procedure TFormMain.ActionSaveAsExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
SourceFileDialog.OpenDialog := false;
SourceFileDialog.Filename := Page.FileName;
if not SourceFileDialog.Execute then Exit;
Page.FileName := SourceFileDialog.Filename;
SaveFile(EditorTabs.CurIndex);
end;
procedure TFormMain.ActionCloseExecute(Sender: PObj);
begin
if EditorTabs.Count = 0 then Exit;
CloseEditorTab(EditorTabs.CurIndex);
end;
procedure TFormMain.CloseEditorTab(Tab: Integer);
var
Index: Integer;
Page: PEditorPage;
begin
Page := EditorPage(Tab);
if not Assigned(Page) then Exit;
if Page.Modified then
case MsgBox(Format(SUnsavedFile, [Page.FileName]), MB_ICONQUESTION or MB_YESNOCANCEL) of
ID_YES: SaveFile(Tab);
ID_CANCEL: Exit;
end;
Index := EditorTabs.CurIndex;
EditorTabs.TC_Remove(Tab).Free;
if EditorTabs.Count > 0 then
EditorTabs.CurIndex := Min(Index, EditorTabs.Count - 1);
end;
function TFormMain.EditorPage(Tab: Integer): PEditorPage;
begin
if (Tab < 0) or (Tab >= EditorTabs.Count) then
Result := nil
else
Result := PEditorPage(EditorTabs.Pages[Tab].CustomObj);
end;
procedure TFormMain.EditorTabsMouseDblClk(Sender: PControl; var Mouse: TMouseEventData);
begin
CloseEditorTab(EditorTabs.TC_TabAtPos(Mouse.X, Mouse.Y));
end;
procedure TFormMain.OpenFile(const FileName: string);
var
i: Integer;
Page: PEditorPage;
begin
if not FileExists(FileName) then Exit;
for i := 0 to EditorTabs.Count - 1 do
if SameText(FileName, EditorPage(i).FileName) then
begin
EditorTabs.CurIndex := i;
EditorPage(i).Editor.Focused := true;
Exit;
end;
Page := NewEditorTab(ExtractFileName(FileName));
Page.FileName := FileName;
SetHilighter(Page);
Page.Editor.Edit.Text := StrLoadFromFile(FileName);
end;
procedure TFormMain.SaveFile(Tab: Integer);
var
Page: PEditorPage;
begin
Page := EditorPage(Tab);
if not Assigned(Page) then Exit;
if Page.FileName = '' then
begin
SourceFileDialog.OpenDialog := false;
SourceFileDialog.Filename := Page.FileName;
if not SourceFileDialog.Execute then Exit;
Page.FileName := SourceFileDialog.Filename;
end;
EditorTabs.TC_Items[Tab] := ExtractFileName(Page.FileName);
Page.Modified := false;
StrSaveToFile(Page.FileName, Page.Editor.Edit.Text);
end;
procedure TFormMain.ActionCopyExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
Page.Editor.Perform(WM_COPY, 0, 0);
end;
procedure TFormMain.ActionCutExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
Page.Editor.Perform(WM_CUT, 0, 0);
end;
procedure TFormMain.ActionPasteExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
Page.Editor.Perform(WM_PASTE, 0, 0);
end;
procedure TFormMain.ActionSelectAllExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
Page.Editor.Edit.SetSel(Point(0, 0), Point(0, Page.Editor.Edit.Count), Point(0, 0));
end;
procedure TFormMain.ActionUndoExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
Page.Editor.Edit.Undo;
end;
procedure TFormMain.ActionRedoExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
Page.Editor.Edit.Redo;
end;
procedure TFormMain.KOLFormClose(Sender: PObj; var Accept: Boolean);
var
i: Integer;
Modified: Boolean;
begin
Modified := false;
for i := 0 to EditorTabs.Count - 1 do
if EditorPage(i).Modified then
Modified := true;
Accept := true;
ReadWriteFormPosition(ifmWrite);
if Modified then
case MsgBox(SUnsavedFiles, MB_ICONQUESTION or MB_YESNOCANCEL) of
ID_YES: for i := 0 to EditorTabs.Count - 1 do
if EditorPage(i).Modified then
SaveFile(i);
ID_CANCEL: Accept := false;
end;
end;
procedure TFormMain.EditorMenuToggleBookmark(Sender: PMenu; Item: Integer);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
if Page.Editor.Edit.Bookmarks[EditorMenu.Items[Item].Tag].Y = Page.Editor.Edit.Caret.Y then
Page.Editor.Edit.Bookmarks[EditorMenu.Items[Item].Tag] := Point(0, -1)
else
Page.Editor.Edit.Bookmarks[EditorMenu.Items[Item].Tag] := Page.Editor.Edit.Caret;
end;
procedure TFormMain.EditorMenuGotoBookmark(Sender: PMenu; Item: Integer);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
if (Page.Editor.Edit.Bookmarks[EditorMenu.Items[Item].Tag].Y >= 0) then
begin
Page.Editor.Edit.Caret := Page.Editor.Edit.Bookmarks[EditorMenu.Items[Item].Tag];
Page.Editor.Edit.CaretToView;
end;
end;
procedure TFormMain.EditorMenuPopup(Sender: PObj);
var
i: Integer;
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
for i := 0 to EditorMenu.Count - 1 do
if (EditorMenu.ParentItem(i) <> -1) and (EditorMenu.Items[EditorMenu.ItemHandle[EditorMenu.ParentItem(i)]].Tag = 42) then
EditorMenu.ItemChecked[i] := Page.Editor.Edit.Bookmarks[EditorMenu.Items[EditorMenu.ItemHandle[i]].Tag].Y >= 0;
ActionHilight.Checked := Assigned(Page.Editor.Edit.OnScanToken);
end;
procedure TFormMain.ActionCloseAllExecute(Sender: PObj);
begin
while EditorTabs.Count > 0 do
CloseEditorTab(0);
end;
procedure TFormMain.ActionGotoExecute(Sender: PObj);
var
Page: PEditorPage;
S: string;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
S := InputDialogBox(Form, SGotoLine, Int2Str(Page.Editor.Edit.Caret.Y + 1));
if S = '' then Exit;
Page.Editor.Edit.Caret := Point(0, Max(0, Min(Str2Int(S) - 1, Page.Editor.Edit.Count - 1)));
Page.Editor.Edit.CaretToView;
end;
procedure TFormMain.ActionIndentExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
Page.Editor.Edit.Indent(Page.Editor.Edit.TabSize);
end;
procedure TFormMain.ActionUnindentExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
Page.Editor.Edit.Indent(-Page.Editor.Edit.TabSize);
end;
procedure TFormMain.ActionSearchExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
if Page.Editor.Edit.SelectionAvailable and (Pos(#13, Page.Editor.Edit.Selection) = 0) then
FormSearch.Find := Page.Editor.Edit.Selection
else
FormSearch.Find := Page.Editor.Edit.WordAtPos(Page.Editor.Edit.Caret);
FormSearch.Options := FormSearch.Options - [froReplace];
if FormSearch.Form.ShowModal <> ID_OK then Exit;
Page.SearchPoint := Page.Editor.Edit.Caret;
Page.SearchOptions := FormSearch.Options;
Page.FindText := FormSearch.Find;
Page.ReplaceText := FormSearch.Replace;
ActionFindNext.Execute;
end;
procedure TFormMain.ActionFindNextExecute(Sender: PObj);
var
Page: PEditorPage;
OldPos: TPoint;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
OldPos := Page.SearchPoint;
Page.SearchPoint := Page.Editor.Edit.FindReplace(Page.FindText, Page.ReplaceText, Page.SearchPoint, Page.SearchOptions + [froSpaces], true);
if (Page.SearchPoint.X = OldPos.X) and (Page.SearchPoint.Y = OldPos.Y) then
MsgBox(SSearchCompleted, MB_ICONINFORMATION);
end;
procedure TFormMain.ActionHilightExecute(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
if not Assigned(Page) then Exit;
if Assigned(Page.Editor.Edit.OnScanToken) then
Page.Editor.Edit.OnScanToken := nil
else
Page.Editor.Edit.OnScanToken := Page.Hilighter.ScanToken;
Page.Editor.Invalidate;
end;
procedure TFormMain.EditorTabsDropFiles(Sender: PControl; const FileList: KOL_String; const Pt: TPoint);
var
List: string;
begin
List := FileList;
while Length(List) > 0 do
OpenFile(Token(List, #13));
end;
procedure TFormMain.SetHilighter(Page: PEditorPage);
const
CExtensions: array[0..1] of string = ('.c', '.h');
var
i: Integer;
begin
for i := 0 to High(CExtensions) do
if SameText(ExtractFileExt(Page.FileName), CExtensions[i]) then
begin
Page.Editor.Edit.OnScanToken := Page.Hilighter.ScanToken;
Exit;
end;
Page.Editor.Edit.OnScanToken := nil;
end;
procedure TFormMain.ActionOptionsExecute(Sender: PObj);
var
i: Integer;
begin
if FormOptions.Form.ShowModal <> ID_OK then Exit;
for i := 0 to EditorTabs.Count - 1 do
SetEditorOptions(EditorPage(i));
end;
procedure TFormMain.ActionSaveAllExecute(Sender: PObj);
var
i: Integer;
begin
for i := 0 to EditorTabs.Count - 1 do
SaveFile(i);
end;
procedure TFormMain.SetEditorOptions(Page: PEditorPage);
begin
if not Assigned(Page) then Exit;
with Page^, FormOptions^ do
begin
Gutter.Color1 := SampleGutter.Color1;
Gutter.Font.Assign(SampleGutter.Font);
Gutter.Visible := SampleGutter.Visible;
Editor.Font.Assign(SampleEditor.Font);
Editor.Edit.Options := SampleEditor.Edit.Options - [oeReadOnly];
Editor.Edit.AutoCompleteMinWordLength := SampleEditor.Edit.AutoCompleteMinWordLength;
Editor.Edit.RightMarginChars := SampleEditor.Edit.RightMarginChars;
Editor.Edit.RightMarginColor := SampleEditor.Edit.RightMarginColor;
Editor.Edit.TabSize := SampleEditor.Edit.TabSize;
Hilighter.Styles := SampleHilighter.Styles;
end;
end;
procedure TFormMain.ReadWriteFormPosition(Mode: TIniFileMode);
begin
FormOptions.Ini.Mode := Mode;
with FormOptions.Ini^ do
begin
Section := 'MainForm';
if not FormOptions.SavePosCheck.Checked then
begin
ClearSection;
Exit;
end;
Form.WindowState := TWindowState(ValueInteger('State', Integer(Form.WindowState)));
if Form.WindowState <> wsMaximized then
begin
Form.Left := ValueInteger('Left', Form.Left);
Form.Top := ValueInteger('Top', Form.Top);
Form.Width := ValueInteger('Width', Form.Width);
Form.Height := ValueInteger('Height', Form.Height);
end;
ToolsTabs.Width := ValueInteger('ToolsSize', ToolsTabs.Width);
MessagesList.Height := ValueInteger('MessagesSize', MessagesList.Height);
end;
end;
procedure TFormMain.KOLFormShow(Sender: PObj);
var
i: Integer;
begin
ReadWriteFormPosition(ifmRead);
for i := 1 to ParamCount + 1 do
OpenFile(ParamStr(i));
end;
procedure TFormMain.ActionListUpdateActions(Sender: PObj);
var
Page: PEditorPage;
begin
Page := EditorPage(EditorTabs.CurIndex);
ActionSave.Enabled := Assigned(Page) and Page.Modified;
ActionSaveAs.Enabled := ActionSave.Enabled;
ActionSaveAll.Enabled := EditorTabs.Count > 0;
ActionClose.Enabled := Assigned(Page);
ActionCloseAll.Enabled := EditorTabs.Count > 0;
ActionCopy.Enabled := Assigned(Page) and Page.Editor.Edit.SelectionAvailable;
ActionCut.Enabled := ActionCopy.Enabled;
ActionPaste.Enabled := Assigned(Page);
ActionSelectAll.Enabled := Assigned(Page);
ActionRedo.Enabled := Assigned(Page) and Page.Editor.Edit.CanRedo;
ActionUndo.Enabled := Assigned(Page) and Page.Editor.Edit.CanUndo;
ActionSearch.Enabled := Assigned(Page);
ActionFindNext.Enabled := Assigned(Page) and (Page.FindText <> '');
ActionGoto.Enabled := Assigned(Page);
ActionHilight.Enabled := Assigned(Page);
ActionIndent.Enabled := Assigned(Page) and Page.Editor.Edit.SelectionAvailable;
ActionUnindent.Enabled := ActionIndent.Enabled;
ActionProjectAdd.Enabled := ProjectTree.TVSelected <> 0;
end;
procedure TFormMain.ProjectTreeMenuPopup(Sender: PObj);
begin
PMenu(Sender).NotPopup := ProjectTree.TVSelected = 0;
end;
procedure TFormMain.ActionNewProjectExecute(Sender: PObj);
var
Item: Cardinal;
begin
Item := ProjectTree.TVInsert(TVI_ROOT, TVI_FIRST, 'New project');
ProjectTree.TVItemImage[Item] := 2;
ProjectTree.TVItemSelImg[Item] := 2;
end;
procedure TFormMain.ActionProjectAddExecute(Sender: PObj);
var
Item: Cardinal;
begin
if ProjectTree.TVSelected = 0 then Exit;
Item := ProjectTree.TVInsert(ProjectTree.TVSelected, TVI_LAST, 'New file');
ProjectTree.TVExpand(ProjectTree.TVSelected, TVE_EXPAND);
ProjectTree.TVItemImage[Item] := 0;
ProjectTree.TVItemSelImg[Item] := 0;
end;
procedure TFormMain.ActionAboutExecute(Sender: PObj);
begin
FormAbout.Form.ShowModal;
end;
end.
|
{**********************************************}
{ TBarSeries Component Editor Dialog }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeeStackBarEdit;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
Chart, Series, TeCanvas, TeePenDlg, TeeProcs;
type
TStackBarSeriesEditor = class(TForm)
CBYOrigin: TCheckBox;
EYOrigin: TEdit;
RGMultiBar: TRadioGroup;
Label1: TLabel;
EGroup: TEdit;
UDGroup: TUpDown;
procedure FormShow(Sender: TObject);
procedure CBYOriginClick(Sender: TObject);
procedure EYOriginChange(Sender: TObject);
procedure RGMultiBarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EGroupChange(Sender: TObject);
private
{ Private declarations }
CreatingForm : Boolean;
Bar : TCustomBarSeries;
Procedure EnableGroup;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
procedure TStackBarSeriesEditor.FormShow(Sender: TObject);
begin
Bar:=TCustomBarSeries(Tag);
if Assigned(Bar) then
With Bar do
begin
CBYOrigin.Checked :=UseYOrigin;
EYOrigin.Text :=FloatToStr(YOrigin);
EYOrigin.Enabled :=UseYOrigin;
RGMultiBar.ItemIndex :=Ord(MultiBar);
UDGroup.Position :=StackGroup;
EnableGroup;
end;
CreatingForm:=False;
end;
procedure TStackBarSeriesEditor.CBYOriginClick(Sender: TObject);
begin
if not CreatingForm then
begin
Bar.UseYOrigin:=CBYOrigin.Checked;
EYOrigin.Enabled:=Bar.UseYOrigin;
if EYOrigin.Enabled then EYOrigin.SetFocus;
end;
end;
procedure TStackBarSeriesEditor.EYOriginChange(Sender: TObject);
begin
if not CreatingForm then
with Bar do YOrigin:=StrToFloatDef(EYOrigin.Text,YOrigin);
end;
procedure TStackBarSeriesEditor.RGMultiBarClick(Sender: TObject);
begin
if not CreatingForm then
begin
Bar.MultiBar:=TMultiBar(RGMultiBar.ItemIndex);
EnableGroup;
end;
end;
Procedure TStackBarSeriesEditor.EnableGroup;
begin
UDGroup.Enabled:=(Bar.MultiBar=mbStacked) or (Bar.MultiBar=mbStacked100);
EGroup.Enabled:=UDGroup.Enabled;
end;
procedure TStackBarSeriesEditor.FormCreate(Sender: TObject);
begin
CreatingForm:=True;
Align:=alClient;
end;
procedure TStackBarSeriesEditor.EGroupChange(Sender: TObject);
begin
if not CreatingForm then Bar.StackGroup:=UDGroup.Position
end;
initialization
RegisterClass(TStackBarSeriesEditor);
end.
|
unit ProductParametersQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DSWrap;
type
TProductParametersW = class(TDSWrap)
private
FParamSubParamID: TFieldWrap;
FID: TFieldWrap;
FProductCategoryID: TParamWrap;
FParentProductID: TFieldWrap;
FProductID: TFieldWrap;
FValue: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure ApplyFilter(AProductID: Integer; const AParamSubParamID: Integer);
property ParamSubParamID: TFieldWrap read FParamSubParamID;
property ID: TFieldWrap read FID;
property ProductCategoryID: TParamWrap read FProductCategoryID;
property ParentProductID: TFieldWrap read FParentProductID;
property ProductID: TFieldWrap read FProductID;
property Value: TFieldWrap read FValue;
end;
TQueryProductParameters = class(TQueryBase)
private
FW: TProductParametersW;
{ Private declarations }
protected
public
constructor Create(AOwner: TComponent); override;
function SearchByProductCategoryId(AProductCategoryId: Integer): Integer;
property W: TProductParametersW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TQueryProductParameters.Create(AOwner: TComponent);
begin
inherited;
FW := TProductParametersW.Create(FDQuery);
end;
function TQueryProductParameters.SearchByProductCategoryId(AProductCategoryId
: Integer): Integer;
begin
Result := SearchEx([TParamRec.Create(W.ProductCategoryID.FullName,
AProductCategoryId), TParamRec.Create(W.ProductCategoryID.FullName,
AProductCategoryId)]);
end;
constructor TProductParametersW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'pv.ID', '', True);
FParamSubParamID := TFieldWrap.Create(Self, 'pv.ParamSubParamID');
FParentProductID := TFieldWrap.Create(Self, 'p.ParentProductId');
FProductID := TFieldWrap.Create(Self, 'pv.ProductId');
FValue := TFieldWrap.Create(Self, 'pv.Value');
// Параметр SQL запроса
FProductCategoryID := TParamWrap.Create(Self, 'ppc.ProductCategoryId');
end;
procedure TProductParametersW.ApplyFilter(AProductID: Integer;
const AParamSubParamID: Integer);
begin
Assert(AProductID > 0);
Assert(AParamSubParamID > 0);
DataSet.Filter := Format('(%s=%d) and (%s=%d)',
[ProductID.FieldName, AProductID, ParamSubParamID.FieldName,
AParamSubParamID]);
DataSet.Filtered := True;
end;
end.
|
{***************************************************************
*
* Project : UDPServer
* Unit Name: UDPServerMain
* Purpose : UDP demo - server project
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:43:04
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit UDPServerMain;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, IdWinsock, stdctrls,
{$ENDIF}
SysUtils, Classes, IdBaseComponent, IdAntiFreezeBase, IdAntiFreeze,
IdComponent, IdUDPBase, IdUDPClient, IdStack, IdUDPServer, IdSocketHandle;
type
TUDPMainForm = class(TForm)
SourceGroupBox: TGroupBox;
HostNameLabel: TLabel;
HostAddressLabel: TLabel;
HostName: TLabel;
HostAddress: TLabel;
UDPServer: TIdUDPServer;
UDPAntiFreeze: TIdAntiFreeze;
PortLabel: TLabel;
Port: TLabel;
BufferSizeLabel: TLabel;
BufferSize: TLabel;
UDPMemo: TMemo;
procedure FormCreate(Sender: TObject);
procedure UDPServerUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
private
{ Private declarations }
public
{ Public declarations }
end;
var
UDPMainForm: TUDPMainForm;
implementation
const
HOSTNAMELENGTH = 80;
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TUDPMainForm.FormCreate(Sender: TObject);
begin
HostName.Caption := UDPServer.LocalName;
HostAddress.Caption := GStack.LocalAddress;
Port.Caption := IntToStr(UDPServer.DefaultPort);
BufferSize.Caption := IntToStr(UDPServer.BufferSize);
UDPServer.Active := True;
end;
procedure TUDPMainForm.UDPServerUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
var
DataStringStream: TStringStream;
s: String;
begin
DataStringStream := TStringStream.Create('');
try
DataStringStream.CopyFrom(AData, AData.Size);
UDPMemo.Lines.Add('Received "' + DataStringStream.DataString + '" from ' + ABinding.PeerIP + ' on port ' + IntToStr(ABinding.PeerPort));
s := 'Replied from ' + UDPServer.LocalName + ' to "' + DataStringStream.DataString + '"';
ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, s[1], Length(s));
finally
DataStringStream.Free;
end;
end;
end.
|
unit MustacheDefCmd;
interface
procedure MustacheDef(
tableName : string;
mustacheFile : String;
extraJSON : string;
databaseName : String;
userId, password : String;
hostName : String;
hostPort : Integer);
implementation
uses
SysUtils,
StrUtils,
db,
edbcomps,
SynMustache,
SessionManager, JSONHelper;
procedure MustacheDef(
tableName : string;
mustacheFile : String;
extraJSON : string;
databaseName : String;
userId, password : String;
hostName : String;
hostPort : Integer);
var
db : TEDBDatabase;
sessionMgr : TSessionManager;
ds : TEDBQuery;
sSQL : String;
outStr : String;
fieldName,
fieldType : String;
isFirstField : Boolean;
json : String;
procedure RenderMustache;
var
f : TextFile;
s, line : String;
mustache : TSynMustache;
begin
if mustacheFile[1] = '@' then // read from file
begin
AssignFile(f, strutils.RightStr(mustacheFile, length(mustacheFile) - 1));
Reset(f);
s := '';
while not Eof(f) do
begin
readln(f, line);
s := s + #13#10 + line;
end;
CloseFile(f);
end
else
s := mustacheFile;
mustache := TSynMustache.Parse(s);
;
// '{{#tableDef}}This is {{table}}! {{/tableDef}}');
Writeln(ReplaceStr(mustache.RenderJSON(json, nil, mustache.HelpersGetStandardList()), '\n', #13#10));
end;
(*
"table" : "name",
"fields" : [{"name":"xx",
"isIdentity": false,
"isGenerated": false,
"type": "integer",
"is<type>": "true", // so that mustache can do different things for different types
"description": "abc",
"length": 0,
"precision": 0,
"scale": 0
}, ...]
*)
function MakeFieldJSON(ds : TDataSet) : String;
begin
Result := '{' +
JSONElement('name', ds.FieldByName('FieldName').AsString) + ',' +
JSONElementBool('isIdentity', ds.FieldByName('Identity').AsBoolean) + ',' +
JSONElementBool('isGenerated', ds.FieldByName('Generated').AsBoolean) + ',' +
JSONElement('type', ds.FieldByName('Type').AsString) + ',' +
JSONElementBool('is'+ds.FieldByName('Type').AsString, true) + ',' +
JSONElement('description', ds.FieldByName('Description').AsString) + ',' +
JSONElement('length', ds.FieldByName('Length').AsInteger) + ',' +
JSONElement('precision', ds.FieldByName('Precision').AsInteger) + ',' +
JSONElement('scale', ds.FieldByName('Scale').AsInteger) +
'}';
end;
begin
sessionMgr := TSessionManager.Create(userId, password, hostName, hostPort);
db := TEDBDatabase.Create(nil);
db.OnStatusMessage := sessionMgr.Status;
db.OnLogMessage := sessionMgr.Status;
db.SessionName := sessionMgr.session.Name;
db.Database := databaseName;
db.LoginPrompt := true;
db.DatabaseName := databaseName + DateTimeToStr(now);
ds := TEDBQuery.Create(nil);
ds.SessionName := sessionMgr.session.SessionName;
ds.DatabaseName := db.Database;
sSQL := 'Select Tables.Name TableName, '
+ 'c.Name FieldName, c.Description, c.Type, '
+ 'c.Length, c.Precision, c.Scale, '
+ 'c.Generated, c.Identity '
+ ' From Information.Tables t inner join Information.TableColumns c on t.Name = c.TableName ';
// if tableName <> '*' then
sSQL := sSQL + 'Where t.Name = ''' + tableName + ''' ';
sSQL := sSQL + 'Order by t.Name, c.OrdinalPos';
ds.SQL.Add(sSQL);
ds.ExecSQL;
json := '';
isFirstField := true;
while not ds.Eof do
begin
tableName := ds.FieldByName('TableName').AsString;
if not isFirstField then
json := json + ',';
json := json + MakeFieldJSON(ds);
isFirstField := false;
ds.Next;
end;
FreeAndNil(ds);
FreeAndNil(db);
json := JSONArray('fields', json);
json := '"tableDef": {' + JSONElement('table', tableName) + ',' + json + '}';
if extraJSON <> '' then
json := json + ',' + extraJSON;
json := '{' + json + '}';
if mustacheFile = '' then
Writeln(json)
else
RenderMustache;
end;
end.
|
unit URepositorioVacinaNova;
interface
uses
UVacinaNova
, UEntidade
, UPaciente
, URepositorioPaciente
, URepositorioDB
, SqlExpr
;
type
TRepositorioVacinaNova = class(TRepositorioDB<TVACINANOVA>)
private
FRepositorioPaciente: TRepositorioPaciente;
public
constructor Create;
//destructor Destroy; override;
procedure AtribuiDBParaEntidade(const coVACINANOVA: TVACINANOVA); override;
procedure AtribuiEntidadeParaDB(const coVACINANOVA: TVACINANOVA;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
, SysUtils
, StrUtils;
{ TRepositorioVacinaNova }
constructor TRepositorioVACINANOVA.Create;
begin
inherited Create(TVACINANOVA, TBL_VACINA_NOVA, FLD_ENTIDADE_ID, STR_VACINA_NOVA);
FRepositorioPaciente.Create;
end;
procedure TRepositorioVACINANOVA.AtribuiDBParaEntidade(const coVACINANOVA: TVACINANOVA);
begin
inherited;
with FSQLSelect do
begin
//coVACINANOVA.COD_SUS := TPACIENTE(
//FRepositorioPaciente.Retorna(FieldByName(FLD_CODIGO_SUS).AsInteger));
coVACINANOVA.IDADE := FieldByName(FLD_IDADE).AsString ;
coVACINANOVA.DOSE := FieldByName(FLD_DOSE).AsString;
coVACINANOVA.VACINA := FieldByName(FLD_VACINA).AsString;
// coVACINANOVA.APLICADA := FieldByName(FLD_APLICADA).AsString;
//coVACINANOVA.DATA_APLICAÇÃO := FieldByName(FLD_DATA_APLICACAO).AsDateTime;
end;
end;
procedure TRepositorioVACINANOVA.AtribuiEntidadeParaDB(const coVACINANOVA: TVACINANOVA;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
//ParamByName(FLD_CODIGO_SUS).AsString := coVACINANOVA.COD_SUS;
ParamByName(FLD_IDADE).AsString := coVACINANOVA.IDADE ;
ParamByName(FLD_DOSE).AsString := coVACINANOVA.DOSE ;
ParamByName(FLD_VACINA).AsString := coVACINANOVA.VACINA;
//ParamByName(FLD_APLICADA).AsString := coVACINANOVA.APLICADA ;
//ParamByName(FLD_DATA_APLICACAO).AsDateTime := coVACINANOVA.DATA_APLICAÇÃO;
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Runtime Library }
{ Win32 sockets API Interface Unit }
{ }
{ Copyright (C) 1996,99 Inprise Corporation }
{ }
{*******************************************************}
unit WinSock;
{$WEAKPACKAGEUNIT}
interface
uses Windows;
{ HPPEMIT '#include <windows.h>'}
type
{$EXTERNALSYM u_char}
u_char = Char;
{$EXTERNALSYM u_short}
u_short = Word;
{$EXTERNALSYM u_int}
u_int = Integer;
{$EXTERNALSYM u_long}
u_long = Longint;
{ The new type to be used in all
instances which refer to sockets. }
{$EXTERNALSYM TSocket}
TSocket = u_int;
const
{$EXTERNALSYM FD_SETSIZE}
FD_SETSIZE = 64;
type
// the following emits are a workaround to the name conflict with
// procedure FD_SET and struct fd_set in winsock.h
(*$HPPEMIT '#include <winsock.h>'*)
(*$HPPEMIT 'namespace Winsock'*)
(*$HPPEMIT '{'*)
(*$HPPEMIT 'typedef fd_set *PFDSet;'*) // due to name conflict with procedure FD_SET
(*$HPPEMIT 'typedef fd_set TFDSet;'*) // due to name conflict with procedure FD_SET
(*$HPPEMIT '}'*)
{$NODEFINE PFDSet}
PFDSet = ^TFDSet;
{$NODEFINE TFDSet}
TFDSet = record
fd_count: u_int;
fd_array: array[0..FD_SETSIZE-1] of TSocket;
end;
PTimeVal = ^TTimeVal;
{$EXTERNALSYM timeval}
timeval = record
tv_sec: Longint;
tv_usec: Longint;
end;
TTimeVal = timeval;
const
{$EXTERNALSYM IOCPARM_MASK}
IOCPARM_MASK = $7f;
{$EXTERNALSYM IOC_VOID}
IOC_VOID = $20000000;
{$EXTERNALSYM IOC_OUT}
IOC_OUT = $40000000;
{$EXTERNALSYM IOC_IN}
IOC_IN = $80000000;
{$EXTERNALSYM IOC_INOUT}
IOC_INOUT = (IOC_IN or IOC_OUT);
{$EXTERNALSYM FIONREAD}
FIONREAD = IOC_OUT or { get # bytes to read }
((Longint(SizeOf(Longint)) and IOCPARM_MASK) shl 16) or
(Longint(Byte('f')) shl 8) or 127;
{$EXTERNALSYM FIONBIO}
FIONBIO = IOC_IN or { set/clear non-blocking i/o }
((Longint(SizeOf(Longint)) and IOCPARM_MASK) shl 16) or
(Longint(Byte('f')) shl 8) or 126;
{$EXTERNALSYM FIOASYNC}
FIOASYNC = IOC_IN or { set/clear async i/o }
((Longint(SizeOf(Longint)) and IOCPARM_MASK) shl 16) or
(Longint(Byte('f')) shl 8) or 125;
type
PHostEnt = ^THostEnt;
{$EXTERNALSYM hostent}
hostent = record
h_name: PChar;
h_aliases: ^PChar;
h_addrtype: Smallint;
h_length: Smallint;
case Byte of
0: (h_addr_list: ^PChar);
1: (h_addr: ^PChar)
end;
THostEnt = hostent;
PNetEnt = ^TNetEnt;
{$EXTERNALSYM netent}
netent = record
n_name: PChar;
n_aliases: ^PChar;
n_addrtype: Smallint;
n_net: u_long;
end;
TNetEnt = netent;
PServEnt = ^TServEnt;
{$EXTERNALSYM servent}
servent = record
s_name: PChar;
s_aliases: ^PChar;
s_port: Word;
s_proto: PChar;
end;
TServEnt = servent;
PProtoEnt = ^TProtoEnt;
{$EXTERNALSYM protoent}
protoent = record
p_name: PChar;
p_aliases: ^Pchar;
p_proto: Smallint;
end;
TProtoEnt = protoent;
const
{ Protocols }
{$EXTERNALSYM IPPROTO_IP}
IPPROTO_IP = 0; { dummy for IP }
{$EXTERNALSYM IPPROTO_ICMP}
IPPROTO_ICMP = 1; { control message protocol }
{$EXTERNALSYM IPPROTO_IGMP}
IPPROTO_IGMP = 2; { group management protocol }
{$EXTERNALSYM IPPROTO_GGP}
IPPROTO_GGP = 3; { gateway^2 (deprecated) }
{$EXTERNALSYM IPPROTO_TCP}
IPPROTO_TCP = 6; { tcp }
{$EXTERNALSYM IPPROTO_PUP}
IPPROTO_PUP = 12; { pup }
{$EXTERNALSYM IPPROTO_UDP}
IPPROTO_UDP = 17; { user datagram protocol }
{$EXTERNALSYM IPPROTO_IDP}
IPPROTO_IDP = 22; { xns idp }
{$EXTERNALSYM IPPROTO_ND}
IPPROTO_ND = 77; { UNOFFICIAL net disk proto }
{$EXTERNALSYM IPPROTO_RAW}
IPPROTO_RAW = 255; { raw IP packet }
{$EXTERNALSYM IPPROTO_MAX}
IPPROTO_MAX = 256;
{ Port/socket numbers: network standard functions}
{$EXTERNALSYM IPPORT_ECHO}
IPPORT_ECHO = 7;
{$EXTERNALSYM IPPORT_DISCARD}
IPPORT_DISCARD = 9;
{$EXTERNALSYM IPPORT_SYSTAT}
IPPORT_SYSTAT = 11;
{$EXTERNALSYM IPPORT_DAYTIME}
IPPORT_DAYTIME = 13;
{$EXTERNALSYM IPPORT_NETSTAT}
IPPORT_NETSTAT = 15;
{$EXTERNALSYM IPPORT_FTP}
IPPORT_FTP = 21;
{$EXTERNALSYM IPPORT_TELNET}
IPPORT_TELNET = 23;
{$EXTERNALSYM IPPORT_SMTP}
IPPORT_SMTP = 25;
{$EXTERNALSYM IPPORT_TIMESERVER}
IPPORT_TIMESERVER = 37;
{$EXTERNALSYM IPPORT_NAMESERVER}
IPPORT_NAMESERVER = 42;
{$EXTERNALSYM IPPORT_WHOIS}
IPPORT_WHOIS = 43;
{$EXTERNALSYM IPPORT_MTP}
IPPORT_MTP = 57;
{ Port/socket numbers: host specific functions }
{$EXTERNALSYM IPPORT_TFTP}
IPPORT_TFTP = 69;
{$EXTERNALSYM IPPORT_RJE}
IPPORT_RJE = 77;
{$EXTERNALSYM IPPORT_FINGER}
IPPORT_FINGER = 79;
{$EXTERNALSYM IPPORT_TTYLINK}
IPPORT_TTYLINK = 87;
{$EXTERNALSYM IPPORT_SUPDUP}
IPPORT_SUPDUP = 95;
{ UNIX TCP sockets }
{$EXTERNALSYM IPPORT_EXECSERVER}
IPPORT_EXECSERVER = 512;
{$EXTERNALSYM IPPORT_LOGINSERVER}
IPPORT_LOGINSERVER = 513;
{$EXTERNALSYM IPPORT_CMDSERVER}
IPPORT_CMDSERVER = 514;
{$EXTERNALSYM IPPORT_EFSSERVER}
IPPORT_EFSSERVER = 520;
{ UNIX UDP sockets }
{$EXTERNALSYM IPPORT_BIFFUDP}
IPPORT_BIFFUDP = 512;
{$EXTERNALSYM IPPORT_WHOSERVER}
IPPORT_WHOSERVER = 513;
{$EXTERNALSYM IPPORT_ROUTESERVER}
IPPORT_ROUTESERVER = 520;
{ Ports < IPPORT_RESERVED are reserved for
privileged processes (e.g. root). }
{$EXTERNALSYM IPPORT_RESERVED}
IPPORT_RESERVED = 1024;
{ Link numbers }
{$EXTERNALSYM IMPLINK_IP}
IMPLINK_IP = 155;
{$EXTERNALSYM IMPLINK_LOWEXPER}
IMPLINK_LOWEXPER = 156;
{$EXTERNALSYM IMPLINK_HIGHEXPER}
IMPLINK_HIGHEXPER = 158;
type
{$EXTERNALSYM SunB}
SunB = packed record
s_b1, s_b2, s_b3, s_b4: u_char;
end;
{$EXTERNALSYM SunW}
SunW = packed record
s_w1, s_w2: u_short;
end;
PInAddr = ^TInAddr;
{$EXTERNALSYM in_addr}
in_addr = record
case integer of
0: (S_un_b: SunB);
1: (S_un_w: SunW);
2: (S_addr: u_long);
end;
TInAddr = in_addr;
PSockAddrIn = ^TSockAddrIn;
{$EXTERNALSYM sockaddr_in}
sockaddr_in = record
case Integer of
0: (sin_family: u_short;
sin_port: u_short;
sin_addr: TInAddr;
sin_zero: array[0..7] of Char);
1: (sa_family: u_short;
sa_data: array[0..13] of Char)
end;
TSockAddrIn = sockaddr_in;
const
{$EXTERNALSYM INADDR_ANY}
INADDR_ANY = $00000000;
{$EXTERNALSYM INADDR_LOOPBACK}
INADDR_LOOPBACK = $7F000001;
{$EXTERNALSYM INADDR_BROADCAST}
INADDR_BROADCAST = $FFFFFFFF;
{$EXTERNALSYM INADDR_NONE}
INADDR_NONE = $FFFFFFFF;
{$EXTERNALSYM WSADESCRIPTION_LEN}
WSADESCRIPTION_LEN = 256;
{$EXTERNALSYM WSASYS_STATUS_LEN}
WSASYS_STATUS_LEN = 128;
type
PWSAData = ^TWSAData;
{$EXTERNALSYM WSAData}
WSAData = record // !!! also WSDATA
wVersion: Word;
wHighVersion: Word;
szDescription: array[0..WSADESCRIPTION_LEN] of Char;
szSystemStatus: array[0..WSASYS_STATUS_LEN] of Char;
iMaxSockets: Word;
iMaxUdpDg: Word;
lpVendorInfo: PChar;
end;
TWSAData = WSAData;
{$EXTERNALSYM PTransmitFileBuffers}
PTransmitFileBuffers = ^TTransmitFileBuffers;
{$EXTERNALSYM _TRANSMIT_FILE_BUFFERS}
_TRANSMIT_FILE_BUFFERS = record
Head: Pointer;
HeadLength: DWORD;
Tail: Pointer;
TailLength: DWORD;
end;
{$EXTERNALSYM TTransmitFileBuffers}
TTransmitFileBuffers = _TRANSMIT_FILE_BUFFERS;
{$EXTERNALSYM TRANSMIT_FILE_BUFFERS}
TRANSMIT_FILE_BUFFERS = _TRANSMIT_FILE_BUFFERS;
const
{$EXTERNALSYM TF_DISCONNECT}
TF_DISCONNECT = $01;
{$EXTERNALSYM TF_REUSE_SOCKET}
TF_REUSE_SOCKET = $02;
{$EXTERNALSYM TF_WRITE_BEHIND}
TF_WRITE_BEHIND = $04;
{ Options for use with [gs]etsockopt at the IP level. }
{$EXTERNALSYM IP_OPTIONS}
IP_OPTIONS = 1;
{$EXTERNALSYM IP_MULTICAST_IF}
IP_MULTICAST_IF = 2; { set/get IP multicast interface }
{$EXTERNALSYM IP_MULTICAST_TTL}
IP_MULTICAST_TTL = 3; { set/get IP multicast timetolive }
{$EXTERNALSYM IP_MULTICAST_LOOP}
IP_MULTICAST_LOOP = 4; { set/get IP multicast loopback }
{$EXTERNALSYM IP_ADD_MEMBERSHIP}
IP_ADD_MEMBERSHIP = 5; { add an IP group membership }
{$EXTERNALSYM IP_DROP_MEMBERSHIP}
IP_DROP_MEMBERSHIP = 6; { drop an IP group membership }
{$EXTERNALSYM IP_TTL}
IP_TTL = 7; { set/get IP Time To Live }
{$EXTERNALSYM IP_TOS}
IP_TOS = 8; { set/get IP Type Of Service }
{$EXTERNALSYM IP_DONTFRAGMENT}
IP_DONTFRAGMENT = 9; { set/get IP Don't Fragment flag }
{$EXTERNALSYM IP_DEFAULT_MULTICAST_TTL}
IP_DEFAULT_MULTICAST_TTL = 1; { normally limit m'casts to 1 hop }
{$EXTERNALSYM IP_DEFAULT_MULTICAST_LOOP}
IP_DEFAULT_MULTICAST_LOOP = 1; { normally hear sends if a member }
{$EXTERNALSYM IP_MAX_MEMBERSHIPS}
IP_MAX_MEMBERSHIPS = 20; { per socket; must fit in one mbuf }
{ This is used instead of -1, since the
TSocket type is unsigned.}
{$EXTERNALSYM INVALID_SOCKET =}
INVALID_SOCKET = TSocket(NOT(0));
{$EXTERNALSYM SOCKET_ERROR =}
SOCKET_ERROR = -1;
{ Types }
{$EXTERNALSYM SOCK_STREAM}
SOCK_STREAM = 1; { stream socket }
{$EXTERNALSYM SOCK_DGRAM}
SOCK_DGRAM = 2; { datagram socket }
{$EXTERNALSYM SOCK_RAW}
SOCK_RAW = 3; { raw-protocol interface }
{$EXTERNALSYM SOCK_RDM}
SOCK_RDM = 4; { reliably-delivered message }
{$EXTERNALSYM SOCK_SEQPACKET}
SOCK_SEQPACKET = 5; { sequenced packet stream }
{ Option flags per-socket. }
{$EXTERNALSYM SO_DEBUG}
SO_DEBUG = $0001; { turn on debugging info recording }
{$EXTERNALSYM SO_ACCEPTCONN}
SO_ACCEPTCONN = $0002; { socket has had listen() }
{$EXTERNALSYM SO_REUSEADDR}
SO_REUSEADDR = $0004; { allow local address reuse }
{$EXTERNALSYM SO_KEEPALIVE}
SO_KEEPALIVE = $0008; { keep connections alive }
{$EXTERNALSYM SO_DONTROUTE}
SO_DONTROUTE = $0010; { just use interface addresses }
{$EXTERNALSYM SO_BROADCAST}
SO_BROADCAST = $0020; { permit sending of broadcast msgs }
{$EXTERNALSYM SO_USELOOPBACK}
SO_USELOOPBACK = $0040; { bypass hardware when possible }
{$EXTERNALSYM SO_LINGER}
SO_LINGER = $0080; { linger on close if data present }
{$EXTERNALSYM SO_OOBINLINE}
SO_OOBINLINE = $0100; { leave received OOB data in line }
{$EXTERNALSYM SO_DONTLINGER}
SO_DONTLINGER = $ff7f;
{ Additional options. }
{$EXTERNALSYM SO_SNDBUF}
SO_SNDBUF = $1001; { send buffer size }
{$EXTERNALSYM SO_RCVBUF}
SO_RCVBUF = $1002; { receive buffer size }
{$EXTERNALSYM SO_SNDLOWAT}
SO_SNDLOWAT = $1003; { send low-water mark }
{$EXTERNALSYM SO_RCVLOWAT}
SO_RCVLOWAT = $1004; { receive low-water mark }
{$EXTERNALSYM SO_SNDTIMEO}
SO_SNDTIMEO = $1005; { send timeout }
{$EXTERNALSYM SO_RCVTIMEO}
SO_RCVTIMEO = $1006; { receive timeout }
{$EXTERNALSYM SO_ERROR}
SO_ERROR = $1007; { get error status and clear }
{$EXTERNALSYM SO_TYPE}
SO_TYPE = $1008; { get socket type }
{ Options for connect and disconnect data and options. Used only by
non-TCP/IP transports such as DECNet, OSI TP4, etc. }
{$EXTERNALSYM SO_CONNDATA}
SO_CONNDATA = $7000;
{$EXTERNALSYM SO_CONNOPT}
SO_CONNOPT = $7001;
{$EXTERNALSYM SO_DISCDATA}
SO_DISCDATA = $7002;
{$EXTERNALSYM SO_DISCOPT}
SO_DISCOPT = $7003;
{$EXTERNALSYM SO_CONNDATALEN}
SO_CONNDATALEN = $7004;
{$EXTERNALSYM SO_CONNOPTLEN}
SO_CONNOPTLEN = $7005;
{$EXTERNALSYM SO_DISCDATALEN}
SO_DISCDATALEN = $7006;
{$EXTERNALSYM SO_DISCOPTLEN}
SO_DISCOPTLEN = $7007;
{ Option for opening sockets for synchronous access. }
{$EXTERNALSYM SO_OPENTYPE}
SO_OPENTYPE = $7008;
{$EXTERNALSYM SO_SYNCHRONOUS_ALERT}
SO_SYNCHRONOUS_ALERT = $10;
{$EXTERNALSYM SO_SYNCHRONOUS_NONALERT}
SO_SYNCHRONOUS_NONALERT = $20;
{ Other NT-specific options. }
{$EXTERNALSYM SO_MAXDG}
SO_MAXDG = $7009;
{$EXTERNALSYM SO_MAXPATHDG}
SO_MAXPATHDG = $700A;
{$EXTERNALSYM SO_UPDATE_ACCEPT_CONTEXT}
SO_UPDATE_ACCEPT_CONTEXT = $700B;
{$EXTERNALSYM SO_CONNECT_TIME}
SO_CONNECT_TIME = $700C;
{ TCP options. }
{$EXTERNALSYM TCP_NODELAY}
TCP_NODELAY = $0001;
{$EXTERNALSYM TCP_BSDURGENT}
TCP_BSDURGENT = $7000;
{ Address families. }
{$EXTERNALSYM AF_UNSPEC}
AF_UNSPEC = 0; { unspecified }
{$EXTERNALSYM AF_UNIX}
AF_UNIX = 1; { local to host (pipes, portals) }
{$EXTERNALSYM AF_INET}
AF_INET = 2; { internetwork: UDP, TCP, etc. }
{$EXTERNALSYM AF_IMPLINK}
AF_IMPLINK = 3; { arpanet imp addresses }
{$EXTERNALSYM AF_PUP}
AF_PUP = 4; { pup protocols: e.g. BSP }
{$EXTERNALSYM AF_CHAOS}
AF_CHAOS = 5; { mit CHAOS protocols }
{$EXTERNALSYM AF_IPX}
AF_IPX = 6; { IPX and SPX }
{$EXTERNALSYM AF_NS}
AF_NS = 6; { XEROX NS protocols }
{$EXTERNALSYM AF_ISO}
AF_ISO = 7; { ISO protocols }
{$EXTERNALSYM AF_OSI}
AF_OSI = AF_ISO; { OSI is ISO }
{$EXTERNALSYM AF_ECMA}
AF_ECMA = 8; { european computer manufacturers }
{$EXTERNALSYM AF_DATAKIT}
AF_DATAKIT = 9; { datakit protocols }
{$EXTERNALSYM AF_CCITT}
AF_CCITT = 10; { CCITT protocols, X.25 etc }
{$EXTERNALSYM AF_SNA}
AF_SNA = 11; { IBM SNA }
{$EXTERNALSYM AF_DECnet}
AF_DECnet = 12; { DECnet }
{$EXTERNALSYM AF_DLI}
AF_DLI = 13; { Direct data link interface }
{$EXTERNALSYM AF_LAT}
AF_LAT = 14; { LAT }
{$EXTERNALSYM AF_HYLINK}
AF_HYLINK = 15; { NSC Hyperchannel }
{$EXTERNALSYM AF_APPLETALK}
AF_APPLETALK = 16; { AppleTalk }
{$EXTERNALSYM AF_NETBIOS}
AF_NETBIOS = 17; { NetBios-style addresses }
{$EXTERNALSYM AF_VOICEVIEW}
AF_VOICEVIEW = 18; { VoiceView }
{$EXTERNALSYM AF_FIREFOX}
AF_FIREFOX = 19; { FireFox }
{$EXTERNALSYM AF_UNKNOWN1}
AF_UNKNOWN1 = 20; { Somebody is using this! }
{$EXTERNALSYM AF_BAN}
AF_BAN = 21; { Banyan }
{$EXTERNALSYM AF_MAX}
AF_MAX = 22;
type
{ Structure used by kernel to store most addresses. }
{$EXTERNALSYM PSOCKADDR}
PSOCKADDR = ^TSockAddr;
{$EXTERNALSYM TSockAddr}
TSockAddr = sockaddr_in;
{ Structure used by kernel to pass protocol information in raw sockets. }
PSockProto = ^TSockProto;
{$EXTERNALSYM sockproto}
sockproto = record
sp_family: u_short;
sp_protocol: u_short;
end;
TSockProto = sockproto;
const
{ Protocol families, same as address families for now. }
{$EXTERNALSYM PF_UNSPEC}
PF_UNSPEC = AF_UNSPEC;
{$EXTERNALSYM PF_UNIX}
PF_UNIX = AF_UNIX;
{$EXTERNALSYM PF_INET}
PF_INET = AF_INET;
{$EXTERNALSYM PF_IMPLINK}
PF_IMPLINK = AF_IMPLINK;
{$EXTERNALSYM PF_PUP}
PF_PUP = AF_PUP;
{$EXTERNALSYM PF_CHAOS}
PF_CHAOS = AF_CHAOS;
{$EXTERNALSYM PF_NS}
PF_NS = AF_NS;
{$EXTERNALSYM PF_IPX}
PF_IPX = AF_IPX;
{$EXTERNALSYM PF_ISO}
PF_ISO = AF_ISO;
{$EXTERNALSYM PF_OSI}
PF_OSI = AF_OSI;
{$EXTERNALSYM PF_ECMA}
PF_ECMA = AF_ECMA;
{$EXTERNALSYM PF_DATAKIT}
PF_DATAKIT = AF_DATAKIT;
{$EXTERNALSYM PF_CCITT}
PF_CCITT = AF_CCITT;
{$EXTERNALSYM PF_SNA}
PF_SNA = AF_SNA;
{$EXTERNALSYM PF_DECnet}
PF_DECnet = AF_DECnet;
{$EXTERNALSYM PF_DLI}
PF_DLI = AF_DLI;
{$EXTERNALSYM PF_LAT}
PF_LAT = AF_LAT;
{$EXTERNALSYM PF_HYLINK}
PF_HYLINK = AF_HYLINK;
{$EXTERNALSYM PF_APPLETALK}
PF_APPLETALK = AF_APPLETALK;
{$EXTERNALSYM PF_VOICEVIEW}
PF_VOICEVIEW = AF_VOICEVIEW;
{$EXTERNALSYM PF_FIREFOX}
PF_FIREFOX = AF_FIREFOX;
{$EXTERNALSYM PF_UNKNOWN1}
PF_UNKNOWN1 = AF_UNKNOWN1;
{$EXTERNALSYM PF_BAN}
PF_BAN = AF_BAN;
{$EXTERNALSYM PF_MAX}
PF_MAX = AF_MAX;
type
{ Structure used for manipulating linger option. }
PLinger = ^TLinger;
{$EXTERNALSYM linger}
linger = record
l_onoff: u_short;
l_linger: u_short;
end;
TLinger = linger;
const
{ Level number for (get/set)sockopt() to apply to socket itself. }
{$EXTERNALSYM SOL_SOCKET}
SOL_SOCKET = $ffff; {options for socket level }
{ Maximum queue length specifiable by listen. }
{$EXTERNALSYM SOMAXCONN}
SOMAXCONN = 5;
{$EXTERNALSYM MSG_OOB}
MSG_OOB = $1; {process out-of-band data }
{$EXTERNALSYM MSG_PEEK}
MSG_PEEK = $2; {peek at incoming message }
{$EXTERNALSYM MSG_DONTROUTE}
MSG_DONTROUTE = $4; {send without using routing tables }
{$EXTERNALSYM MSG_MAXIOVLEN}
MSG_MAXIOVLEN = 16;
{$EXTERNALSYM MSG_PARTIAL}
MSG_PARTIAL = $8000; {partial send or recv for message xport }
{ Define constant based on rfc883, used by gethostbyxxxx() calls. }
{$EXTERNALSYM MAXGETHOSTSTRUCT}
MAXGETHOSTSTRUCT = 1024;
{ Define flags to be used with the WSAAsyncSelect() call. }
{$EXTERNALSYM FD_READ}
FD_READ = $01;
{$EXTERNALSYM FD_WRITE}
FD_WRITE = $02;
{$EXTERNALSYM FD_OOB}
FD_OOB = $04;
{$EXTERNALSYM FD_ACCEPT}
FD_ACCEPT = $08;
{$EXTERNALSYM FD_CONNECT}
FD_CONNECT = $10;
{$EXTERNALSYM FD_CLOSE}
FD_CLOSE = $20;
{ All Windows Sockets error constants are biased by WSABASEERR from the "normal" }
{$EXTERNALSYM WSABASEERR}
WSABASEERR = 10000;
{ Windows Sockets definitions of regular Microsoft C error constants }
{$EXTERNALSYM WSAEINTR}
WSAEINTR = (WSABASEERR+4);
{$EXTERNALSYM WSAEBADF}
WSAEBADF = (WSABASEERR+9);
{$EXTERNALSYM WSAEACCES}
WSAEACCES = (WSABASEERR+13);
{$EXTERNALSYM WSAEFAULT}
WSAEFAULT = (WSABASEERR+14);
{$EXTERNALSYM WSAEINVAL}
WSAEINVAL = (WSABASEERR+22);
{$EXTERNALSYM WSAEMFILE}
WSAEMFILE = (WSABASEERR+24);
{ Windows Sockets definitions of regular Berkeley error constants }
{$EXTERNALSYM WSAEWOULDBLOCK}
WSAEWOULDBLOCK = (WSABASEERR+35);
{$EXTERNALSYM WSAEINPROGRESS}
WSAEINPROGRESS = (WSABASEERR+36);
{$EXTERNALSYM WSAEALREADY}
WSAEALREADY = (WSABASEERR+37);
{$EXTERNALSYM WSAENOTSOCK}
WSAENOTSOCK = (WSABASEERR+38);
{$EXTERNALSYM WSAEDESTADDRREQ}
WSAEDESTADDRREQ = (WSABASEERR+39);
{$EXTERNALSYM WSAEMSGSIZE}
WSAEMSGSIZE = (WSABASEERR+40);
{$EXTERNALSYM WSAEPROTOTYPE}
WSAEPROTOTYPE = (WSABASEERR+41);
{$EXTERNALSYM WSAENOPROTOOPT}
WSAENOPROTOOPT = (WSABASEERR+42);
{$EXTERNALSYM WSAEPROTONOSUPPORT}
WSAEPROTONOSUPPORT = (WSABASEERR+43);
{$EXTERNALSYM WSAESOCKTNOSUPPORT}
WSAESOCKTNOSUPPORT = (WSABASEERR+44);
{$EXTERNALSYM WSAEOPNOTSUPP}
WSAEOPNOTSUPP = (WSABASEERR+45);
{$EXTERNALSYM WSAEPFNOSUPPORT}
WSAEPFNOSUPPORT = (WSABASEERR+46);
{$EXTERNALSYM WSAEAFNOSUPPORT}
WSAEAFNOSUPPORT = (WSABASEERR+47);
{$EXTERNALSYM WSAEADDRINUSE}
WSAEADDRINUSE = (WSABASEERR+48);
{$EXTERNALSYM WSAEADDRNOTAVAIL}
WSAEADDRNOTAVAIL = (WSABASEERR+49);
{$EXTERNALSYM WSAENETDOWN}
WSAENETDOWN = (WSABASEERR+50);
{$EXTERNALSYM WSAENETUNREACH}
WSAENETUNREACH = (WSABASEERR+51);
{$EXTERNALSYM WSAENETRESET}
WSAENETRESET = (WSABASEERR+52);
{$EXTERNALSYM WSAECONNABORTED}
WSAECONNABORTED = (WSABASEERR+53);
{$EXTERNALSYM WSAECONNRESET}
WSAECONNRESET = (WSABASEERR+54);
{$EXTERNALSYM WSAENOBUFS}
WSAENOBUFS = (WSABASEERR+55);
{$EXTERNALSYM WSAEISCONN}
WSAEISCONN = (WSABASEERR+56);
{$EXTERNALSYM WSAENOTCONN}
WSAENOTCONN = (WSABASEERR+57);
{$EXTERNALSYM WSAESHUTDOWN}
WSAESHUTDOWN = (WSABASEERR+58);
{$EXTERNALSYM WSAETOOMANYREFS}
WSAETOOMANYREFS = (WSABASEERR+59);
{$EXTERNALSYM WSAETIMEDOUT}
WSAETIMEDOUT = (WSABASEERR+60);
{$EXTERNALSYM WSAECONNREFUSED}
WSAECONNREFUSED = (WSABASEERR+61);
{$EXTERNALSYM WSAELOOP}
WSAELOOP = (WSABASEERR+62);
{$EXTERNALSYM WSAENAMETOOLONG}
WSAENAMETOOLONG = (WSABASEERR+63);
{$EXTERNALSYM WSAEHOSTDOWN}
WSAEHOSTDOWN = (WSABASEERR+64);
{$EXTERNALSYM WSAEHOSTUNREACH}
WSAEHOSTUNREACH = (WSABASEERR+65);
{$EXTERNALSYM WSAENOTEMPTY}
WSAENOTEMPTY = (WSABASEERR+66);
{$EXTERNALSYM WSAEPROCLIM}
WSAEPROCLIM = (WSABASEERR+67);
{$EXTERNALSYM WSAEUSERS}
WSAEUSERS = (WSABASEERR+68);
{$EXTERNALSYM WSAEDQUOT}
WSAEDQUOT = (WSABASEERR+69);
{$EXTERNALSYM WSAESTALE}
WSAESTALE = (WSABASEERR+70);
{$EXTERNALSYM WSAEREMOTE}
WSAEREMOTE = (WSABASEERR+71);
{$EXTERNALSYM WSAEDISCON}
WSAEDISCON = (WSABASEERR+101);
{ Extended Windows Sockets error constant definitions }
{$EXTERNALSYM WSASYSNOTREADY}
WSASYSNOTREADY = (WSABASEERR+91);
{$EXTERNALSYM WSAVERNOTSUPPORTED}
WSAVERNOTSUPPORTED = (WSABASEERR+92);
{$EXTERNALSYM WSANOTINITIALISED}
WSANOTINITIALISED = (WSABASEERR+93);
{ Error return codes from gethostbyname() and gethostbyaddr()
(when using the resolver). Note that these errors are
retrieved via WSAGetLastError() and must therefore follow
the rules for avoiding clashes with error numbers from
specific implementations or language run-time systems.
For this reason the codes are based at WSABASEERR+1001.
Note also that [WSA]NO_ADDRESS is defined only for
compatibility purposes. }
{ Authoritative Answer: Host not found }
{$EXTERNALSYM WSAHOST_NOT_FOUND}
WSAHOST_NOT_FOUND = (WSABASEERR+1001);
{$EXTERNALSYM HOST_NOT_FOUND}
HOST_NOT_FOUND = WSAHOST_NOT_FOUND;
{ Non-Authoritative: Host not found, or SERVERFAIL }
{$EXTERNALSYM WSATRY_AGAIN}
WSATRY_AGAIN = (WSABASEERR+1002);
{$EXTERNALSYM TRY_AGAIN}
TRY_AGAIN = WSATRY_AGAIN;
{ Non recoverable errors, FORMERR, REFUSED, NOTIMP }
{$EXTERNALSYM WSANO_RECOVERY}
WSANO_RECOVERY = (WSABASEERR+1003);
{$EXTERNALSYM NO_RECOVERY}
NO_RECOVERY = WSANO_RECOVERY;
{ Valid name, no data record of requested type }
{$EXTERNALSYM WSANO_DATA}
WSANO_DATA = (WSABASEERR+1004);
{$EXTERNALSYM NO_DATA}
NO_DATA = WSANO_DATA;
{ no address, look for MX record }
{$EXTERNALSYM WSANO_ADDRESS}
WSANO_ADDRESS = WSANO_DATA;
{$EXTERNALSYM NO_ADDRESS}
NO_ADDRESS = WSANO_ADDRESS;
{ Windows Sockets errors redefined as regular Berkeley error constants.
These are commented out in Windows NT to avoid conflicts with errno.h.
Use the WSA constants instead. }
{$EXTERNALSYM EWOULDBLOCK}
EWOULDBLOCK = WSAEWOULDBLOCK;
{$EXTERNALSYM EINPROGRESS}
EINPROGRESS = WSAEINPROGRESS;
{$EXTERNALSYM EALREADY}
EALREADY = WSAEALREADY;
{$EXTERNALSYM ENOTSOCK}
ENOTSOCK = WSAENOTSOCK;
{$EXTERNALSYM EDESTADDRREQ}
EDESTADDRREQ = WSAEDESTADDRREQ;
{$EXTERNALSYM EMSGSIZE}
EMSGSIZE = WSAEMSGSIZE;
{$EXTERNALSYM EPROTOTYPE}
EPROTOTYPE = WSAEPROTOTYPE;
{$EXTERNALSYM ENOPROTOOPT}
ENOPROTOOPT = WSAENOPROTOOPT;
{$EXTERNALSYM EPROTONOSUPPORT}
EPROTONOSUPPORT = WSAEPROTONOSUPPORT;
{$EXTERNALSYM ESOCKTNOSUPPORT}
ESOCKTNOSUPPORT = WSAESOCKTNOSUPPORT;
{$EXTERNALSYM EOPNOTSUPP}
EOPNOTSUPP = WSAEOPNOTSUPP;
{$EXTERNALSYM EPFNOSUPPORT}
EPFNOSUPPORT = WSAEPFNOSUPPORT;
{$EXTERNALSYM EAFNOSUPPORT}
EAFNOSUPPORT = WSAEAFNOSUPPORT;
{$EXTERNALSYM EADDRINUSE}
EADDRINUSE = WSAEADDRINUSE;
{$EXTERNALSYM EADDRNOTAVAIL}
EADDRNOTAVAIL = WSAEADDRNOTAVAIL;
{$EXTERNALSYM ENETDOWN}
ENETDOWN = WSAENETDOWN;
{$EXTERNALSYM ENETUNREACH}
ENETUNREACH = WSAENETUNREACH;
{$EXTERNALSYM ENETRESET}
ENETRESET = WSAENETRESET;
{$EXTERNALSYM ECONNABORTED}
ECONNABORTED = WSAECONNABORTED;
{$EXTERNALSYM ECONNRESET}
ECONNRESET = WSAECONNRESET;
{$EXTERNALSYM ENOBUFS}
ENOBUFS = WSAENOBUFS;
{$EXTERNALSYM EISCONN}
EISCONN = WSAEISCONN;
{$EXTERNALSYM ENOTCONN}
ENOTCONN = WSAENOTCONN;
{$EXTERNALSYM ESHUTDOWN}
ESHUTDOWN = WSAESHUTDOWN;
{$EXTERNALSYM ETOOMANYREFS}
ETOOMANYREFS = WSAETOOMANYREFS;
{$EXTERNALSYM ETIMEDOUT}
ETIMEDOUT = WSAETIMEDOUT;
{$EXTERNALSYM ECONNREFUSED}
ECONNREFUSED = WSAECONNREFUSED;
{$EXTERNALSYM ELOOP}
ELOOP = WSAELOOP;
{$EXTERNALSYM ENAMETOOLONG}
ENAMETOOLONG = WSAENAMETOOLONG;
{$EXTERNALSYM EHOSTDOWN}
EHOSTDOWN = WSAEHOSTDOWN;
{$EXTERNALSYM EHOSTUNREACH}
EHOSTUNREACH = WSAEHOSTUNREACH;
{$EXTERNALSYM ENOTEMPTY}
ENOTEMPTY = WSAENOTEMPTY;
{$EXTERNALSYM EPROCLIM}
EPROCLIM = WSAEPROCLIM;
{$EXTERNALSYM EUSERS}
EUSERS = WSAEUSERS;
{$EXTERNALSYM EDQUOT}
EDQUOT = WSAEDQUOT;
{$EXTERNALSYM ESTALE}
ESTALE = WSAESTALE;
{$EXTERNALSYM EREMOTE}
EREMOTE = WSAEREMOTE;
{ Socket function prototypes }
{$EXTERNALSYM accept}
function accept(s: TSocket; addr: PSockAddr; addrlen: PInteger): TSocket; stdcall;
{$EXTERNALSYM bind}
function bind(s: TSocket; var addr: TSockAddr; namelen: Integer): Integer; stdcall;
{$EXTERNALSYM closesocket}
function closesocket(s: TSocket): Integer; stdcall;
{$EXTERNALSYM connect}
function connect(s: TSocket; var name: TSockAddr; namelen: Integer): Integer; stdcall;
{$EXTERNALSYM ioctlsocket}
function ioctlsocket(s: TSocket; cmd: DWORD; var arg: u_long): Integer; stdcall;
{$EXTERNALSYM getpeername}
function getpeername(s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; stdcall;
{$EXTERNALSYM getsockname}
function getsockname(s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; stdcall;
{$EXTERNALSYM getsockopt}
function getsockopt(s: TSocket; level, optname: Integer; optval: PChar; var optlen: Integer): Integer; stdcall;
{$EXTERNALSYM htonl}
function htonl(hostlong: u_long): u_long; stdcall;
{$EXTERNALSYM htons}
function htons(hostshort: u_short): u_short; stdcall;
{$EXTERNALSYM inet_addr}
function inet_addr(cp: PChar): u_long; stdcall; {PInAddr;} { TInAddr }
{$EXTERNALSYM inet_ntoa}
function inet_ntoa(inaddr: TInAddr): PChar; stdcall;
{$EXTERNALSYM listen}
function listen(s: TSocket; backlog: Integer): Integer; stdcall;
{$EXTERNALSYM ntohl}
function ntohl(netlong: u_long): u_long; stdcall;
{$EXTERNALSYM ntohs}
function ntohs(netshort: u_short): u_short; stdcall;
{$EXTERNALSYM recv}
function recv(s: TSocket; var Buf; len, flags: Integer): Integer; stdcall;
{$EXTERNALSYM recvfrom}
function recvfrom(s: TSocket; var Buf; len, flags: Integer;
var from: TSockAddr; var fromlen: Integer): Integer; stdcall;
{$EXTERNALSYM select}
function select(nfds: Integer; readfds, writefds, exceptfds: PFDSet;
timeout: PTimeVal): Longint; stdcall;
{$EXTERNALSYM send}
function send(s: TSocket; var Buf; len, flags: Integer): Integer; stdcall;
{$EXTERNALSYM sendto}
function sendto(s: TSocket; var Buf; len, flags: Integer; var addrto: TSockAddr;
tolen: Integer): Integer; stdcall;
{$EXTERNALSYM setsockopt}
function setsockopt(s: TSocket; level, optname: Integer; optval: PChar;
optlen: Integer): Integer; stdcall;
{$EXTERNALSYM shutdown}
function shutdown(s: TSocket; how: Integer): Integer; stdcall;
{$EXTERNALSYM socket}
function socket(af, Struct, protocol: Integer): TSocket; stdcall;
{$EXTERNALSYM gethostbyaddr}
function gethostbyaddr(addr: Pointer; len, Struct: Integer): PHostEnt; stdcall;
{$EXTERNALSYM gethostbyname}
function gethostbyname(name: PChar): PHostEnt; stdcall;
{$EXTERNALSYM gethostname}
function gethostname(name: PChar; len: Integer): Integer; stdcall;
{$EXTERNALSYM getservbyport}
function getservbyport(port: Integer; proto: PChar): PServEnt; stdcall;
{$EXTERNALSYM getservbyname}
function getservbyname(name, proto: PChar): PServEnt; stdcall;
{$EXTERNALSYM getprotobynumber}
function getprotobynumber(proto: Integer): PProtoEnt; stdcall;
{$EXTERNALSYM getprotobyname}
function getprotobyname(name: PChar): PProtoEnt; stdcall;
{$EXTERNALSYM WSAStartup}
function WSAStartup(wVersionRequired: word; var WSData: TWSAData): Integer; stdcall;
{$EXTERNALSYM WSACleanup}
function WSACleanup: Integer; stdcall;
{$EXTERNALSYM WSASetLastError}
procedure WSASetLastError(iError: Integer); stdcall;
{$EXTERNALSYM WSAGetLastError}
function WSAGetLastError: Integer; stdcall;
{$EXTERNALSYM WSAIsBlocking}
function WSAIsBlocking: BOOL; stdcall;
{$EXTERNALSYM WSAUnhookBlockingHook}
function WSAUnhookBlockingHook: Integer; stdcall;
{$EXTERNALSYM WSASetBlockingHook}
function WSASetBlockingHook(lpBlockFunc: TFarProc): TFarProc; stdcall;
{$EXTERNALSYM WSACancelBlockingCall}
function WSACancelBlockingCall: Integer; stdcall;
{$EXTERNALSYM WSAAsyncGetServByName}
function WSAAsyncGetServByName(HWindow: HWND; wMsg: u_int;
name, proto, buf: PChar; buflen: Integer): THandle; stdcall;
{$EXTERNALSYM WSAAsyncGetServByPort}
function WSAAsyncGetServByPort( HWindow: HWND; wMsg, port: u_int;
proto, buf: PChar; buflen: Integer): THandle; stdcall;
{$EXTERNALSYM WSAAsyncGetProtoByName}
function WSAAsyncGetProtoByName(HWindow: HWND; wMsg: u_int;
name, buf: PChar; buflen: Integer): THandle; stdcall;
{$EXTERNALSYM WSAAsyncGetProtoByNumber}
function WSAAsyncGetProtoByNumber(HWindow: HWND; wMsg: u_int; number: Integer;
buf: PChar; buflen: Integer): THandle; stdcall;
{$EXTERNALSYM WSAAsyncGetHostByName}
function WSAAsyncGetHostByName(HWindow: HWND; wMsg: u_int;
name, buf: PChar; buflen: Integer): THandle; stdcall;
{$EXTERNALSYM WSAAsyncGetHostByAddr}
function WSAAsyncGetHostByAddr(HWindow: HWND; wMsg: u_int; addr: PChar;
len, Struct: Integer; buf: PChar; buflen: Integer): THandle; stdcall;
{$EXTERNALSYM WSACancelAsyncRequest}
function WSACancelAsyncRequest(hAsyncTaskHandle: THandle): Integer; stdcall;
{$EXTERNALSYM WSAAsyncSelect}
function WSAAsyncSelect(s: TSocket; HWindow: HWND; wMsg: u_int; lEvent: Longint): Integer; stdcall;
{$EXTERNALSYM WSARecvEx}
function WSARecvEx(s: TSocket; var buf; len: Integer; var flags: Integer): Integer; stdcall;
{$EXTERNALSYM __WSAFDIsSet}
function __WSAFDIsSet(s: TSocket; var FDSet: TFDSet): Bool; stdcall;
{$EXTERNALSYM TransmitFile}
function TransmitFile(hSocket: TSocket; hFile: THandle; nNumberOfBytesToWrite: DWORD;
nNumberOfBytesPerSend: DWORD; lpOverlapped: POverlapped;
lpTransmitBuffers: PTransmitFileBuffers; dwReserved: DWORD): BOOL; stdcall;
{$EXTERNALSYM AcceptEx}
function AcceptEx(sListenSocket, sAcceptSocket: TSocket;
lpOutputBuffer: Pointer; dwReceiveDataLength, dwLocalAddressLength,
dwRemoteAddressLength: DWORD; var lpdwBytesReceived: DWORD;
lpOverlapped: POverlapped): BOOL; stdcall;
{$EXTERNALSYM GetAcceptExSockaddrs}
procedure GetAcceptExSockaddrs(lpOutputBuffer: Pointer;
dwReceiveDataLength, dwLocalAddressLength, dwRemoteAddressLength: DWORD;
var LocalSockaddr: TSockAddr; var LocalSockaddrLength: Integer;
var RemoteSockaddr: TSockAddr; var RemoteSockaddrLength: Integer); stdcall;
{$EXTERNALSYM WSAMakeSyncReply}
function WSAMakeSyncReply(Buflen, Error: Word): Longint;
{$EXTERNALSYM WSAMakeSelectReply}
function WSAMakeSelectReply(Event, Error: Word): Longint;
{$EXTERNALSYM WSAGetAsyncBuflen}
function WSAGetAsyncBuflen(Param: Longint): Word;
{$EXTERNALSYM WSAGetAsyncError}
function WSAGetAsyncError(Param: Longint): Word;
{$EXTERNALSYM WSAGetSelectEvent}
function WSAGetSelectEvent(Param: Longint): Word;
{$EXTERNALSYM WSAGetSelectError}
function WSAGetSelectError(Param: Longint): Word;
{$EXTERNALSYM FD_CLR}
procedure FD_CLR(Socket: TSocket; var FDSet: TFDSet);
{$EXTERNALSYM FD_ISSET}
function FD_ISSET(Socket: TSocket; var FDSet: TFDSet): Boolean;
{$EXTERNALSYM FD_SET}
procedure FD_SET(Socket: TSocket; var FDSet: TFDSet); // renamed due to conflict with fd_set (above)
{$EXTERNALSYM FD_ZERO}
procedure FD_ZERO(var FDSet: TFDSet);
implementation
const
winsocket = 'wsock32.dll';
function WSAMakeSyncReply;
begin
WSAMakeSyncReply:= MakeLong(Buflen, Error);
end;
function WSAMakeSelectReply;
begin
WSAMakeSelectReply:= MakeLong(Event, Error);
end;
function WSAGetAsyncBuflen;
begin
WSAGetAsyncBuflen:= LOWORD(Param);
end;
function WSAGetAsyncError;
begin
WSAGetAsyncError:= HIWORD(Param);
end;
function WSAGetSelectEvent;
begin
WSAGetSelectEvent:= LOWORD(Param);
end;
function WSAGetSelectError;
begin
WSAGetSelectError:= HIWORD(Param);
end;
procedure FD_CLR(Socket: TSocket; var FDSet: TFDSet);
var
I: Integer;
begin
I := 0;
while I < FDSet.fd_count do
begin
if FDSet.fd_array[I] = Socket then
begin
while I < FDSet.fd_count - 1 do
begin
FDSet.fd_array[I] := FDSet.fd_array[I + 1];
Inc(I);
end;
Dec(FDSet.fd_count);
Break;
end;
Inc(I);
end;
end;
function FD_ISSET(Socket: TSocket; var FDSet: TFDSet): Boolean;
begin
Result := __WSAFDIsSet(Socket, FDSet);
end;
procedure FD_SET(Socket: TSocket; var FDSet: TFDSet);
begin
if FDSet.fd_count < FD_SETSIZE then
begin
FDSet.fd_array[FDSet.fd_count] := Socket;
Inc(FDSet.fd_count);
end;
end;
procedure FD_ZERO(var FDSet: TFDSet);
begin
FDSet.fd_count := 0;
end;
function accept; external winsocket name 'accept';
function bind; external winsocket name 'bind';
function closesocket; external winsocket name 'closesocket';
function connect; external winsocket name 'connect';
function getpeername; external winsocket name 'getpeername';
function getsockname; external winsocket name 'getsockname';
function getsockopt; external winsocket name 'getsockopt';
function htonl; external winsocket name 'htonl';
function htons; external winsocket name 'htons';
function inet_addr; external winsocket name 'inet_addr';
function inet_ntoa; external winsocket name 'inet_ntoa';
function ioctlsocket; external winsocket name 'ioctlsocket';
function listen; external winsocket name 'listen';
function ntohl; external winsocket name 'ntohl';
function ntohs; external winsocket name 'ntohs';
function recv; external winsocket name 'recv';
function recvfrom; external winsocket name 'recvfrom';
function select; external winsocket name 'select';
function send; external winsocket name 'send';
function sendto; external winsocket name 'sendto';
function setsockopt; external winsocket name 'setsockopt';
function shutdown; external winsocket name 'shutdown';
function socket; external winsocket name 'socket';
function gethostbyaddr; external winsocket name 'gethostbyaddr';
function gethostbyname; external winsocket name 'gethostbyname';
function getprotobyname; external winsocket name 'getprotobyname';
function getprotobynumber; external winsocket name 'getprotobynumber';
function getservbyname; external winsocket name 'getservbyname';
function getservbyport; external winsocket name 'getservbyport';
function gethostname; external winsocket name 'gethostname';
function WSAAsyncSelect; external winsocket name 'WSAAsyncSelect';
function WSARecvEx; external winsocket name 'WSARecvEx';
function WSAAsyncGetHostByAddr; external winsocket name 'WSAAsyncGetHostByAddr';
function WSAAsyncGetHostByName; external winsocket name 'WSAAsyncGetHostByName';
function WSAAsyncGetProtoByNumber; external winsocket name 'WSAAsyncGetProtoByNumber';
function WSAAsyncGetProtoByName; external winsocket name 'WSAAsyncGetProtoByName';
function WSAAsyncGetServByPort; external winsocket name 'WSAAsyncGetServByPort';
function WSAAsyncGetServByName; external winsocket name 'WSAAsyncGetServByName';
function WSACancelAsyncRequest; external winsocket name 'WSACancelAsyncRequest';
function WSASetBlockingHook; external winsocket name 'WSASetBlockingHook';
function WSAUnhookBlockingHook; external winsocket name 'WSAUnhookBlockingHook';
function WSAGetLastError; external winsocket name 'WSAGetLastError';
procedure WSASetLastError; external winsocket name 'WSASetLastError';
function WSACancelBlockingCall; external winsocket name 'WSACancelBlockingCall';
function WSAIsBlocking; external winsocket name 'WSAIsBlocking';
function WSAStartup; external winsocket name 'WSAStartup';
function WSACleanup; external winsocket name 'WSACleanup';
function __WSAFDIsSet; external winsocket name '__WSAFDIsSet';
function TransmitFile; external winsocket name 'TransmitFile';
function AcceptEx; external winsocket name 'AcceptEx';
procedure GetAcceptExSockaddrs; external winsocket name 'GetAcceptExSockaddrs';
end.
|
unit Controller.ControllerUser;
interface
procedure Registry;
implementation
uses
Horse,
Services.SeviceUser,
DataSet.Serialize,
System.JSON,
Data.DB;
procedure DoUserListAll(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LService: TServiceUser;
begin
LService := TServiceUser.Create(Nil);
try
Res.Send(LService.listAll.ToJSONArray);
finally
LService.Free;
end;
end;
procedure DoGet(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LId : String;
LService : TServiceUser;
begin
LService := TServiceUser.Create(nil);
try
LId := Req.Params.Items['id'];
if LService.GetById(LId).IsEmpty then
Res.Send( EHorseException.;
raise EHorseException.Create(THTTPStatus.NotFound, 'Not Found');
Res.Send(LService.QryUser.ToJSONObject());
finally
LService.Free;
end;
end;
procedure DoUserPost(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LService: TServiceUser;
LData: TJSONObject;
begin
LService := TServiceUser.Create(nil);
try
LData := Req.Body<TJSONObject>;
if LService.Append(LData) then
Res.Send(LService.AppendUser.ToJSONObject);
finally
LService.Free;
end;
end;
procedure DoUsersDelete(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LId : String;
LService : TServiceUser;
begin
LService := TServiceUser.Create(nil);
try
LId := Req.Params.Items['id'];
if LService.GetById(LId).IsEmpty then
raise EHorseException.Create(THTTPStatus.NotFound, 'Not Found');
if LService.Delete then
Res.Status(THTTPStatus.NoContent);
finally
LService.Free;
end;
end;
procedure Registry;
begin
THorse.Get('/users', DoUserListAll);
THorse.Get('/users/:id', DoGet);
THorse.Post('/users', DoUserPost);
THorse.Delete('/users/:id', DoUsersDelete);
end;
end.
|
program HelloWorld;
var
s: string;
x, y: integer;
z: real; // 小数
a: char; // 1文字
flag: boolean;
begin
s := 'hello';
writeln(s);
x := 10;
writeln(x);
y := -20;
writeln(y);
z := 10.2345;
writeln(z);
a := 'A';
writeln(a);
flag := true;
writeln(flag);
end.
|
unit UnProduto;
interface
uses Classes;
type
TipoDeProduto = (tdpComprado, tdpProduzido);
TProduto = class
private
FCodigo: string;
FDescricao: string;
{ TODO: implementar tipo de produto fabricado ou comprado
FTipoDeProduto: TipoDeProduto;
}
FValor: Real;
public
constructor Create(const Codigo: string; const Descricao: string; const Valor: Real); reintroduce;
function GetCodigo: string;
function GetDescricao: string;
function GetValor: Real;
end;
TItem = class
private
FIdentificacao: string;
FProduto: TProduto;
FNumeroPedidos: Integer;
FPedidos: array of Real;
public
function AumentarQuantidadeEm(const Aumento: Real): TItem;
function Identificacao(const Identificacao: string): TItem;
function ObterIdentificacao: string;
function ObterProduto: TProduto;
function ObterQuantidade: Real;
function Produto(const Produto: TProduto): TItem;
function Quantidade(const Quantidade: Integer): TItem;
end;
implementation
{ TProduto }
constructor TProduto.Create(const Codigo, Descricao: string; const Valor: Real);
begin
Self.FCodigo := Codigo;
Self.FDescricao := Descricao;
Self.FValor := Valor;
end;
function TProduto.GetCodigo: string;
begin
Result := Self.FCodigo
end;
function TProduto.GetDescricao: string;
begin
Result := Self.FDescricao
end;
function TProduto.GetValor: Real;
begin
Result := Self.FValor
end;
{ TItem }
function TItem.AumentarQuantidadeEm(const Aumento: Real): TItem;
begin
Self.FNumeroPedidos := Self.FNumeroPedidos + 1;
SetLength(Self.FPedidos, Self.FNumeroPedidos);
Self.FPedidos[Self.FNumeroPedidos-1] := Aumento;
Result := Self;
end;
function TItem.Identificacao(const Identificacao: string): TItem;
begin
Self.FIdentificacao := Identificacao;
Result := Self;
end;
function TItem.ObterIdentificacao: string;
begin
Result := Self.FIdentificacao;
end;
function TItem.ObterProduto: TProduto;
begin
Result := Self.FProduto;
end;
function TItem.ObterQuantidade: Real;
var
i: Integer;
begin
Result := 0;
for i := 0 to Self.FNumeroPedidos-1 do
Result := Result + Self.FPedidos[i]
end;
function TItem.Produto(const Produto: TProduto): TItem;
begin
Self.FProduto := Produto;
Result := Self;
end;
function TItem.Quantidade(const Quantidade: Integer): TItem;
begin
Self.AumentarQuantidadeEm(Quantidade);
Result := Self;
end;
end.
|
Program Area_Rectangulo ;
var comprimento, largura, area:real;
Begin
//Pede as medidas, o comprimento e a largura
Writeln('Introduza o valor do comprimento');
Readln(comprimento);
Writeln('Introduza o valor da largura');
Readln(largura);
//Calcula a Área
area:=comprimento * largura;
//Condição. O valor do comprimento ou largura nao pode ser negativo.
if (largura<=0) or (comprimento <=0)then
Writeln('Os valores introduzidos são inválidos')
else
Writeln('A área do retângulo é: ', area:0:2);
End.
|
unit uImport;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Windows;
function FindImportLibrary(hModule: THandle; pLibName: PAnsiChar): PPointer;
function FindImportFunction(pLibrary: PPointer; pFunction: Pointer): PPointer;
function ReplaceImportFunction(pOldFunction: PPointer; pNewFunction: Pointer): Pointer;
implementation
type
{$IFDEF WIN64}
PIMAGE_NT_HEADERS = PIMAGE_NT_HEADERS64;
{$ELSE}
PIMAGE_NT_HEADERS = PIMAGE_NT_HEADERS32;
{$ENDIF}
function FindImageDirectory(hModule: THandle; Index: Integer; out DataDir: PIMAGE_DATA_DIRECTORY): Pointer;
var
pNTHeaders: PIMAGE_NT_HEADERS;
pModule: PByte absolute hModule;
pDosHeader: PIMAGE_DOS_HEADER absolute hModule;
begin
if pDosHeader^.e_magic = IMAGE_DOS_SIGNATURE then
begin
pNTHeaders := @pModule[pDosHeader^.e_lfanew];
if pNTHeaders^.Signature = IMAGE_NT_SIGNATURE then
begin
DataDir := @pNTHeaders^.OptionalHeader.DataDirectory[Index];
Result := @pModule[DataDir^.VirtualAddress];
Exit;
end;
end;
Result := nil;
end;
function FindImportLibrary(hModule: THandle; pLibName: PAnsiChar): PPointer;
var
pEnd: PByte;
pImpDir: PIMAGE_DATA_DIRECTORY;
pImpDesc: PIMAGE_IMPORT_DESCRIPTOR;
pModule: PAnsiChar absolute hModule;
begin
pImpDesc := FindImageDirectory(hModule, IMAGE_DIRECTORY_ENTRY_IMPORT, pImpDir);
if pImpDesc = nil then Exit(nil);
pEnd := PByte(pImpDesc) + pImpDir^.Size;
while (PByte(pImpDesc) < pEnd) and (pImpDesc^.FirstThunk <> 0) do
begin
if StrComp(@pModule[pImpDesc^.Name], pLibName) = 0 then
begin
Result := @pModule[pImpDesc^.FirstThunk];
Exit;
end;
Inc(pImpDesc);
end;
Result := nil;
end;
function FindImportFunction(pLibrary: PPointer; pFunction: Pointer): PPointer;
begin
while Assigned(pLibrary^) do
begin
if pLibrary^ = pFunction then Exit(pLibrary);
Inc(pLibrary);
end;
Result := nil;
end;
function ReplaceImportFunction(pOldFunction: PPointer; pNewFunction: Pointer): Pointer;
var
dwOldProtect: DWORD = 0;
begin
if VirtualProtect(pOldFunction, SizeOf(Pointer), PAGE_READWRITE, dwOldProtect) then
begin
Result := pOldFunction^;
pOldFunction^ := pNewFunction;
VirtualProtect(pOldFunction, SizeOf(Pointer), dwOldProtect, dwOldProtect);
end;
end;
end.
|
program Prog1;
type
list = ^node_data;
node_data = record
data: integer;
next: list
end;
procedure remove_second_element(l: list);
var
x: list;
begin
{ проверяем, что 2й элемент существует }
if (l <> nil) and (l^.next <> nil) then begin
x := l^.next;
if x^.next <> nil then { если 2й элемент -- не последний -- испольуем его ссылку на след-й }
l^.next := x^.next
else { иначе -- удаляем ссылку }
l^.next := nil;
dispose(x);
end;
end;
procedure pop(l: list);
var
x: list;
begin
if l <> nil then begin
{ находим предпоследний элемент. Он хранится в x }
x := l;
while l^.next <> nil do begin
x := l;
l := l^.next;
end;
dispose(x^.next); { очищаем память, выделенную под последний элемент }
x^.next := nil { удаляем ссылку на последний элемент }
end;
end;
procedure print_list(l: list);
var
x: list;
begin
while l <> nil do
begin
x := l^.next;
write(l^.data, ' ');
l := x;
end;
writeln;
end;
var
head, node: list;
i, n: integer;
begin
{ заполняем список }
head := nil;
write('Enter list length: ');
readln(n);
writeln('Enter list (one element per line)');
for i:=1 to n do
begin
new(node);
node^.next := head;
readln(node^.data);
head := node;
end;
Write('Input list is: ');
print_list(head);
{ выполняем процедуры }
write('List without 2dn element: ');
remove_second_element(head);
print_list(head);
write('List without last element: ');
pop(head);
print_list(head);
end.
|
unit DNASequenceGeneratorUnit;
{$mode objfpc}{$H+}
interface
procedure generateSequence(name: String; lengthSequence: Integer);
//constantes para verificar la longitud de entrada
const
longitud_min = 7;
longitud_max = 1000000;
//se crea un arreglo
type
vector = array [0..3] of String;
var
sequences: vector; //arreglo para guardar los valores
fileOut: TextFile; //archivo
i: Integer; //contador
randomSequence: Integer; //generador random de 0 3
longitud: Integer; //longitud digita por el usuario
nameFile: String; //nombre del archivo
//---------------------Fin de declaraciones---------------\\
implementation
uses
Classes, SysUtils;
procedure generateSequence(name: String; lengthSequence: Integer);
begin
WriteLn('Creando el archivo con el nombre: ', name);
WriteLn('Con una secuencia de largo: ', lengthSequence);
//crea el archivo
AssignFile(fileOut,name);
Rewrite(fileOut);
for i:= 1 to lengthSequence do
begin
randomSequence:= Random(4);
randomSequence:= Random(4);
//ingresa al archivo valores random del arreglo sequences
Write(fileOut,sequences[randomSequence]);
end;
//cierra el archivo
CloseFile(fileOut);
WriteLn('Termino de crear el archivo');
end;
end.
|
unit UOptions;
interface
uses Windows, SysUtils, Classes, Dialogs, forms, graphics, Messages, Types, JvJCLUtils,
Variants, pngimage, JvJVCLUtils, math;
type
TRGBArray = array[0..0] of TRGBTriple;
pRGBArray = ^TRGBArray;
const
CRLF = #10#13;
asX11ColorValues : array[0..139] of TColor =
($FFF8F0, $D7EBFA, $FFFF00, $D4FF7F, $FFFFF0, $DCF5F5, $C4E4FF, $000000,
$CDEBFF, $FF0000, $E22B8A, $2A2AA5, $87B8DE, $A09E5F, $00FF7F, $1E69D2,
$507FFF, $ED9564, $DCF8FF, $3C14DC, $FFFF00, $8B0000, $8B8B00, $0B86B8,
$A9A9A9, $006400, $6BB7BD, $8B008B, $2F6B55, $008CFF, $CC3299, $00008B,
$7A96E9, $8FBC8F, $8B3D48, $4F4F2F, $D1CE00, $D30094, $9314FF, $FFBF00,
$696969, $FF901E, $2222B2, $F0FAFF, $228B22, $FF00FF, $DCDCDC, $FFF8F8,
$00D7FF, $20A5DA, $808080, $008000, $2FFFAD, $F0FFF0, $B469FF, $5C5CCD,
$82004B, $F0FFFF, $8CE6F0, $FAE6E6, $F5F0FF, $00FC7C, $CDFAFF, $E6D8AD,
$8080F0, $FFFFE0, $D2FAFA, $90EE90, $D3D3D3, $C1B6FF, $7AA0FF, $AAB220,
$FACE87, $998877, $DEC4B0, $E0FFFF, $00FF00, $32CD32, $E6F0FA, $FF00FF,
$000080, $AACD66, $CD0000, $D355BA, $DB7093, $71B33C, $EE687B, $9AFA00,
$CCD148, $8515C7, $701919, $FAFFF5, $E1E4FF, $B5E4FF, $ADDEFF, $800000,
$E6F5FD, $008080, $238E6B, $00A5FF, $0045FF, $D670DA, $AAE8EE, $98FB98,
$EEEEAF, $9370DB, $D5EFFF, $B9DAFF, $3F85CD, $CBC0FF, $DDA0DD, $E6E0B0,
$800080, $0000FF, $8F8FBC, $E16941, $13458B, $7280FA, $60A4F4, $578B2E,
$EEF5FF, $2D52A0, $C0C0C0, $EBCE87, $CD5A6A, $908070, $FAFAFF, $7FFF00,
$B48246, $8CB4D2, $808000, $D8BFD8, $4763FF, $D0E040, $EE82EE, $B3DEF5,
$FFFFFF, $F5F5F5, $00FFFF, $32CD9A);
asX11ColorNames : array[0..139] of string =
('AliceBlue', 'AntiqueWhite', 'Aqua', 'Aquamarine', 'Azure', 'Beige',
'Bisque', 'Black', 'BlanchedAlmond', 'Blue', 'BlueViolet', 'Brown',
'BurlyWood', 'CadetBlue', 'Chartreuse', 'Chocolate', 'Coral',
'CornflowerBlue', 'Cornsilk', 'Crimson', 'Cyan', 'DarkBlue', 'DarkCyan',
'DarkGoldenrod', 'DarkGray', 'DarkGreen', 'DarkKhaki', 'DarkMagenta',
'DarkOliveGreen', 'DarkOrange', 'DarkOrchid', 'DarkRed', 'DarkSalmon',
'DarkSeaGreen', 'DarkSlateBlue', 'DarkSlateGray', 'DarkTurquoise',
'DarkViolet', 'DeepPink', 'DeepSkyBlue', 'DimGray', 'DodgerBlue',
'FireBrick', 'FloralWhite', 'ForestGreen', 'Fuchsia', 'Gainsboro',
'GhostWhite', 'Gold', 'Goldenrod', 'Gray', 'Green', 'GreenYellow',
'Honeydew', 'HotPink', 'IndianRed', 'Indigo', 'Ivory', 'Khaki',
'Lavender', 'LavenderBlush', 'LawnGreen', 'LemonChiffon', 'LightBlue',
'LightCoral', 'LightCyan', 'LightGoldenrodYellow', 'LightGreen',
'LightGrey', 'LightPink', 'LightSalmon', 'LightSeaGreen', 'LightSkyBlue',
'LightSlateGray', 'LightSteelBlue', 'LightYellow', 'Lime', 'LimeGreen',
'Linen', 'Magenta', 'Maroon', 'MediumAquamarine', 'MediumBlue',
'MediumOrchid', 'MediumPurple', 'MediumSeaGreen', 'MediumSlateBlue',
'MediumSpringGreen', 'MediumTurquoise', 'MediumVioletRed', 'MidnightBlue',
'MintCream', 'MistyRose', 'Moccasin', 'NavajoWhite', 'Navy', 'OldLace',
'Olive', 'OliveDrab', 'Orange', 'OrangeRed', 'Orchid', 'PaleGoldenrod',
'PaleGreen', 'PaleTurquoise', 'PaleVioletRed', 'PapayaWhip', 'PeachPuff',
'Peru', 'Pink', 'Plum', 'PowderBlue', 'Purple', 'Red', 'RosyBrown',
'RoyalBlue', 'SaddleBrown', 'Salmon', 'SandyBrown', 'SeaGreen', 'Seashell',
'Sienna', 'Silver', 'SkyBlue', 'SlateBlue', 'SlateGray', 'Snow',
'SpringGreen', 'SteelBlue', 'Tan', 'Teal', 'Thistle', 'Tomato', 'Turquoise',
'Violet', 'Wheat', 'White', 'WhiteSmoke', 'Yellow', 'YellowGreen');
procedure BmpColorize(R0, G0, B0: integer; var png, png2: tpngobject);
procedure colorizer(acolor: tcolor; var png: tpngobject);
function ColorDarkenMultiplier(AColor: TColor; AMultiplier: Double): TColor;
procedure DrawTransparentBitmap(Dest: TCanvas; X, Y, W, H: Integer;
Rect: TRect; Bitmap: TBitmap; TransparentColor: TColor);
procedure DrawBitmapInRect(Canvas: TCanvas; Rect: TRect; Bitmap: TBitmap);
procedure MakeReflected(ADest, ASource: TBitmap; AMirrorSize: Integer; aGradient: Boolean);
procedure ItemHTDrawEx(Canvas: TCanvas; Rect: TRect;
const State: TOwnerDrawState; const Text: string; var Width: Integer;
CalcWidth: Boolean; MouseX, MouseY: Integer; var MouseOnLink: Boolean;
var LinkName: string);
{ example for Text parameter : 'Item 1 <b>bold</b> <i>italic ITALIC <br><FONT COLOR="clRed">red <FONT COLOR="clgreen">green <FONT COLOR="clblue">blue </i>' }
function ItemHTDraw(Canvas: TCanvas; Rect: TRect;
const State: TOwnerDrawState; const Text: string): string;
function ItemHTWidth(Canvas: TCanvas; Rect: TRect;
const State: TOwnerDrawState; const Text: string): Integer;
function ItemHTPlain(const Text: string): string;
function ItemHTHeight(Canvas: TCanvas; const Text: string): Integer;
function PrepareText(const A: string): string;
implementation
const
cBR = '<BR>';
cHR = '<HR>';
cTagBegin = '<';
cTagEnd = '>';
cLT = '<';
cGT = '>';
cQuote = '"';
cCENTER = 'CENTER';
cRIGHT = 'RIGHT';
cHREF = 'HREF';
cIND = 'IND';
cCOLOR = 'COLOR';
cSIZE = 'SIZE';
cBGCOLOR = 'BGCOLOR';
cMAILTO = 'MAILTO:';
cURLTYPE = '://';
(******************************************************************************)
procedure BmpColorize(R0, G0, B0: integer; var png, png2: tpngobject);
var
x, y : integer;
Rowa : Prgbarray;
Rowb : Prgbarray;
R, G, B : integer;
// H0 : integer;
// H,S,V : integer;
begin
for y := 0 to png.height - 1 do
begin
rowa := png2.Scanline[y];
rowb := png.Scanline[y];
for x := 0 to png.width - 1 do
begin
R := (rowa[x].RgbtRed div 4) + (R0 {div 1});
G := (rowa[x].Rgbtgreen div 4) + (G0 {div 2});
B := (rowa[x].Rgbtblue div 4) + (B0 {div 3});
if R > 255 then
R := 255
else if R < 0 then
R := 0;
if G > 255 then
G := 255
else if G < 0 then
G := 0;
if B > 255 then
B := 255
else if B < 0 then
B := 0;
rowb[x].Rgbtred := R;
rowb[x].Rgbtgreen := G;
rowb[x].Rgbtblue := B;
end;
end;
end;
procedure colorizer(acolor: tcolor; var png: tpngobject);
var
R0, G0, B0 : integer;
png2 : tpngobject;
begin
aColor := ColorToRGB(aColor);
png2 := TPNGObject.Create;
png2.Assign(png);
R0 := GetRValue((acolor));
G0 := GetGValue((acolor));
B0 := GetBValue((acolor));
BmpColorize(R0, G0, B0, png2, png);
png.assign(png2);
png2.Free;
end;
function ColorDarkenMultiplier(AColor: TColor; AMultiplier: Double): TColor;
var
ARed, AGreen, ABlue: Integer;
begin
AColor := ColorToRGB(AColor);
ARed := (AColor and $FF);
AGreen := (AColor and $FF00) shr 8;
ABlue := (AColor and $FF0000) shr 16;
ARed := Trunc(ARed - ARed * AMultiplier);
AGreen := Trunc(AGreen - AGreen * AMultiplier);
ABlue := Trunc(ABlue - ABlue * AMultiplier);
if ARed > 255 then
ARed := 255;
if AGreen > 255 then
AGreen := 255;
if ABlue > 255 then
ABlue := 255;
if ARed < 0 then
ARed := 0;
if AGreen < 0 then
AGreen := 0;
if ABlue < 0 then
ABlue := 0;
Result := ARed + (AGreen shl 8) + (ABlue shl 16);
end;
function WidthOf(R: TRect): Integer;
begin
Result := R.Right - R.Left;
end;
function HeightOf(R: TRect): Integer;
begin
Result := R.Bottom - R.Top;
end;
function MinL(A, B: LongInt): LongInt;
begin
if (A < B) then
Result := A
else
Result := B;
end;
function MaxL(A, B: LongInt): LongInt;
begin
if (A < B) then
Result := B
else
Result := A;
end;
procedure DrawTransparentBitmapPrim(DC: HDC; Bitmap: HBitmap;
xStart, yStart, Width, Height: Integer; Rect: TRect;
TransparentColor: TColorRef);
{-draw transparent bitmap}
var
BM : Windows.TBitmap;
cColor : TColorRef;
bmAndBack : hBitmap;
bmAndObject : hBitmap;
bmAndMem : hBitmap;
bmSave : hBitmap;
bmBackOld : hBitmap;
bmObjectOld : hBitmap;
bmMemOld : hBitmap;
bmSaveOld : hBitmap;
hdcMem : hDC;
hdcBack : hDC;
hdcObject : hDC;
hdcTemp : hDC;
hdcSave : hDC;
ptSize : TPoint;
ptRealSize : TPoint;
ptBitSize : TPoint;
ptOrigin : TPoint;
begin
hdcTemp := CreateCompatibleDC(DC);
SelectObject(hdcTemp, Bitmap);
GetObject(Bitmap, SizeOf(BM), @BM);
ptRealSize.x := MinL(Rect.Right - Rect.Left, BM.bmWidth - Rect.Left);
ptRealSize.y := MinL(Rect.Bottom - Rect.Top, BM.bmHeight - Rect.Top);
DPtoLP(hdcTemp, ptRealSize, 1);
ptOrigin.x := Rect.Left;
ptOrigin.y := Rect.Top;
{convert from device to logical points}
DPtoLP(hdcTemp, ptOrigin, 1);
{get width of bitmap}
ptBitSize.x := BM.bmWidth;
{get height of bitmap}
ptBitSize.y := BM.bmHeight;
DPtoLP(hdcTemp, ptBitSize, 1);
if (ptRealSize.x = 0) or (ptRealSize.y = 0) then
begin
ptSize := ptBitSize;
ptRealSize := ptSize;
end
else
ptSize := ptRealSize;
if (Width = 0) or (Height = 0) then
begin
Width := ptSize.x;
Height := ptSize.y;
end;
{create DCs to hold temporary data}
hdcBack := CreateCompatibleDC(DC);
hdcObject := CreateCompatibleDC(DC);
hdcMem := CreateCompatibleDC(DC);
hdcSave := CreateCompatibleDC(DC);
{create a bitmap for each DC}
{monochrome DC}
bmAndBack := CreateBitmap(ptSize.x, ptSize.y, 1, 1, nil);
bmAndObject := CreateBitmap(ptSize.x, ptSize.y, 1, 1, nil);
bmAndMem := CreateCompatibleBitmap(DC, MaxL(ptSize.x, Width), MaxL(ptSize.y,
Height));
bmSave := CreateCompatibleBitmap(DC, ptBitSize.x, ptBitSize.y);
{select a bitmap object to store pixel data}
bmBackOld := SelectObject(hdcBack, bmAndBack);
bmObjectOld := SelectObject(hdcObject, bmAndObject);
bmMemOld := SelectObject(hdcMem, bmAndMem);
bmSaveOld := SelectObject(hdcSave, bmSave);
SetMapMode(hdcTemp, GetMapMode(DC));
{save the bitmap sent here, it will be overwritten}
BitBlt(hdcSave, 0, 0, ptBitSize.x, ptBitSize.y, hdcTemp, 0, 0, SRCCOPY);
{set the background color of the source DC to the color,}
{contained in the parts of the bitmap that should be transparent}
cColor := SetBkColor(hdcTemp, TransparentColor);
{create the object mask for the bitmap by performing a BitBlt()}
{from the source bitmap to a monochrome bitmap}
BitBlt(hdcObject, 0, 0, ptSize.x, ptSize.y, hdcTemp, ptOrigin.x, ptOrigin.y,
SRCCOPY);
{set the background color of the source DC back to the original color}
SetBkColor(hdcTemp, cColor);
{create the inverse of the object mask}
BitBlt(hdcBack, 0, 0, ptSize.x, ptSize.y, hdcObject, 0, 0, NOTSRCCOPY);
{copy the background of the main DC to the destination}
BitBlt(hdcMem, 0, 0, Width, Height, DC, xStart, yStart, SRCCOPY);
{mask out the places where the bitmap will be placed}
StretchBlt(hdcMem, 0, 0, Width, Height, hdcObject, 0, 0, ptSize.x, ptSize.y,
SRCAND);
{mask out the transparent colored pixels on the bitmap}
BitBlt(hdcTemp, ptOrigin.x, ptOrigin.y, ptSize.x, ptSize.y, hdcBack, 0, 0,
SRCAND);
{XOR the bitmap with the background on the destination DC}
StretchBlt(hdcMem, 0, 0, Width, Height, hdcTemp, ptOrigin.x, ptOrigin.y,
ptSize.x, ptSize.y, SRCPAINT);
{copy the destination to the screen}
BitBlt(DC, xStart, yStart, MaxL(ptRealSize.x, Width), MaxL(ptRealSize.y,
Height), hdcMem, 0, 0, SRCCOPY);
{place the original bitmap back into the bitmap sent}
BitBlt(hdcTemp, 0, 0, ptBitSize.x, ptBitSize.y, hdcSave, 0, 0, SRCCOPY);
{delete the memory bitmaps}
DeleteObject(SelectObject(hdcBack, bmBackOld));
DeleteObject(SelectObject(hdcObject, bmObjectOld));
DeleteObject(SelectObject(hdcMem, bmMemOld));
DeleteObject(SelectObject(hdcSave, bmSaveOld));
{delete the memory DCs}
DeleteDC(hdcMem);
DeleteDC(hdcBack);
DeleteDC(hdcObject);
DeleteDC(hdcSave);
DeleteDC(hdcTemp);
end;
procedure DrawTransparentBitmap(Dest: TCanvas; X, Y, W, H: Integer;
Rect: TRect; Bitmap: TBitmap; TransparentColor: TColor);
var
MemImage : TBitmap;
R : TRect;
begin
MemImage := TBitmap.Create;
try
R := Bounds(0, 0, Bitmap.Width, Bitmap.Height);
if TransparentColor = clNone then
begin
if (WidthOf(Rect) <> 0) and (HeightOf(Rect) <> 0) then
R := Rect;
MemImage.Width := WidthOf(R);
MemImage.Height := HeightOf(R);
MemImage.Canvas.CopyRect(Bounds(0, 0, MemImage.Width, MemImage.Height),
Bitmap.Canvas, R);
if (W = 0) or (H = 0) then
Dest.Draw(X, Y, MemImage)
else
Dest.StretchDraw(Bounds(X, Y, W, H), MemImage);
end
else
begin
MemImage.Width := WidthOf(R);
MemImage.Height := HeightOf(R);
MemImage.Canvas.CopyRect(R, Bitmap.Canvas, R);
if TransparentColor = clDefault then
TransparentColor := MemImage.Canvas.Pixels[0, MemImage.Height - 1];
DrawTransparentBitmapPrim(Dest.Handle, MemImage.Handle, X, Y, W, H,
Rect, ColorToRGB(TransparentColor and not $02000000));
end;
finally
MemImage.Free;
end;
end;
procedure DrawBitmapInRect(Canvas: TCanvas; Rect: TRect; Bitmap: TBitmap);
var
X, Y : Integer;
begin
with Canvas do
begin
X := (Rect.Right - Rect.Left - Bitmap.Width) div 2 + Rect.Left;
Y := (Rect.Bottom - Rect.Top - Bitmap.Height) div 2 + Rect.Top;
BrushCopy(Classes.Rect(X, Y, X + Bitmap.Width, Y + Bitmap.Height), Bitmap,
Classes.Rect(0, 0, Bitmap.Width, Bitmap.Height), clBlack);
end;
end;
procedure PixelFilterAlphaBlend(var D, S: TRGBQuad;
AAlpha: Integer = $FF; AProcessPerChannelAlpha: Boolean = True);
begin
D.rgbBlue := (D.rgbBlue * ($FF - AAlpha) + S.rgbBlue * AAlpha) shr 8;
D.rgbGreen := (D.rgbGreen * ($FF - AAlpha) + S.rgbGreen * AAlpha) shr 8;
D.rgbRed := (D.rgbRed * ($FF - AAlpha) + S.rgbRed * AAlpha) shr 8;
end;
procedure MakeReflected(ADest, ASource: TBitmap; AMirrorSize: Integer; aGradient: Boolean);
var
AAlpha : Single;
AAlphaDelta : Single;
DS, SS : PRGBQuad;
I, J, A : Integer;
begin
if ASource.PixelFormat <> pf32bit then
Exit;
AAlpha := $80;
AAlphaDelta := AAlpha / AMirrorSize;
ADest.PixelFormat := pf32bit;
ADest.Width := ASource.Width;
ADest.Height := ASource.Height + AMirrorSize;
ADest.Canvas.Brush.Color := clWhite;
if aGradient then
GradientFillRect(ADest.Canvas,
ADest.Canvas.ClipRect,
$FEFDFC,
$DAB3A9,
fdTopToBottom,
255);
ADest.Canvas.Draw(0, 0, ASource);
for I := 0 to AMirrorSize - 1 do
begin
DS := ADest.ScanLine[ASource.Height + I];
SS := ASource.ScanLine[ASource.Height - I - 1];
A := Round(AAlpha);
for J := 0 to ASource.Width - 1 do
begin
PixelFilterAlphaBlend(DS^, SS^, A, False);
Inc(DS);
Inc(SS);
end;
AAlpha := AAlpha - AAlphaDelta;
end;
end;
function BeforeTag(var Str: string; DeleteToTag: Boolean = False): string;
begin
if Pos(cTagBegin, Str) > 0 then
begin
Result := Copy(Str, 1, Pos(cTagBegin, Str) - 1);
if DeleteToTag then
Delete(Str, 1, Pos(cTagBegin, Str) - 1);
end
else
begin
Result := Str;
if DeleteToTag then
Str := '';
end;
end;
function GetChar(const Str: string; Pos: Word; Up: Boolean = False): Char;
begin
if Length(Str) >= Pos then
Result := Str[Pos]
else
Result := ' ';
if Up then
Result := UpCase(Result);
end;
function DeleteTag(const Str: string): string;
begin
Result := Str;
if (GetChar(Result, 1) = cTagBegin) and (Pos(cTagEnd, Result) > 1) then
Delete(Result, 1, Pos(cTagEnd, Result));
end;
procedure ItemHTDrawEx(Canvas: TCanvas; Rect: TRect;
const State: TOwnerDrawState; const Text: string; var Width: Integer;
CalcWidth: Boolean; MouseX, MouseY: Integer; var MouseOnLink: Boolean;
var LinkName: string);
const
DefaultLeft = 0; // (ahuser) was 2
var
vText, vM, TagPrp, Prp, TempLink, PSize: string;
vCount : Integer;
vStr : TStringList;
Selected : Boolean;
Alignment : TAlignment;
Trans, IsLink : Boolean;
CurLeft : Integer;
// for begin and end
OldFontStyles : TFontStyles;
OldFontColor : TColor;
OldBrushColor : TColor;
OldAlignment : TAlignment;
OldFont : TFont;
// for font style
RemFontColor,
RemBrushColor : TColor;
function ExtractPropertyValue(const Tag: string; PropName: string): string;
begin
Result := '';
PropName := UpperCase(PropName);
if Pos(PropName, UpperCase(Tag)) > 0 then
begin
Result := Copy(Tag, Pos(PropName, UpperCase(Tag)) + Length(PropName), Length(Tag));
Result := Copy(Result, Pos(cQuote, Result) + 1, Length(Result));
Result := Copy(Result, 1, Pos(cQuote, Result) - 1);
end;
end;
procedure Style(const Style: TFontStyle; const Include: Boolean);
begin
if Assigned(Canvas) then
if Include then
Canvas.Font.Style := Canvas.Font.Style + [Style]
else
Canvas.Font.Style := Canvas.Font.Style - [Style];
end;
function CalcPos(const Str: string): Integer;
begin
case Alignment of
taRightJustify:
Result := (Rect.Right - Rect.Left) - ItemHTWidth(Canvas, Rect, State, Str);
taCenter:
Result := (Rect.Right - Rect.Left - ItemHTWidth(Canvas, Rect, State, Str)) div 2;
else
Result := DefaultLeft;
end;
if Result <= 0 then
Result := DefaultLeft;
end;
procedure Draw(const M: string);
var
Width, Height : Integer;
R : TRect;
begin
R := Rect;
Inc(R.Left, CurLeft);
if Assigned(Canvas) then
begin
Width := Canvas.TextWidth(M);
Height := CanvasMaxTextHeight(Canvas);
if IsLink and not MouseOnLink then
if (MouseY in [R.Top..R.Top + Height]) and
(MouseX in [R.Left..R.Left + Width]) then
begin
MouseOnLink := True;
Canvas.Font.Color := clRed; // hover link
LinkName := TempLink;
end;
if not CalcWidth then
begin
{$IFDEF VCL}
if Trans then
Canvas.Brush.Style := bsClear; // for transparent
{$ENDIF VCL}
{$IFDEF VisualCLX}
if not Trans then
Canvas.FillRect(R); // for opaque ( transparent = False )
{$ENDIF VisualCLX}
Canvas.TextOut(R.Left, R.Top, M);
end;
CurLeft := CurLeft + Width;
end;
end;
procedure NewLine;
begin
if Assigned(Canvas) then
if vCount < vStr.Count - 1 then
begin
Width := Max(Width, CurLeft);
CurLeft := DefaultLeft;
Rect.Top := Rect.Top + CanvasMaxTextHeight(Canvas);
end;
end;
begin
// (p3) remove warnings
OldFontColor := 0;
OldBrushColor := 0;
RemFontColor := 0;
RemBrushColor := 0;
OldAlignment := taLeftJustify;
OldFont := TFont.Create;
if Canvas <> nil then
begin
OldFontStyles := Canvas.Font.Style;
OldFontColor := Canvas.Font.Color;
OldBrushColor := Canvas.Brush.Color;
OldAlignment := Alignment;
RemFontColor := Canvas.Font.Color;
RemBrushColor := Canvas.Brush.Color;
end;
try
Alignment := taLeftJustify;
IsLink := False;
MouseOnLink := False;
vText := Text;
vStr := TStringList.Create;
vStr.Text := PrepareText(vText);
Trans := True;
LinkName := '';
TempLink := '';
Selected := (odSelected in State) or (odDisabled in State);
Width := DefaultLeft;
CurLeft := DefaultLeft;
vM := '';
for vCount := 0 to vStr.Count - 1 do
begin
vText := vStr[vCount];
CurLeft := CalcPos(vText);
while Length(vText) > 0 do
begin
vM := BeforeTag(vText, True);
vM := StringReplace(vM, '<', cLT, [rfReplaceAll, rfIgnoreCase]); // <--+ this must be here
vM := StringReplace(vM, '>', cGT, [rfReplaceAll, rfIgnoreCase]); // <--/
if GetChar(vText, 1) = cTagBegin then
begin
Draw(vM);
if Pos(cTagEnd, vText) = 0 then
Insert(cTagEnd, vText, 2);
if GetChar(vText, 2) = '/' then
begin
case GetChar(vText, 3, True) of
'A':
begin
IsLink := False;
Canvas.Font.Assign(OldFont);
end;
'B':
Style(fsBold, False);
'I':
Style(fsItalic, False);
'U':
Style(fsUnderline, False);
'S':
Style(fsStrikeOut, False);
'F':
begin
if not Selected then // restore old colors
begin
Canvas.Font.Color := RemFontColor;
Canvas.Brush.Color := RemBrushColor;
Trans := True;
end;
end;
end
end
else
begin
case GetChar(vText, 2, True) of
'A':
begin
if GetChar(vText, 3, True) = 'L' then // ALIGN
begin
TagPrp := UpperCase(Copy(vText, 2, Pos(cTagEnd, vText) - 2));
if Pos(cCENTER, TagPrp) > 0 then
Alignment := taCenter
else if Pos(cRIGHT, TagPrp) > 0 then
Alignment := taRightJustify
else
Alignment := taLeftJustify;
CurLeft := DefaultLeft;
if not CalcWidth then
CurLeft := CalcPos(vText);
end
else
begin // A HREF
TagPrp := Copy(vText, 2, Pos(cTagEnd, vText) - 2);
if Pos(cHREF, UpperCase(TagPrp)) > 0 then
begin
IsLink := True;
OldFont.Assign(Canvas.Font);
if not Selected then
Canvas.Font.Color := clBlue;
TempLink := ExtractPropertyValue(TagPrp, cHREF);
end;
end;
end;
'B':
Style(fsBold, True);
'I':
if GetChar(vText, 3, True) = 'N' then //IND="%d"
begin
TagPrp := Copy(vText, 2, Pos(cTagEnd, vText) - 2);
CurLeft := StrToInt(ExtractPropertyValue(TagPrp, cIND)); // ex IND="10"
end
else
Style(fsItalic, True); // ITALIC
'U':
Style(fsUnderline, True);
'S':
Style(fsStrikeOut, True);
'H':
if (GetChar(vText, 3, True) = 'R') and (not CalcWidth) and Assigned(Canvas) then // HR
begin
if odDisabled in State then // only when disabled
Canvas.Pen.Color := Canvas.Font.Color;
Canvas.Pen.Color := Canvas.Font.Color;
Canvas.MoveTo(0, Rect.Top + CanvasMaxTextHeight(Canvas));
Canvas.LineTo(Rect.Right, Rect.Top + CanvasMaxTextHeight(Canvas));
end;
'F':
if (Pos(cTagEnd, vText) > 0) and (not Selected) and Assigned(Canvas) and not
CalcWidth then // F from FONT
begin
TagPrp := UpperCase(Copy(vText, 2, Pos(cTagEnd, vText) - 2));
RemFontColor := Canvas.Font.Color;
RemBrushColor := Canvas.Brush.Color;
if Pos(cCOLOR, TagPrp) > 0 then
begin
Prp := ExtractPropertyValue(TagPrp, cCOLOR);
Canvas.Font.Color := StringToColor(Prp);
end;
if Pos(cSIZE, TagPrp) > 0 then
begin
PSize := ExtractPropertyValue(TagPrp, cSIZE);
Canvas.Font.Size := StrToInt(PSize);
end;
if Pos(cBGCOLOR, TagPrp) > 0 then
begin
Prp := ExtractPropertyValue(TagPrp, cBGCOLOR);
Canvas.Brush.Color := StringToColor(Prp);
Trans := False;
end;
end;
end;
end;
vText := DeleteTag(vText);
vM := '';
end;
end;
Draw(vM);
NewLine;
vM := '';
end;
finally
if Canvas <> nil then
begin
Canvas.Font.Style := OldFontStyles;
Canvas.Font.Color := OldFontColor;
Canvas.Brush.Color := OldBrushColor;
Alignment := OldAlignment;
{ Canvas.Font.Color := RemFontColor;
Canvas.Brush.Color:= RemBrushColor;}
end;
FreeAndNil(vStr);
FreeAndNil(OldFont);
end;
Width := Max(Width, CurLeft - DefaultLeft);
end;
// Kaczkowski - end
function ItemHTDraw(Canvas: TCanvas; Rect: TRect; const State: TOwnerDrawState;
const Text: string): string;
var
W : Integer;
S : Boolean;
St : string;
begin
ItemHTDrawEx(Canvas, Rect, State, Text, {HideSelColor,} W, False, 0, 0, S, St);
end;
function ItemHTPlain(const Text: string): string; // Kaczkowski: optimised
var
S : string;
begin
Result := '';
S := PrepareText(Text);
while Pos(cTagBegin, S) > 0 do
begin
Result := Result + Copy(S, 1, Pos(cTagBegin, S) - 1);
if Pos(cTagEnd, S) > 0 then
Delete(S, 1, Pos(cTagEnd, S))
else
Delete(S, 1, Pos(cTagBegin, S));
end;
Result := Result + S;
end;
function ItemHTWidth(Canvas: TCanvas; Rect: TRect;
const State: TOwnerDrawState; const Text: string): Integer;
var
S : Boolean;
St : string;
begin
ItemHTDrawEx(Canvas, Rect, State, Text, Result, True, 0, 0, S, St);
end;
// Kaczkowski - begin
function ItemHTHeight(Canvas: TCanvas; const Text: string): Integer;
var
Str : TStringList;
begin
try
Str := TStringList.Create;
Str.Text := PrepareText(Text);
Result := Str.Count * CanvasMaxTextHeight(Canvas);
finally
FreeAndNil(Str);
end;
if Result = 0 then
Result := CanvasMaxTextHeight(Canvas); // if Str.count = 0;
Inc(Result);
end;
function IsHyperLink(Canvas: TCanvas; Rect: TRect; const State: TOwnerDrawState;
const Text: string; MouseX, MouseY: Integer; var HyperLink: string): Boolean; overload;
var
W : Integer;
begin
ItemHTDrawEx(Canvas, Rect, State, Text, W, False, MouseX, MouseY, Result, HyperLink);
end;
function IsHyperLink(Canvas: TCanvas; Rect: TRect; const Text: string;
MouseX, MouseY: Integer; var HyperLink: string): Boolean; overload;
var
W : Integer;
begin
ItemHTDrawEx(Canvas, Rect, [], Text, W, False, MouseX, MouseY, Result, HyperLink);
end;
function PrepareText(const A: string): string;
type
THtmlCode = packed record
Html: PChar;
Text: Char;
end;
const
Conversions : array[0..6] of THtmlCode =
(
(Html: '&'; Text: '&'),
(Html: '"'; Text: '"'),
(Html: '®'; Text: '®'),
(Html: '©'; Text: '©'),
(Html: '™'; Text: '™'),
(Html: '€'; Text: '€'),
(Html: ' '; Text: ' ')
);
var
I : Integer;
begin
Result := A;
for I := Low(Conversions) to High(Conversions) do
with Conversions[I] do
Result := StringReplace(Result, Html, Text, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, sLineBreak, '', [rfReplaceAll, rfIgnoreCase]); // only <BR> can be new line
Result := StringReplace(Result, cBR, sLineBreak, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, cHR, cHR + sLineBreak, [rfReplaceAll, rfIgnoreCase]); // fixed <HR><BR>
end;
end.
|
{Escriba un programa en PASCAL que calcule el MCD (Máximo Común Divisor) para dos naturales n y m dados.
Recuerde que el MCD (m,0) = m y MCD(n,m) = MCD(m,n mod m).
¿Qué estructura de control utiliza y por qué? ¿Cuántas variables utiliza?
Ejemplos:
n=42 y m=30
MCD = 6
n=132 y m=168
MCD = 12 }
//MCD(n,m) = MCD(m,n mod m).
program ejercicio1;
var n, m, num1, num2 : integer;
begin
writeln('Ingrese n.');
readln(n);
writeln('Ingrese m.');
readln(m);
num1:= n;
num2 := m;
while (n <> m) do
if n > m then
begin
n := n - m;
//write(' n --->',n,' ');
end
else
begin
m := m - n;
//write(' m --->',m,' ');
end;
writeln('el MCD entre ',num1,' y ',num2,' es: ',n)
end. |
unit fGMV_InputLite;
{
================================================================================
*
* Application: Vitals
* Revision: $Revision: 1 $ $Modtime: 4/17/09 2:31p $
* Developer: ddomain.user@domain.ext/doma.user@domain.ext
* Site: Hines OIFO
*
* Description: Main form for entering a new series of vitals for pt.
*
* Notes:
*
================================================================================
* $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSDATAENTRY/fGMV_InputLite.pas $
*
* $History: fGMV_InputLite.pas $
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSDATAENTRY
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:38p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSDATAENTRY
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 1/20/09 Time: 3:42p
* Updated in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSDATAENTRY
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSDATAENTRY
*
* ***************** Version 7 *****************
* User: Zzzzzzandria Date: 6/17/08 Time: 4:04p
* Updated in $/Vitals/5.0 (Version 5.0)/VitalsGUI2007/Vitals/VITALSDATAENTRY
*
* ***************** Version 5 *****************
* User: Zzzzzzandria Date: 3/03/08 Time: 4:07p
* Updated in $/Vitals GUI 2007/Vitals/VITALSDATAENTRY
*
* ***************** Version 4 *****************
* User: Zzzzzzandria Date: 2/20/08 Time: 1:42p
* Updated in $/Vitals GUI 2007/Vitals/VITALSDATAENTRY
* Build 5.0.23.0
*
* ***************** Version 3 *****************
* User: Zzzzzzandria Date: 1/07/08 Time: 6:51p
* Updated in $/Vitals GUI 2007/Vitals/VITALSDATAENTRY
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 7/17/07 Time: 2:30p
* Updated in $/Vitals GUI 2007/Vitals-5-0-18/VITALSDATAENTRY
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/14/07 Time: 10:29a
* Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSDATAENTRY
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:43p
* Created in $/Vitals/VITALS-5-0-18/VitalsDataEntry
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:33p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsDataEntry
*
* ***************** Version 4 *****************
* User: Zzzzzzandria Date: 7/22/05 Time: 3:51p
* Updated in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsDataEntry
*
* ***************** Version 3 *****************
* User: Zzzzzzandria Date: 7/06/05 Time: 12:11p
* Updated in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsDataEntry
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 7/05/05 Time: 9:38a
* Updated in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, No CCOW) - Delphi 6/VitalsDataEntry
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 3:35p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, No CCOW) - Delphi 6/VitalsDataEntry
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 4/23/04 Time: 1:21p
* Updated in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSDATAENTRY
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 4/16/04 Time: 4:20p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSDATAENTRY
*
* ***************** Version 2 *****************
* User: Zzzzzzandria Date: 2/06/04 Time: 4:47p
* Updated in $/VitalsLite/VitalsLiteDLL
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/30/04 Time: 4:30p
* Created in $/VitalsLite/VitalsLiteDLL
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/15/04 Time: 3:06p
* Created in $/VitalsLite/VitalsLiteDLL
* Vitals Lite DLL
*
================================================================================
}
interface
uses
Windows,
ShellAPI,
Messages,
SysUtils,
System.DateUtils, {for incMinute}
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
ExtCtrls,
ComCtrls,
Menus,
StdActns,
ActnList,
ImgList,
ToolWin,
Buttons,
Grids,
uGMV_Template,
uGMV_Const,
AppEvnts,
Math
{$IFDEF USEVSMONITOR}
,
uGMV_Monitor,
uVHA_ATE740X,
System.Actions, System.ImageList
{$ENDIF}
;
type
TfrmGMV_InputLite = class(TForm)
pnlBottom: TPanel;
pnlInput: TPanel;
pnlParams: TPanel;
pnlTemplates: TPanel;
gbxTemplates: TGroupBox;
imgTemplates: TImageList;
Panel2: TPanel;
Panel4: TPanel;
Panel5: TPanel;
Panel6: TPanel;
tv: TTreeView;
pnlTemplInfo: TPanel;
lblTemplInfo: TLabel;
splParams: TSplitter;
splLastVitals: TSplitter;
pnlButtons: TPanel;
btnSave: TButton;
btnCancel: TButton;
alInputVitals: TActionList;
acMetricStyleChange: TAction;
acSavePreferences: TAction;
acLoadPreferences: TAction;
acPatientSelected: TAction;
splPatients: TSplitter;
pnlTools: TPanel;
pnlPatient: TPanel;
pnlSettings: TPanel;
lblHospital: TLabel;
lblDateTime: TLabel;
acTemplateClicked: TAction;
acSetOnPass: TAction;
acSaveInput: TAction;
ImageList1: TImageList;
acCheckBoxesChange: TAction;
PopupMenu2: TPopupMenu;
PatienOnPass1: TMenuItem;
acDateTimeSelector: TAction;
acHospitalSelector: TAction;
acTemplateSelect: TAction;
lblHospitalCap: TLabel;
Label2: TLabel;
tlbInput: TToolBar;
sbtnHospitals: TSpeedButton;
acParamsShowHide: TAction;
acVitalsShowHide: TAction;
acAdjustToolbars: TAction;
acTemplateSelector: TAction;
ToolButton2: TToolButton;
sbtnTemplates: TSpeedButton;
pnlInputTemplate: TPanel;
pnlInputTemplateHeader: TPanel;
hc: THeaderControl;
pnlScrollBox: TPanel;
sbxMain: TScrollBox;
pnlLatestVitalsBg: TPanel;
pnlLatestVitalsHeader: TPanel;
pnlOptions: TPanel;
bvU: TBevel;
ckbOnPass: TCheckBox;
pnlCPRSMetricStyle: TPanel;
chkCPRSSTyle: TCheckBox;
Bevel1: TBevel;
Panel13: TPanel;
strgLV: TStringGrid;
WindowClose1: TWindowClose;
bvUnavailable: TBevel;
lblUnavailable: TLabel;
ckbUnavailable: TCheckBox;
chkbCloseOnSave: TCheckBox;
chkOneUnavailableBox: TCheckBox;
acUnavailableBoxStatus: TAction;
gbDateTime: TGroupBox;
dtpDate: TDateTimePicker;
dtpTime: TDateTimePicker;
sbtnToolShowParams: TSpeedButton;
pnlParamTools: TPanel;
SpeedButton4: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton2: TSpeedButton;
Panel10: TPanel;
sbtnTemplateTree: TSpeedButton;
Panel3: TPanel;
sbtnShowLatestVitals: TSpeedButton;
gbxPatients: TGroupBox;
Panel1: TPanel;
Panel8: TPanel;
Panel9: TPanel;
lvSelPatients: TListView;
alDevice: TActionList;
acGetCASMEDDescription: TAction;
btnSaveAndExit: TButton;
pnlMonitor: TPanel;
sbMonitor: TSpeedButton;
acMonitorGetData: TAction;
SpeedButton1: TSpeedButton;
SpeedButton5: TSpeedButton;
cbR: TCheckBox;
cbU: TCheckBox;
Bevel2: TBevel;
Bevel3: TBevel;
Panel7: TPanel;
cbConversionWarning: TCheckBox;
Bevel4: TBevel;
acPatientInfo: TAction;
MainMenu1: TMainMenu;
acPatientInfo1: TMenuItem;
edPatientName: TEdit;
edPatientInfo: TEdit;
Hospital1: TMenuItem;
ExpView1: TMenuItem;
LatestV1: TMenuItem;
DateTime1: TMenuItem;
StatusBar: TStatusBar;
acShowStatusBar: TAction;
ShowHideStatusBar1: TMenuItem;
File1: TMenuItem;
View1: TMenuItem;
N1: TMenuItem;
acEnableU: TAction;
acEnableR: TAction;
acExit: TAction;
N2: TMenuItem;
Exit1: TMenuItem;
N3: TMenuItem;
Save1: TMenuItem;
ReadMonitor1: TMenuItem;
N4: TMenuItem;
acLatestVitals: TAction;
LatestVitals1: TMenuItem;
EnableU1: TMenuItem;
EnableR1: TMenuItem;
acUnitsDDL: TAction;
UnitsasDropDownList1: TMenuItem;
procedure btnCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure dtpTimeChange(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure tvChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean);
procedure FormActivate(Sender: TObject);
procedure acMetricStyleChangeExecute(Sender: TObject);
procedure ckbOnPassEnter(Sender: TObject);
procedure ckbOnPassExit(Sender: TObject);
procedure acSavePreferencesExecute(Sender: TObject);
procedure acLoadPreferencesExecute(Sender: TObject);
procedure tvExpanded(Sender: TObject; Node: TTreeNode);
procedure tvCollapsed(Sender: TObject; Node: TTreeNode);
procedure pnlParamsResize(Sender: TObject);
procedure acSetOnPassExecute(Sender: TObject);
procedure acSaveInputExecute(Sender: TObject);
procedure ckbOnPassClick(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure acDateTimeSelectorExecute(Sender: TObject);
procedure acHospitalSelectorExecute(Sender: TObject);
procedure pnlLatestVitalsBgResize(Sender: TObject);
procedure strgLVDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
procedure FormCreate(Sender: TObject);
procedure ckbUnavailableEnter(Sender: TObject);
procedure ckbUnavailableExit(Sender: TObject);
procedure ckbUnavailableClick(Sender: TObject);
procedure acUnavailableBoxStatusExecute(Sender: TObject);
procedure acParamsShowHideExecute(Sender: TObject);
procedure acAdjustToolbarsExecute(Sender: TObject);
procedure acVitalsShowHideExecute(Sender: TObject);
procedure lvSelPatientsClick(Sender: TObject);
procedure lvSelPatientsChanging(Sender: TObject; Item: TListItem; Change: TItemChange; var AllowChange: Boolean);
procedure lvSelPatientsChange(Sender: TObject; Item: TListItem; Change: TItemChange);
procedure FormDestroy(Sender: TObject);
procedure acGetCASMEDDataExecute(Sender: TObject);
procedure acGetCASMEDDescriptionExecute(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure acMonitorGetDataExecute(Sender: TObject);
procedure cbRClick(Sender: TObject);
procedure hcMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure cbConversionWarningClick(Sender: TObject);
procedure pnlPatientEnter(Sender: TObject);
procedure pnlPatientExit(Sender: TObject);
procedure pnlPatientClick(Sender: TObject);
procedure acPatientInfoExecute(Sender: TObject);
procedure edPatientNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure acShowStatusBarExecute(Sender: TObject);
procedure pnlPatientMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure pnlPatientMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure acLatestVitalsExecute(Sender: TObject);
procedure acEnableUExecute(Sender: TObject);
procedure acEnableRExecute(Sender: TObject);
procedure acUnitsDDLExecute(Sender: TObject);
private
fGMV_TemplateArray: Array of TGMV_Template;
FTmpltRoot: TTreeNode;
FTmpltDomainRoot: TTreeNode;
FTmpltInstitutionRoot: TTreeNode;
FTmpltHopsitalLocationRoot: TTreeNode;
FTmpltNewPersonRoot: TTreeNode;
FNewTemplate: string;
FNewTemplateDescription: String;
FDefaultTemplate, // AAN 08/27/2002
FInputTemplate: TGMV_Template;
FTemplateData: string;
FDFN: string;
CurrentTime: TDateTime; // AAN 07/11/2002
fStatus: String;
fFileVersion: String; // zzzzzzandria 050415
fFileComments: String; // zzzzzzandria 050415
// VS monitor support;
{$IFDEF USEVSMONITOR}
fMonitor: TGMV_Monitor;
sCasmedPort: String;
bCasmedUsed: Boolean;
Casmed: TATE740X;
{$ENDIF}
bShowVitals, bShowParams: Boolean;
bDataUpdated: Boolean;
bSlave: Boolean;
_FCurrentPtIEN: string;
_FHospitalIEN: String;
procedure _SetCurrentPtIEN(const Value: string);
procedure LoadTreeView;
procedure InsertTemplate(Template: TGMV_Template; GoToTemplate: Boolean = False);
procedure SetVitalsList(InputTemplate: String);
procedure ClearVitalsList;
procedure CleanUpVitalsList;
procedure UpdateLatestVitals(aPatient: String; bSilent: Boolean);
procedure FocusInputField;
function InputString: String;
procedure SaveData(DT: TDateTime);
procedure CMHospitalUpdate(var Message: TMessage); message CM_UPDATELOOKUP;
procedure CMVitalChanged(var Message: TMessage); message CM_VITALCHANGED;
procedure UpdatePatient(aPatient: String);
procedure PatientSelected;
procedure setStatus(aStatus: String);
procedure setPatientInfoView(aName, anInfo: String);
procedure updatePatientInfoView;
function getPatientName: String;
procedure CleanUp;
public
property Status: String read fStatus write setStatus;
property _CurrentPtIEN: String read _FCurrentPtIEN write _SetCurrentPtIEN;
procedure InputLite(PatientDFN: String; PatientLocationIEN: string; InputTemplate: string; aDateTime: TDateTime);
protected
procedure CMSaveInput(var Message: TMessage); message CM_SAVEINPUT; // AAN 2003/06/06
{$IFDEF USEVSMONITOR}
procedure MonitorProcess;
procedure CasmedStatusIndicator(aStatus: String);
procedure CasmedProcess;
{$ENDIF}
end;
function VitalsInputDLG(aPatient, aLocation, aTemplate, aSignature: String; aDateTime: TDateTime; aName, anInfo: String): Integer;
// function FormatLV(aSL:TStringList;aDelim:String):TStringList;
// procedure VitalsLiteInput(aPatient, aLocation, aTemplate,aSignature:ShortString;
// function GetLatestVitals(aBroker:TRPCBroker;aPatient,aDelim:String;bSilent:Boolean):TStringList;
procedure InputVitals(PatientDFN: string; PatientLocationIEN: string; InputTemplate: string; LV: TListView; aLocationName: String);
function VitalsInputForm(aPatient, aLocation, aTemplate, aSignature: String; aDateTime: TDateTime): TfrmGMV_InputLite;
function GetLatestVitals(aPatient, aDelim: String; bSilent: Boolean): TStringList;
var
frmGMV_InputLite: TfrmGMV_InputLite;
// InputOne21: TfraGMV_InputOne2;
implementation
uses
mGMV_InputOne2
{$IFNDEF DLL}
,
fGMV_Splash,
fGMV_AboutDlg
{$ENDIF}
,
uGMV_Common,
uGMV_GlobalVars,
uGMV_User,
uGMV_FileEntry,
uGMV_Utils,
uGMV_SaveRestore,
fGMV_HospitalSelector2,
uGMV_VitalTypes,
uGMV_Setup,
RS232,
uGMV_Engine,
uGMV_VersionInfo // zzzzzzandria 050415
,
fGMV_PtInfo,
fGMV_DateTimeDLG,
uGMV_Log,
system.UITypes;
const
indMultipleInput: Integer = 19;
indSingleCurrent: Integer = 17;
indMultipleCurrent: Integer = 18;
indOnPass: Integer = 5;
indUnavail: Integer = 5;
indSingleInput: Integer = 3;
indBlankInput: Integer = 13;
_WindowName = 'VitalsLite';
stsDLL = 'DLL';
stsDIALOG = 'DIALOG';
stsCPRS = 'CPRS';
stsDefault = 'DEFAULT';
{$R *.DFM}
procedure InputVitals(PatientDFN: string; PatientLocationIEN: string; InputTemplate: string; LV: TListView; aLocationName: String);
var
InputVitalsForm: TfrmGMV_InputLite;
LI: TListItem;
lc: TListColumn;
i: Integer;
anEvt: TLVChangeEvent;
CurrentServerDateTime: TDateTime;
sHospitalLocationID, sHospitalLocationName,
sWindowSettings, sDateTime, sTemplate: String;
// Have some problems with: RestoreWindowSettings(TForm(InputVitalsForm));
procedure RestoreWin;
var
RetList: TStrings;
begin
RetList := TStringList.Create;
try
try
with InputVitalsForm do
begin
sWindowSettings := InputVitalsForm.ClassName;
sWindowSettings := getUserSettings(sWindowSettings);
if sWindowSettings <> '' then
begin
Left := StrToIntDef(Piece(sWindowSettings, ';', 3), Left);
Top := StrToIntDef(Piece(sWindowSettings, ';', 4), Top);
Width := StrToIntDef(Piece(sWindowSettings, ';', 5), Width);
Height := StrToIntDef(Piece(sWindowSettings, ';', 6), Height);
end
else
begin
Left := (Screen.Width - Width) div 2;
Top := (Screen.Height - Height) div 2;
if Top < 0 Then
Top := 0;
if Left < 0 Then
Left := 0;
end;
end;
except
end;
finally
RetList.Free;
end;
end;
begin
sHospitalLocationID := PatientLocationIEN;
sHospitalLocationName := aLocationName;
if sHospitalLocationID = '' then
begin
if not SelectLocation2(PatientDFN, sHospitalLocationID, sHospitalLocationName) then
begin
MessageDLG('Not enough information to start input' + #13 + 'Select hospital location to proceed', mtInformation, [mbOK], 0);
exit;
end;
end;
try
sDateTime := getCurrentDateTime;
CurrentServerDateTime := FMDateTimeToWindowsDateTime(StrToFloat(sDateTime)); // 10/08/2002 AAN
except
on E: Exception do
begin
MessageDLG('Input Vitals: Unable to set client to the servers time.' + #13#10 + E.Message, mtWarning, [mbOK], 0);
exit;
end;
end;
InputVitalsForm := TfrmGMV_InputLite.Create(Application);
with InputVitalsForm do
try
if (PatientDFN = '') and ((LV = nil) or (LV.Items.Count < 1)) then
MessageDLG('Not enough information to start input' + #13 + 'Select one or more patients to proceed', mtInformation, [mbOK], 0)
else
begin
if PatientDFN = '' then
FDFN := LV.Items[0].SubItems[1]
else
FDFN := PatientDFN;
dtpDate.Date := CurrentServerDateTime;
dtpDate.MaxDate := dtpDate.Date;
dtpTime.DateTime := CurrentServerDateTime;
CurrentTime := dtpTime.DateTime;
_FHospitalIEN := sHospitalLocationID;
lblHospital.Caption := sHospitalLocationName;
acLoadPreferencesExecute(nil);
RestoreWin;
LoadTreeView;
if tv <> nil then
begin
// AAN 08/27/2002 Default template handling------------------ begin
sTemplate := Piece(FNewTemplate, '|', 2);
if sTemplate = '' then
try
sTemplate := FDefaultTemplate.TemplateName;
except
end;
for i := 0 to tv.Items.Count - 1 do
begin
if sTemplate = tv.Items[i].Text then
begin
tv.Selected := tv.Items[i];
break;
end;
end;
end;
if LV <> nil then
begin
lvSelPatients.SmallImages := imgTemplates;
if lvSelPatients.Columns.Count < 3 then
begin
lc := lvSelPatients.Columns.Add;
lc.Width := 150;
lc := lvSelPatients.Columns.Add;
lc.Width := 0;
lc := lvSelPatients.Columns.Add;
lc.Width := 0;
lc := lvSelPatients.Columns.Add;
lc.Width := 0;
end;
anEvt := lvSelPatients.OnChange;
lvSelPatients.OnChange := nil;
try
for i := 0 to LV.Items.Count - 1 do
begin
LI := lvSelPatients.Items.Add;
LI.Caption := LV.Items[i].SubItems[0];
LI.SubItems.Add(LV.Items[i].SubItems[0]);
LI.SubItems.Add(LV.Items[i].SubItems[1]);
LI.SubItems.Add(LV.Items[i].SubItems[2]);
LI.SubItems.Add('');
LI.Checked := False;
end;
Finally
lvSelPatients.OnChange := anEvt;
End;
if lvSelPatients.Items.Count > 0 then
begin
lvSelPatients.ItemFocused := lvSelPatients.Items[0];
lvSelPatientsClick(nil);
btnSaveAndExit.Visible := False;
end;
if lvSelPatients.Items.Count < 2 then
begin
gbxPatients.Visible := False;
splPatients.Visible := False;
end;
end
else
begin
gbxPatients.Visible := False;
splPatients.Visible := False;
updatePatientInfoView; // zzzzzzandria 060309
UpdateLatestVitals(FDFN, False);
end;
ShowModal;
bDataUpdated := False;
acSavePreferencesExecute(nil);
SaveWindowSettings(TForm(InputVitalsForm));
end;
finally
Free;
end;
end;
function VitalsInputDLG(aPatient, aLocation, aTemplate, aSignature: String; aDateTime: TDateTime; aName, anInfo: String): Integer;
var
aTime: TDateTime;
procedure SaveWindowSettings(Form: TForm);
var
s: String;
State: TWindowState;
begin
State := Form.WindowState;
Form.WindowState := wsNormal;
Form.Visible := False;
s := IntToStr(Screen.Width) + ';' + IntToStr(Screen.Height) + ';' + IntToStr(Form.Left) + ';' + IntToStr(Form.Top) + ';' + IntToStr(Form.Width) + ';' + IntToStr(Form.Height) + ';' + IntToStr(Integer(State));
s := setUserSettings(_WindowName, s);
if Piece(s, '^', 1) = '-1' then
MessageDLG('Unable to set parameter ' + _WindowName + '.' + #13 + 'Error Message: ' + Piece(s, '^', 2), mtError, [mbOK], 0);
end;
begin
Result := -1;
try
aTime := Now;
SetUpGlobals;
EventStop('Setup Globals', '', aTime);
aTime := Now;
GMVUser.SetupSignOnParams;
GMVUser.SetupUser;
EventStop('Setup User', '', aTime);
aTime := Now;
Application.CreateForm(TfrmGMV_InputLite, frmGMV_InputLite);
//frmGMV_InputLite := TfrmGMV_InputLite.Create(nil);
EventStop('Create Vitals Lite form', '', aTime);
aTime := EventStart('InputLite -- Begin');
frmGMV_InputLite.InputLite(aPatient, aLocation, aTemplate, aDateTime);
EventStop('InputLite -- End', '', aTime);
if frmGMV_InputLite._FHospitalIEN <> '' then
begin
try
frmGMV_InputLite.setPatientInfoView(aName, anInfo); // zzzzzzandria 060309
PositionForm(frmGMV_InputLite);
{ Result := } frmGMV_InputLite.ShowModal;
aTime := EventStart('Save form -- Begin');
{ These next two are commented because the form is already freed via caFree in OnClose }
// frmGMV_InputLite.acSavePreferencesExecute(nil);
// SaveWindowSettings(TForm(frmGMV_InputLite));
EventStop('Save form -- End', '', aTime);
except
on E: Exception do
ShowMessage('Error saving user preferences:'#13#13 + E.Message);
end;
end
else
ShowMessage('To enter Vitals select the patient location first');
// finally { added an exception to show there is an error }
// frmGMV_InputLite.Free
CleanUpGlobals;
Result := -1;
except
on E: Exception do
ShowMessage('Error while calling VitalsInputDLG: ' + E.Message);
end;
end;
function FormatLV(aSL: TStringList; aDelim: String): TStringList;
var
AbNormal: Boolean;
sBMI, sVital, sDate, sTime, sKey, sValue, sQual, sMetric, sEnteredBy, s, ss: string;
i: Integer;
SL: TStringList;
{$IFDEF PATCH_5_0_23}
sSource: String;
{$ENDIF}
const
// 1 5 10 15 20 25 30 35 40 45 50 55 60
// | | | | | | | | | | | | |
KeyWords = 'Temp. Pulse Resp. Pulse Ox B/P Ht. Wt. CVP Circ/Girth Pain Body Mass Index';
// 1 7 13 19 28 32 36 40 44 55 60
// AAN 06/10/02----------------------------------------------------------- Begin
procedure CorrectList(var tSL: TStringList);
var
s: string;
i, j: Integer;
begin
for i := 0 to tSL.Count - 1 do
begin
s := tSL.Strings[i];
j := pos('(,', s);
while j <> 0 do
begin
s := copy(s, 1, j) + copy(s, j + 2, Length(s) - j - 1);
j := pos('(,', s);
end;
tSL.Strings[i] := s;
end;
end;
// AAN 06/10/02------------------------------------------------------------- End
begin
SL := TStringList.Create;
SL.Assign(aSL);
CorrectList(SL);
sBMI := '';
for i := 0 to SL.Count - 1 do
begin
s := SL.Strings[i];
if pos('Body Mass Index:', s) <> 0 then
begin
sVital := 'Body Mass Index';
sEnteredBy := '';
ss := copy(s, 17, Length(s));
ss := TrimLeft(ss);
sBMI := ss;
end
else if pos('Pulse Ox:', s) <> 0 then
begin
sVital := 'Pulse Ox:';
ss := copy(s, 10, Length(s));
ss := TrimLeft(ss);
end
else
begin
sVital := Piece(s, ' ', 1);
ss := copy(s, pos(' ', s), Length(s));
ss := TrimLeft(ss);
end;
s := Piece(sVital, ':', 1);
if s = '' then // two records for the same date/time
begin
ss := TrimLeft(SL.Strings[i]);
sValue := ss;
sDate := '';
sTime := '';
end
else
begin
sKey := s;
s := copy(ss, 1, pos(' ', ss));
if pos('(', s) = 1 then
s := Piece(Piece(s, '(', 2), ')', 1); // to delete ()
sDate := Piece(s, '@', 1);
sTime := Piece(s, '@', 2);
ss := copy(ss, pos(' ', ss), Length(ss));
ss := TrimLeft(ss);
sValue := ss;
end;
sQual := '';
sMetric := '';
{$IFDEF PATCH_5_0_23}
sSource := Piece(sValue, '_', 3);
{$ENDIF}
case pos(sKey, KeyWords) of
// 1 5 10 15 20 25 30 35 40 45 50 55 60
// | | | | | | | | | | | | |
// KeyWords = 'Temp. Pulse Resp. Pulse Ox B/P Ht. Wt. CVP Circ/Girth Pain Body Mass Index';
// 1 7 13 19 28 32 36 40 44 55 60
0:
begin
sDate := '';
sTime := '';
sVital := ' ';
sValue := '';
sMetric := '';
sEnteredBy := '';
{$IFDEF PATCH_5_0_23}
sSource := '';
{$ENDIF}
sQual := SL.Strings[i];
end;
1: // Temp
begin
AbNormal := pos('*', sValue) > 0;
sEnteredBy := Piece(sValue, '_', 2);
sValue := Piece(sValue, '_', 1); // AAN 05/28/2003
sMetric := Piece(sValue, '(', 2, 2);
sMetric := Piece(sMetric, ')', 1);
sQual := sValue;
sValue := Piece(sValue, '(', 1);
if AbNormal and (pos('*', sValue) = 0) then
sValue := sValue + '*';
sQual := Piece(Piece(sQual, ')', 2), '(', 2);
sVital := 'Temperature';
end;
7: // Pulse
begin
AbNormal := pos('*', sValue) > 0;
sEnteredBy := Piece(sValue, '_', 2);
sValue := Piece(sValue, '_', 1); // AAN 05/28/2003
sValue := Piece(sValue, ' ', 1);
if AbNormal and (pos('*', sValue) = 0) then
sValue := sValue + '*';
sQual := Piece(Piece(ss, '(', 2), ')', 1);
sMetric := '';
sVital := 'Pulse';
end;
13: // Resp;
begin
AbNormal := pos('*', sValue) > 0;
sEnteredBy := Piece(sValue, '_', 2);
sValue := Piece(sValue, '_', 1); // AAN 05/28/2003
sValue := Piece(sValue, ' ', 1);
if AbNormal and (pos('*', sValue) = 0) then
sValue := sValue + '*';
sQual := Piece(Piece(ss, '(', 2), ')', 1);
sMetric := '';
sVital := 'Respiration';
end;
19: // Pulse Ox;
begin
// ABNormal := pos('*',sValue) > 0;
sEnteredBy := Piece(sValue, '_', 2);
sValue := Piece(sValue, '_', 1); // AAN 05/28/2003
sValue := Piece(sValue, '_', 1);
sQual := Trim(Piece(sValue, ' ', 2, 10));
if (pos('P', sValue) <> 1) and (pos('U', sValue) <> 1) and (pos('R', sValue) <> 1) then
sValue := Piece(sValue, '%', 1) + '%';
sMetric := '';
sVital := 'Pulse Oximetry';
if pos('*', sQual) = 1 then
begin
sValue := sValue + '*';
sQual := Trim(Piece(sQual, '*', 2));
end;
end;
28: // B/P
begin
AbNormal := pos('*', sValue) > 0;
sEnteredBy := Piece(sValue, '_', 2);
sValue := Piece(sValue, '_', 1); // AAN 05/28/2003
sValue := Piece(sValue, ' ', 1);
if AbNormal and (pos('*', sValue) = 0) then
sValue := sValue + '*';
sQual := Piece(Piece(ss, '(', 2), ')', 1);
sMetric := '';
sVital := 'Blood Pressure';
end;
32: // Height
begin
AbNormal := pos('*', sValue) > 0;
sEnteredBy := Piece(sValue, '_', 2);
sValue := Piece(sValue, '_', 1); // AAN 05/28/2003
sMetric := Piece(sValue, '(', 2, 2);
sMetric := Piece(sMetric, ')', 1);
sQual := sValue;
sValue := Piece(sValue, '(', 1);
if AbNormal and (pos('*', sValue) = 0) then
sValue := sValue + '*';
sQual := Piece(Piece(sQual, ')', 2), '(', 2);
sVital := 'Height';
end;
36: // Weight
begin
AbNormal := pos('*', sValue) > 0;
sEnteredBy := Piece(sValue, '_', 2);
sValue := Piece(sValue, '_', 1); // AAN 05/28/2003
sMetric := Piece(sValue, '(', 2, 2);
sMetric := Piece(sMetric, ')', 1);
sQual := sValue;
sValue := Piece(sValue, '(', 1);
if AbNormal and (pos('*', sValue) = 0) then
sValue := sValue + '*';
sQual := Piece(Piece(sQual, ')', 2), '(', 2);
sVital := 'Weight';
end;
40: // CVP
begin
AbNormal := pos('*', sValue) > 0;
sEnteredBy := Piece(sValue, '_', 2);
sValue := Piece(sValue, '_', 1); // AAN 05/28/2003
sMetric := Piece(sValue, '(', 2, 2);
sMetric := Piece(sMetric, ')', 1);
sQual := sValue;
sValue := Piece(sValue, '(', 1);
if AbNormal and (pos('*', sValue) = 0) then
sValue := sValue + '*';
sQual := Piece(Piece(sQual, ')', 2), '(', 2);
sVital := 'CVP';
end;
44:
begin
AbNormal := pos('*', sValue) > 0;
sEnteredBy := Piece(sValue, '_', 2);
sValue := Piece(sValue, '_', 1); // AAN 05/28/2003
sMetric := Piece(sValue, '(', 2, 2);
sMetric := Piece(sMetric, ')', 1);
sQual := sValue;
sValue := Piece(sValue, '(', 1);
if AbNormal and (pos('*', sValue) = 0) then
sValue := sValue + '*';
sQual := Piece(Piece(sQual, ')', 2), '(', 2);
sVital := 'Circumference/Girth';
end;
55: // Pain
begin
AbNormal := pos('*', sValue) > 0;
sEnteredBy := Piece(sValue, '_', 2);
sValue := Piece(sValue, '_', 1);
if AbNormal and (pos('*', sValue) = 0) then
sValue := sValue + '*';
sVital := 'Pain';
end;
60: // Body Mass Index;
begin
sQual := '';
sMetric := '';
sDate := '';
sTime := '';
sValue := sBMI;
end;
end;
if ((Trim(sVital) = '') and (pos('There', Trim(sQual)) = 1)) then
begin
SL.Strings[i] := aDelim + 'There are' + aDelim + 'no results' + aDelim + 'to report' + aDelim + aDelim;
end
else
begin
SL.Strings[i] := sDate + ' ' + sTime + aDelim + sVital + aDelim + sValue + aDelim + sMetric + aDelim + sQual + aDelim + sEnteredBy
{$IFDEF PATCH_5_0_23}
+ aDelim + sSource
{$ENDIF}
;
end;
end;
SL.Insert(0, 'Date & Time' + aDelim + 'Vital' + aDelim + 'USS Value' + aDelim + 'Metric Value' + aDelim + 'Qualifiers' + aDelim + 'Entered by'
{$IFDEF PATCH_5_0_23}
+ aDelim + 'Data Source'
{$ENDIF}
);
Result := SL;
end;
function VitalsInputForm(aPatient, aLocation, aTemplate, aSignature: String; aDateTime: TDateTime): TfrmGMV_InputLite;
begin
try
Application.CreateForm(TfrmGMV_InputLite, frmGMV_InputLite);
frmGMV_InputLite.Status := stsDLL;
frmGMV_InputLite.InputLite(aPatient, aLocation, aTemplate, aDateTime);
frmGMV_InputLite.pnlTools.Visible := False;
frmGMV_InputLite.chkbCloseOnSave.Visible := False;
frmGMV_InputLite.pnlButtons.Width := frmGMV_InputLite.btnSave.Width + frmGMV_InputLite.btnSave.Left + 6;
frmGMV_InputLite.BorderStyle := bsNone;
Result := frmGMV_InputLite;
except
Result := nil;
end;
end;
function GetLatestVitals(aPatient, aDelim: String; bSilent: Boolean): TStringList;
var
aSL: TStringList;
begin
aSL := getLatestVitalsByDFN(aPatient, bSilent);
Result := FormatLV(aSL, '^');
aSL.Free;
end;
/// /////////////////////////////////////////////////////////////////////////////
procedure TfrmGMV_InputLite.InputLite(PatientDFN: string; PatientLocationIEN: string; InputTemplate: string; aDateTime: TDateTime);
var
i: Integer;
sDateTime, sCaption, sTemplate: String;
sWindowSettings: String;
aSL: TStrings;
aTime: TDateTime;
// Have some problems with: RestoreWindowSettings(TForm(InputVitalsForm));
procedure RestoreWin;
begin
try
sWindowSettings := ClassName;
sWindowSettings := getUserSettings(_WindowName);
if sWindowSettings <> '' then
begin
Left := StrToIntDef(Piece(sWindowSettings, ';', 3), Left);
Top := StrToIntDef(Piece(sWindowSettings, ';', 4), Top);
Width := StrToIntDef(Piece(sWindowSettings, ';', 5), Width);
Height := StrToIntDef(Piece(sWindowSettings, ';', 6), Height);
end;
except
end;
end;
procedure setWindowCaption;
begin
sCaption := ' Vitals Lite Enter';
if fFileComments <> '' then
sCaption := sCaption + ' (' + fFileComments + ') ';
sCaption := sCaption + ' User: ' + GMVUser.Name;
if GMVUser.Title <> '' then
sCaption := sCaption + ' (' + GMVUser.Title + ')';
sCaption := sCaption + ' Division: ' + GMVUser.Division;
Caption := sCaption;
end;
begin
aSL := TStringList.Create;
try
gbxPatients.Visible := False;
setWindowCaption;
chkbCloseOnSave.Visible := True;
btnSaveAndExit.Visible := False;
bSlave := True;
FDFN := PatientDFN;
// select a location first
if (PatientLocationIEN = '') or (PatientLocationIEN = '0') then
acHospitalSelectorExecute(nil)
else
begin
sCaption := getFileField('44', '2', PatientLocationIEN);
if (pos('WARD', uppercase(sCaption)) <> 0) or (pos('CLINIC', uppercase(sCaption)) <> 0) then
begin
_FHospitalIEN := PatientLocationIEN;
sCaption := getFileField('44', '.01', _FHospitalIEN); // zzzzzzandria 050210
lblHospital.Caption := sCaption;
end
else
_FHospitalIEN := PatientLocationIEN;
end;
sCaption := getFileField('44', '.01', _FHospitalIEN); // zzzzzzandria 050210
lblHospital.Caption := sCaption;
try
sDateTime := getCurrentDateTime;
dtpDate.Date := FMDateTimeToWindowsDateTime(StrToFloat(sDateTime)); // 10/08/2002 AAN
dtpDate.MaxDate := dtpDate.Date;
dtpTime.DateTime := FMDateTimeToWindowsDateTime(StrToFloat(sDateTime));
{$IFDEF DLL}
chkbCloseOnSave.Visible := False; // zzzzzzandria 050209
btnSaveAndExit.Visible := True;
// CurrentTime := Now;
if aDateTime <> 0 then
begin
CurrentTime := aDateTime; // zzzzzzandra 20081008 fixing discepency between PC and VistA
//dtpDate.MaxDate := 0; // Gotta reset MaxDate here since the datetime came from the DLL Client
//dtpDate.Date := 0;
dtpDate.MaxDate := CurrentTime;
dtpDate.Date := Trunc(CurrentTime);
dtpTime.DateTime := CurrentTime;
end
else
CurrentTime := dtpDate.Date;
dtpTimeChange(nil);
{$ELSE}
CurrentTime := dtpTime.DateTime;
{$ENDIF}
except
on E: EConvertError do
MessageDLG('Input Lite: Unable to set client to the servers time.' + #13#10 + E.Message, mtWarning, [mbOK], 0);
on E: Exception do
begin
ShowMessage('Exception reads: ' + E.Message);
raise
end;
end;
aTime := Now;
acLoadPreferencesExecute(nil);
EventStop('LoadPreferences', '', aTime);
aTime := Now;
RestoreWin;
EventStop('RestoreWin', '', aTime);
aTime := Now;
LoadTreeView;
if tv <> nil then
begin
sTemplate := Piece(FNewTemplate, '|', 2);
if sTemplate = '' then
try
sTemplate := FDefaultTemplate.TemplateName;
except
end;
for i := 0 to tv.Items.Count - 1 do
begin
if sTemplate = tv.Items[i].Text then
begin
tv.Selected := tv.Items[i];
break;
end;
end;
end;
EventStop('Restore template tree', '', aTime);
aTime := Now;
UpdatePatient(FDFN);
EventStop('Update patient', '', aTime);
finally
aSL.Free;
end;
end;
/// /////////////////////////////////////////////////////////////////////////////
procedure TfrmGMV_InputLite.UpdatePatient(aPatient: String);
begin
{$IFNDEF DLL}
updatePatientInfoView;
{$ENDIF}
UpdateLatestVitals(aPatient, False);
end;
procedure TfrmGMV_InputLite._SetCurrentPtIEN(const Value: string);
begin
_FCurrentPtIEN := Value;
FDFN := Value;
{$IFNDEF DLL}
lblHospital.Caption := getHospitalLocationByID(_CurrentPtIEN);
{$ENDIF}
UpdatePatient(_CurrentPtIEN);
end;
procedure TfrmGMV_InputLite.FocusInputField;
var
i: Integer;
begin
for i := 0 to sbxMain.ControlCount - 1 do
if sbxMain.Controls[i] is TfraGMV_InputOne2 then
begin
ActiveControl := TfraGMV_InputOne2(sbxMain.Controls[i]).cbxInput;
break;
end;
end;
procedure TfrmGMV_InputLite.btnCancelClick(Sender: TObject);
begin
if (InputString <> '') then
begin
if (MessageDLG('Some of the input fields contain data.' + #13 + #13
// +'Do you really want to close the input window?',
+ 'Click "Yes" to exit without saving the data' + #13 + #10 + 'Click "No" to return to the input template', mtConfirmation, [mbYes, mbNo], 0) <> mrYes) then
exit
else
bDataUpdated := False;
end;
if bSlave then
begin
acSavePreferencesExecute(nil);
SaveWindowSettings(Self);
end;
Close;
end;
procedure TfrmGMV_InputLite.FormClose(Sender: TObject; var Action: TCloseAction);
var
i: Integer;
begin
for i := sbxMain.ComponentCount - 1 downto 0 do
if sbxMain.Components[i] is TfraGMV_InputOne2 then
TfraGMV_InputOne2(sbxMain.Components[i]).Free;
if bSlave then
begin
// commented by zzzzzzandria on 050209
// acSaveInputExecute(nil);
if InputString = '' then
Action := caFree // DLL
else
Action := caNone;
end;
end;
procedure TfrmGMV_InputLite.ClearVitalsList;
var
i: Integer;
p: TPanel;
begin
i := 0;
while sbxMain.ComponentCount > 0 do
begin
if sbxMain.Components[i] is TfraGMV_InputOne2 then
TfraGMV_InputOne2(sbxMain.Components[i]).Free
else if sbxMain.Components[i] is TPanel then
begin
p := TPanel(sbxMain.Components[i]);
p.Free;
end
else
inc(i);
if i > sbxMain.ComponentCount then
break;
end;
end;
procedure TfrmGMV_InputLite.SetVitalsList(InputTemplate: String);
var
InputOne2: TfraGMV_InputOne2; // ZZZZZZBELLC
i: Integer;
begin
Screen.Cursor := crHourGlass;
sbxMain.Visible := False;
try
ClearVitalsList;
acSaveInput.Enabled := False;
except
end;
if assigned(FInputTemplate) then
FreeAndNil(FInputTemplate);
FInputTemplate := GetTemplateObject(Piece(InputTemplate, '|', 1), Piece(InputTemplate, '|', 2));
if FInputTemplate <> nil then
begin
FTemplateData := Piece(FInputTemplate.XPARValue, '|', 2);
i := 1;
while Piece(FTemplateData, ';', i) <> '' do
begin
try
InputOne2 := TfraGMV_InputOne2.Create(sbxMain); // works in unit
InputOne2.DFN := FDFN; // zzzzzzandria 2009 02 27
acSaveInput.Enabled := True;
with InputOne2 do
begin
ConversionWarning := False;
cbConversionWarning.Checked := False;
Parent := sbxMain;
Name := 'tmplt' + IntToStr(i);
if (i mod 2) = 0 then
pnlMain.Color := $00B1B1B1
else
pnlMain.Color := clBtnFace;
TemplateVital := TGMV_TemplateVital.CreateFromXPAR(Piece(FTemplateData, ';', i));
DefaultTemplateVital := TemplateVital;
lblNum.Caption := IntToStr(i) + '. ';
if i < 10 then
begin
lblNum.Caption := '&' + lblNum.Caption;
lblNum.FocusControl := cbxInput;
end;
Top := i * Height;
TabOrder := Top;
Align := alTop;
try
ckbMetricClick(nil); // AAN 08/16/2002
except
end;
end;
except
on E: Exception do
MessageDialog('Error', 'Error creating input template ' + #13 + E.Message, mtError, mbYesNoCancel, 0, 0);
end;
inc(i);
end;
try
acMetricStyleChangeExecute(nil);
except
end;
end;
sbxMain.Visible := True;
bDataUpdated := False;
FocusInputField;
Screen.Cursor := crDefault;
end;
procedure TfrmGMV_InputLite.dtpTimeChange(Sender: TObject);
begin
if trunc(dtpDate.Date) + frac(dtpTime.Time) > CurrentTime then
dtpTime.Time := CurrentTime;
lblDateTime.Caption := ' ' + FormatDateTime(GMV_DateFormat, dtpDate.Date) + ' ' + FormatDateTime(GMV_TimeFormat, dtpTime.Time);
end;
procedure TfrmGMV_InputLite.FormResize(Sender: TObject);
begin
hc.Sections[3].Width := 118;
hc.Sections[4].Width := 116;
hc.Sections[5].Width := 78;
hc.Sections[6].Width := hc.Width - hc.Sections[0].Width - hc.Sections[1].Width - hc.Sections[2].Width - hc.Sections[3].Width - hc.Sections[4].Width - hc.Sections[5].Width;
strgLV.ColWidths[0] := hc.Sections[0].Width + hc.Sections[1].Width + hc.Sections[2].Width + 2;
strgLV.ColWidths[1] := hc.Sections[3].Width - 2;
strgLV.ColWidths[2] := hc.Sections[4].Width;
strgLV.ColWidths[3] := hc.Sections[5].Width;
strgLV.ColWidths[4] := hc.Sections[6].Width - 100;
strgLV.ColWidths[5] := 100;
if Height > Screen.Height then
Height := Screen.Height;
acAdjustToolbars.Execute;
end;
procedure TfrmGMV_InputLite.LoadTreeView;
var
tmpList: TStringList;
i: Integer;
begin
tv.Enabled := False;
tv.Items.BeginUpdate;
tv.ShowRoot := True;
tv.Ctl3D := False;
with tv.Items do
begin
Clear;
CleanUp;
FTmpltRoot := nil;
FTmpltDomainRoot := AddChild(FTmpltRoot, GMVENTITYNAMES[teDomain]);
FTmpltInstitutionRoot := AddChild(FTmpltRoot, GMVENTITYNAMES[teInstitution]);
FTmpltHopsitalLocationRoot := AddChild(FTmpltRoot, GMVENTITYNAMES[teHospitalLocation]);
if GMVAllowUserTemplates then
FTmpltNewPersonRoot := AddChild(FTmpltRoot, GMVENTITYNAMES[teNewPerson]);
end;
try
tmpList := getTemplateListByID('');
for i := 1 to tmpList.Count - 1 do
begin
SetLength(fGMV_TemplateArray, Length(fGMV_TemplateArray) +1);
fGMV_TemplateArray[high(fGMV_TemplateArray)] := TGMV_Template.CreateFromXPAR(tmpList[i]);
InsertTemplate(fGMV_TemplateArray[high(fGMV_TemplateArray)]);
end;
finally
FreeAndNil(tmpList);
end;
// tv.Ctl3D := False;
tv.AlphaSort;
tv.Enabled := True;
tv.TopItem := tv.Items.GetFirstNode;
tv.Items.EndUpdate;
Refresh;
end;
procedure TfrmGMV_InputLite.InsertTemplate(Template: TGMV_Template; GoToTemplate: Boolean = False);
var
TypeRoot: TTreeNode;
oRoot: TTreeNode;
NewNode: TTreeNode;
function OwnerRoot: TTreeNode;
begin
Result := nil;
try
oRoot := TypeRoot.getFirstChild;
except
oRoot := nil;
end;
while oRoot <> nil do
begin
if TGMV_TemplateOwner(oRoot.Data).Entity = Template.Entity then
begin
Result := oRoot;
exit;
end
else
oRoot := TypeRoot.GetNextChild(oRoot);
end;
if oRoot = nil then
begin
if Template.EntityType = teNewPerson then
begin
if GMVAllowUserTemplates then
Result := tv.Items.AddChildObject(TypeRoot, TitleCase(Template.Owner.OwnerName), Template.Owner);
end
else
Result := tv.Items.AddChildObject(TypeRoot, Template.Owner.OwnerName, Template.Owner);
end;
end;
begin
case Template.EntityType of
teUnknown:
TypeRoot := nil;
teDomain:
TypeRoot := FTmpltDomainRoot;
teInstitution:
TypeRoot := FTmpltInstitutionRoot;
teHospitalLocation:
TypeRoot := FTmpltHopsitalLocationRoot;
teNewPerson:
TypeRoot := FTmpltNewPersonRoot;
end;
NewNode := tv.Items.AddChildObject(OwnerRoot, Template.TemplateName, Template);
if (GMVDefaultTemplates <> nil) and GMVDefaultTemplates.IsDefault(Template.Entity, Template.TemplateName) then
begin
NewNode.ImageIndex := GMVIMAGES[iiDefaultTemplate];
NewNode.SelectedIndex := GMVIMAGES[iiDefaultTemplate];
// Default Template Data;
if Template.EntityType = teDomain then
FDefaultTemplate := Template;
end
else
begin
NewNode.ImageIndex := GMVIMAGES[iiTemplate];
NewNode.SelectedIndex := GMVIMAGES[iiTemplate];
end;
if GoToTemplate then
begin
NewNode.Selected := True;
tv.SetFocus;
end;
end;
procedure TfrmGMV_InputLite.tvChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean);
begin
if Node = nil then
exit;
try
if Node.Level > 1 then
begin
FNewTemplate := TGMV_Template(Node.Data).Entity + '|' + TGMV_Template(Node.Data).TemplateName;
FNewTemplateDescription := Piece(TGMV_Template(Node.Data).XPARValue, '|', 1);
SetVitalsList(FNewTemplate + '^' + FNewTemplateDescription);
pnlInputTemplateHeader.Caption := ' Vitals input template: <' + TGMV_Template(Node.Data).TemplateName + '>';
lblTemplInfo.Caption := Piece(TGMV_Template(Node.Data).XPARValue, '|', 1);
end
else
lblTemplInfo.Caption := '';
tv.hint := lblTemplInfo.Caption;
except
end;
end;
procedure TfrmGMV_InputLite.CleanUpVitalsList;
var
i: Integer;
begin
for i := 0 to sbxMain.ComponentCount - 1 do
if sbxMain.Components[i] is TfraGMV_InputOne2 then
try
TfraGMV_InputOne2(sbxMain.Components[i]).cbxInput.ItemIndex := -1;
TfraGMV_InputOne2(sbxMain.Components[i]).cbxInput.Text := '';
TfraGMV_InputOne2(sbxMain.Components[i]).cbxUnavailable.Checked := False;
TfraGMV_InputOne2(sbxMain.Components[i]).cbxRefused.Checked := False;
TfraGMV_InputOne2(sbxMain.Components[i]).TemplateVital := TfraGMV_InputOne2(sbxMain.Components[i]).DefaultTemplateVital;
TfraGMV_InputOne2(sbxMain.Components[i]).SetMetricStyle(chkCPRSSTyle.Checked);
// AAN 2003/09/17
TfraGMV_InputOne2(sbxMain.Components[i]).ckbMetricClick(nil);
TfraGMV_InputOne2(sbxMain.Components[i]).ClearPO2FlowRateAndPercentage;
except
end;
ckbOnPass.Checked := False; // zzzzzzandria 050429
ckbUnavailable.Checked := False; // zzzzzzandria 050429
bDataUpdated := False;
end;
procedure TfrmGMV_InputLite.FormActivate(Sender: TObject);
begin
dtpTimeChange(Sender);
acUnavailableBoxStatusExecute(Sender); // ?
cbRClick(nil);
end;
procedure TfrmGMV_InputLite.acMetricStyleChangeExecute(Sender: TObject);
var
i: Integer;
begin
for i := 0 to sbxMain.ComponentCount - 1 do
if sbxMain.Components[i] is TfraGMV_InputOne2 then
TfraGMV_InputOne2(sbxMain.Components[i]).SetMetricStyle(chkCPRSSTyle.Checked);
acMetricStyleChange.Checked := acMetricStyleChange.Enabled;
acUnitsDDL.Checked := chkCPRSSTyle.Checked;
end;
procedure TfrmGMV_InputLite.CMHospitalUpdate(var Message: TMessage);
begin
end;
procedure TfrmGMV_InputLite.ckbOnPassEnter(Sender: TObject);
begin
bvU.Visible := True;
end;
procedure TfrmGMV_InputLite.ckbOnPassExit(Sender: TObject);
begin
bvU.Visible := False;
end;
procedure TfrmGMV_InputLite.acSavePreferencesExecute(Sender: TObject);
procedure saveBoolean(aSetting: TGMV_UserSetting; aValue: Boolean; aTrue, aFalse: String);
begin
if aValue then
GMVUser.Setting[aSetting] := aTrue
else
GMVUser.Setting[aSetting] := aFalse;
end;
begin
if FNewTemplate <> '' then // zzzzzzandria 050209
GMVUser.Setting[usDefaultTemplate] := FNewTemplate;
if chkOneUnavailableBox.Checked then
GMVUser.Setting[usOneUnavailableBox] := 'OneUnavailableBox'
else
GMVUser.Setting[usOneUnavailableBox] := 'ManyUnavailableBoxes';
(*
if chkbCloseOnSave.Checked then
GMVUser.Setting[usCloseInputWindowAfterSave] :='CloseInputWindowAfterSave'
else
GMVUser.Setting[usCloseInputWindowAfterSave] :='DoNotCloseInputWindow';
saveBoolean(usCloseInputWindowAfterSave,chkbCloseOnSave.Checked,
'CloseInputWindowAfterSave','DoNotCloseInputWindow');
*)
// if chkCPRSStyle.Checked then GMVUser.Setting[usMetricStyle] :='CPRSMetricStyle'
// else GMVUser.Setting[usMetricStyle] :='VitalsMetricStyle';
saveBoolean(usMetricStyle, chkCPRSSTyle.Checked, 'CPRSMetricStyle', 'VitalsMetricStyle');
GMVUser.Setting[usParamTreeWidth] := IntToStr(pnlParams.Width);
// if bShowParams then GMVUser.Setting[usTemplateTree] := 'ShowTemplates'
// else GMVUser.Setting[usTemplateTree] := 'NoTemplates';
saveBoolean(usTemplateTree, bShowParams, 'ShowTemplates', 'NoTemplates');
GMVUser.Setting[usLastVitalsListHeight] := IntToStr(pnlLatestVitalsBg.Height);
if bShowVitals then
GMVUser.Setting[usLastVitals] := 'ShowLastVitals'
else
GMVUser.Setting[usLastVitals] := 'NoLatestVitals';
if cbR.Checked then
setUserSettings('RefuseStatus', 'ON')
else
setUserSettings('RefuseStatus', 'OFF');
if cbU.Checked then
setUserSettings('UnavailableStatus', 'ON')
else
setUserSettings('UnavailableStatus', 'OFF');
(* commented 2008-04-23 zzzzzzandria
if cbU.Checked then setUserSettings('ConversionWarningStatus','ON')
else setUserSettings('ConversionWarningStatus','OFF');
*)
end;
procedure TfrmGMV_InputLite.acLoadPreferencesExecute(Sender: TObject);
var
s: String;
i: Integer;
begin
try
FNewTemplate := GMVUser.Setting[usDefaultTemplate];
except
FNewTemplate := '';
end;
bShowVitals := not(GMVUser.Setting[usLastVitals] = 'ShowLastVitals');
acVitalsShowHideExecute(nil);
s := GMVUser.Setting[usLastVitalsListHeight];
if s <> '' then
try
pnlLatestVitalsBg.Height := StrToInt(s);
except
pnlLatestVitalsBg.Height := pnlInput.Height div 4;
end
else
pnlLatestVitalsBg.Height := pnlInput.Height div 4;
bShowParams := not(GMVUser.Setting[usTemplateTree] = 'ShowTemplates');
acParamsShowHideExecute(nil);
s := GMVUser.Setting[usParamTreeWidth];
if s <> '' then
try
i := StrToInt(s);
pnlParams.Width := i;
except
pnlParams.Width := 150;
end
else
pnlParams.Width := 150;
chkCPRSSTyle.Checked := GMVUser.Setting[usMetricStyle] = 'CPRSMetricStyle';
acMetricStyleChangeExecute(Sender);
// chkOneUnavailableBox.Checked :=
// GMVUser.Setting[usOneUnavailableBox] ='OneUnavailableBox';
chkOneUnavailableBox.Checked := False; // AAN 05/21/2003
acUnavailableBoxStatusExecute(Sender);
{ zzzzzzandria 20050209
chkbCloseOnSave.Checked :=
GMVUser.Setting[usCloseInputWindowAfterSave] ='CloseInputWindowAfterSave';
}
s := getUserSettings('RefuseStatus');
cbR.Checked := s <> 'OFF';
s := getUserSettings('UnavailableStatus');
cbU.Checked := s <> 'OFF';
{ zzzzzzandria 2008-04-23 commented
s := getUserSettings('ConversionWarningStatus');
cbConversionWarning.Checked := s = 'ON';
}
end;
procedure TfrmGMV_InputLite.UpdateLatestVitals(aPatient: String; bSilent: Boolean);
var
aSL: TStringList;
TheSL: TStringList;
i, j: Integer;
s: String;
begin
aSL := getLatestVitalsByDFN(aPatient, bSilent);
TheSL := FormatLV(aSL, '^');
strgLV.RowCount := TheSL.Count + 1;
strgLV.Cells[0, 0] := 'Date & Time';
strgLV.Cells[1, 0] := 'Vital';
strgLV.Cells[2, 0] := 'USS Value';
strgLV.Cells[3, 0] := 'Metric Value';
strgLV.Cells[4, 0] := 'Qualifiers';
strgLV.Cells[5, 0] := 'Entered by';
{$IFDEF PATCH_5_0_23}
strgLV.Cells[6, 0] := 'Data Source';
{$ENDIF}
{$IFDEF AANTEST}
ShowMessage(aSL.Text + #13#10 + TheSL.Text); // zzzzzzandria 050429
{$ENDIF}
for i := 1 to TheSL.Count - 1 do // first row contains headers
begin
s := TheSL.Strings[i];
for j := 0 to strgLV.ColCount - 1 do
strgLV.Cells[j, i] := Piece(s, '^', j + 1);
end;
TheSL.Free;
aSL.Free;
end;
procedure TfrmGMV_InputLite.tvExpanded(Sender: TObject; Node: TTreeNode);
begin
if Node.Level < 2 then
Node.ImageIndex := 1;
end;
procedure TfrmGMV_InputLite.tvCollapsed(Sender: TObject; Node: TTreeNode);
begin
if Node.Level < 2 then
Node.ImageIndex := 0;
end;
procedure TfrmGMV_InputLite.pnlParamsResize(Sender: TObject);
begin
pnlPatient.Width := pnlParams.Width + 5;
acAdjustToolbars.Execute;
end;
procedure TfrmGMV_InputLite.acSetOnPassExecute(Sender: TObject);
var
i: Integer;
begin
if (Sender = ckbUnavailable) and ckbUnavailable.Checked and ckbOnPass.Checked then
ckbOnPass.Checked := False
else if ckbOnPass.Checked and ckbUnavailable.Checked then
ckbUnavailable.Checked := False;
for i := 0 to sbxMain.ComponentCount - 1 do
begin
if sbxMain.Components[i] is TfraGMV_InputOne2 then
begin
if (ckbOnPass.Checked) or (ckbUnavailable.Checked) // AAN 12/09/2002
then
begin
TfraGMV_InputOne2(sbxMain.Components[i]).DisablePanel;
TfraGMV_InputOne2(sbxMain.Components[i]).cbxRefused.Enabled := False;
TfraGMV_InputOne2(sbxMain.Components[i]).cbxUnavailable.Enabled := False;
end
else
begin
if TfraGMV_InputOne2(sbxMain.Components[i]).cbxRefused.Checked or TfraGMV_InputOne2(sbxMain.Components[i]).cbxUnavailable.Checked then
TfraGMV_InputOne2(sbxMain.Components[i]).DisablePanel
else
TfraGMV_InputOne2(sbxMain.Components[i]).EnablePanel;
TfraGMV_InputOne2(sbxMain.Components[i]).cbxRefused.Enabled := True;
TfraGMV_InputOne2(sbxMain.Components[i]).cbxUnavailable.Enabled := True;
end;
end
end;
if acSetOnPass.Enabled then
acSetOnPass.Checked := True
else
acSetOnPass.Checked := False;
end;
procedure TfrmGMV_InputLite.SaveData(DT: TDateTime);
var
sPO2: String;
i: Integer;
s1, s2, X: String;
begin
sPO2 := getVitalTypeIEN('PULSE OXIMETRY'); // zzzzzzandria 050715
for i := 0 to sbxMain.ControlCount - 1 do
begin
if sbxMain.Controls[i] is TfraGMV_InputOne2 then
with TfraGMV_InputOne2(sbxMain.Controls[i]) do
begin
X := '';
if ckbOnPass.Checked then
begin
X := FloatToStr(DT) + '^' + FDFN + '^' + VitalIEN + ';Pass;' + '^' + _FHospitalIEN + '^' + GMVUser.DUZ + '*';
end
else if ckbUnavailable.Checked then
begin
X := FloatToStr(DT) + '^' + FDFN + '^' + VitalIEN + ';Unavailable;' + '^' + _FHospitalIEN + '^' + GMVUser.DUZ + '*';
end
else if VitalsRate <> '' then
begin
s1 := VitalsRate;
(* zzzzzzandria 20071220 ==== No special treatment for sPO2 ====================
// AAN 2003/06/30 -- do not show qualifiers for PulseOx if there is no rate
if (piece(s1,';',1) = sPO2) // PulseOx ID {'21'}
and (piece(s1,';',3)='') // no value for the Flow rate for PulseOx
// uncomment the next line if you'd like to ignore "no Flow Rate" for the Room Air
and (pos('ROOM AIR',uppercase(lblQualifiers.Caption))=0) // Method is not <Room Air>
then
s2 := ''
else
============================================================================= *)
s2 := VitalsQualifiers;
X := FloatToStr(DT) + '^' + FDFN + '^' + s1 + '^' + _FHospitalIEN + '^' + GMVUser.DUZ + '*' + s2;
end;
if X <> '' then
begin
// CallRemoteProc(RPCBroker, 'GMV ADD VM', [x], nil,[rpcSilent,rpcNoresChk]);
// if RPCBroker.Results.Count > 1 then
// MessageDlg(RPCBroker.Results.Text, mtError, [mbok], 0);
X := addVM(X);
if X <> '' then
MessageDLG(X, mtError, [mbOK], 0);
end;
end;
end;
{$IFDEF USEVSMONITOR}
// CASMED support////////////////////////////////////////////////
// zzzzzzabdria 20080929 check added to speed up cases when the device is not used
if bCasmedUsed then
try
if not Assigned(Casmed) then
Casmed := TATE740X.Create(sCasmedPort);
Casmed.NewPatient;
bCasmedUsed := False;
finally
FreeAndNil(Casmed);
end;
{$ENDIF} /// ///////////////////////////////////////////////////////////////////
CleanUpVitalsList;
UpdatePatient(FDFN);
end;
procedure TfrmGMV_InputLite.acSaveInputExecute(Sender: TObject);
const
sLastProcessedMessage = 'The last patient in the list processed' + #13 + 'Close the input window?';
sSelectHospital = 'Please select a valid hospital location for this patient.';
var
aTime: TDateTime;
sNoDataEntered: String;
DT: TDateTime;
procedure AssignImageIndex(anIndex: Integer);
begin
if lvSelPatients.ItemFocused.SubItems[3] = '' then
begin
lvSelPatients.ItemFocused.ImageIndex := anIndex;
lvSelPatients.ItemFocused.SubItems[3] := IntToStr(anIndex);
end
else
begin
lvSelPatients.ItemFocused.SubItems[3] := lvSelPatients.ItemFocused.SubItems[3] + ' ' + IntToStr(anIndex);
lvSelPatients.ItemFocused.ImageIndex := indMultipleInput;
end;
end;
function CheckData(aDT: TDateTime): Boolean;
var
i: Integer;
begin
for i := 0 to sbxMain.ComponentCount - 1 do
if not TfraGMV_InputOne2(sbxMain.Components[i]).Check(aDT) then
break;
Result := i = sbxMain.ComponentCount;
if not Result then
begin
TfraGMV_InputOne2(sbxMain.Components[i]).cbxInput.SelStart := 0;
TfraGMV_InputOne2(sbxMain.Components[i]).cbxInput.SelLength := Length(TfraGMV_InputOne2(sbxMain.Components[i]).cbxInput.Text);
TfraGMV_InputOne2(sbxMain.Components[i]).cbxInput.SetFocus;
end;
end;
procedure ProcessNext(ResultIndex: Integer);
begin
if (lvSelPatients = nil) or (lvSelPatients.Items.Count < 2) then
begin
if bSlave then // DLL
begin
if chkbCloseOnSave.Checked or (Sender = btnSaveAndExit) // added zzzzzzandria 050707 for DLL use
then
begin
Close;
Exit; // Get out of here now, we just triggered the form Destroy with caFree
end
else
UpdateLatestVitals(FDFN, True);
end
else
begin
// Do we need to close window if the list contains only one patient?
// Yes we do
// Do we need to have a message?
// No we don't
// s := LastProcessedMessage;
// if MessageDlgS(S,mtInformation,mbOKCancel,0) = mrOK then
if Sender = btnSaveAndExit then
ModalResult := mrOk;
end;
end;
try
if lvSelPatients.ItemFocused.Index < 0 then
lvSelPatients.ItemFocused := lvSelPatients.Items[0];
except
lvSelPatients.ItemFocused := lvSelPatients.Items[0];
end;
try
if lvSelPatients.ItemFocused.Index < 0 then
lvSelPatients.ItemFocused := lvSelPatients.Items[0];
if lvSelPatients.ItemFocused.Index < lvSelPatients.Items.Count - 1 then
begin
AssignImageIndex(ResultIndex);
lvSelPatients.ItemFocused := lvSelPatients.Items[lvSelPatients.ItemFocused.Index + 1];
lvSelPatients.ItemFocused.ImageIndex := 1;
lvSelPatientsClick(Sender);
CleanUpVitalsList;
SetVitalsList(FNewTemplate + '^' + FNewTemplateDescription); // ZZZZZZBELLC
if not lvSelPatients.CheckBoxes then
ckbOnPass.Checked := False;
FocusInputField;
end
else
begin
AssignImageIndex(ResultIndex);
lvSelPatients.Invalidate;
// lvSelPatientsClick(Sender);// may be it is too much
if lvSelPatients.Items.Count < 2 then
ModalResult := mrOk
else if MessageDLG(sLastProcessedMessage, mtInformation, mbOKCancel, 0) = mrOk then
ModalResult := mrOk;
end;
except
end;
end;
begin
// Check all input panels for valid values
DT := WindowsDateTimeToFMDateTime(trunc(dtpDate.Date) + (dtpTime.DateTime - trunc(dtpTime.Date)));
if not CheckData(DT) then
exit;
// Hospital location should be set before saving data -- 03/14/2003 AAN
if (_FHospitalIEN = '') or (_FHospitalIEN = '0') then
MessageDLG(sSelectHospital, mtWarning, [mbOK], 0)
else
begin
if InputString <> '' then
begin
aTime := EventStart('Save Vitals -- Begin');
SaveData(DT);
EventStop('Save Vitals -- End', '', aTime);
if ckbOnPass.Checked then
ProcessNext(indOnPass)
else
ProcessNext(indSingleInput);
end
else
begin
sNoDataEntered := 'No data entered for patient ' + #13 + getPatientName + #13;
case lvSelPatients.Items.Count of
0, 1:
begin
if (MessageDLG(sNoDataEntered + 'Close the window?', mtInformation, [mbYes, mbNo], 0) = mrYes) then
if bSlave then
Close
else
ModalResult := mrOk;
end;
else
begin
if (MessageDLG(sNoDataEntered + 'Process next Patient?', mtInformation, [mbYes, mbNo], 0) = mrYes) then
ProcessNext(indBlankInput);
end;
end;
end;
end;
end;
procedure TfrmGMV_InputLite.ckbOnPassClick(Sender: TObject);
begin
acSetOnPassExecute(ckbOnPass);
if not ckbOnPass.Checked then
cbRClick(nil);
end;
procedure TfrmGMV_InputLite.SpeedButton2Click(Sender: TObject);
begin
pnlOptions.Visible := not pnlOptions.Visible;
end;
procedure TfrmGMV_InputLite.acDateTimeSelectorExecute(Sender: TObject);
var
aTime: TDateTime;
begin
Application.CreateForm(TfGMV_DateTime, fGMV_DateTime);
with fGMV_DateTime do
begin
// Enter date could not be less then a year before -- //AAN 12/12/2002
fGMV_DateTime.mncCalendar.minDate := Now - 365; // AAN 12/12/2002
fGMV_DateTime.mncCalendar.Date := dtpDate.Date;
fGMV_DateTime.edtTime.Text := FormatDateTime(GMV_TimeFormat, dtpTime.Time);
fGMV_DateTime.SetDateTimeText;
if fGMV_DateTime.ShowModal <> mrCancel then
begin
CurrentTime := fGMV_DateTime.mncCalendar.MaxDate;
aTime := trunc(fGMV_DateTime.mncCalendar.Date) + StrToTime(fGMV_DateTime.edtTime.Text);
if dtpDate.MaxDate < aTime then
dtpDate.MaxDate := aTime;
dtpDate.Date := aTime;
dtpTime.Time := trunc(aTime) + StrToTime(fGMV_DateTime.edtTime.Text);
dtpTimeChange(Sender);
end;
end;
fGMV_DateTime.Free;
end;
procedure TfrmGMV_InputLite.acHospitalSelectorExecute(Sender: TObject);
var
sLocationID, sLocationName: String;
begin
sLocationID := _FHospitalIEN;
sLocationName := '';
if SelectLocation2(FDFN, sLocationID, sLocationName) then
begin
_FHospitalIEN := sLocationID;
lblHospital.Caption := sLocationName;
end;
end;
procedure TfrmGMV_InputLite.pnlLatestVitalsBgResize(Sender: TObject);
begin
if pnlLatestVitalsBg.Height > (pnlInput.Height div 4) * 3 then
pnlLatestVitalsBg.Height := (pnlInput.Height div 4) * 3;
if pnlLatestVitalsBg.Height < pnlInput.Height div 5 then
pnlLatestVitalsBg.Height := pnlInput.Height div 5;
end;
procedure TfrmGMV_InputLite.CMVitalChanged(var Message: TMessage);
begin
bDataUpdated := True;
end;
function TfrmGMV_InputLite.InputString: String;
var
i: Integer;
s: String;
begin
s := '';
for i := 0 to sbxMain.ControlCount - 1 do
if sbxMain.Controls[i] is TfraGMV_InputOne2 then
with TfraGMV_InputOne2(sbxMain.Controls[i]) do
if ckbOnPass.Checked then
s := s + 'OnPass'
else
s := s + VitalsRate;
Result := s;
end;
procedure TfrmGMV_InputLite.strgLVDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
with strgLV.canvas do
begin
if ARow = 0 then
Brush.Color := clBtnFace
else if pos('*', strgLV.Cells[2, ARow]) <> 0 then
begin
Font.Color := DisplayColors[GMVAbnormalText];
// if pos(FormatDateTime('mm/dd/yy',Now),strgLV.Cells[0,ARow])<>0 then
// Brush.Color := DisplayColors[GMVAbnormalTodayBkgd]
// else
Brush.Color := DisplayColors[GMVAbnormalBkgd];
end
else
begin
Font.Color := DisplayColors[GMVnormalText];
// if pos(FormatDateTime('mm/dd/yy',Now),strgLV.Cells[0,ARow])<>0 then
// Brush.Color := DisplayColors[GMVnormalTodayBkgd]
// else
Brush.Color := DisplayColors[GMVnormalBkgd];
end;
FillRect(Rect);
TextRect(Rect, Rect.Left + 2, Rect.Top, strgLV.Cells[ACol, ARow]);
end;
end;
procedure TfrmGMV_InputLite.FormCreate(Sender: TObject);
var
i: Integer;
begin
bSlave := False;
pnlMonitor.Visible := False;
with TVersionInfo.Create(Self) do
try
fFileVersion := FileVersion;
fFileComments := Comments;
finally
Free;
end;
{$IFDEF USEVSMONITOR}
fMonitor := TGMV_Monitor.Create;
pnlMonitor.Visible := True;
if (fMonitor <> nil) and fMonitor.Active then
sbMonitor.Caption := 'Read Monitor' // 2009-04-15 fMonitor.Model // ReadMonitor
else
begin
FreeAndNil(fMonitor);
sCasmedPort := '';
for i := 1 to ParamCount do // zzzzzzandria 20090112
begin
if InString(ParamStr(i), ['/casmed='], False) then
begin
sCasmedPort := Piece(ParamStr(i), '=', 2);
break;
end;
end;
end;
{$ENDIF}
{$IFDEF DLL}
HelpContext := 3;
{$ENDIF}
end;
procedure TfrmGMV_InputLite.ckbUnavailableEnter(Sender: TObject);
begin
bvUnavailable.Visible := True;
end;
procedure TfrmGMV_InputLite.ckbUnavailableExit(Sender: TObject);
begin
bvUnavailable.Visible := False;
end;
procedure TfrmGMV_InputLite.ckbUnavailableClick(Sender: TObject);
begin
acSetOnPassExecute(ckbUnavailable);
end;
procedure TfrmGMV_InputLite.acUnavailableBoxStatusExecute(Sender: TObject);
procedure SetUStatus(aStatus: Boolean);
var
i: Integer;
begin
ckbUnavailable.Visible := aStatus;
lblUnavailable.Visible := aStatus;
for i := 0 to sbxMain.ComponentCount - 1 do
begin
if sbxMain.Components[i] is TfraGMV_InputOne2 then
begin
TfraGMV_InputOne2(sbxMain.Components[i]).cbxUnavailable.Visible := not aStatus;
TfraGMV_InputOne2(sbxMain.Components[i]).cbxUnavailable.Checked := ckbUnavailable.Checked;
TfraGMV_InputOne2(sbxMain.Components[i]).cbxUnavailable.Enabled := True;
end;
end;
if aStatus then
begin
hc.Sections[2].Text := 'Refused';
end
else
hc.Sections[2].Text := 'U... R...'
end;
begin
SetUStatus(chkOneUnavailableBox.Checked);
end;
procedure TfrmGMV_InputLite.CMSaveInput(var Message: TMessage);
begin
acSaveInputExecute(nil);
end;
procedure TfrmGMV_InputLite.acParamsShowHideExecute(Sender: TObject);
begin
bShowParams := not bShowParams;
// sbtnTemplateTree.Down := bShowParams;
sbtnToolShowParams.Down := bShowParams;
if pnlParams.Visible and not bShowParams then
splParams.Visible := False;
pnlParams.Visible := bShowParams;
if Sender <> nil then
try
FormResize(Sender);
except
end;
if pnlParams.Visible then
splParams.Visible := True;
acParamsShowHide.Checked := bShowParams;
end;
procedure TfrmGMV_InputLite.acAdjustToolbarsExecute(Sender: TObject);
var
LabelLen, PanelLen: Integer;
begin
PanelLen := pnlTools.Width - pnlPatient.Width - pnlParamTools.Width - pnlMonitor.Width;
LabelLen := Max((lblHospital.Width + lblHospital.Left + 4), (lblDateTime.Width + lblDateTime.Left + 4));
if PanelLen < LabelLen then
begin
pnlTools.Visible := False;
pnlTools.Visible := True;
tlbInput.Align := alTop;
tlbInput.Visible := True;
Application.ProcessMessages;
end
else
tlbInput.Visible := False;
pnlParamTools.Visible := not tlbInput.Visible;
end;
procedure TfrmGMV_InputLite.acVitalsShowHideExecute(Sender: TObject);
begin
bShowVitals := not bShowVitals;
sbtnShowLatestVitals.Down := bShowVitals;
if pnlLatestVitalsBg.Visible and not bShowVitals then
splLastVitals.Visible := False;
pnlLatestVitalsBg.Visible := bShowVitals;
if pnlLatestVitalsBg.Visible then
begin
splLastVitals.Visible := True;
end
else
pnlInputTemplate.Align := alClient;
acVitalsShowHide.Checked := bShowVitals;
end;
procedure TfrmGMV_InputLite.lvSelPatientsClick(Sender: TObject);
begin
PatientSelected;
acSetOnPassExecute(Sender);
cbRClick(nil); // zzzzzzandria 060223
end;
procedure TfrmGMV_InputLite.lvSelPatientsChanging(Sender: TObject; Item: TListItem; Change: TItemChange; var AllowChange: Boolean);
var
i: Integer;
bFlag: Boolean;
begin
bFlag := True;
for i := 0 to sbxMain.ComponentCount - 1 do
begin
if sbxMain.Components[i] is TfraGMV_InputOne2 then
begin
bFlag := bFlag and TfraGMV_InputOne2(sbxMain.Components[i]).Valid;
if not bFlag then
break;
end;
end;
AllowChange := bFlag;
end;
procedure TfrmGMV_InputLite.lvSelPatientsChange(Sender: TObject; Item: TListItem; Change: TItemChange);
begin
try
if (Item.SubItems[1] = FDFN) and (InputString <> '') and // 2003/08/29 AAN
bDataUpdated then
if (MessageDLG('You are selecting another patient.' + #13 + 'Some of the input fields contain data.' + #13 + #13 + 'Save this data for the patient "' + getPatientName + '"?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
begin
acSaveInputExecute(Sender);
end
else
begin
bDataUpdated := False; // 2003/08/29 AAN
end
else // 2003/08/29 AAN
bDataUpdated := InputString <> ''; // 2003/08/29 AAN
except
end;
end;
procedure TfrmGMV_InputLite.PatientSelected;
var
i: Integer;
s, sPatientID: String;
begin
for i := 0 to lvSelPatients.Items.Count - 1 do
try
s := lvSelPatients.Items[i].SubItems[3];
if s = '' then
// if lvSelPatients.Items[i].ImageIndex = 1 then
lvSelPatients.Items[i].ImageIndex := 0
else if pos(' ', s) <> 0 then
lvSelPatients.Items[i].ImageIndex := indMultipleInput
else
// lvSelPatients.Items[i].ImageIndex := indSingleInput;
lvSelPatients.Items[i].ImageIndex := StrToInt(s);
except
end;
try
sPatientID := lvSelPatients.ItemFocused.SubItems[1];
if lvSelPatients.ItemFocused.SubItems[3] = '' then
lvSelPatients.ItemFocused.ImageIndex := 1
else if pos(' ', lvSelPatients.ItemFocused.SubItems[3]) <> 0 then
lvSelPatients.ItemFocused.ImageIndex := indMultipleCurrent
else
lvSelPatients.ItemFocused.ImageIndex := indSingleCurrent;
except
sPatientID := '';
end;
if sPatientID = '' then
exit;
if lvSelPatients.CheckBoxes then
ckbOnPass.Checked := lvSelPatients.ItemFocused.Checked;
setPatientInfoView(lvSelPatients.ItemFocused.SubItems[0], lvSelPatients.ItemFocused.SubItems[2]); // zzzzzzandria 060309
pnlLatestVitalsHeader.Caption := ' Latest Vitals for patient <' + getPatientName + '>';
FDFN := sPatientID;
UpdateLatestVitals(sPatientID, True);
bDataUpdated := InputString <> '';
end;
procedure TfrmGMV_InputLite.FormDestroy(Sender: TObject);
begin
if Status = stsDLL then
CleanUpGlobals;
if assigned(FInputTemplate) then
FreeAndNil(FInputTemplate);
CleanUp;
{$IFDEF USEVSMONITOR}
if fMonitor <> nil then
FreeAndNil(fMonitor);
if Assigned(Casmed) then
FreeAndNil(Casmed);
{$ENDIF}
end;
procedure TfrmGMV_InputLite.setStatus(aStatus: String);
begin
fStatus := aStatus;
if fStatus = stsDLL then
begin
SetUpGlobals;
GMVUser.SetupSignOnParams;
GMVUser.SetupUser;
end;
end;
/// ///////////////////////////////////////////////////////////////// CASMED UNIT
procedure TfrmGMV_InputLite.acGetCASMEDDescriptionExecute(Sender: TObject);
begin
{$IFDEF USEVSMONITOR}
Screen.Cursor := crHourGlass;
if (fMonitor <> nil) and fMonitor.Active then
begin
ShowMessage(fMonitor.Description);
Screen.Cursor := crDefault;
end
else
begin
// StatusBar.Visible := True; // uncomment to show the status of the instrument
ShowMessage(getCasmedDescription(Casmed, sCasmedPort, CasmedStatusIndicator));
end;
Screen.Cursor := crDefault;
{$ENDIF}
end;
{$IFDEF USEVSMONITOR}
procedure TfrmGMV_InputLite.CasmedStatusIndicator(aStatus: String);
var
sKey: String;
i: Integer;
begin
sKey := Piece(uppercase(aStatus), ':', 1);
i := StatusBar.Panels.Count - 1;
if sKey = 'MODEL' then
i := 1;
if sKey = 'PORT' then
i := 2;
if sKey = 'STATUS' then
i := 3;
StatusBar.Panels[i].Text := ' ' + aStatus + ' ';
Application.ProcessMessages;
end;
procedure TfrmGMV_InputLite.CasmedProcess;
var
i: Integer;
anIn: TfraGMV_InputOne2;
rr, rTemp: Real;
sBP: String;
sPulse: String;
sTemp: String;
sTempUnit: String;
sSpO2: String;
sCasmedError: String;
begin
try
// StatusBar.Visible := True; // incomment to indicate instrument status
Screen.Cursor := crHourGlass;
if not Assigned(Casmed) then
Casmed := newATE740X(sCasmedPort, sCasmedError, CasmedStatusIndicator);
Screen.Cursor := crDefault;
bCasmedUsed := False;
sCasmedError := errCheckStatus { errCasmedNotFound };
if not Assigned(Casmed) then
begin
ShowMessage(sCasmedError);
exit;
end;
if Casmed.Numerics <> 'ERROR' then
begin
sBP := Casmed.sBP;
sPulse := Casmed.sPulse;
sSpO2 := Casmed.sSpO2;
rTemp := Casmed.fTemp; // rTemp := 33.3;
sTemp := Casmed.sTemp; // sTemp := '33.3';
sTempUnit := Casmed.TempUnit; // sTempUnit := 'C';
FreeAndNil(Casmed);
// Casmed.ClosePort;
end
else
begin
ShowMessage('Error getting data from CASMED');
FreeAndNil(Casmed);
// Casmed.ClosePort;
exit;
end;
// zzzzzzandria 20080929 tracking use of the monitor
bCasmedUsed := (sBP <> '') or (sPulse <> '') or (sSpO2 <> '') or (rTemp <> 0) or (sTemp <> '') or (sTempUnit <> '');
for i := 0 to sbxMain.ComponentCount - 1 do
begin
if sbxMain.Components[i] is TfraGMV_InputOne2 then
begin
anIn := TfraGMV_InputOne2(sbxMain.Components[i]);
if (anIn.TemplateVital.VitalName = 'TEMPERATURE') and (sTemp <> '') then
begin
if sTempUnit = copy(anIn.lblUnit.Caption, 2, 1) then
anIn.cbxInput.Text := sTemp
else
begin
if sTempUnit = 'C' then
rr := ConvertCtoF(rTemp)
else
rr := ConvertFtoC(rTemp);
sTemp := Format('%4.1f', [rr]);
anIn.cbxInput.Text := sTemp
end;
anIn.Check(0);
sTemp := '';
end;
if (anIn.TemplateVital.VitalName = 'PULSE') and (sPulse <> '') then
begin
anIn.cbxInput.Text := sPulse;
sPulse := '';
end;
if (anIn.TemplateVital.VitalName = 'BLOOD PRESSURE') and (sBP <> '') then
begin
anIn.cbxInput.Text := sBP;
sBP := '';
end;
if (anIn.TemplateVital.VitalName = 'PULSE OXIMETRY') and (sSpO2 <> '') then
begin
anIn.cbxInput.Text := sSpO2;
sSpO2 := '';
end;
end;
end;
except
on E: Exception do
begin
ShowMessage('Getting CASMED instrument data error:' + #13#10 + E.Message);
if Assigned(Casmed) then
FreeAndNil(Casmed);
end;
end;
end;
/// ///////////////////////////////////////////////////////////// CASMED UNIT END
procedure TfrmGMV_InputLite.MonitorProcess;
var
sBP, sBPSystolic, sBPDiastolic, sBPMean, sPulse, sSpO2, sTemp, sTempUnit: String;
rTemp, rr: Real;
i: Integer;
anIn: TfraGMV_InputOne2;
begin
if fMonitor = nil then
exit;
fMonitor.GetData;
sBP := fMonitor.sBP;
sPulse := fMonitor.sPulse;
sSpO2 := fMonitor.sSpO2;
sTemp := fMonitor.sTemp; // sTemp := '33.3';
sTempUnit := fMonitor.sTempUnit; // sTempUnit := 'C';
for i := 0 to sbxMain.ComponentCount - 1 do
begin
if sbxMain.Components[i] is TfraGMV_InputOne2 then
begin
anIn := TfraGMV_InputOne2(sbxMain.Components[i]);
if (anIn.TemplateVital.VitalName = 'TEMPERATURE') and (sTemp <> '') then
begin
if sTempUnit = copy(anIn.lblUnit.Caption, 2, 1) then
anIn.cbxInput.Text := sTemp
else
begin
rTemp := StrToFloat(sTemp);
if sTempUnit = 'C' then
rr := ConvertCtoF(rTemp)
else
rr := ConvertFtoC(rTemp);
sTemp := Format('%4.1f', [rr]);
anIn.cbxInput.Text := sTemp
end;
anIn.Check(0);
sTemp := '';
end;
if (anIn.TemplateVital.VitalName = 'PULSE') and (sPulse <> '') then
begin
anIn.cbxInput.Text := sPulse;
sPulse := '';
end;
if (anIn.TemplateVital.VitalName = 'BLOOD PRESSURE') and (sBP <> '') then
begin
anIn.cbxInput.Text := sBP;
sBP := '';
end;
if (anIn.TemplateVital.VitalName = 'Systolic_blood_pressure') and (sBP <> '') then
begin
sBPSystolic := sBP;
sBP := '';
end;
if (anIn.TemplateVital.VitalName = 'Diastolic_blood_pressure') and (sBP <> '') then
begin
sBPDiastolic := sBP;
sBP := '';
end;
if (anIn.TemplateVital.VitalName = 'Mean_arterial_pressure') and (sBP <> '') then
begin
sBPMean := sBP;
sBP := '';
end;
if (anIn.TemplateVital.VitalName = 'PULSE OXIMETRY') and (sSpO2 <> '') then
begin
anIn.cbxInput.Text := sSpO2;
sSpO2 := '';
end;
end;
end;
end;
{$ENDIF}
procedure TfrmGMV_InputLite.acMonitorGetDataExecute(Sender: TObject);
begin
{$IFDEF USEVSMONITOR}
if Assigned(fMonitor) and fMonitor.Active then
MonitorProcess
else
CasmedProcess;
{$ENDIF}
end;
procedure TfrmGMV_InputLite.acGetCASMEDDataExecute(Sender: TObject);
begin
end;
/// /////////////////////////////////////////////////////////////////////////////
procedure TfrmGMV_InputLite.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Key = Word('Z')) and (ssCtrl in Shift) then
acGetCASMEDDescriptionExecute(nil); // CASMED
if Key = VK_ESCAPE then
btnCancelClick(nil);
if Key = VK_F1 then
Application.HelpCommand(0, 0);
if (Key = VK_Return) and (ActiveControl = pnlPatient) then
acPatientInfo.Execute;
end;
procedure TfrmGMV_InputLite.cbRClick(Sender: TObject);
var
i: Integer;
begin
for i := 0 to sbxMain.ComponentCount - 1 do
begin
if sbxMain.Components[i] is TfraGMV_InputOne2 then
begin
if not ckbOnPass.Checked then
begin
TfraGMV_InputOne2(sbxMain.Components[i]).cbxUnavailable.Enabled := cbU.Checked;
TfraGMV_InputOne2(sbxMain.Components[i]).cbxRefused.Enabled := cbR.Checked;
end;
end
end;
acEnableU.Checked := cbU.Checked;
acEnableR.Checked := cbR.Checked;
end;
procedure TfrmGMV_InputLite.hcMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
j, i: Integer;
begin
hc.Enabled := True;
j := 0;
for i := 0 to hc.Sections.Count - 1 do
begin
j := j + hc.Sections[i].Width;
if j > X then
begin
case i of
0:
hc.hint := 'Template Line Number';
2:
hc.hint := 'U - Unavailable, R - Refused';
3:
hc.hint := 'Vital Type';
4:
hc.hint := 'Vital Value';
5:
hc.hint := 'Vital Value Units';
6:
hc.hint := 'Vital Value Qualifiers';
else
hc.hint := hc.Sections[i].Text;
end;
break;
end;
end;
end;
procedure TfrmGMV_InputLite.cbConversionWarningClick(Sender: TObject);
var
i: Integer;
begin
for i := 0 to sbxMain.ComponentCount - 1 do
begin
if sbxMain.Components[i] is TfraGMV_InputOne2 then
TfraGMV_InputOne2(sbxMain.Components[i]).ConversionWarning := cbConversionWarning.Checked;
end;
end;
procedure TfrmGMV_InputLite.pnlPatientEnter(Sender: TObject);
begin
pnlPatient.BevelInner := bvRaised; // zzzzzzandria 060308
end;
procedure TfrmGMV_InputLite.pnlPatientExit(Sender: TObject);
begin
pnlPatient.BevelInner := bvNone; // zzzzzzandria 060308
end;
procedure TfrmGMV_InputLite.pnlPatientClick(Sender: TObject);
begin
acPatientInfo.Execute;
end;
procedure TfrmGMV_InputLite.acPatientInfoExecute(Sender: TObject);
begin
ShowPatientInfo(FDFN, 'Patient Inquiry for: ' + edPatientName.Text + ' ' + edPatientInfo.Text); // zzzzzzandria 060308
end;
procedure TfrmGMV_InputLite.setPatientInfoView(aName, anInfo: String);
begin
edPatientName.Text := aName;
edPatientInfo.Text := anInfo;
{$IFDEF DLL}
Caption := 'Vitals Lite: Enter Vitals for ' + aName + ' ' + anInfo;
{$ELSE}
Caption := 'Vitals: Enter Vitals for ' + aName + ' ' + anInfo;
{$ENDIF}
end;
function TfrmGMV_InputLite.getPatientName: String;
begin
Result := edPatientName.Text;
end;
procedure TfrmGMV_InputLite.updatePatientInfoView;
var
SL: TStringList;
begin
SL := getPatientHeader(FDFN);
setPatientInfoView(FormatPatientName(SL[1]), FormatPatientInfo(SL[1] + SL[2]));
SL.Free;
end;
procedure TfrmGMV_InputLite.edPatientNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_Return then
acPatientInfo.Execute;
end;
procedure TfrmGMV_InputLite.acShowStatusBarExecute(Sender: TObject);
begin
// StatusBar.Visible := not StatusBar.Visible; // uncomment to indicate instrument status
end;
procedure TfrmGMV_InputLite.pnlPatientMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
pnlPatient.BevelOuter := bvLowered;
end;
procedure TfrmGMV_InputLite.pnlPatientMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
pnlPatient.BevelOuter := bvRaised;
acPatientInfo.Execute;
end;
procedure TfrmGMV_InputLite.acLatestVitalsExecute(Sender: TObject);
begin
ShowPatientLatestVitals(FDFN, 'Latest Vitals for: ' + edPatientName.Text + ' ' + edPatientInfo.Text);
end;
procedure TfrmGMV_InputLite.acEnableUExecute(Sender: TObject);
begin
cbU.Checked := not cbU.Checked;
end;
procedure TfrmGMV_InputLite.acEnableRExecute(Sender: TObject);
begin
cbR.Checked := not cbR.Checked;
end;
procedure TfrmGMV_InputLite.acUnitsDDLExecute(Sender: TObject);
begin
chkCPRSSTyle.Checked := not chkCPRSSTyle.Checked;
acMetricStyleChangeExecute(Sender);
end;
procedure TfrmGMV_InputLite.CleanUp;
var
I: Integer;
begin
for I := Low(fGMV_TemplateArray) to High(fGMV_TemplateArray) do
begin
FreeandNil(fGMV_TemplateArray[i]);
end;
SetLength(fGMV_TemplateArray, 0);
end;
end.
|
unit BCEditor.Editor.Scroll;
interface
uses
Classes, Forms, StdCtrls, BCEditor.Types, BCEditor.Editor.Scroll.Hint;
const
BCEDITOR_DEFAULT_SCROLL_OPTIONS = [soAutosizeMaxWidth, soPastEndOfLine, soShowHint];
type
TBCEditorScroll = class(TPersistent)
strict private
FBars: TScrollStyle;
FHint: TBCEditorScrollHint;
FMaxWidth: Integer;
FOnChange: TNotifyEvent;
FOptions: TBCEditorScrollOptions;
procedure DoChange;
procedure SetBars(const Value: TScrollStyle);
procedure SetHint(const Value: TBCEditorScrollHint);
procedure SetOptions(const Value: TBCEditorScrollOptions);
procedure SetMaxWidth(Value: Integer);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Bars: TScrollStyle read FBars write SetBars default TScrollStyle.ssBoth;
property Hint: TBCEditorScrollHint read FHint write SetHint;
property MaxWidth: Integer read FMaxWidth write SetMaxWidth default 1024;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property Options: TBCEditorScrollOptions read FOptions write SetOptions default BCEDITOR_DEFAULT_SCROLL_OPTIONS;
end;
implementation
uses
BCEditor.Utils;
{ TBCEditorScroll }
constructor TBCEditorScroll.Create;
begin
inherited;
FOptions := BCEDITOR_DEFAULT_SCROLL_OPTIONS;
FMaxWidth := 1024;
FBars := TScrollStyle.ssBoth;
FHint := TBCEditorScrollHint.Create;
end;
destructor TBCEditorScroll.Destroy;
begin
FHint.Free;
inherited;
end;
procedure TBCEditorScroll.SetBars(const Value: TScrollStyle);
begin
if FBars <> Value then
begin
FBars := Value;
DoChange;
end;
end;
procedure TBCEditorScroll.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBCEditorScroll.Assign(Source: TPersistent);
begin
if Source is TBCEditorScroll then
with Source as TBCEditorScroll do
begin
Self.FBars := FBars;
Self.FHint.Assign(FHint);
Self.FOptions := FOptions;
Self.FMaxWidth := FMaxWidth;
Self.DoChange;
end
else
inherited Assign(Source);
end;
procedure TBCEditorScroll.SetOptions(const Value: TBCEditorScrollOptions);
begin
if Value <> FOptions then
begin
FOptions := Value;
DoChange;
end;
end;
procedure TBCEditorScroll.SetMaxWidth(Value: Integer);
begin
Value := MinMax(Value, 1, MaxInt - 1);
if FMaxWidth <> Value then
begin
FMaxWidth := Value;
DoChange;
end;
end;
procedure TBCEditorScroll.SetHint(const Value: TBCEditorScrollHint);
begin
FHint.Assign(Value);
end;
end.
|
unit testlegendreunit;
interface
uses Math, Sysutils, Ap, legendre;
function TestLegendreCalculate(Silent : Boolean):Boolean;
function testlegendreunit_test_silent():Boolean;
function testlegendreunit_test():Boolean;
implementation
function TestLegendreCalculate(Silent : Boolean):Boolean;
var
Err : Double;
SumErr : Double;
CErr : Double;
Threshold : Double;
N : AlglibInteger;
MaxN : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
Pass : AlglibInteger;
C : TReal1DArray;
X : Double;
V : Double;
T : Double;
WasErrors : Boolean;
begin
Err := 0;
SumErr := 0;
CErr := 0;
Threshold := 1.0E-9;
WasErrors := False;
//
// Testing Legendre polynomials values
//
N:=0;
while N<=10 do
begin
LegendreCoefficients(N, C);
Pass:=1;
while Pass<=10 do
begin
X := 2*RandomReal-1;
V := LegendreCalculate(N, X);
T := 1;
I:=0;
while I<=N do
begin
V := V-C[I]*T;
T := T*X;
Inc(I);
end;
Err := Max(Err, AbsReal(V));
Inc(Pass);
end;
Inc(N);
end;
//
// Testing Clenshaw summation
//
MaxN := 20;
SetLength(C, MaxN+1);
Pass:=1;
while Pass<=10 do
begin
X := 2*RandomReal-1;
V := 0;
N:=0;
while N<=MaxN do
begin
C[N] := 2*RandomReal-1;
V := V+LegendreCalculate(N, X)*C[N];
SumErr := Max(SumErr, AbsReal(V-LegendreSum(C, N, X)));
Inc(N);
end;
Inc(Pass);
end;
//
// Testing coefficients
//
LegendreCoefficients(0, C);
CErr := Max(CErr, AbsReal(C[0]-1));
LegendreCoefficients(1, C);
CErr := Max(CErr, AbsReal(C[0]-0));
CErr := Max(CErr, AbsReal(C[1]-1));
LegendreCoefficients(2, C);
CErr := Max(CErr, AbsReal(C[0]+AP_Double(1)/2));
CErr := Max(CErr, AbsReal(C[1]-0));
CErr := Max(CErr, AbsReal(C[2]-AP_Double(3)/2));
LegendreCoefficients(3, C);
CErr := Max(CErr, AbsReal(C[0]-0));
CErr := Max(CErr, AbsReal(C[1]+AP_Double(3)/2));
CErr := Max(CErr, AbsReal(C[2]-0));
CErr := Max(CErr, AbsReal(C[3]-AP_Double(5)/2));
LegendreCoefficients(4, C);
CErr := Max(CErr, AbsReal(C[0]-AP_Double(3)/8));
CErr := Max(CErr, AbsReal(C[1]-0));
CErr := Max(CErr, AbsReal(C[2]+AP_Double(30)/8));
CErr := Max(CErr, AbsReal(C[3]-0));
CErr := Max(CErr, AbsReal(C[4]-AP_Double(35)/8));
LegendreCoefficients(9, C);
CErr := Max(CErr, AbsReal(C[0]-0));
CErr := Max(CErr, AbsReal(C[1]-AP_Double(315)/128));
CErr := Max(CErr, AbsReal(C[2]-0));
CErr := Max(CErr, AbsReal(C[3]+AP_Double(4620)/128));
CErr := Max(CErr, AbsReal(C[4]-0));
CErr := Max(CErr, AbsReal(C[5]-AP_Double(18018)/128));
CErr := Max(CErr, AbsReal(C[6]-0));
CErr := Max(CErr, AbsReal(C[7]+AP_Double(25740)/128));
CErr := Max(CErr, AbsReal(C[8]-0));
CErr := Max(CErr, AbsReal(C[9]-AP_Double(12155)/128));
//
// Reporting
//
WasErrors := AP_FP_Greater(Err,Threshold) or AP_FP_Greater(SumErr,Threshold) or AP_FP_Greater(CErr,Threshold);
if not Silent then
begin
Write(Format('TESTING CALCULATION OF THE LEGENDRE POLYNOMIALS'#13#10'',[]));
Write(Format('Max error %5.3e'#13#10'',[
Err]));
Write(Format('Summation error %5.3e'#13#10'',[
SumErr]));
Write(Format('Coefficients error %5.3e'#13#10'',[
CErr]));
Write(Format('Threshold %5.3e'#13#10'',[
Threshold]));
if not WasErrors then
begin
Write(Format('TEST PASSED'#13#10'',[]));
end
else
begin
Write(Format('TEST FAILED'#13#10'',[]));
end;
end;
Result := not WasErrors;
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testlegendreunit_test_silent():Boolean;
begin
Result := TestLegendreCalculate(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testlegendreunit_test():Boolean;
begin
Result := TestLegendreCalculate(False);
end;
end. |
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Datasnap.DSProxyWriter;
interface
uses Data.DBXPlatform, Datasnap.DSCommonProxy, System.Generics.Collections, System.Masks, System.SysUtils;
type
TDSProxyWriter = class;
TDSProxyWriterFactory = class
public
class function Instance: TDSProxyWriterFactory; static;
class procedure RegisterWriter(const Id: string; const WriterClass: TObjectClass); static;
class procedure UnregisterWriter(const Id: string); static;
class function HasWriter(const Id: string): Boolean;
class function GetWriter(const Id: string): TDSProxyWriter; static;
class function RegisteredWritersList: TDBXStringArray; static;
constructor Create;
destructor Destroy; override;
private
class var
FSingleton: TDSProxyWriterFactory;
FRegisteredWriters: TDictionary<string,TObjectClass>;
end;
TDSProxyWriteFeature = (feConnectsWithDSRestConnection, feConnectsWithDBXConnection, feRESTClient, feDBXClient);
TDSProxyWriteFeatures = set of TDSProxyWriteFeature;
TDSProxyWriterProperties = record
UsesUnits: string;
DefaultExcludeClasses: string;
DefaultExcludeMethods: string;
DefaultEncoding: TEncoding;
Author: string;
Comment: string;
Language: string;
Features: TDSProxyWriteFeatures;
end;
TDSProxyFileDescription = record
ID: string;
DefaultFileExt: string;
end;
TDSProxyFileDescriptions = array of TDSProxyFileDescription;
TDSCustomProxyWriter = class;
TDSProxyWriter = class abstract(TFactoryObject)
public
function CreateProxyWriter: TDSCustomProxyWriter; virtual; abstract;
function Properties: TDSProxyWriterProperties; virtual; abstract;
function FileDescriptions: TDSProxyFileDescriptions; virtual; abstract;
end;
TDSProxyParamAccess = record
TypeIdentifier: string;
Getter: string;
Setter: string;
TypeUnit: string;
constructor Create(const ATypeId, AGetter, ASetter: string; const ATypeUnit: string = '');
end;
TDSCustomProxyWriter = class abstract
public
constructor Create;
destructor Destroy; override;
procedure WriteProxy; virtual;
protected
procedure WriteImplementation; virtual; abstract;
procedure WriteInterface; virtual; abstract;
procedure WriteFileHeader; virtual;
function GetTimeStamp: string; virtual;
procedure DerivedWrite(const Line: string); virtual; abstract;
procedure DerivedWriteLine; virtual; abstract;
function GetAssignmentString: string; virtual; abstract;
function IncludeClassName(const ClassName: string): Boolean;
function IncludeMethodName(const MethodName: string): Boolean;
function IncludeClass(const ProxyClass: TDSProxyClass): Boolean; virtual;
function IncludeMethod(const ProxyMethod: TDSProxyMethod): Boolean; virtual;
procedure WriteLine(const Line: string); overload;
procedure Indent;
procedure Outdent;
procedure WriteLine; overload;
function IsKnownTableTypeName(const Name: string): Boolean; virtual;
function IsKnownDBXValueTypeName(const Name: string): Boolean; virtual;
function IsKnownJSONTypeName(const Name: string): Boolean; virtual;
function GetDelphiTypeName(const Param: TDSProxyParameter): string; virtual;
function GetDelphiUnitName(const Param: TDSProxyParameter): string; virtual;
function GetGetter(const Param: TDSProxyParameter): string;
function GetSetter(const Param: TDSProxyParameter): string;
function GetCreateDataSetReader(const Param: TDSProxyParameter): string; virtual; abstract;
function GetCreateParamsReader(const Param: TDSProxyParameter): string; virtual; abstract;
protected type
TCustomTypeMapPair = TPair<Integer, Integer>;
strict private
FMetadata: TDSProxyMetadata;
FOwnsMetaData: Boolean;
FCustomTypeMap: TDictionary<TCustomTypeMapPair, TDSProxyParamAccess>;
private
procedure ClearMasks;
function InclusionTest(const Includes: TDBXStringArray; const Excludes: TDBXStringArray; const Name: string): Boolean;
procedure SetMetaDataLoader(const Value: IDSProxyMetaDataLoader);
protected
FUnitFileName: string;
FIndentString: string;
FIndentIncrement: Integer;
FMetaDataLoader: IDSProxyMetaDataLoader;
procedure AddCustomTypeMap(const ADbxDataType: Integer; const AProxyParamRec: TDSProxyParamAccess); overload;
procedure AddCustomTypeMap(const ADbxDataType, ADbxSubDataType: Integer; const AProxyParamRec: TDSProxyParamAccess); overload;
procedure RemoveCustomTypeMap(const ADbxDataType: Integer);
private
FIndentSpaces: Integer;
FMasks: TDictionary<string, TMask>;
FIncludeClasses: TDBXStringArray;
FExcludeClasses: TDBXStringArray;
FIncludeMethods: TDBXStringArray;
FExcludeMethods: TDBXStringArray;
FProxyWriters: TDictionary<string, IDSProxyWriter>;
function GetMetadata: TDSProxyMetadata;
procedure SetExcludeClasses(const Value: TDBXStringArray);
procedure SetExcludeMethods(const Value: TDBXStringArray);
procedure SetIncludeClasses(const Value: TDBXStringArray);
procedure SetIncludeMethods(const Value: TDBXStringArray);
public
property Metadata: TDSProxyMetadata read GetMetadata;
property MetaDataLoader: IDSProxyMetaDataLoader read FMetaDataLoader write SetMetaDataLoader;
property ProxyWriters: TDictionary<string, IDSProxyWriter> read FProxyWriters;
property UnitFileName: string read FUnitFileName write FUnitFileName;
property IncludeClasses: TDBXStringArray read FIncludeClasses write SetIncludeClasses;
property ExcludeClasses: TDBXStringArray read FExcludeClasses write SetExcludeClasses;
property IncludeMethods: TDBXStringArray read FIncludeMethods write SetIncludeMethods;
property ExcludeMethods: TDBXStringArray read FExcludeMethods write SetExcludeMethods;
protected
property AssignmentString: string read GetAssignmentString;
property CustomTypeMap: TDictionary<TCustomTypeMapPair, TDSProxyParamAccess> read FCustomTypeMap;
end;
const
// value from toolsapi.pas
sDSProxyDelphiLanguage = 'Delphi';
sDSProxyCppLanguage = 'C++';
sDSProxyJavaScriptLanguage = 'Java Script';
implementation
uses Data.DBXCommon, Datasnap.DSClientResStrs, System.Generics.Defaults
{$IFDEF MACOS}
, Macapi.CoreFoundation
{$ENDIF MACOS}
;
{ TDSClientProxyWriterFactory }
class function TDSProxyWriterFactory.Instance: TDSProxyWriterFactory;
begin
if FSingleton = nil then
FSingleton := TDSProxyWriterFactory.Create;
Result := FSingleton;
end;
class procedure TDSProxyWriterFactory.RegisterWriter(const Id: string; const WriterClass: TObjectClass);
begin
if Instance <> nil then
begin
if Instance.FRegisteredWriters.ContainsKey(Id) then
Instance.FRegisteredWriters.Items[Id] := WriterClass
else
Instance.FRegisteredWriters.Add(Id, WriterClass);
end;
end;
class procedure TDSProxyWriterFactory.UnregisterWriter(const Id: string);
begin
if Instance <> nil then
begin
if Instance.FRegisteredWriters.ContainsKey(Id) then
begin
Instance.FRegisteredWriters.Remove(Id);
if Instance.FRegisteredWriters.Count = 0 then
FreeAndNil(FSingleton);
end;
end;
end;
class function TDSProxyWriterFactory.HasWriter(const Id: string): Boolean;
begin
Result := (Instance <> nil) and Instance.FRegisteredWriters.ContainsKey(Id);
end;
class function TDSProxyWriterFactory.GetWriter(const Id: string): TDSProxyWriter;
var
Clazz: TObjectClass;
begin
if Id = '' then
raise TDSProxyException.Create(SNoWriter);
if not HasWriter(Id) then
raise TDSProxyException.CreateFmt(SUnknownWriter, [Id]);
if Instance.FRegisteredWriters.ContainsKey(Id) then
begin
Clazz := Instance.FRegisteredWriters[Id];
try
Exit(TDSProxyWriter(Clazz.Create));
except
on E: Exception do
;
end;
Result := nil;
end
else
Result := nil;
end;
class function TDSProxyWriterFactory.RegisteredWritersList: TDBXStringArray;
begin
if Instance <> nil then
Result := TDBXStringArray(Instance.FRegisteredWriters.Keys.ToArray)
else
SetLength(Result, 0);
end;
constructor TDSProxyWriterFactory.Create;
begin
inherited Create;
FRegisteredWriters := TDictionary<string,TObjectClass>.Create(TIStringComparer.Ordinal);
end;
destructor TDSProxyWriterFactory.Destroy;
begin
FreeAndNil(FRegisteredWriters);
FSingleton := nil;
inherited Destroy;
end;
procedure TDSCustomProxyWriter.WriteFileHeader;
var
GeneratedMessage: string;
Line: string;
LTimeStamp: string;
begin
GeneratedMessage := '// ' + SGeneratedCode;
LTimeStamp := GetTimeStamp;
if Trim(LTimeStamp) <> '' then
LTimeStamp := '// ' + LTimeStamp;
Line := '// ';
WriteLine(Line);
WriteLine(GeneratedMessage);
if Trim(LTimeStamp) <> '' then
WriteLine(LTimeStamp);
WriteLine(Line);
WriteLine;
end;
procedure TDSCustomProxyWriter.AddCustomTypeMap(const ADbxDataType: Integer;
const AProxyParamRec: TDSProxyParamAccess);
begin
AddCustomTypeMap(ADbxDataType, TDBXDataTypes.UnknownType, AProxyParamRec);
end;
procedure TDSCustomProxyWriter.AddCustomTypeMap(const ADbxDataType, ADbxSubDataType: Integer;
const AProxyParamRec: TDSProxyParamAccess);
begin
FCustomTypeMap.AddOrSetValue(TCustomTypeMapPair.Create(ADbxDataType, ADbxSubDataType), AProxyParamRec);
end;
procedure TDSCustomProxyWriter.ClearMasks;
begin
FMasks.Clear;
end;
constructor TDSCustomProxyWriter.Create;
begin
inherited Create;
FMasks := TObjectDictionary<string, TMask>.Create([doOwnsValues]);
FCustomTypeMap := TDictionary<TCustomTypeMapPair, TDSProxyParamAccess>.Create;
FProxyWriters := TDictionary<string, IDSProxyWriter>.Create;
end;
function TDSCustomProxyWriter.InclusionTest(const Includes: TDBXStringArray; const Excludes: TDBXStringArray; const Name: string): Boolean;
function IsMatch(const Pattern: string): Boolean;
var
Mask: TMask;
begin
if not FMasks.TryGetValue(Pattern, Mask) then
begin
Mask := TMask.Create(Trim(Pattern));
FMasks.Add(Pattern, Mask);
end;
Result := Mask.Matches(Name);
end;
var
Index: Integer;
begin
Result := True;
if Excludes <> nil then
begin
for Index := 0 to Length(Excludes) - 1 do
if IsMatch(Excludes[Index]) then
Exit(False);
end;
if Includes <> nil then
begin
for Index := 0 to Length(Includes) - 1 do
if IsMatch(Includes[Index]) then
Exit(True);
Result := False;
end;
end;
function TDSCustomProxyWriter.IncludeClassName(const ClassName: string): Boolean;
begin
Result := InclusionTest(FIncludeClasses, FExcludeClasses, ClassName);
end;
function TDSCustomProxyWriter.IncludeMethodName(const MethodName: string): Boolean;
begin
Result := InclusionTest(FIncludeMethods, FExcludeMethods, MethodName);
end;
procedure TDSCustomProxyWriter.WriteLine(const Line: string);
begin
DerivedWrite(FIndentString + Line);
DerivedWriteLine;
end;
procedure TDSCustomProxyWriter.Indent;
var
Index: Integer;
begin
FIndentSpaces := FIndentSpaces + FIndentIncrement;
for Index := 0 to FIndentIncrement - 1 do
FIndentString := FIndentString + ' ';
end;
procedure TDSCustomProxyWriter.Outdent;
var
Index: Integer;
begin
FIndentSpaces := FIndentSpaces - FIndentIncrement;
FIndentString := '';
for Index := 0 to FIndentSpaces - 1 do
FIndentString := FIndentString + ' ';
end;
procedure TDSCustomProxyWriter.RemoveCustomTypeMap(const ADbxDataType: Integer);
begin
FCustomTypeMap.Remove(TCustomTypeMapPair.Create(ADbxDataType, TDBXDataTypes.UnknownType));
end;
procedure TDSCustomProxyWriter.SetExcludeClasses(const Value: TDBXStringArray);
begin
ClearMasks;
FExcludeClasses := Value;
end;
procedure TDSCustomProxyWriter.SetExcludeMethods(const Value: TDBXStringArray);
begin
ClearMasks;
FExcludeMethods := Value;
end;
procedure TDSCustomProxyWriter.SetIncludeClasses(const Value: TDBXStringArray);
begin
ClearMasks;
FIncludeClasses := Value;
end;
procedure TDSCustomProxyWriter.SetIncludeMethods(const Value: TDBXStringArray);
begin
ClearMasks;
FIncludeMethods := Value;
end;
procedure TDSCustomProxyWriter.SetMetaDataLoader(
const Value: IDSProxyMetaDataLoader);
begin
FMetaDataLoader := Value;
end;
procedure TDSCustomProxyWriter.WriteLine;
begin
DerivedWriteLine;
end;
procedure TDSCustomProxyWriter.WriteProxy;
begin
WriteFileHeader;
WriteInterface;
WriteImplementation;
end;
function TDSCustomProxyWriter.IsKnownTableTypeName(const Name: string): Boolean;
begin
if not Name.IsEmpty then
begin
if (string.Compare(Name, 'TDataSet') = 0) or (string.Compare(Name, 'TParams') = 0) then
Exit(True);
end;
Result := False;
end;
function TDSCustomProxyWriter.IsKnownDBXValueTypeName(const Name: string): Boolean;
begin
if not Name.IsEmpty then
begin
if (string.Compare(Name.Substring(0, 4), 'TDBX') = 0) and (Name.IndexOf('Value') = Name.Length - 5) then
Exit(True);
end;
Result := False;
end;
function TDSCustomProxyWriter.IsKnownJSONTypeName(const Name: string): Boolean;
begin
if not Name.IsEmpty then
begin
if string.Compare(Name.Substring(0, 5), 'TJSON') = 0 then
Exit(True);
end;
Result := False;
end;
destructor TDSCustomProxyWriter.Destroy;
begin
FCustomTypeMap.Free;
FMasks.Free;
FProxyWriters.Free;
if FOwnsMetaData then
FMetadata.Free;
inherited;
end;
function TDSCustomProxyWriter.GetDelphiUnitName(const Param: TDSProxyParameter): string;
var
Pair: TCustomTypeMapPair;
Item: TDSProxyParamAccess;
begin
Pair := TCustomTypeMapPair.Create(Param.DataType, Param.SubDataType);
if FCustomTypeMap.TryGetValue(Pair, Item) then
Result := Item.TypeUnit
else
Result := '';
if Result = '' then
Result := Param.TypeUnit;
end;
function TDSCustomProxyWriter.GetDelphiTypeName(const Param: TDSProxyParameter): string;
var
Name: string;
Pair: TCustomTypeMapPair;
Item: TDSProxyParamAccess;
begin
Pair := TCustomTypeMapPair.Create(Param.DataType, Param.SubDataType);
if FCustomTypeMap.TryGetValue(Pair, Item) and not IsKnownDBXValueTypeName(Param.TypeName) then
Exit(Item.TypeIdentifier);
Name := Param.TypeName;
if not Name.IsEmpty then
Exit(Name);
case Param.DataType of
TDBXDataTypes.AnsiStringType:
Name := 'AnsiString';
TDBXDataTypes.BooleanType:
Name := 'Boolean';
TDBXDataTypes.Int8Type:
Name := 'ShortInt';
TDBXDataTypes.UInt8Type:
Name := 'Byte';
TDBXDataTypes.Int16Type:
Name := 'SmallInt';
TDBXDataTypes.UInt16Type:
Name := 'Word';
TDBXDataTypes.Int32Type:
Name := 'Integer';
TDBXDataTypes.Int64Type:
Name := 'Int64';
TDBXDataTypes.WideStringType:
Name := 'String';
TDBXDataTypes.SingleType:
Name := 'Single';
TDBXDataTypes.DoubleType:
Name := 'Double';
TDBXDataTypes.BcdType:
Name := 'TBcd';
TDBXDataTypes.TimeType:
Name := 'TDBXTime';
TDBXDataTypes.DatetimeType:
Name := 'TDateTime';
TDBXDataTypes.DateType:
Name := 'TDBXDate';
TDBXDataTypes.TimeStampType:
Name := 'TSQLTimeStamp';
TDBXDataTypes.TimeStampOffsetType:
Name := 'TSQLTimeStampOffset';
TDBXDataTypes.CurrencyType:
Name := 'Currency';
TDBXDataTypes.TableType:
if IsKnownTableTypeName(Param.TypeName) then
Name := Param.TypeName
else
Name := 'TDBXReader';
TDBXDataTypes.BinaryBlobType:
Name := 'TStream';
TDBXDataTypes.VariantType:
Name := 'Variant';
TDBXDataTypes.DbxConnectionType:
Name := 'TDBXConnection';
else
Name := '{UnknownType(' + IntToStr(Param.DataType) + ')}';
end;
Result := Name;
end;
function TDSCustomProxyWriter.GetGetter(const Param: TDSProxyParameter): string;
var
Getter: string;
Pair: TCustomTypeMapPair;
Item: TDSProxyParamAccess;
begin
Pair := TCustomTypeMapPair.Create(Param.DataType, Param.SubDataType);
if FCustomTypeMap.TryGetValue(Pair, Item) then
Exit(Item.Getter);
case Param.DataType of
TDBXDataTypes.AnsiStringType:
Getter := 'GetAnsiString';
TDBXDataTypes.BooleanType:
Getter := 'GetBoolean';
TDBXDataTypes.Int8Type:
Getter := 'GetInt8';
TDBXDataTypes.UInt8Type:
Getter := 'GetUInt8';
TDBXDataTypes.Int16Type:
Getter := 'GetInt16';
TDBXDataTypes.UInt16Type:
Getter := 'GetUInt16';
TDBXDataTypes.Int32Type:
Getter := 'GetInt32';
TDBXDataTypes.Int64Type:
Getter := 'GetInt64';
TDBXDataTypes.WideStringType:
Getter := 'GetWideString';
TDBXDataTypes.SingleType:
Getter := 'GetSingle';
TDBXDataTypes.DoubleType:
Getter := 'GetDouble';
TDBXDataTypes.BcdType:
Getter := 'GetBcd';
TDBXDataTypes.TimeType:
Getter := 'GetTime';
TDBXDataTypes.DatetimeType:
Getter := 'AsDateTime';
TDBXDataTypes.DateType:
Getter := 'GetDate';
TDBXDataTypes.TimeStampType:
Getter := 'GetTimeStamp';
TDBXDataTypes.TimeStampOffsetType:
Getter := 'GetTimeStampOffset';
TDBXDataTypes.CallbackType:
Getter := 'GetCallbackValue';
TDBXDataTypes.JsonValueType:
Getter := 'GetJSONValue';
TDBXDataTypes.CurrencyType:
Getter := 'AsCurrency';
TDBXDataTypes.TableType:
Getter := 'GetDBXReader';
TDBXDataTypes.BinaryBlobType:
Getter := 'GetStream';
TDBXDataTypes.VariantType:
Getter := 'AsVariant';
else
Getter := '{UnknownType(' + IntToStr(Param.DataType) + ')}';
end;
Result := Getter;
end;
function TDSCustomProxyWriter.GetMetadata: TDSProxyMetadata;
begin
if FMetaData = nil then
begin
FMetaData := TDSProxyMetadata.Create;
FOwnsMetaData := True;
if FMetaDataLoader <> nil then
FMetaDataLoader.Load(FMetaData);
end;
Result := FMetaData;
end;
function TDSCustomProxyWriter.GetSetter(const Param: TDSProxyParameter): string;
var
Setter: string;
HasOwnerOption: Boolean;
Pair: TCustomTypeMapPair;
Item: TDSProxyParamAccess;
begin
HasOwnerOption := False;
case Param.DataType of
TDBXDataTypes.AnsiStringType:
Setter := 'SetAnsiString';
TDBXDataTypes.BooleanType:
Setter := 'SetBoolean';
TDBXDataTypes.Int8Type:
Setter := 'SetInt8';
TDBXDataTypes.UInt8Type:
Setter := 'SetUInt8';
TDBXDataTypes.Int16Type:
Setter := 'SetInt16';
TDBXDataTypes.UInt16Type:
Setter := 'SetUInt16';
TDBXDataTypes.Int32Type:
Setter := 'SetInt32';
TDBXDataTypes.Int64Type:
Setter := 'SetInt64';
TDBXDataTypes.WideStringType:
Setter := 'SetWideString';
TDBXDataTypes.SingleType:
Setter := 'SetSingle';
TDBXDataTypes.DoubleType:
Setter := 'SetDouble';
TDBXDataTypes.BcdType:
Setter := 'SetBcd';
TDBXDataTypes.TimeType:
Setter := 'SetTime';
TDBXDataTypes.DatetimeType:
Setter := 'AsDateTime';
TDBXDataTypes.DateType:
Setter := 'SetDate';
TDBXDataTypes.TimeStampType:
Setter := 'SetTimeStamp';
TDBXDataTypes.TimeStampOffsetType:
Setter := 'SetTimeStampOffset';
TDBXDataTypes.CallbackType:
Setter := 'SetCallbackValue';
TDBXDataTypes.JsonValueType:
begin
Setter := 'SetJSONValue';
HasOwnerOption := True;
end;
TDBXDataTypes.CurrencyType:
Setter := 'AsCurrency';
TDBXDataTypes.TableType:
begin
Setter := 'SetDBXReader';
HasOwnerOption := True;
end;
TDBXDataTypes.BinaryBlobType:
begin
Setter := 'SetStream';
HasOwnerOption := True;
end;
TDBXDataTypes.VariantType:
Setter := 'AsVariant';
else
Setter := '{UnknownType(' + IntToStr(Param.DataType) + ')}';
end;
Pair := TCustomTypeMapPair.Create(Param.DataType, Param.SubDataType);
if FCustomTypeMap.TryGetValue(Pair, Item) then
// Use same HasOwnerOption value
Setter := Item.Setter;
if Setter.Chars[0] = 'S' then
begin
if (Param.DataType = TDBXDataTypes.TableType) and IsKnownTableTypeName(Param.TypeName) then
begin
if string.Compare(Param.TypeName, 'TDataSet', True) = 0 then
Exit(Setter + GetCreateDataSetReader(Param))
else if string.Compare(Param.TypeName, 'TParams', True) = 0 then
Exit(Setter + GetCreateParamsReader(Param));
end;
if IsKnownDBXValueTypeName(Param.TypeName) then
Exit(Setter + '(' + Param.ParameterName + '.Value.' + GetGetter(Param) + ')');
Setter := Setter + '(' + Param.ParameterName;
if HasOwnerOption then
Setter := Setter + ', FInstanceOwner)'
else
Setter := Setter + ')';
end
else
Setter := Setter + ' ' + AssignmentString + ' ' + Param.ParameterName;
Result := Setter;
end;
function TDSCustomProxyWriter.GetTimeStamp: string;
var
LNow: TDateTime;
begin
LNow := Now;
Result := FormatDateTime(FormatSettings.ShortDateFormat, LNow) + ' ' + FormatDateTime(FormatSettings.LongTimeFormat, LNow);
end;
function TDSCustomProxyWriter.IncludeClass(
const ProxyClass: TDSProxyClass): Boolean;
begin
Result := IncludeClassName(ProxyClass.ProxyClassName);
end;
function TDSCustomProxyWriter.IncludeMethod(
const ProxyMethod: TDSProxyMethod): Boolean;
begin
Result := INcludeMethodName(ProxyMethod.ProxyMethodName);
end;
{ TDSProxyParamAccess }
constructor TDSProxyParamAccess.Create(const ATypeId, AGetter, ASetter: string; const ATypeUnit: string);
begin
TypeIdentifier := ATypeId;
Getter := AGetter;
Setter := ASetter;
TypeUnit := ATypeUnit;
end;
end.
|
unit Unit7;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, UnitMil, ExtCtrls, Unit2, Unit1, modulbus;
type
TForm7 = class(TForm)
Button_OK: TButton;
Button_UPDATE: TButton;
Label1: TLabel;
Panel2: TPanel;
Label2: TLabel;
ListBox1: TListBox;
Button_selall: TButton;
Button_diselall: TButton;
procedure Button_OKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button_UPDATEClick(Sender: TObject);
procedure Button_selallClick(Sender: TObject);
procedure Button_diselallClick(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
end;
var
Form7: TForm7;
const
IFK_ID = $CC;
IFK_Ver = $CD;
implementation
{$R *.DFM}
// Kopiert die vom user makierten eintraege in die IFK liste
procedure TForm7.Button_OKClick(Sender: TObject);
var index:integer;
myIFKOnline: TStrings;
begin
myIFKOnline:= TStringList.Create;
myIFKOnline.Clear;
index:= 0;
// makierten einträge kopieren
while (index < Listbox1.Items.Count) do begin
if(Listbox1.Selected[index]) then begin
myIFKOnline.Add(IFKOnline[index]);
end;
index:=index+1;
end;
IFKOnline.Clear;
IFKOnline:= myIFKOnline;
Form2.ListBox1.Items.Add(IntTostr(IFKOnline.Count)+' IFK selected');
Form2.ListBox1.Items.Add('-------------------------------------------');
Form7.Close;
end;
procedure TForm7.FormCreate(Sender: TObject);
var x,y:integer;
begin
Scaled := true;
x := Screen.width;
y := Screen.height;
if(y <> ScreenHeightDev) or (x <> ScreenWidthDev) then begin
form7.height := (form7.clientheight * y div ScreenHeightDev)+
form7.height - form7.clientheight;
form7.width := (form7.clientwidth * x div ScreenWidthDev)+
form7.height - form7.clientheight;
scaleBy(x, ScreenwidthDev);
end;
//IFK
Form7.Panel2.Caption := IntToStr(IFKCount);
Form7.ListBox1.Items.Clear;
Form7.ListBox1.Items := IFKOnline;
Form7.Button_UPDATE.Click();
end;
// Sucht IFKs am bus, liest die ID, SW-Versiom und Revision aus
// sortiert die nicht programmierbaren aus
// nicht programierbar < FA hex
// Versionen: von 15-12 Version,
// 11-08 Revision
// 07-00 nichts
procedure TForm7.Button_UPDATEClick(Sender: TObject);
var index, myIFKCount:integer;
version,ifkid: _WORD;
ErrorStatus, status:_DWORD;
myIFKOnline: TStrings;
myIFKString: String;
myVer: Byte;
myRev: Byte;
begin
index:= 0;
myIFKCount:= 0;
ErrorStatus:= 0;
myIFKCount:= 0;
myIFKOnline:= TStringList.Create;
myIFKOnline.Clear;
// Liste loeschen
IFKOnline.Clear;
Form7.ListBox1.Items.Clear;
// IFKs suchen
IFKFound(IFKOnline, IFKCount);
Form7.Panel2.Caption := IntToStr(IFKCount);
// IFKs liste durchgehen & aussotieren
while (index < IFKCount) do begin
IFKAdress := StrToInt('$' + IFKOnline[index]);
// IFK ID & version abfragen
PCI_IfkRead(Cardauswahl, IFKAdress, IFK_ID, ifkid, ErrorStatus);
PCI_IfkRead(Cardauswahl, IFKAdress, IFK_Ver, version, ErrorStatus);
ifkid:= ifkid Shr 8;
version:= version Shr 8;
myVer:= version Shr 4;
myRev:= version and $F;
// handelt es sich um eine gesuchte -> merken
if(ifkid >= $FA) then begin
myIFKCount:= myIFKCount + 1;
myIFKString:= IFKOnline[index]+ ' '+
'ID:'+ IntToHex(ifkid, 2)+ ' '+
'Nr:'+ IFK_IDCODE.Strings[ifkid]+ ' '+
'Ver.:'+ IntToStr(myVer) + ' '+
'Rev.:'+ IntToStr(myRev);
ListBox1.Items.Add(myIFKString);
myIFKOnline.Add(IFKOnline[index]);
myIFKCount:=myIFKCount + 1;
end;
index := index + 1;
end;
IFKOnline.Clear;
IFKOnline:= myIFKOnline;
IFKCount:= myIFKCount;
Form7.Button_selall.Click();
end;
procedure TForm7.Button_selallClick(Sender: TObject);
begin
Listbox1.Perform(LB_SELITEMRANGE, 1, MakeLong(0, Listbox1.Items.Count - 1));
end;
procedure TForm7.Button_diselallClick(Sender: TObject);
begin
Listbox1.Perform(LB_SELITEMRANGE, 0, MakeLong(0, Listbox1.Items.Count - 1));
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.