text stringlengths 14 6.51M |
|---|
unit Capuccino;
interface
uses
Bebida, System.SysUtils;
type
TCapucino = class(TBebida)
public
function Custo: Currency; override;
function GetDescricao: string; override;
end;
implementation
{ TCapucino }
function TCapucino.Custo: Currency;
begin
inherited;
Result := 3.50;
end;
function TCapucino.GetDescricao: string;
begin
inherited;
Result := 'Capuccino, ';
end;
end.
|
unit Comp_UControls;
interface
uses
Controls, Graphics, Types, Messages, Classes, ExtCtrls, Windows,
Comp_UIntf, Comp_UTypes;
type
TPaintState = set of (ptPainting);
{ TScUserControl }
TScUserControl = class(TCustomControl, IViewOwner)
private
{$IFNDEF PADDING}
FPadding: TPadding;
FMargins: TMargins;
procedure SetPadding(const Value: TPadding);
procedure SetMargins(const Value: TMargins);
{$ENDIF}
protected
FPaintingState: TPaintState; // что за свойство ???
{ IViewOwner }
function GetCanvas: TCanvas;
function GetHandle: THandle;
protected
function CanFocusParent: Boolean;
procedure DoPaddingChange(Sender: TObject); virtual;
procedure EraseRect(Rect: TRect);
{ Invalidation Methods }
procedure ValidateRect(const Source: TRect);
procedure InvalidateRect(const Source: TRect);
{ Messages }
procedure WMEraseBkGnd(var Message: TWMEraseBkGnd); message WM_ERASEBKGND;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Action;
property Align;
property Anchors;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property Hint;
{$IFNDEF PADDING} // для компилятора выше ver120
property Margins: TMargins read FMargins write SetMargins;
property Padding: TPadding read FPadding write SetPadding;
{$ELSE}
property Margins;
property Padding;
{$ENDIF}
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
{$IFDEF GESTURES}
property Touch;
{$ENDIF}
property Visible;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
{$IFDEF GESTURES}
property OnGesture;
{$ENDIF}
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
end;
{ TScControl }
TScControl = class(TScUserControl)
private
{ Property Fields }
FBorderColor: TColor;
FBorderSize: Integer;
FBorderStyle: TScBorderStyle;
FHintLocation: TPoint;
FHintPauseTimer: TTimer;
FHintText: WideString;
FHintWindow: THintWindow;
FOnPaint: TNotifyEvent;
FTagString: string;
function GetPaddingRect: TRect;
{ Property Acessors }
procedure SetBorderColor(const Value: TColor);
procedure SetBorderSize(const Value: Integer);
procedure SetBorderStyle(const Value: TScBorderStyle);
protected
procedure ActivateHint(Location: TPoint; Text: WideString);
procedure DeactivateHint;
procedure DoHintPauseTimer(Sender: TObject);
procedure DoPaint; dynamic;
procedure EraseBkGnd(const Source: TRect);
procedure PaintWindow(DC: HDC); override;
{ Delphi Messages }
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
{ Win32 Messages }
procedure WMNCCalcSize(var Message: TWMNCCalcSize); message WM_NCCALCSIZE;
procedure WMNCPaint(var Message: TMessage); message WM_NCPAINT;
{ Properties }
property PaddingRect: TRect read GetPaddingRect;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property BorderColor: TColor read FBorderColor write SetBorderColor default clBtnShadow;
property BorderSize: Integer read FBorderSize write SetBorderSize default 0;
property BorderStyle: TScBorderStyle read FBorderStyle write SetBorderStyle default btSolid;
property TagString: string read FTagString write FTagString;
property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
end;
{ TScStyledControl6 }
IScStyledControl = interface
['{8C2B9330-60A2-4F08-901F-07B704705EF3}']
function CanStyle(Option: TScStyleOption): Boolean;
function GetStyleOptions: TScStyleOptions;
procedure SetStyleOptions(const Value: TScStyleOptions);
property StyleOptions: TScStyleOptions read GetStyleOptions write SetStyleOptions;
end;
{ IScColorSchemedControl }
IScColorSchemedControl = interface
['{52D010ED-732E-4D12-8EF0-7147D4017980}']
procedure Invalidate;
end;
TScStyledControl = class(TScControl, IScStyledControl, IScColorSchemedControl)
private
FStyleOptions: TScStyleOptions;
function GetStyleOptions: TScStyleOptions;
procedure SetStyleOptions(const Value: TScStyleOptions);
protected
procedure StyleChanged; virtual;
public
constructor Create(AOwner: TComponent); override;
function CanStyle(Option: TScStyleOption): Boolean;
published
property StyleOptions: TScStyleOptions read GetStyleOptions write SetStyleOptions
default [soNativeStyles];
{$IFDEF STYLE_SERVICES}
property StyleElements;
{$ENDIF}
end;
implementation
uses
Forms, SysUtils;
{$REGION 'TScUserControl'}
{ TScUserControl }
function TScUserControl.CanFocusParent: Boolean;
var
Form: TWinControl;
begin
Form := GetParentForm(Self);
Result := Assigned(Form) and Form.Showing;
end;
constructor TScUserControl.Create(AOwner: TComponent);
begin
inherited;
FPaintingState := [];
{$IFNDEF PADDING}
FMargins := TMargins.Create(Self);
FPadding := TPadding.Create(Self);
{$ENDIF}
Padding.OnChange := DoPaddingChange;
{$IFDEF GESTURES}
ControlStyle := ControlStyle + [csGestures];
{$ENDIF}
end;
destructor TScUserControl.Destroy;
begin
{$IFNDEF PADDING}
FMargins.Free;
FPadding.Free;
{$ENDIF}
inherited;
end;
procedure TScUserControl.DoPaddingChange(Sender: TObject);
begin
Realign;
end;
procedure TScUserControl.EraseRect(Rect: TRect);
begin
Canvas.Brush.Color := Color;
Canvas.FillRect(Rect);
end;
function TScUserControl.GetCanvas: TCanvas;
begin
Result := Canvas;
end;
function TScUserControl.GetHandle: THandle;
begin
Result := Handle;
end;
procedure TScUserControl.InvalidateRect(const Source: TRect);
begin
if HandleAllocated and not(ptPainting in FPaintingState) then
{$IFDEF UNSAFE}
Windows.InvalidateRect(Handle, @Source, False);
{$ELSE}
Windows.InvalidateRect(Handle, Source, False);
{$ENDIF}
end;
{$IFNDEF PADDING}
procedure TScUserControl.SetMargins(const Value: TMargins);
begin
FMargins.Assign(Value);
end;
procedure TScUserControl.SetPadding(const Value: TPadding);
begin
FPadding.Assign(Value);
FPadding.OnChange := DoPaddingChange;
end;
{$ENDIF}
procedure TScUserControl.ValidateRect(const Source: TRect);
begin
if HandleAllocated then
{$IFDEF UNSAFE}
Windows.ValidateRect(Handle, @Source);
{$ELSE}
Windows.ValidateRect(Handle, Source);
{$ENDIF}
end;
procedure TScUserControl.WMEraseBkGnd(var Message: TWMEraseBkGnd);
begin
Message.Result := 1;
end;
{$ENDREGION}
{$REGION 'TScControl'}
{ TScControl }
procedure TScControl.ActivateHint(Location: TPoint; Text: WideString);
begin
if Text = ''
then Exit;
FHintLocation := Location;
FHintText := Text;
{ Should pause? }
if not Assigned(FHintWindow) then
begin
FHintPauseTimer := TTimer.Create(Self);
FHintPauseTimer.Interval := Application.HintPause;
FHintPauseTimer.OnTimer := DoHintPauseTimer;
end else
DoHintPauseTimer(Self); { Call now }
end;
procedure TScControl.CMMouseLeave(var Message: TMessage);
begin
inherited;
DeactivateHint;
end;
constructor TScControl.Create(AOwner: TComponent);
begin
inherited;
FBorderColor := clBtnShadow;
FBorderSize := 0;
FBorderStyle := btSolid;
FTagString := EmptyStr;
end;
procedure TScControl.DeactivateHint;
begin
{ Stop & Destroy }
FreeAndNil(FHintPauseTimer);
if Assigned(FHintWindow) then
begin
FHintWindow.ReleaseHandle;
{ Destroy }
if Assigned(FHintWindow) then FreeAndNil(FHintWindow);
end;
end;
destructor TScControl.Destroy;
begin
{ Destroy Obj. }
DeactivateHint;
inherited;
end;
procedure TScControl.DoHintPauseTimer(Sender: TObject);
var
HintRect: TRect;
begin
{ Release previous? }
DeactivateHint;
{ Create Hint Window }
FHintWindow := HintWindowClass.Create(nil);
FHintWindow.Color := clInfoBk;
{ Set Position & Activate }
{ Calculate Rect }
HintRect := FHintWindow.CalcHintRect(Screen.Width, FHintText, nil);
{ Cordinates must be "Screen" }
HintRect.TopLeft := ClientToScreen(FHintLocation);
HintRect.Bottom := HintRect.Top + HintRect.Bottom;
HintRect.Right := HintRect.Left + HintRect.Right;
{ Show Hint }
FHintWindow.ActivateHint(HintRect, FHintText);
end;
procedure TScControl.DoPaint;
begin
if Assigned(FOnPaint) then FOnPaint(Self);
end;
procedure TScControl.EraseBkGnd(const Source: TRect);
begin
with Canvas do
begin
Brush.Color := Color;
FillRect(Source);
end;
end;
function TScControl.GetPaddingRect: TRect;
begin
Result := ClientRect;
Comp_UTypes.SetPadding(Result, Padding);
end;
procedure TScControl.PaintWindow(DC: HDC);
begin
inherited;
DoPaint;
end;
procedure TScControl.SetBorderColor(const Value: TColor);
begin
if Value <> FBorderColor then
begin
FBorderColor := Value;
Perform(CM_BORDERCHANGED, 0, 0);
end;
end;
procedure TScControl.SetBorderSize(const Value: Integer);
begin
if Value <> FBorderSize then
begin
FBorderSize := Value;
Perform(CM_BORDERCHANGED, 0, 0);
end;
end;
procedure TScControl.SetBorderStyle(const Value: TScBorderStyle);
begin
if Value <> FBorderStyle then
begin
FBorderStyle := Value;
Perform(CM_BORDERCHANGED, 0, 0);
end;
end;
procedure TScControl.WMNCCalcSize(var Message: TWMNCCalcSize);
var
Params: PNCCalcSizeParams;
begin
inherited;
Params := Message.CalcSize_Params;
with Params^ do
begin
InflateRect(rgrc[0], -Integer(FBorderSize), -Integer(FBorderSize));
end;
end;
procedure TScControl.WMNCPaint(var Message: TMessage);
var
Device: HDC;
Pen: HPEN;
i: Integer;
R: TRect;
P: array[0..2] of TPoint;
HightlightColor, ShadowColor: TColor;
begin
{ Required for scrollbars }
inherited;
{ Can draw? }
if BorderSize > 0 then
begin
case BorderStyle of
btSolid:
begin
HightlightColor := FBorderColor;
ShadowColor := FBorderColor;
end;
btLowered:
begin
HightlightColor := clBtnHighlight;
ShadowColor := clBtnShadow;
end;
else
begin
HightlightColor := clBtnShadow;
ShadowColor := clBtnHighlight;
end;
end;
Device := GetWindowDC(Handle);
try
GetWindowRect(Handle, R);
OffsetRect(R, -R.Left, -R.Top);
Pen := CreatePen(PS_SOLID, 1, ColorToRGB(ShadowColor));
try
SelectObject(Device, Pen);
P[0] := Point(R.Left, R.Bottom - 1);
P[1] := R.TopLeft;
P[2] := Point(R.Right, R.Top);
Polyline(Device, P, 3);
for i := 2 to BorderSize do
begin
Inc(P[0].X);
Dec(P[0].Y);
Inc(P[1].X);
Inc(P[1].Y);
Dec(P[2].X);
Inc(P[2].Y);
Polyline(Device, P, 3);
end;
finally
DeleteObject(Pen);
end;
Pen := CreatePen(PS_SOLID, 1, ColorToRGB(HightlightColor));
try
SelectObject(Device, Pen);
P[0] := Point(R.Left + 1, R.Bottom - 1);
P[1] := Point(R.Right - 1, R.Bottom - 1);
P[2] := Point(R.Right - 1, R.Top);
Polyline(Device, P, 3);
for i := 2 to BorderSize do
begin
Inc(P[0].X);
Dec(P[0].Y);
Dec(P[1].X);
Dec(P[1].Y);
Dec(P[2].X);
Inc(P[2].Y);
Polyline(Device, P, 3);
end;
finally
DeleteObject(Pen);
end;
finally
ReleaseDC(Handle, Device);
end;
end;
end;
{$ENDREGION}
{$REGION 'TScStyledControl'}
{ TScStyledControl }
function TScStyledControl.CanStyle(Option: TScStyleOption): Boolean;
begin
case Option of
soVCLStyles:
begin
Result := False;
if not(csDesigning in ComponentState) then
if (soVCLStyles in FStyleOptions) then
begin
Result := SupportStyle([soVCLStyles]);
end;
end;
soNativeStyles: Result := (soNativeStyles in FStyleOptions) and Themed;
else Result := False;
end;
end;
constructor TScStyledControl.Create(AOwner: TComponent);
begin
inherited;
FStyleOptions := [soNativeStyles];
end;
function TScStyledControl.GetStyleOptions: TScStyleOptions;
begin
Result := FStyleOptions;
end;
procedure TScStyledControl.SetStyleOptions(const Value: TScStyleOptions);
begin
if Value <> FStyleOptions then
begin
FStyleOptions := Value;
StyleChanged;
end;
end;
procedure TScStyledControl.StyleChanged;
begin
Invalidate;
end;
{$ENDREGION}
end.
|
unit ADAPT.Demo.PrecisionThreads.MainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Objects, FMX.Layouts, FMX.Edit, FMX.EditBox, FMX.SpinBox,
FMX.Controls.Presentation, FMX.StdCtrls,
ADAPT.Demo.PrecisionThreads.TestThread,
ADAPT.Intf, ADAPT,
ADAPT.Threads.Intf;
type
TDemoForm = class(TForm)
Layout1: TLayout;
PaintBox1: TPaintBox;
Label1: TLabel;
sbTickRateLimit: TSpinBox;
Label2: TLabel;
sbDesiredTickRate: TSpinBox;
Label3: TLabel;
sbHIstoryLimit: TSpinBox;
Label4: TLabel;
sbWorkSimMax: TSpinBox;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
procedure sbHIstoryLimitChange(Sender: TObject);
procedure sbWorkSimMaxChange(Sender: TObject);
private
FPerformanceLog: ITestPerformanceDataCircularList;
FPerformanceSummary: ITestPerformanceSummary;
FThread: TTestThread;
procedure PerformanceCallback(const APerformanceLog: ITestPerformanceDataCircularList; const APerformanceSummary: ITestPerformanceSummary);
procedure RedrawGraph;
public
{ Public declarations }
end;
var
DemoForm: TDemoForm;
implementation
uses
System.Math,
ADAPT.Collections;
procedure TDemoForm.FormDestroy(Sender: TObject);
begin
FThread.Free;
end;
procedure TDemoForm.PerformanceCallback(const APerformanceLog: ITestPerformanceDataCircularList; const APerformanceSummary: ITestPerformanceSummary);
begin
FThread.TickRateDesired := sbDesiredTickRate.Value;
FThread.TickRateLimit := sbTickRateLimit.Value;
FPerformanceLog := APerformanceLog;
FPerformanceSummary := APerformanceSummary;
Invalidate;
end;
procedure TDemoForm.RedrawGraph;
const
MARGIN_LEFT: Single = 10;
MARGIN_RIGHT: Single = 10;
MARGIN_TOP: Single = 10;
MARGIN_BOTTOM: Single = 10;
MARGIN_DIVIDER: Single = 10;
COLOR_BACKGROUND: TAlphaColor = TAlphaColors.Cornflowerblue;
COLOR_BACKGROUND_KEY: TAlphaColor = TAlphaColors.Black;
COLOR_BACKGROUND_GRAPH: TAlphaColor = TAlphaColors.Black;
COLOR_SERIES_DESIREDTICKRATE: TAlphaColor = TAlphaColors.Orange;
COLOR_SERIES_EXTRATIME: TAlphaColor = TAlphaColors.Limegreen;
COLOR_SERIES_TICKRATELIMIT: TAlphaColor = TAlphaColors.Maroon;
COLOR_SERIES_TICKRATE: TAlphaColor = TAlphaColors.Red;
COLOR_SERIES_TICKRATEAVERAGE: TAlphaColor = TAlphaColors.Pink;
COLOR_SERIES_TICKRATEAVERAGEOVER: TAlphaColor = TAlphaColors.Purple;
COLOR_GRAPH_LINES: TAlphaColor = TAlphaColors.Darkgreen;
RADIUS_BLOB: Single = 4;
var
LRectOuter,
LRectInner,
LRectGraph: TRectF;
LSeriesMarginX: Single;
I: Integer;
LRateLowest, LRateHighest, LRateRange,
LLastPercent, LThisPercent: ADFloat;
begin
// Calculate Rects
LRectOuter := PaintBox1.ClipRect;
LRectInner := RectF(
LRectOuter.Left + MARGIN_LEFT,
LRectOuter.Top + MARGIN_TOP,
LRectOuter.Right - MARGIN_RIGHT,
LRectOuter.Bottom - MARGIN_BOTTOM
);
LRectGraph := LRectInner;
// Calculate Margins
LSeriesMarginX := LRectGraph.Width / (FPerformanceLog.Capacity - 1);
// Calculate Tick Rate Constraints
LRateLowest := MinValue([
FPerformanceSummary.DesiredTickRateMin,
FPerformanceSummary.TickRateLimitMin,
FPerformanceSummary.TickRateMin,
FPerformanceSummary.TickRateAverageMin
]);
LRateHighest := MaxValue([
FPerformanceSummary.DesiredTickRateMax,
FPerformanceSummary.TickRateLimitMax,
FPerformanceSummary.TickRateMax,
FPerformanceSummary.TickRateAverageMax
]);
LRateRange := LRateHighest - LRateLowest;
PaintBox1.Canvas.BeginScene;
try
// Fill Outer Rect
PaintBox1.Canvas.ClearRect(LRectOuter, COLOR_BACKGROUND);
// Fill Graph Rect
PaintBox1.Canvas.ClearRect(LRectGraph, COLOR_BACKGROUND_GRAPH);
// Draw Series
if FPerformanceLog <> nil then
begin
// Draw Graph Lines
PaintBox1.Canvas.Stroke.Thickness := 0.5;
for I := 1 to FPerformanceLog.Capacity - 1 do
begin
if (I <> 0) and (I <> FPerformanceLog.Capacity) then
begin
PaintBox1.Canvas.Stroke.Color := COLOR_GRAPH_LINES;
PaintBox1.Canvas.DrawLine(
PointF(
(I * LSeriesMarginX) + LRectGraph.Left,
LRectGraph.Top
),
PointF(
(I * LSeriesMarginX) + LRectGraph.Left,
LRectGraph.Bottom
),
0.5
);
end;
end;
// Draw Performance Data
for I := 0 to FPerformanceLog.Count - 1 do
begin
PaintBox1.Canvas.Stroke.Thickness := 1;
// Tick Rate Limit
PaintBox1.Canvas.Stroke.Color := COLOR_SERIES_TICKRATELIMIT;
PaintBox1.Canvas.Fill.Color := COLOR_SERIES_TICKRATELIMIT;
{ Blob }
LThisPercent := (FPerformanceLog[I].TickRateLimit / LRateHighest) * 100;
PaintBox1.Canvas.FillEllipse(
RectF(
(((I) * LSeriesMarginX) + LRectGraph.Left) - RADIUS_BLOB,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent)) - RADIUS_BLOB,
(((I) * LSeriesMarginX) + LRectGraph.Left) + RADIUS_BLOB,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent)) + RADIUS_BLOB
),
1
);
{ Link Lines }
if I > 0 then
begin
LLastPercent := (FPerformanceLog[I - 1].TickRateLimit / LRateHighest) * 100;
PaintBox1.Canvas.DrawLine(
PointF(
((I - 1) * LSeriesMarginX) + LRectGraph.Left,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LLastPercent))
),
PointF(
((I) * LSeriesMarginX) + LRectGraph.Left,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent))
),
1
);
end;
// Tick Rate Limit
PaintBox1.Canvas.Stroke.Color := COLOR_SERIES_DESIREDTICKRATE;
PaintBox1.Canvas.Fill.Color := COLOR_SERIES_DESIREDTICKRATE;
{ Blob }
LThisPercent := (FPerformanceLog[I].DesiredTickRate / LRateHighest) * 100;
PaintBox1.Canvas.FillEllipse(
RectF(
(((I) * LSeriesMarginX) + LRectGraph.Left) - RADIUS_BLOB,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent)) - RADIUS_BLOB,
(((I) * LSeriesMarginX) + LRectGraph.Left) + RADIUS_BLOB,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent)) + RADIUS_BLOB
),
1
);
{ Link Lines }
if I > 0 then
begin
LLastPercent := (FPerformanceLog[I - 1].DesiredTickRate / LRateHighest) * 100;
PaintBox1.Canvas.DrawLine(
PointF(
((I - 1) * LSeriesMarginX) + LRectGraph.Left,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LLastPercent))
),
PointF(
((I) * LSeriesMarginX) + LRectGraph.Left,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent))
),
1
);
end;
// Tick Rate Average
PaintBox1.Canvas.Stroke.Color := COLOR_SERIES_TICKRATEAVERAGE;
PaintBox1.Canvas.Fill.Color := COLOR_SERIES_TICKRATEAVERAGE;
{ Blob }
LThisPercent := (FPerformanceLog[I].TickRateAverage / LRateHighest) * 100;
PaintBox1.Canvas.FillEllipse(
RectF(
(((I) * LSeriesMarginX) + LRectGraph.Left) - RADIUS_BLOB,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent)) - RADIUS_BLOB,
(((I) * LSeriesMarginX) + LRectGraph.Left) + RADIUS_BLOB,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent)) + RADIUS_BLOB
),
1
);
{ Link Lines }
if I > 0 then
begin
LLastPercent := (FPerformanceLog[I - 1].TickRateAverage / LRateHighest) * 100;
PaintBox1.Canvas.DrawLine(
PointF(
((I - 1) * LSeriesMarginX) + LRectGraph.Left,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LLastPercent))
),
PointF(
((I) * LSeriesMarginX) + LRectGraph.Left,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent))
),
1
);
end;
// Tick Rate
PaintBox1.Canvas.Stroke.Color := COLOR_SERIES_TICKRATE;
PaintBox1.Canvas.Fill.Color := COLOR_SERIES_TICKRATE;
{ Blob }
LThisPercent := (FPerformanceLog[I].TickRate / LRateHighest) * 100;
PaintBox1.Canvas.FillEllipse(
RectF(
(((I) * LSeriesMarginX) + LRectGraph.Left) - RADIUS_BLOB,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent)) - RADIUS_BLOB,
(((I) * LSeriesMarginX) + LRectGraph.Left) + RADIUS_BLOB,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent)) + RADIUS_BLOB
),
1
);
{ Link Lines }
if I > 0 then
begin
LLastPercent := (FPerformanceLog[I - 1].TickRate / LRateHighest) * 100;
PaintBox1.Canvas.DrawLine(
PointF(
((I - 1) * LSeriesMarginX) + LRectGraph.Left,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LLastPercent))
),
PointF(
((I) * LSeriesMarginX) + LRectGraph.Left,
(LRectGraph.Bottom - ((LRectGraph.Height / 100) * LThisPercent))
),
1
);
end;
end;
end;
finally
PaintBox1.Canvas.EndScene;
end;
end;
procedure TDemoForm.FormCreate(Sender: TObject);
begin
FThread := TTestThread.Create;
FThread.TickCallback := PerformanceCallback;
end;
procedure TDemoForm.PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
begin
RedrawGraph;
end;
procedure TDemoForm.sbHIstoryLimitChange(Sender: TObject);
begin
FThread.HistoryLimit := Round(sbHIstoryLimit.Value);
end;
procedure TDemoForm.sbWorkSimMaxChange(Sender: TObject);
begin
FThread.WorkSimMax := Round(sbWorkSimMax.Value);
end;
{$R *.fmx}
end.
|
unit uProjeto_Controller;
interface
uses uiProjeto_Interface;
type
TProjeto = class(TInterfacedObject, iProjeto)
private
FId : Integer;
FNome : String;
FValor : Currency;
procedure SetId(const Value: Integer);
procedure SetNome(const Value: String);
procedure SetValor(const Value: Currency);
public
constructor Create(Id : Integer; Nome : String; Valor : Currency);
property Id : Integer read FId write SetId;
property Nome : String read FNome write SetNome;
property Valor : Currency read FValor write SetValor;
end;
implementation
{ TProjeto }
constructor TProjeto.Create(Id: Integer; Nome: String; Valor: Currency);
begin
FId := Id;
FNome := Nome;
FValor := Valor;
end;
procedure TProjeto.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TProjeto.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TProjeto.SetValor(const Value: Currency);
begin
FValor := Value;
end;
end.
|
{******************************************************************************
* *
* PROJECT : EOS Digital Software Development Kit EDSDK *
* NAME : EDSDKError.pas *
* *
* Description: This is the Sample code to show the usage of EDSDK. *
* *
* *
*******************************************************************************
* *
* Written and developed by Camera Design Dept.53 *
* Copyright Canon Inc. 2006 All Rights Reserved *
* *
*******************************************************************************
* File Update Information: *
* DATE Identify Comment *
* ----------------------------------------------------------------------- *
* 06-03-22 F-001 create first version. *
* *
******************************************************************************}
unit EDSDKError;
interface
{ --------------- Definition of Error Codes -------------- }
{ ED-SDK Error Code Masks }
const
EDS_ISSPECIFIC_MASK = $80000000;
EDS_COMPONENTID_MASK = $7F000000;
EDS_RESERVED_MASK = $00FF0000;
EDS_ERRORID_MASK = $0000FFFF;
{ ED-SDK Base Component IDs }
const
EDS_CMP_ID_CLIENT_COMPONENTID = $01000000;
EDS_CMP_ID_LLSDK_COMPONENTID = $02000000;
EDS_CMP_ID_HLSDK_COMPONENTID = $03000000;
{ ED-SDK Functin Success Code }
const
EDS_ERR_OK = $00000000;
{ ED-SDK Generic Error IDs }
// Miscellaneous errors
const
EDS_ERR_UNIMPLEMENTED = $00000001; { Not implemented }
EDS_ERR_INTERNAL_ERROR = $00000002; { Internal error }
EDS_ERR_MEM_ALLOC_FAILED = $00000003; { Memory allocation error }
EDS_ERR_MEM_FREE_FAILED = $00000004; { Memory release error }
EDS_ERR_OPERATION_CANCELLED = $00000005; { Operation canceled }
EDS_ERR_INCOMPATIBLE_VERSION = $00000006; { Version error }
EDS_ERR_NOT_SUPPORTED = $00000007; { Not supported }
EDS_ERR_UNEXPECTED_EXCEPTION = $00000008; { Unexpected exception }
EDS_ERR_PROTECTION_VIOLATION = $00000009; { Protection violation }
EDS_ERR_MISSING_SUBCOMPONENT = $0000000A; { Missing subcomponent }
EDS_ERR_SELECTION_UNAVAILABLE = $0000000B; { Selection unavailable }
// File errors
const
EDS_ERR_FILE_IO_ERROR = $00000020; { I/O error }
EDS_ERR_FILE_TOO_MANY_OPEN = $00000021; { Too many files open }
EDS_ERR_FILE_NOT_FOUND = $00000022; { File does not exist }
EDS_ERR_FILE_OPEN_ERROR = $00000023; { Open error }
EDS_ERR_FILE_CLOSE_ERROR = $00000024; { Close error }
EDS_ERR_FILE_SEEK_ERROR = $00000025; { Seek error }
EDS_ERR_FILE_TELL_ERROR = $00000026; { Tell error }
EDS_ERR_FILE_READ_ERROR = $00000027; { Read error }
EDS_ERR_FILE_WRITE_ERROR = $00000028; { Write error }
EDS_ERR_FILE_PERMISSION_ERROR = $00000029; { Permission error }
EDS_ERR_FILE_DISK_FULL_ERROR = $0000002A; { Disk full }
EDS_ERR_FILE_ALREADY_EXISTS = $0000002B; { File already exists }
EDS_ERR_FILE_FORMAT_UNRECOGNIZED = $0000002C; { Format error }
EDS_ERR_FILE_DATA_CORRUPT = $0000002D; { Invalid data }
EDS_ERR_FILE_NAMING_NA = $0000002E; { File naming error }
// Directory errors
const
EDS_ERR_DIR_NOT_FOUND = $00000040; { Directory does not exist }
EDS_ERR_DIR_IO_ERROR = $00000041; { I/O error }
EDS_ERR_DIR_ENTRY_NOT_FOUND = $00000042; { No file in directroy }
EDS_ERR_DIR_ENTRY_EXISTS = $00000043; { File in directory }
EDS_ERR_DIR_NOT_EMPTY = $00000044; { Directory full }
// Property errors
const
EDS_ERR_PROPERTIES_UNAVAILABLE = $00000050; { Property unavailable }
EDS_ERR_PROPERTIES_MISMATCH = $00000051; { Property mismatch }
EDS_ERR_PROPERTIES_NOT_LOADED = $00000053; { Property not loaded }
// Function Parameter errors
const
EDS_ERR_INVALID_PARAMETER = $00000060; { Invalid function parameter }
EDS_ERR_INVALID_HANDLE = $00000061; { Handle error }
EDS_ERR_INVALID_POINTER = $00000062; { Pointer error }
EDS_ERR_INVALID_INDEX = $00000063; { Index error }
EDS_ERR_INVALID_LENGTH = $00000064; { Length error }
EDS_ERR_INVALID_FN_POINTER = $00000065; { Function pointer error }
EDS_ERR_INVALID_SORT_FN = $00000066; { Sort functoin error }
{ Device errors }
const
EDS_ERR_DEVICE_NOT_FOUND = $00000080; { Device not found }
EDS_ERR_DEVICE_BUSY = $00000081; { Device busy }
EDS_ERR_DEVICE_INVALID = $00000082; { Device error }
EDS_ERR_DEVICE_EMERGENCY = $00000083; { Device emergency }
EDS_ERR_DEVICE_MEMORY_FULL = $00000084; { Device memory full }
EDS_ERR_DEVICE_INTERNAL_ERROR = $00000085; { Internal device error }
EDS_ERR_DEVICE_INVALID_PARAMETER = $00000086; { Device invalid parameter }
EDS_ERR_DEVICE_NO_DISK = $00000087; { No Disk }
EDS_ERR_DEVICE_DISK_ERROR = $00000088; { Disk error }
EDS_ERR_DEVICE_CF_GATE_CHANGED = $00000089; { The CF gate has been changed }
EDS_ERR_DEVICE_DIAL_CHANGED = $0000008A; { The dial has been changed }
EDS_ERR_DEVICE_NOT_INSTALLED = $0000008B; { Device not installed }
EDS_ERR_DEVICE_STAY_AWAKE = $0000008C; { Device connected in awake mode }
EDS_ERR_DEVICE_NOT_RELEASED = $0000008D; { Device not released }
{ Stream errors }
const
EDS_ERR_STREAM_IO_ERROR = $000000A0; { Stream I/O error }
EDS_ERR_STREAM_NOT_OPEN = $000000A1; { Stream open error }
EDS_ERR_STREAM_ALREADY_OPEN = $000000A2; { Stream already open }
EDS_ERR_STREAM_OPEN_ERROR = $000000A3; { Failed to open stream }
EDS_ERR_STREAM_CLOSE_ERROR = $000000A4; { Failed to close stream }
EDS_ERR_STREAM_SEEK_ERROR = $000000A5; { Stream seek error }
EDS_ERR_STREAM_TELL_ERROR = $000000A6; { Stream tell error }
EDS_ERR_STREAM_READ_ERROR = $000000A7; { Failed to read stream }
EDS_ERR_STREAM_WRITE_ERROR = $000000A8; { Failed to write stream }
EDS_ERR_STREAM_PERMISSION_ERROR = $000000A9; { Permission error }
EDS_ERR_STREAM_COULDNT_BEGIN_THREAD = $000000AA; { Could not start reading thumbnail }
EDS_ERR_STREAM_BAD_OPTIONS = $000000AB; { Invalid stream option }
EDS_ERR_STREAM_END_OF_STREAM = $000000AC; { Invalid stream termination }
{ Communications errors }
const
EDS_ERR_COMM_PORT_IS_IN_USE = $000000C0; { Port in use }
EDS_ERR_COMM_DISCONNECTED = $000000C1; { Port disconnected }
EDS_ERR_COMM_DEVICE_INCOMPATIBLE = $000000C2; { Incompatible device }
EDS_ERR_COMM_BUFFER_FULL = $000000C3; { Buffer full }
EDS_ERR_COMM_USB_BUS_ERR = $000000C4; { USB bus error }
{ Lock/Unlock }
const
EDS_ERR_USB_DEVICE_LOCK_ERROR = $000000D0; { Failed to lock the UI }
EDS_ERR_USB_DEVICE_UNLOCK_ERROR = $000000D1; { Failed to unlock the UI }
{ STI/WIA (Windows)}
const
EDS_ERR_STI_UNKNOWN_ERROR = $000000E0; { Unknown STI }
EDS_ERR_STI_INTERNAL_ERROR = $000000E1; { Internal STI error }
EDS_ERR_STI_DEVICE_CREATE_ERROR = $000000E2; { Device creation error }
EDS_ERR_STI_DEVICE_RELEASE_ERROR = $000000E3; { Device release error }
EDS_ERR_DEVICE_NOT_LAUNCHED = $000000E4; { Device startup faild }
{ OTHER General error }
const
EDS_ERR_ENUM_NA = $000000F0; { Enumeration terminated }
EDS_ERR_INVALID_FN_CALL = $000000F1; { Called in a mode when the function could not be used }
EDS_ERR_HANDLE_NOT_FOUND = $000000F2; { Handle not found }
EDS_ERR_INVALID_ID = $000000F3; { Invalid ID }
EDS_ERR_WAIT_TIMEOUT_ERROR = $000000F4; { Time out }
EDS_ERR_LAST_GENERIC_ERROR_PLUS_ONE = $000000F5; { Not used }
{ PTP }
const
EDS_ERR_SESSION_NOT_OPEN = $00002003;
EDS_ERR_INVALID_TRANSACTIONID = $00002004;
EDS_ERR_INCOMPLETE_TRANSFER = $00002007;
EDS_ERR_INVALID_STRAGEID = $00002008;
EDS_ERR_DEVICEPROP_NOT_SUPPORTED = $0000200A;
EDS_ERR_INVALID_OBJECTFORMATCODE = $0000200B;
EDS_ERR_SELF_TEST_FAILED = $00002011;
EDS_ERR_PARTIAL_DELETION = $00002012;
EDS_ERR_SPECIFICATION_BY_FORMAT_UNSUPPORTED = $00002014;
EDS_ERR_NO_VALID_OBJECTINFO = $00002015;
EDS_ERR_INVALID_CODE_FORMAT = $00002016;
EDS_ERR_UNKNOWN_VENDER_CODE = $00002017;
EDS_ERR_CAPTURE_ALREADY_TERMINATED = $00002018;
EDS_ERR_INVALID_PARENTOBJECT = $0000201A;
EDS_ERR_INVALID_DEVICEPROP_FORMAT = $0000201B;
EDS_ERR_INVALID_DEVICEPROP_VALUE = $0000201C;
EDS_ERR_SESSION_ALREADY_OPEN = $0000201E;
EDS_ERR_TRANSACTION_CANCELLED = $0000201F;
EDS_ERR_SPECIFICATION_OF_DESTINATION_UNSUPPORTED = $00002020;
{ PTP Vendor }
const
EDS_ERR_UNKNOWN_COMMAND = $0000A001;
EDS_ERR_OPERATION_REFUSED = $0000A005;
EDS_ERR_LENS_COVER_CLOSE = $0000A006;
EDS_ERR_LOW_BATTERY = $0000A101;
EDS_ERR_OBJECT_NOTREADY = $0000A102;
{ Capture Error}
const
EDS_ERR_TAKE_PICTURE_AF_NG = $00008D01;
EDS_ERR_TAKE_PICTURE_RESERVED = $00008D02;
EDS_ERR_TAKE_PICTURE_MIRROR_UP_NG = $00008D03;
EDS_ERR_TAKE_PICTURE_SENSOR_CLEANING_NG = $00008D04;
EDS_ERR_TAKE_PICTURE_SILENCE_NG = $00008D05;
EDS_ERR_TAKE_PICTURE_NO_CARD_NG = $00008D06;
EDS_ERR_TAKE_PICTURE_CARD_NG = $00008D07;
EDS_ERR_TAKE_PICTURE_CARD_PROTECT_NG = $00008D08;
implementation
end.
|
unit BasePopupDetail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopup, RzButton, RzTabs,
Vcl.StdCtrls, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel;
type
TfrmBasePopupDetail = class(TfrmBasePopup)
pcDetail: TRzPageControl;
tsDetail: TRzTabSheet;
pnlDetail: TRzPanel;
pnlCancel: TRzPanel;
btnCancel: TRzShapeButton;
pnlSave: TRzPanel;
btnSave: TRzShapeButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnCancelClick(Sender: TObject);
procedure btnYesClick(Sender: TObject);
private
{ Private declarations }
protected
procedure Save; virtual; abstract;
procedure Cancel; virtual; abstract;
procedure BindToObject; virtual; abstract;
function ValidEntry: boolean; virtual; abstract;
public
{ Public declarations }
end;
implementation
{$R *.dfm}
uses
IFinanceDialogs;
procedure TfrmBasePopupDetail.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
if ModalResult in [mrClose,mrCancel] then Cancel;
end;
procedure TfrmBasePopupDetail.btnCancelClick(Sender: TObject);
begin
inherited;
ModalResult := mrCancel;
end;
procedure TfrmBasePopupDetail.btnYesClick(Sender: TObject);
begin
inherited;
BindToObject;
if ValidEntry then
begin
try
Save;
ModalResult := mrOK;
except
on e: Exception do ShowErrorBox(e.Message);
end;
end;
end;
end.
|
{ *********************************************************************** }
{ }
{ Delphi Runtime Library }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{ *********************************************************************** }
unit VarCmplx;
{ This unit contains complex number handling via a custom variant type.
The native format for complex numbers in this is rectangular [x + yi] but
limited conversion support for polar format [r*CIS(theta)] is provided.
Some of the functions, concepts or constants in this unit were provided by
Earl F. Glynn (www.efg2.com), who in turn, made the following acknowledgments..
Some ideas in this UNIT were borrowed from "A Pascal Tool for Complex
Numbers", Journal of Pascal, Ada, & Modula-2, May/June 1985, pp. 23-29.
Many complex formulas were taken from Chapter 4, "Handbook of Mathematical
Functions" (Ninth Printing), Abramowitz and Stegun (editors), Dover, 1972.
Some of the functions and concepts in this unit have been cross checked
against: Wolfram Research's mathematical functions site (functions.wolfram.com).
Additional help and concepts were provided by Matthias Thoma.
}
interface
uses
Variants;
{ Complex variant creation utils }
function VarComplexCreate: Variant; overload;
function VarComplexCreate(const AReal: Double): Variant; overload;
function VarComplexCreate(const AReal, AImaginary: Double): Variant; overload;
function VarComplexCreate(const AText: string): Variant; overload;
function VarComplex: TVarType;
function VarIsComplex(const AValue: Variant): Boolean;
function VarAsComplex(const AValue: Variant): Variant;
function VarComplexSimplify(const AValue: Variant): Variant;
{ Complex variant support }
function VarComplexAbsSqr(const AValue: Variant): Double;
function VarComplexAbs(const AValue: Variant): Double;
function VarComplexAngle(const AValue: Variant): Double;
function VarComplexSign(const AValue: Variant): Variant;
function VarComplexConjugate(const AValue: Variant): Variant;
function VarComplexInverse(const AValue: Variant): Variant;
function VarComplexExp(const AValue: Variant): Variant;
function VarComplexLn(const AValue: Variant): Variant;
function VarComplexLog2(const AValue: Variant): Variant;
function VarComplexLog10(const AValue: Variant): Variant;
function VarComplexLogN(const AValue: Variant; const X: Double): Variant;
function VarComplexSqr(const AValue: Variant): Variant;
function VarComplexSqrt(const AValue: Variant): Variant;
function VarComplexPower(const AValue, APower: Variant): Variant;
function VarComplexTimesPosI(const AValue: Variant): Variant;
function VarComplexTimesNegI(const AValue: Variant): Variant;
function VarComplexTimesImaginary(const AValue: Variant; const AFactor: Double): Variant;
function VarComplexTimesReal(const AValue: Variant; const AFactor: Double): Variant;
{ Complex variant trig support }
function VarComplexCos(const AValue: Variant): Variant;
function VarComplexSin(const AValue: Variant): Variant;
function VarComplexTan(const AValue: Variant): Variant;
function VarComplexCot(const AValue: Variant): Variant;
function VarComplexSec(const AValue: Variant): Variant;
function VarComplexCsc(const AValue: Variant): Variant;
function VarComplexArcCos(const AValue: Variant): Variant;
function VarComplexArcSin(const AValue: Variant): Variant;
function VarComplexArcTan(const AValue: Variant): Variant;
function VarComplexArcCot(const AValue: Variant): Variant;
function VarComplexArcSec(const AValue: Variant): Variant;
function VarComplexArcCsc(const AValue: Variant): Variant;
function VarComplexCosH(const AValue: Variant): Variant;
function VarComplexSinH(const AValue: Variant): Variant;
function VarComplexTanH(const AValue: Variant): Variant;
function VarComplexCotH(const AValue: Variant): Variant;
function VarComplexSecH(const AValue: Variant): Variant;
function VarComplexCscH(const AValue: Variant): Variant;
function VarComplexArcCosH(const AValue: Variant): Variant;
function VarComplexArcSinH(const AValue: Variant): Variant;
function VarComplexArcTanH(const AValue: Variant): Variant;
function VarComplexArcCotH(const AValue: Variant): Variant;
function VarComplexArcSecH(const AValue: Variant): Variant;
function VarComplexArcCscH(const AValue: Variant): Variant;
procedure VarComplexToPolar(const AValue: Variant; var ARadius, ATheta: Double;
AFixTheta: Boolean = True);
function VarComplexFromPolar(const ARadius, ATheta: Double): Variant;
var
ComplexNumberSymbol: string = 'i';
ComplexNumberSymbolBeforeImaginary: Boolean = False;
ComplexNumberDefuzzAtZero: Boolean = True;
implementation
uses
VarUtils, SysUtils, Math, SysConst, RTLConsts, TypInfo, Classes;
type
{ Complex variant type handler }
TComplexVariantType = class(TPublishableVariantType, IVarStreamable)
protected
function LeftPromotion(const V: TVarData; const Operator: TVarOp;
out RequiredVarType: TVarType): Boolean; override;
function GetInstance(const V: TVarData): TObject; override;
public
procedure Clear(var V: TVarData); override;
function IsClear(const V: TVarData): Boolean; override;
procedure Copy(var Dest: TVarData; const Source: TVarData;
const Indirect: Boolean); override;
procedure Cast(var Dest: TVarData; const Source: TVarData); override;
procedure CastTo(var Dest: TVarData; const Source: TVarData;
const AVarType: TVarType); override;
procedure BinaryOp(var Left: TVarData; const Right: TVarData;
const Operator: TVarOp); override;
procedure UnaryOp(var Right: TVarData; const Operator: TVarOp); override;
function CompareOp(const Left: TVarData; const Right: TVarData;
const Operator: Integer): Boolean; override;
procedure StreamIn(var Dest: TVarData; const Stream: TStream);
procedure StreamOut(const Source: TVarData; const Stream: TStream);
end;
var
{ Complex variant type handler instance }
ComplexVariantType: TComplexVariantType = nil;
type
{ Complex data that the complex variant points to }
TComplexData = class(TPersistent)
private
FReal, FImaginary: Double;
function GetAsString: String;
procedure SetAsString(const Value: String);
function GetRadius: Double;
function GetTheta: Double;
function GetFixedTheta: Double;
procedure SetReal(const AValue: Double);
procedure SetImaginary(const AValue: Double);
protected
procedure SetValueToComplexInfinity;
procedure SetValue(const AReal: Double; const AImaginary: Double = 0); overload;
procedure SetValue(const AData: TComplexData); overload;
public
// the many ways to create
constructor Create(const AReal: Double); overload;
constructor Create(const AReal, AImaginary: Double); overload;
constructor Create(const AText: string); overload;
constructor Create(const AData: TComplexData); overload;
// non-destructive operations
function GetAbsSqr: Double;
function GetAbs: Double;
function GetAngle: Double;
function Equals(const Right: TComplexData): Boolean; overload;
function Equals(const AText: string): Boolean; overload;
function Equals(const AReal, AImaginary: Double): Boolean; overload;
function IsZero: Boolean;
// conversion operations
procedure GetAsPolar(var ARadius, ATheta: Double; AFixTheta: Boolean = True);
procedure SetAsPolar(const ARadius, ATheta: Double);
// destructive operations
procedure DoAdd(const Right: TComplexData); overload;
procedure DoAdd(const AReal, AImaginary: Double); overload;
procedure DoSubtract(const Right: TComplexData); overload;
procedure DoSubtract(const AReal, AImaginary: Double); overload;
procedure DoMultiply(const Right: TComplexData); overload;
procedure DoMultiply(const AReal, AImaginary: Double); overload;
procedure DoDivide(const Right: TComplexData); overload;
procedure DoDivide(const AReal, AImaginary: Double); overload;
// inverted versions of the above (ie. value - self instead of self - value)
procedure DoInvAdd(const AReal, AImaginary: Double);
procedure DoInvSubtract(const AReal, AImaginary: Double);
procedure DoInvMultiply(const AReal, AImaginary: Double);
procedure DoInvDivide(const AReal, AImaginary: Double);
procedure DoNegate;
procedure DoSign;
procedure DoConjugate;
procedure DoInverse;
procedure DoExp;
procedure DoLn;
procedure DoLog10;
procedure DoLog2;
procedure DoLogN(const X: Double);
procedure DoSqr;
procedure DoSqrt;
procedure DoTimesImaginary(const AValue: Double);
procedure DoTimesReal(const AValue: Double);
procedure DoPower(const APower: TComplexData);
procedure DoCos;
procedure DoSin;
procedure DoTan;
procedure DoCot;
procedure DoCsc;
procedure DoSec;
procedure DoArcCos;
procedure DoArcSin;
procedure DoArcTan;
procedure DoArcCot;
procedure DoArcCsc;
procedure DoArcSec;
procedure DoCosH;
procedure DoSinH;
procedure DoTanH;
procedure DoCotH;
procedure DoCscH;
procedure DoSecH;
procedure DoArcCosH;
procedure DoArcSinH;
procedure DoArcTanH;
procedure DoArcCotH;
procedure DoArcCscH;
procedure DoArcSecH;
// conversion
property AsString: String read GetAsString write SetAsString;
published
property Real: Double read FReal write SetReal;
property Imaginary: Double read FImaginary write SetImaginary;
property Radius: Double read GetRadius;
property Theta: Double read GetTheta;
property FixedTheta: Double read GetFixedTheta;
end;
{ Helper record that helps crack open TVarData }
TComplexVarData = packed record
VType: TVarType;
Reserved1, Reserved2, Reserved3: Word;
VComplex: TComplexData;
Reserved4: LongInt;
end;
{ TComplexData }
constructor TComplexData.Create(const AReal: Double);
begin
inherited Create;
SetValue(AReal);
end;
constructor TComplexData.Create(const AReal, AImaginary: Double);
begin
inherited Create;
SetValue(AReal, AImaginary);
end;
constructor TComplexData.Create(const AText: string);
begin
inherited Create;
AsString := AText;
end;
constructor TComplexData.Create(const AData: TComplexData);
begin
inherited Create;
SetValue(AData.Real, AData.Imaginary);
end;
function TComplexData.GetAsString: String;
const
cFormats: array [Boolean] of string = ('%2:g %1:s %3:g%0:s',
'%2:g %1:s %0:s%3:g'); { do not localize }
cSign: array [Boolean] of string = ('-', '+');
begin
Result := Format(cFormats[ComplexNumberSymbolBeforeImaginary],
[ComplexNumberSymbol, cSign[Imaginary >= 0], Real, Abs(Imaginary)]);
end;
procedure TComplexData.DoNegate;
begin
SetValue(-Real, -Imaginary);
end;
procedure TComplexData.DoSign;
var
LTemp: TComplexData;
begin
if not IsZero then
begin
LTemp := TComplexData.Create(Real * Real + Imaginary * Imaginary);
try
LTemp.DoSqrt;
DoDivide(LTemp);
finally
LTemp.Free;
end;
end;
end;
procedure TComplexData.SetAsString(const Value: String);
var
LPart, LLeftover: string;
LReal, LImaginary: Double;
LSign: Integer;
function ParseNumber(const AText: string; out ARest: string;
out ANumber: Double): Boolean;
var
LAt: Integer;
LFirstPart: string;
begin
Result := True;
Val(AText, ANumber, LAt);
if LAt <> 0 then
begin
ARest := Copy(AText, LAt, MaxInt);
LFirstPart := Copy(AText, 1, LAt - 1);
Val(LFirstPart, ANumber, LAt);
if LAt <> 0 then
Result := False;
end;
end;
function ParseWhiteSpace(const AText: string; out ARest: string): Boolean;
var
LAt: Integer;
begin
LAt := 1;
if AText <> '' then
begin
while AText[LAt] = ' ' do
Inc(LAt);
ARest := Copy(AText, LAt, MaxInt);
end;
Result := ARest <> '';
end;
procedure ParseError(const AMessage: string);
begin
raise EConvertError.CreateFmt(SCmplxErrorSuffix, [AMessage,
Copy(Value, 1, Length(Value) - Length(LLeftOver)),
Copy(Value, Length(Value) - Length(LLeftOver) + 1, MaxInt)]);
end;
procedure ParseErrorEOS;
begin
raise EConvertError.CreateFmt(SCmplxUnexpectedEOS, [Value]);
end;
begin
// where to start?
LLeftover := Value;
// first get the real portion
if not ParseNumber(LLeftover, LPart, LReal) then
ParseError(SCmplxCouldNotParseReal);
// is that it?
if not ParseWhiteSpace(LPart, LLeftover) then
SetValue(LReal)
// if there is more then parse the complex part
else
begin
// look for the concat symbol
LSign := 1;
if LLeftover[1] = '-' then
LSign := -1
else if LLeftover[1] <> '+' then
ParseError(SCmplxCouldNotParsePlus);
LPart := Copy(LLeftover, 2, MaxInt);
// skip any whitespace
ParseWhiteSpace(LPart, LLeftover);
// symbol before?
if ComplexNumberSymbolBeforeImaginary then
begin
if not AnsiSameText(Copy(LLeftOver, 1, Length(ComplexNumberSymbol)),
ComplexNumberSymbol) then
ParseError(Format(SCmplxCouldNotParseSymbol, [ComplexNumberSymbol]));
LPart := Copy(LLeftover, Length(ComplexNumberSymbol) + 1, MaxInt);
// skip any whitespace
ParseWhiteSpace(LPart, LLeftover);
end;
// imaginary part
if not ParseNumber(LLeftover, LPart, LImaginary) then
ParseError(SCmplxCouldNotParseImaginary);
// correct for sign
LImaginary := LImaginary * LSign;
// symbol after?
if not ComplexNumberSymbolBeforeImaginary then
begin
// skip any whitespace
ParseWhiteSpace(LPart, LLeftover);
// make sure there is symbol!
if not AnsiSameText(Copy(LLeftOver, 1, Length(ComplexNumberSymbol)),
ComplexNumberSymbol) then
ParseError(Format(SCmplxCouldNotParseSymbol, [ComplexNumberSymbol]));
LPart := Copy(LLeftover, Length(ComplexNumberSymbol) + 1, MaxInt);
end;
// make sure the rest of the string is whitespaces
ParseWhiteSpace(LPart, LLeftover);
if LLeftover <> '' then
ParseError(SCmplxUnexpectedChars);
// make it then
SetValue(LReal, LImaginary);
end;
end;
procedure TComplexData.DoAdd(const Right: TComplexData);
begin
SetValue(Real + Right.Real, Imaginary + Right.Imaginary);
end;
procedure TComplexData.DoAdd(const AReal, AImaginary: Double);
begin
SetValue(Real + AReal, Imaginary + AImaginary);
end;
procedure TComplexData.DoInvAdd(const AReal, AImaginary: Double);
begin
SetValue(AReal + Real, AImaginary + Imaginary);
end;
procedure TComplexData.DoSubtract(const Right: TComplexData);
begin
SetValue(Real - Right.Real, Imaginary - Right.Imaginary);
end;
procedure TComplexData.DoSubtract(const AReal, AImaginary: Double);
begin
SetValue(Real - AReal, Imaginary - AImaginary);
end;
procedure TComplexData.DoInvSubtract(const AReal, AImaginary: Double);
begin
SetValue(AReal - Real, AImaginary - Imaginary);
end;
procedure TComplexData.DoMultiply(const Right: TComplexData);
begin
DoMultiply(Right.Real, Right.Imaginary);
end;
procedure TComplexData.DoMultiply(const AReal, AImaginary: Double);
begin
SetValue((Real * AReal) - (Imaginary * AImaginary),
(Real * AImaginary) + (Imaginary * AReal));
end;
procedure TComplexData.DoInvMultiply(const AReal, AImaginary: Double);
begin
SetValue((AReal * Real) - (AImaginary * Imaginary),
(AReal * Imaginary) + (AImaginary * Real));
end;
procedure TComplexData.DoDivide(const Right: TComplexData);
begin
DoDivide(Right.Real, Right.Imaginary);
end;
procedure TComplexData.DoDivide(const AReal, AImaginary: Double);
var
LDenominator: Double;
begin
LDenominator := (AReal * AReal) + (AImaginary * AImaginary);
if Math.IsZero(LDenominator) then
raise EZeroDivide.Create(SDivByZero);
SetValue(((Real * AReal) + (Imaginary * AImaginary)) / LDenominator,
((Imaginary * AReal) - (Real * AImaginary)) / LDenominator);
end;
procedure TComplexData.DoInvDivide(const AReal, AImaginary: Double);
var
LDenominator: Double;
begin
LDenominator := GetAbsSqr;
if Math.IsZero(LDenominator) then
raise EZeroDivide.Create(SDivByZero);
SetValue(((AReal * Real) + (AImaginary * Imaginary)) / LDenominator,
((AImaginary * Real) - (AReal * Imaginary)) / LDenominator);
end;
procedure TComplexData.SetValueToComplexInfinity;
begin
FReal := NaN;
FImaginary := NaN;
end;
procedure TComplexData.SetReal(const AValue: Double);
begin
FReal := AValue;
if ComplexNumberDefuzzAtZero and Math.IsZero(FReal) then
FReal := 0;
end;
procedure TComplexData.SetImaginary(const AValue: Double);
begin
FImaginary := AValue;
if ComplexNumberDefuzzAtZero and Math.IsZero(FImaginary) then
FImaginary := 0;
end;
procedure TComplexData.SetValue(const AReal, AImaginary: Double);
begin
Real := AReal;
Imaginary := AImaginary;
end;
procedure TComplexData.SetValue(const AData: TComplexData);
begin
Real := AData.Real;
Imaginary := AData.Imaginary;
end;
function TComplexData.GetAbs: Double;
begin
Result := Sqrt(GetAbsSqr);
end;
function TComplexData.GetAbsSqr: Double;
begin
Result := Real * Real + Imaginary * Imaginary;
end;
function TComplexData.GetAngle: Double;
begin
Result := ArcTan2(Imaginary, Real);
end;
procedure TComplexData.DoCos;
begin
SetValue(Cos(Real) * CosH(Imaginary), -Sin(Real) * SinH(Imaginary));
end;
procedure TComplexData.DoSin;
begin
SetValue(Sin(Real) * CosH(Imaginary), Cos(Real) * SinH(Imaginary));
end;
procedure TComplexData.DoTan;
var
LDenominator: Double;
begin
if Equals(PI / 2, 0) then
SetValueToComplexInfinity
else
begin
LDenominator := Cos(2.0 * Real) + CosH(2.0 * Imaginary);
if Math.IsZero(LDenominator) then
raise EZeroDivide.Create(SDivByZero);
SetValue(Sin(2.0 * Real) / LDenominator, SinH(2.0 * Imaginary) / LDenominator);
end;
end;
procedure TComplexData.DoCot;
var
LTemp: TComplexData;
begin
if IsZero then
SetValueToComplexInfinity
else
begin
LTemp := TComplexData.Create(Self);
try
LTemp.DoSin;
DoCos;
DoDivide(LTemp);
finally
LTemp.Free;
end;
end;
end;
procedure TComplexData.DoCsc;
begin
if IsZero then
SetValueToComplexInfinity
else
begin
DoSin;
DoInvDivide(1, 0);
end;
end;
procedure TComplexData.DoSec;
begin
if Equals(PI / 2, 0) then
SetValueToComplexInfinity
else
begin
DoCos;
DoInvDivide(1, 0);
end;
end;
procedure TComplexData.DoArcCos;
var
LTemp: TComplexData;
begin
LTemp := TComplexData.Create(Self);
try
LTemp.DoSqr;
LTemp.DoInvSubtract(1, 0);
LTemp.DoSqrt;
DoTimesImaginary(1);
DoAdd(LTemp);
DoLn;
DoTimesImaginary(1);
DoInvAdd(PI / 2, 0);
finally
LTemp.Free;
end;
end;
procedure TComplexData.DoArcSin;
var
LTemp: TComplexData;
begin
LTemp := TComplexData.Create(Self);
try
LTemp.DoSqr;
LTemp.DoInvSubtract(1, 0);
LTemp.DoSqrt;
DoTimesImaginary(1);
DoAdd(LTemp);
DoLn;
DoTimesImaginary(-1);
finally
LTemp.Free;
end;
end;
procedure TComplexData.DoArcTan;
var
LTemp1, LTemp2: TComplexData;
begin
if Equals(0, 1) then
SetValue(0, Infinity)
else if Equals(0, -1) then
SetValue(0, -Infinity)
else
begin
LTemp1 := nil;
LTemp2 := nil;
try
LTemp1 := TComplexData.Create(Self);
LTemp1.DoTimesImaginary(1);
LTemp2 := TComplexData.Create(LTemp1);
LTemp1.DoInvSubtract(1, 0);
LTemp1.DoLn;
LTemp2.DoInvAdd(1, 0);
LTemp2.DoLn;
LTemp1.DoSubtract(LTemp2);
SetValue(0, 1);
DoDivide(2, 0);
DoMultiply(LTemp1);
finally
LTemp2.Free;
LTemp1.Free;
end;
end;
end;
procedure TComplexData.DoArcCot;
begin
DoInverse;
DoArcTan;
end;
procedure TComplexData.DoArcCsc;
begin
if IsZero then
SetValueToComplexInfinity
else
begin
DoInverse;
DoArcSin;
end;
end;
procedure TComplexData.DoArcSec;
begin
if IsZero then
SetValueToComplexInfinity
else
begin
DoInverse;
DoArcCos;
end;
end;
procedure TComplexData.DoCosH;
begin
SetValue(CosH(Real) * Cos(Imaginary), SinH(Real) * Sin(Imaginary));
end;
procedure TComplexData.DoSinH;
begin
SetValue(SinH(Real) * Cos(Imaginary), CosH(Real) * Sin(Imaginary));
end;
procedure TComplexData.DoTanH;
var
LTemp: TComplexData;
begin
if IsZero then
SetValue(0)
else
begin
LTemp := TComplexData.Create(Self);
try
LTemp.DoCosH;
DoSinH;
DoDivide(LTemp);
finally
LTemp.Free;
end;
end;
end;
procedure TComplexData.DoCotH;
begin
if IsZero then
SetValueToComplexInfinity
else
begin
DoTanH;
DoInverse;
end;
end;
procedure TComplexData.DoCscH;
begin
if IsZero then
SetValueToComplexInfinity
else
begin
DoSinH;
DoInverse;
end;
end;
procedure TComplexData.DoSecH;
begin
DoCosH;
DoInverse;
end;
procedure TComplexData.DoArcCosH;
var
LTemp1, LTemp2: TComplexData;
begin
LTemp1 := nil;
LTemp2 := nil;
try
LTemp1 := TComplexData.Create(Self);
LTemp1.DoAdd(1, 0);
LTemp1.DoSqrt;
LTemp2 := TComplexData.Create(Self);
LTemp2.DoSubtract(1, 0);
LTemp2.DoSqrt;
LTemp2.DoMultiply(LTemp1);
DoAdd(LTemp2);
DoLn;
finally
LTemp2.Free;
LTemp1.Free;
end;
end;
procedure TComplexData.DoArcSinH;
begin
DoTimesImaginary(1.0);
DoArcSin;
DoTimesImaginary(-1.0);
end;
procedure TComplexData.DoArcTanH;
begin
if Equals(1, 0) then
SetValue(Infinity)
else if Equals(-1, 0) then
SetValue(-Infinity)
else
begin
DoTimesImaginary(1.0);
DoArcTan;
DoTimesImaginary(-1.0);
end;
end;
procedure TComplexData.DoArcCotH;
begin
if Equals(1, 0) then
SetValue(Infinity)
else if Equals(-1, 0) then
SetValue(-Infinity)
else
begin
DoInverse;
DoArcTanH;
end;
end;
procedure TComplexData.DoArcCscH;
begin
if IsZero then
SetValueToComplexInfinity
else
begin
DoInverse;
DoArcSinH;
end;
end;
procedure TComplexData.DoArcSecH;
begin
if IsZero then
SetValue(Infinity)
else
begin
DoInverse;
DoArcCosH;
end;
end;
procedure TComplexData.DoConjugate;
begin
Imaginary := -Imaginary;
end;
procedure TComplexData.DoExp;
var
LExp: Double;
begin
LExp := Exp(Real);
SetValue(LExp * Cos(Imaginary), LExp * Sin(Imaginary));
end;
procedure TComplexData.DoInverse;
var
LDenominator: Double;
begin
LDenominator := GetAbsSqr;
if Math.IsZero(LDenominator) then
raise EZeroDivide.Create(SDivByZero);
SetValue(Real / LDenominator, -(Imaginary / LDenominator));
end;
procedure TComplexData.DoLn;
var
LRadius, LTheta: Double;
begin
if IsZero then
SetValue(-Infinity)
else
begin
GetAsPolar(LRadius, LTheta);
SetValue(Ln(LRadius), LTheta);
end;
end;
procedure TComplexData.DoLog10;
var
LRadius, LTheta: Double;
begin
if IsZero then
SetValue(-Infinity)
else
begin
GetAsPolar(LRadius, LTheta);
SetValue(Ln(LRadius), LTheta);
DoDivide(Ln(10), 0);
end;
end;
procedure TComplexData.DoLog2;
var
LRadius, LTheta: Double;
begin
if IsZero then
SetValue(-Infinity)
else
begin
GetAsPolar(LRadius, LTheta);
SetValue(Ln(LRadius), LTheta);
DoDivide(Ln(2), 0);
end;
end;
procedure TComplexData.DoLogN(const X: Double);
var
LRadius, LTheta: Double;
LTemp: TComplexData;
begin
if IsZero and (X > 0) and (X <> 1) then
SetValue(-Infinity)
else
begin
LTemp := TComplexData.Create(X);
try
LTemp.DoLn;
GetAsPolar(LRadius, LTheta);
SetValue(Ln(LRadius), LTheta);
DoDivide(LTemp);
finally
LTemp.Free;
end;
end;
end;
procedure TComplexData.DoSqr;
begin
SetValue((Real * Real) - (Imaginary * Imaginary),
(Real * Imaginary) + (Imaginary * Real));
end;
procedure TComplexData.DoSqrt;
var
LValue: Double;
begin
if not IsZero then
if Real > 0 then
begin
LValue := GetAbs + Real;
SetValue(Sqrt(LValue / 2), Imaginary / Sqrt(LValue * 2));
end
else
begin
LValue := GetAbs - Real;
if Imaginary < 0 then
SetValue(Abs(Imaginary) / Sqrt(LValue * 2),
-Sqrt(LValue / 2))
else
SetValue(Abs(Imaginary) / Sqrt(LValue * 2),
Sqrt(LValue / 2));
end;
end;
procedure TComplexData.DoTimesImaginary(const AValue: Double);
begin
SetValue(-AValue * Imaginary, AValue * Real);
end;
procedure TComplexData.DoTimesReal(const AValue: Double);
begin
SetValue(AValue * Real, AValue * Imaginary);
end;
function TComplexData.IsZero: Boolean;
begin
Result := Math.IsZero(Real) and Math.IsZero(Imaginary);
end;
function TComplexData.Equals(const Right: TComplexData): Boolean;
begin
Result := Math.SameValue(Real, Right.Real) and
Math.SameValue(Imaginary, Right.Imaginary);
end;
function TComplexData.Equals(const AReal, AImaginary: Double): Boolean;
begin
Result := Math.SameValue(Real, AReal) and Math.SameValue(Imaginary, AImaginary);
end;
function TComplexData.Equals(const AText: string): Boolean;
begin
Result := AnsiSameText(AsString, AText);
end;
procedure TComplexData.DoPower(const APower: TComplexData);
begin
if Math.IsZero(GetAbsSqr) then
if Math.IsZero(APower.GetAbsSqr) then
SetValue(1)
else
SetValue(0)
else
begin
DoLn;
DoMultiply(APower);
DoExp;
end;
end;
procedure TComplexData.GetAsPolar(var ARadius, ATheta: Double; AFixTheta: Boolean);
begin
ATheta := ArcTan2(Imaginary, Real);
ARadius := Sqrt(Real * Real + Imaginary * Imaginary);
if AFixTheta then
begin
while ATheta > Pi do
ATheta := ATheta - 2.0 * Pi;
while ATheta <= -Pi do
ATheta := ATheta + 2.0 * Pi;
end;
end;
procedure TComplexData.SetAsPolar(const ARadius, ATheta: Double);
begin
SetValue(ARadius * Cos(ATheta), ARadius * Sin(ATheta));
end;
function TComplexData.GetRadius: Double;
var
Temp: Double;
begin
GetAsPolar(Result, Temp);
end;
function TComplexData.GetTheta: Double;
var
Temp: Double;
begin
GetAsPolar(Temp, Result, False);
end;
function TComplexData.GetFixedTheta: Double;
var
Temp: Double;
begin
GetAsPolar(Temp, Result, True);
end;
{ TComplexVariantType }
procedure TComplexVariantType.BinaryOp(var Left: TVarData;
const Right: TVarData; const Operator: TVarOp);
begin
if Right.VType = VarType then
case Left.VType of
varString:
case Operator of
opAdd:
Variant(Left) := Variant(Left) + TComplexVarData(Right).VComplex.AsString;
else
RaiseInvalidOp;
end;
else
if Left.VType = VarType then
case Operator of
opAdd:
TComplexVarData(Left).VComplex.DoAdd(TComplexVarData(Right).VComplex);
opSubtract:
TComplexVarData(Left).VComplex.DoSubtract(TComplexVarData(Right).VComplex);
opMultiply:
TComplexVarData(Left).VComplex.DoMultiply(TComplexVarData(Right).VComplex);
opDivide:
TComplexVarData(Left).VComplex.DoDivide(TComplexVarData(Right).VComplex);
else
RaiseInvalidOp;
end
else
RaiseInvalidOp;
end
else
RaiseInvalidOp;
end;
procedure TComplexVariantType.Cast(var Dest: TVarData; const Source: TVarData);
var
LSource, LTemp: TVarData;
begin
VarDataInit(LSource);
try
VarDataCopyNoInd(LSource, Source);
VarDataClear(Dest);
if VarDataIsStr(LSource) then
TComplexVarData(Dest).VComplex := TComplexData.Create(VarDataToStr(LSource))
else
begin
VarDataInit(LTemp);
try
VarDataCastTo(LTemp, LSource, varDouble);
TComplexVarData(Dest).VComplex := TComplexData.Create(LTemp.VDouble);
finally
VarDataClear(LTemp);
end;
end;
Dest.VType := VarType;
finally
VarDataClear(LSource);
end;
end;
procedure TComplexVariantType.CastTo(var Dest: TVarData; const Source: TVarData;
const AVarType: TVarType);
var
LTemp: TVarData;
begin
if Source.VType = VarType then
case AVarType of
varOleStr:
VarDataFromOleStr(Dest, TComplexVarData(Source).VComplex.AsString);
varString:
VarDataFromStr(Dest, TComplexVarData(Source).VComplex.AsString);
else
VarDataInit(LTemp);
try
LTemp.VType := varDouble;
LTemp.VDouble := TComplexVarData(Source).VComplex.Real;
VarDataCastTo(Dest, LTemp, AVarType);
finally
VarDataClear(LTemp);
end;
end
else
inherited;
end;
procedure TComplexVariantType.Clear(var V: TVarData);
begin
V.VType := varEmpty;
FreeAndNil(TComplexVarData(V).VComplex);
end;
function TComplexVariantType.CompareOp(const Left, Right: TVarData;
const Operator: Integer): Boolean;
begin
Result := False;
if (Left.VType = VarType) and (Right.VType = VarType) then
case Operator of
opCmpEQ:
Result := TComplexVarData(Left).VComplex.Equals(TComplexVarData(Right).VComplex);
opCmpNE:
Result := not TComplexVarData(Left).VComplex.Equals(TComplexVarData(Right).VComplex);
else
RaiseInvalidOp;
end
else
RaiseInvalidOp;
end;
procedure TComplexVariantType.Copy(var Dest: TVarData; const Source: TVarData;
const Indirect: Boolean);
begin
if Indirect and VarDataIsByRef(Source) then
VarDataCopyNoInd(Dest, Source)
else
with TComplexVarData(Dest) do
begin
VType := VarType;
VComplex := TComplexData.Create(TComplexVarData(Source).VComplex);
end;
end;
function TComplexVariantType.GetInstance(const V: TVarData): TObject;
begin
Result := TComplexVarData(V).VComplex;
end;
function TComplexVariantType.IsClear(const V: TVarData): Boolean;
begin
Result := (TComplexVarData(V).VComplex = nil) or
TComplexVarData(V).VComplex.IsZero;
end;
function TComplexVariantType.LeftPromotion(const V: TVarData;
const Operator: TVarOp; out RequiredVarType: TVarType): Boolean;
begin
{ TypeX Op Complex }
if (Operator = opAdd) and VarDataIsStr(V) then
RequiredVarType := varString
else
RequiredVarType := VarType;
Result := True;
end;
procedure TComplexVariantType.StreamIn(var Dest: TVarData;
const Stream: TStream);
begin
with TReader.Create(Stream, 1024) do
try
with TComplexVarData(Dest) do
begin
// Order of execution of the ReadFloat is important. If we executed
// VComplex := TComplexData.Create(ReadFloat, ReadFloat) then, depending
// on the mood of the compiler, the two calls to readfloats might
// execute backwards (21 instead of 12).
VComplex := TComplexData.Create;
VComplex.Real := ReadFloat;
VComplex.Imaginary := ReadFloat;
end;
finally
Free;
end;
end;
procedure TComplexVariantType.StreamOut(const Source: TVarData;
const Stream: TStream);
begin
with TWriter.Create(Stream, 1024) do
try
with TComplexVarData(Source).VComplex do
begin
WriteFloat(Real);
WriteFloat(Imaginary);
end;
finally
Free;
end;
end;
procedure TComplexVariantType.UnaryOp(var Right: TVarData;
const Operator: TVarOp);
begin
if Right.VType = VarType then
case Operator of
opNegate:
TComplexVarData(Right).VComplex.DoNegate;
else
RaiseInvalidOp;
end
else
RaiseInvalidOp;
end;
{ Complex variant creation utils }
procedure VarComplexCreateInto(var ADest: Variant; const AComplex: TComplexData);
begin
VarClear(ADest);
TComplexVarData(ADest).VType := VarComplex;
TComplexVarData(ADest).VComplex := AComplex;
end;
function VarComplexCreate: Variant;
begin
VarComplexCreateInto(Result, TComplexData.Create(0));
end;
function VarComplexCreate(const AReal: Double): Variant;
begin
VarComplexCreateInto(Result, TComplexData.Create(AReal));
end;
function VarComplexCreate(const AReal, AImaginary: Double): Variant;
begin
VarComplexCreateInto(Result, TComplexData.Create(AReal, AImaginary));
end;
function VarComplexCreate(const AText: string): Variant;
begin
VarComplexCreateInto(Result, TComplexData.Create(AText));
end;
function VarComplex: TVarType;
begin
Result := ComplexVariantType.VarType;
end;
function VarIsComplex(const AValue: Variant): Boolean;
begin
Result := (TVarData(AValue).VType and varTypeMask) = VarComplex;
end;
function VarAsComplex(const AValue: Variant): Variant;
begin
if not VarIsComplex(AValue) then
VarCast(Result, AValue, VarComplex)
else
Result := AValue;
end;
function VarComplexSimplify(const AValue: Variant): Variant;
begin
if VarIsComplex(AValue) and
Math.IsZero(TComplexVarData(AValue).VComplex.Imaginary) then
Result := TComplexVarData(AValue).VComplex.Real
else
Result := AValue;
end;
{ Complex variant support }
function VarComplexAbsSqr(const AValue: Variant): Double;
var
LTemp: Variant;
begin
VarCast(LTemp, AValue, VarComplex);
Result := TComplexVarData(LTemp).VComplex.GetAbsSqr;
end;
function VarComplexAbs(const AValue: Variant): Double;
var
LTemp: Variant;
begin
VarCast(LTemp, AValue, VarComplex);
Result := TComplexVarData(LTemp).VComplex.GetAbs;
end;
function VarComplexAngle(const AValue: Variant): Double;
var
LTemp: Variant;
begin
VarCast(LTemp, AValue, VarComplex);
Result := TComplexVarData(LTemp).VComplex.GetAngle;
end;
function VarComplexSign(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoSign;
end;
function VarComplexConjugate(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoConjugate;
end;
function VarComplexInverse(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoInverse;
end;
function VarComplexExp(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoExp;
end;
function VarComplexLn(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoLn;
end;
function VarComplexLog10(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoLog10;
end;
function VarComplexLog2(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoLog2;
end;
function VarComplexLogN(const AValue: Variant; const X: Double): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoLogN(X);
end;
function VarComplexSqr(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoSqr;
end;
function VarComplexSqrt(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoSqrt;
end;
function VarComplexTimesPosI(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoTimesImaginary(1.0);
end;
function VarComplexTimesNegI(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoTimesImaginary(-1.0);
end;
function VarComplexTimesImaginary(const AValue: Variant; const AFactor: Double): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoTimesImaginary(AFactor);
end;
function VarComplexTimesReal(const AValue: Variant; const AFactor: Double): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoTimesReal(AFactor);
end;
function VarComplexPower(const AValue, APower: Variant): Variant;
var
LTemp: Variant;
begin
VarCast(Result, AValue, VarComplex);
VarCast(LTemp, APower, VarComplex);
TComplexVarData(Result).VComplex.DoPower(TComplexVarData(LTemp).VComplex);
end;
{ Complex variant trig support }
function VarComplexCos(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoCos;
end;
function VarComplexSin(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoSin;
end;
function VarComplexTan(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoTan;
end;
function VarComplexCot(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoCot;
end;
function VarComplexSec(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoSec;
end;
function VarComplexCsc(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoCsc;
end;
function VarComplexArcCos(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcCos;
end;
function VarComplexArcSin(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcSin;
end;
function VarComplexArcTan(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcTan;
end;
function VarComplexArcCot(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcCot;
end;
function VarComplexArcSec(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcSec;
end;
function VarComplexArcCsc(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcCsc;
end;
function VarComplexCosH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoCosH;
end;
function VarComplexSinH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoSinH;
end;
function VarComplexTanH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoTanH;
end;
function VarComplexCotH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoCotH;
end;
function VarComplexSecH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoSecH;
end;
function VarComplexCscH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoCscH;
end;
function VarComplexArcCosH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcCosH;
end;
function VarComplexArcSinH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcSinH;
end;
function VarComplexArcTanH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcTanH;
end;
function VarComplexArcCotH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcCotH;
end;
function VarComplexArcSecH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcSecH;
end;
function VarComplexArcCscH(const AValue: Variant): Variant;
begin
VarCast(Result, AValue, VarComplex);
TComplexVarData(Result).VComplex.DoArcCscH;
end;
procedure VarComplexToPolar(const AValue: Variant; var ARadius, ATheta: Double;
AFixTheta: Boolean);
var
Temp: Variant;
begin
VarCast(Temp, AValue, VarComplex);
TComplexVarData(Temp).VComplex.GetAsPolar(ARadius, ATheta, AFixTheta);
end;
function VarComplexFromPolar(const ARadius, ATheta: Double): Variant;
begin
Result := VarComplexCreate;
TComplexVarData(Result).VComplex.SetAsPolar(ARadius, ATheta);
end;
initialization
ComplexVariantType := TComplexVariantType.Create;
finalization
FreeAndNil(ComplexVariantType);
end.
|
{**
* @Author: Du xinming
* @Contact: QQ<36511179>; Email<lndxm1979@163.com>
* @Version: 0.0
* @Date: 2018.10
* @Brief:
* Windows IOCP API Wrapper
*}
unit org.utilities.iocp;
interface
uses
System.SysUtils,
Winapi.Windows,
org.utilities,
org.utilities.thread;
type
TIOCP = class(TThreadPool)
private
FIOCPHandle: THandle;
FLogLevel: TLogLevel;
FLogNotify: TLogNotify;
function CreateNewCompletionPort(dwNumberOfConcurrentThreads: DWORD = 0): THandle;
procedure SetLogLevel(const Value: TLogLevel);
protected
procedure WriteLog(LogLevel: TLogLevel; LogContent: string); virtual;
procedure ProcessCompletionPacket(dwNumOfBytes: DWORD; dwCompletionKey: ULONG_PTR; lpOverlapped: POverlapped); virtual; abstract;
procedure DoThreadException(dwNumOfBytes: DWORD; dwCompletionKey: ULONG_PTR; lpOverlapped: POverlapped; E: Exception); virtual; abstract;
public
constructor Create(AThreadCount: Integer);
destructor Destroy; override;
function AssociateDeviceWithCompletionPort(hDevice: THandle; dwCompletionKey: DWORD): DWORD;
function PostQueuedCompletionStatus(dwNumOfBytes: DWORD; dwCompletionKey: ULONG_PTR; lpOverlapped: POverlapped): Boolean;
procedure DoThreadBegin; override;
procedure DoThreadEnd; override;
procedure Execute; override;
procedure Start; override;
procedure Stop; override;
property LogLevel: TLogLevel read FLogLevel write SetLogLevel;
property OnLogNotify: TLogNotify read FLogNotify write FLogNotify;
end;
implementation
uses
System.StrUtils,
System.IniFiles,
System.Classes,
REST.Types,
REST.Json;
{ TIOCP }
function TIOCP.AssociateDeviceWithCompletionPort(hDevice: THandle;
dwCompletionKey: DWORD): DWORD;
var
H: THandle;
ErrDesc: string;
begin
Result := 0;
// 本函数不应该错误,否则要么是参数设置有问题,要么是理解偏差
// 如果出错暂时定为 [致命][不可重用 ]
// dxm 2018.11.10
// ERROR_INVALID_PARAMETER[87]
// 当复用SOCKET时会出现,直接忽略即可
H := CreateIoCompletionPort(hDevice, FIOCPHandle, dwCompletionKey, 0);
if H <> FIOCPHandle then begin
Result := GetLastError();
if Result <> ERROR_INVALID_PARAMETER then begin
ErrDesc := Format('<%s.AssociateDeviceWithCompletionPort.CreateIoCompletionPort> LastErrorCode=%d', [ClassName, Result]);
WriteLog(llFatal, ErrDesc);
end else
Result := 0;
end;
end;
constructor TIOCP.Create(AThreadCount: Integer);
begin
inherited;
FLogLevel := llWarning;
FIOCPHandle := CreateNewCompletionPort(AThreadCount div 2);
end;
function TIOCP.CreateNewCompletionPort(dwNumberOfConcurrentThreads: DWORD): THandle;
var
dwErr: DWORD;
begin
Result := CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, dwNumberOfConcurrentThreads);
dwErr := GetLastError();
if Result = 0 then
raise Exception.CreateFmt('%s.CreateNewCompletionPort.CreateIoCompletionPort> failed with error: %d',
[ClassName, dwErr]);
end;
destructor TIOCP.Destroy;
begin
CloseHandle(FIOCPHandle);
inherited;
end;
procedure TIOCP.DoThreadBegin;
begin
inherited;
end;
procedure TIOCP.DoThreadEnd;
begin
inherited;
end;
procedure TIOCP.Execute;
var
dwNumBytes: DWORD;
CompletionKey: ULONG_PTR;
lpOverlapped: POverlapped;
bRet: LongBool;
dwError: DWORD;
ErrDesc: string;
begin
while not FTerminated do begin
dwNumBytes := 0;
CompletionKey := 0;
lpOverlapped := nil;
bRet := GetQueuedCompletionStatus(
FIOCPHandle,
dwNumBytes,
CompletionKey,
lpOverlapped,
INFINITE);
dwError := GetLastError();
// bRet: TRUE -->成功获取一个完成封包,且该完成封包正常
// FALSE-->1. GetQueuedCompletionStatus调用出错,此时lpOverlapped必为nil
// 2. 成功获取一个完成封包,但该完成封包异常,异常错误码存在于lpOverlapped^.Internal成员中
// 处理策略:
// GetQueuedCompletionStatus调用出错由本函数处理,其它情况由上层处理
if bRet or (lpOverlapped <> nil) then begin
if dwNumBytes <> $FFFFFFFF then begin // {-1}
try
ProcessCompletionPacket(dwNumBytes, CompletionKey, lpOverlapped)
except
on E:Exception do DoThreadException(dwNumBytes, CompletionKey, lpOverlapped, E);
end;
end
else begin
ErrDesc := Format('<%s.GetQueuedCompletionStatus> get a terminate completion packet', [ClassName]);
WriteLog(llWarning, ErrDesc);
FTerminated := True;
end;
end
else begin
ErrDesc := Format('<%s.GetQueuedCompletionStatus> failed with error: %d', [ClassName, dwError]);
WriteLog(llFatal, ErrDesc);
end;
end;
end;
function TIOCP.PostQueuedCompletionStatus(dwNumOfBytes: DWORD;
dwCompletionKey: ULONG_PTR; lpOverlapped: POverlapped): Boolean;
begin
Result := Winapi.Windows.PostQueuedCompletionStatus(
FIOCPHandle,
dwNumOfBytes,
dwCompletionKey,
lpOverlapped);
end;
procedure TIOCP.SetLogLevel(const Value: TLogLevel);
begin
// FLogLevel := Value;
if Value < llWarning then
FLogLevel := llWarning
else
FLogLevel := Value;
end;
procedure TIOCP.Start;
begin
inherited;
end;
procedure TIOCP.Stop;
var
I: Integer;
begin
for I := 0 to Self.ThreadCount - 1 do begin
PostQueuedCompletionStatus($FFFFFFFF, 0, nil);
end;
inherited;
end;
procedure TIOCP.WriteLog(LogLevel: TLogLevel; LogContent: string);
begin
if Assigned(FLogNotify) then begin
LogContent := '[' + LOG_LEVLE_DESC[LogLevel] + ']' + LogContent;
FLogNotify(nil, LogLevel, LogContent);
end;
end;
end.
|
unit SmallClaimsCondoCopyDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, wwdblook, Db, DBTables, ExtCtrls, Grids, Wwtable;
type
TSmallClaimsCondoCopyDialog = class(TForm)
OKButton: TBitBtn;
CancelButton: TBitBtn;
SmallClaimsTable: TTable;
InformationLabel: TLabel;
ParcelGroupBox: TGroupBox;
ParcelGrid: TStringGrid;
ClearButton: TBitBtn;
AddButton: TBitBtn;
DeleteButton: TBitBtn;
CurrentExemptionsTable: TTable;
SmallClaimsExemptionsTable: TTable;
CurrentAssessmentTable: TTable;
SmallClaimsExemptionsAskedTable: TwwTable;
SmallClaimsSpecialDistrictsTable: TTable;
CurrentSpecialDistrictsTable: TTable;
ParcelTable: TTable;
SwisCodeTable: TTable;
PriorAssessmentTable: TTable;
LawyerCodeTable: TTable;
SmallClaimsLookupTable: TTable;
SmallClaimsExemptionsAskedLookupTable: TTable;
procedure OKButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ClearButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
LawyerCode, UnitName,
OriginalSwisSBLKey,
PriorYear, SmallClaimsYear : String;
IndexNumber : LongInt;
SwisSBLKeyList : TStringList;
Procedure SetNumParcelsLabel(NumParcels : Integer);
Procedure AddOneParcel(SwisSBLKey : String);
Procedure CreateOneSmallClaims(SwisSBLKey : String);
end;
var
SmallClaimsCondoCopyDialog: TSmallClaimsCondoCopyDialog;
implementation
{$R *.DFM}
uses WinUtils, Utilitys, PASUtils, GlblVars, GlblCnst,
PASTypes, GrievanceUtilitys, Prog;
{===============================================================}
Procedure TSmallClaimsCondoCopyDialog.FormShow(Sender: TObject);
var
TempRepresentative : String;
PriorProcessingType, SmallClaimsProcessingType : Integer;
Quit : Boolean;
begin
UnitName := 'SmallClaimsCondoCopyDialogUnit';
SwisSBLKeyList := TStringList.Create;
{FXX10082003-1(2.07j1): Don't base the processing type of the current and prior on
the current grievance year, but the year of this grievance.}
SmallClaimsProcessingType := GetProcessingTypeForTaxRollYear(SmallClaimsYear);
PriorYear := IntToStr(StrToInt(SmallClaimsYear) - 1);
PriorProcessingType := GetProcessingTypeForTaxRollYear(PriorYear);
OpenTablesForForm(Self, SmallClaimsProcessingType);
OpenTableForProcessingType(SwisCodeTable, SwisCodeTableName,
SmallClaimsProcessingType, Quit);
OpenTableForProcessingType(CurrentAssessmentTable, AssessmentTableName,
SmallClaimsProcessingType, Quit);
OpenTableForProcessingType(PriorAssessmentTable, AssessmentTableName,
PriorProcessingType, Quit);
OpenTableForProcessingType(CurrentExemptionsTable, ExemptionsTableName,
SmallClaimsProcessingType, Quit);
OpenTableForProcessingType(CurrentSpecialDistrictsTable, SpecialDistrictTableName,
SmallClaimsProcessingType, Quit);
If (Trim(LawyerCode) = '')
then TempRepresentative := LawyerCode
else TempRepresentative := '';
InformationLabel.Caption := 'Please enter the additional parcels that should have a small claims created ' +
'with Index # ' + IntToStr(IndexNumber);
If (TempRepresentative = '')
then InformationLabel.Caption := InformationLabel.Caption + '.'
else InformationLabel.Caption := InformationLabel.Caption + ' and representative = ' +
TempRepresentative;
end; {FormShow}
{============================================================}
Procedure TSmallClaimsCondoCopyDialog.SetNumParcelsLabel(NumParcels : Integer);
begin
ParcelGroupBox.Caption := ' ' + IntToStr(NumParcels) + ' Parcels: ';
end; {SetNumParcelsLabel}
{============================================================}
Function FindLastItem(ParcelGrid : TStringGrid) : Integer;
var
I : Integer;
begin
Result := 0;
with ParcelGrid do
For I := 0 to (RowCount - 1) do
If (Deblank(Cells[0, I]) <> '')
then Result := Result + 1;
end; {FindLastItem}
{============================================================}
Procedure TSmallClaimsCondoCopyDialog.AddOneParcel(SwisSBLKey : String);
var
LastItem : Integer;
begin
LastItem := FindLastItem(ParcelGrid);
with ParcelGrid do
begin
If (LastItem = (RowCount - 1))
then RowCount := RowCount + 1;
Cells[0, LastItem] := ConvertSwisSBLToDashDot(SwisSBLKey);
end; {with ParcelGrid do}
ParcelGrid.Row := LastItem + 1;
end; {AddOneParcel}
{===============================================================}
Procedure TSmallClaimsCondoCopyDialog.ClearButtonClick(Sender: TObject);
begin
If (MessageDlg('Are you sure that you want to clear all of the parcel IDs?',
mtConfirmation, [mbYes, mbNo], 0) = idYes)
then ClearStringGrid(ParcelGrid);
SetNumParcelsLabel(FindLastItem(ParcelGrid));
end; {ClearButtonClick}
{===============================================================}
Procedure TSmallClaimsCondoCopyDialog.AddButtonClick(Sender: TObject);
var
SwisSBLKey : String;
I : Integer;
begin
If ExecuteParcelLocateDialog(SwisSBLKey, True, False, 'Locate Parcel(s)',
True, SwisSBLKeyList)
then
For I := 0 to (SwisSBLKeyList.Count - 1) do
If (Deblank(SwisSBLKeyList[I]) <> '')
then AddOneParcel(SwisSBLKeyList[I]);
SetNumParcelsLabel(FindLastItem(ParcelGrid));
end; {AddButtonClick}
{===============================================================}
Procedure TSmallClaimsCondoCopyDialog.DeleteButtonClick(Sender: TObject);
var
TempRow, I : Integer;
begin
TempRow := ParcelGrid.Row;
{FXX07211999-5: Delete leaves 'X' in grid.}
with ParcelGrid do
begin
For I := (TempRow + 1) to (RowCount - 1) do
Cells[0, (I - 1)] := Cells[0, I];
{Blank out the last row.}
Cells[0, (RowCount - 1)] := '';
end; {with ParcelGrid do}
SetNumParcelsLabel(FindLastItem(ParcelGrid));
end; {DeleteButtonClick}
{===============================================================}
Procedure TSmallClaimsCondoCopyDialog.CreateOneSmallClaims(SwisSBLKey : String);
var
SBLRec : SBLRecord;
SmallClaimsExists, PriorAssessmentFound : Boolean;
begin
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot', 'Suffix'],
[SmallClaimsYear, SwisCode, Section,
SubSection, Block, Lot, Sublot, Suffix]);
FindKeyOld(SwisCodeTable, ['SwisCode'], [Copy(SwisSBLKey, 1, 6)]);
FindKeyOld(CurrentAssessmentTable, ['TaxRollYr', 'SwisSBLKey'],
[SmallClaimsYear, SwisSBLKey]);
with SBLRec do
PriorAssessmentFound := FindKeyOld(PriorAssessmentTable,
['TaxRollYr', 'SwisSBLKey'],
[PriorYear, SwisSBLKey]);
SetRangeOld(CurrentExemptionsTable, ['TaxRollYr', 'SwisSBLKey'],
[SmallClaimsYear, SwisSBLKey], [SmallClaimsYear, SwisSBLKey]);
SetRangeOld(CurrentSpecialDistrictsTable, ['TaxRollYr', 'SwisSBLKey'],
[SmallClaimsYear, SwisSBLKey], [SmallClaimsYear, SwisSBLKey]);
SetRangeOld(SmallClaimsExemptionsAskedLookupTable,
['TaxRollYr', 'SwisSBLKey', 'IndexNumber', 'ExemptionCode'],
[SmallClaimsYear, OriginalSwisSBLKey, IntToStr(IndexNumber), ' '],
[SmallClaimsYear, OriginalSwisSBLKey, IntToStr(IndexNumber), '99999']);
FindKeyOld(SmallClaimsTable, ['TaxRollYr', 'SwisSBLKey', 'IndexNumber'],
[SmallClaimsYear, OriginalSwisSBLKey, IntToStr(IndexNumber)]);
{FXX01222004-1(2.07l1): Check to make sure that the small claims does not exist before copying it.}
SmallClaimsExists := FindKeyOld(SmallClaimsTable, ['TaxRollYr', 'SwisSBLKey', 'IndexNumber'],
[SmallClaimsYear, SwisSBLKey, IntToStr(IndexNumber)]);
If SmallClaimsExists
then MessageDlg('This small claims already exists on parcel ' + ConvertSwisSBLToDashDot(SwisSBLKey) + '.' + #13 +
'No new small claims was created on this parcel.' + #13 +
'Press OK to continue the copy.', mtWarning, [mbOK], 0)
else
with SmallClaimsLookupTable do
try
Append;
FieldByName('TaxRollYr').Text := SmallClaimsYear;
FieldByName('IndexNumber').AsInteger := IndexNumber;
FieldByName('SwisSBLKey').Text := SwisSBLKey;
FieldByName('LawyerCode').Text := LawyerCode;
FieldByName('CurrentName1').Text := ParcelTable.FieldByName('Name1').Text;
FieldByName('CurrentName2').Text := ParcelTable.FieldByName('Name2').Text;
FieldByName('CurrentAddress1').Text := ParcelTable.FieldByName('Address1').Text;
FieldByName('CurrentAddress2').Text := ParcelTable.FieldByName('Address2').Text;
FieldByName('CurrentStreet').Text := ParcelTable.FieldByName('Street').Text;
FieldByName('CurrentCity').Text := ParcelTable.FieldByName('City').Text;
FieldByName('CurrentState').Text := ParcelTable.FieldByName('State').Text;
FieldByName('CurrentZip').Text := ParcelTable.FieldByName('Zip').Text;
FieldByName('CurrentZipPlus4').Text := ParcelTable.FieldByName('ZipPlus4').Text;
If ((Deblank(LawyerCode) = '') or
GlblGrievanceSeperateRepresentativeInfo)
then
begin
{They are representing themselves.}
FieldByName('PetitName1').Text := ParcelTable.FieldByName('Name1').Text;
FieldByName('PetitName2').Text := ParcelTable.FieldByName('Name2').Text;
FieldByName('PetitAddress1').Text := ParcelTable.FieldByName('Address1').Text;
FieldByName('PetitAddress2').Text := ParcelTable.FieldByName('Address2').Text;
FieldByName('PetitStreet').Text := ParcelTable.FieldByName('Street').Text;
FieldByName('PetitCity').Text := ParcelTable.FieldByName('City').Text;
FieldByName('PetitState').Text := ParcelTable.FieldByName('State').Text;
FieldByName('PetitZip').Text := ParcelTable.FieldByName('Zip').Text;
FieldByName('PetitZipPlus4').Text := ParcelTable.FieldByName('ZipPlus4').Text;
end
else SetPetitionerNameAndAddress(SmallClaimsLookupTable, LawyerCodeTable, LawyerCode);
FieldByName('PropertyClassCode').Text := ParcelTable.FieldByName('PropertyClassCode').Text;
FieldByName('OwnershipCode').Text := ParcelTable.FieldByName('OwnershipCode').Text;
FieldByName('ResidentialPercent').AsFloat := ParcelTable.FieldByName('ResidentialPercent').AsFloat;
FieldByName('RollSection').Text := ParcelTable.FieldByName('RollSection').Text;
FieldByName('HomesteadCode').Text := ParcelTable.FieldByName('HomesteadCode').Text;
FieldByName('LegalAddr').Text := ParcelTable.FieldByName('LegalAddr').Text;
FieldByName('LegalAddrNo').Text := ParcelTable.FieldByName('LegalAddrNo').Text;
{FXX01162003-3: Need to include the legal address integer.}
try
FieldByName('LegalAddrInt').AsInteger := ParcelTable.FieldByName('LegalAddrInt').AsInteger;
except
end;
FieldByName('CurrentLandValue').AsInteger := CurrentAssessmentTable.FieldByName('LandAssessedVal').AsInteger;
FieldByName('CurrentTotalValue').AsInteger := CurrentAssessmentTable.FieldByName('TotalAssessedVal').AsInteger;
FieldByName('CurrentFullMarketVal').AsInteger := Round(ComputeFullValue(CurrentAssessmentTable.FieldByName('TotalAssessedVal').AsInteger,
SwisCodeTable,
ParcelTable.FieldByName('PropertyClassCode').Text,
ParcelTable.FieldByName('OwnershipCode').Text,
False));
If PriorAssessmentFound
then
begin
FieldByName('PriorLandValue').AsInteger := PriorAssessmentTable.FieldByName('LandAssessedVal').AsInteger;
FieldByName('PriorTotalValue').AsInteger := PriorAssessmentTable.FieldByName('TotalAssessedVal').AsInteger;
end;
FieldByName('PetitReason').Text := SmallClaimsTable.FieldByName('PetitReason').Text;
FieldByName('PetitSubreasonCode').Text := SmallClaimsTable.FieldByName('PetitSubreasonCode').Text;
TMemoField(FieldByName('PetitSubreason')).Assign(TMemoField(SmallClaimsTable.FieldByName('PetitSubreason')));
TMemoField(FieldByName('Notes')).Assign(TMemoField(SmallClaimsTable.FieldByName('Notes')));
FieldByName('NumberOfParcels').AsInteger := SmallClaimsTable.FieldByName('NumberOfParcels').AsInteger;
try
If (FieldByName('NoticeOfPetition').AsDateTime > StrToDate('1/1/1950'))
then FieldByName('NoticeOfPetition').AsDateTime := SmallClaimsTable.FieldByName('NoticeOfPetition').AsDateTime
else FieldByName('NoticeOfPetition').Text := '';
except
FieldByName('NoticeOfPetition').Text := '';
end;
try
If (FieldByName('NoteOfIssue').AsDateTime > StrToDate('1/1/1950'))
then FieldByName('NoteOfIssue').AsDateTime := SmallClaimsTable.FieldByName('NoteOfIssue').AsDateTime
else FieldByName('NoteOfIssue').Text := '';
except
FieldByName('NoteOfIssue').Text := '';
end;
FieldByName('ArticleType').Text := SmallClaimsTable.FieldByName('ArticleType').Text;
FieldByName('SchoolCode').Text := ParcelTable.FieldByName('SchoolCode').Text;
FieldByName('CurrentEqRate').AsFloat := SwisCodeTable.FieldByName('EqualizationRate').AsFloat;
FieldByName('CurrentUniformPercent').AsFloat := SwisCodeTable.FieldByName('UniformPercentValue').AsFloat;
FieldByName('CurrentRAR').AsFloat := SwisCodeTable.FieldByName('ResAssmntRatio').AsFloat;
{CHG07262004-1(2.08): Option to have attorney information seperate.}
If GlblGrievanceSeperateRepresentativeInfo
then
try
FieldByName('AttyName1').Text := SmallClaimsTable.FieldByName('AttyName1').Text;
FieldByName('AttyName2').Text := SmallClaimsTable.FieldByName('AttyName2').Text;
FieldByName('AttyAddress1').Text := SmallClaimsTable.FieldByName('AttyAddress1').Text;
FieldByName('AttyAddress2').Text := SmallClaimsTable.FieldByName('AttyAddress2').Text;
FieldByName('AttyStreet').Text := SmallClaimsTable.FieldByName('AttyStreet').Text;
FieldByName('AttyCity').Text := SmallClaimsTable.FieldByName('AttyCity').Text;
FieldByName('AttyState').Text := SmallClaimsTable.FieldByName('AttyState').Text;
FieldByName('AttyZip').Text := SmallClaimsTable.FieldByName('AttyZip').Text;
FieldByName('AttyZipPlus4').Text := SmallClaimsTable.FieldByName('AttyZipPlus4').Text;
FieldByName('AttyPhoneNumber').Text := SmallClaimsTable.FieldByName('AttyPhoneNumber').Text;
except
end;
Post;
CopyTableRange(SmallClaimsExemptionsAskedLookupTable, SmallClaimsExemptionsAskedTable,
'TaxRollYr', ['SwisSBLKey'], [SwisSBLKey]);
CopyTableRange(CurrentExemptionsTable, SmallClaimsExemptionsTable,
'TaxRollYr', ['IndexNumber'], [IntToStr(IndexNumber)]);
CopyTableRange(CurrentSpecialDistrictsTable, SmallClaimsSpecialDistrictsTable,
'TaxRollYr', ['IndexNumber'], [IntToStr(IndexNumber)]);
except
SystemSupport(005, SmallClaimsTable,
'Error adding SmallClaims for parcel ' +
ConvertSwisSBLToDashDot(SwisSBLKey) + '.',
UnitName, GlblErrorDlgBox);
end;
end; {CreateOneSmallClaims}
{===============================================================}
Procedure TSmallClaimsCondoCopyDialog.OKButtonClick(Sender: TObject);
var
Continue : Boolean;
I : Integer;
begin
Continue := True;
If (SwisSBLKeyList.Count = 0)
then
begin
MessageDlg('No parcels have been specified to create small claims for.',
mtError, [mbOK], 0);
Continue := False
end
else
begin
ProgressDialog.UserLabelCaption := 'Copying small claims #' + IntToStr(IndexNumber);
ProgressDialog.Start(SwisSBLKeyList.Count, True, True);
For I := 0 to (SwisSBLKeyList.Count - 1) do
begin
ProgressDialog.Update(Self, SwisSBLKeyList[I]);
Application.ProcessMessages;
CreateOneSmallClaims(SwisSBLKeyList[I]);
end; {For I := 0 to (SwisSBLKeyList.Count - 1) do}
ProgressDialog.Finish;
end; {else of If (SwisSBLKeyList.Count = 0)}
If Continue
then
begin
MessageDlg('The small claims has been copied to all of the specified parcels.',
mtInformation, [mbOK], 0);
ModalResult := mrOK;
end;
end; {OKButtonClick}
{======================================================}
Procedure TSmallClaimsCondoCopyDialog.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CloseTablesForForm(Self);
SwisSBLKeyList.Free;
Action := caFree;
end;
end.
|
UNIT ComplexN;
{ some complex number manipulations }
{$I Float.inc}
interface
uses MathLib0;
TYPE
Complex = RECORD
Re, Im : REAL;
END;
VAR
NearlyZero : FLOAT;
{ default based on presence/absence of math chip }
implementation
procedure Conjugate(C1 : Complex; var C2 : Complex);
begin
C2.Re := C1.Re;
C2.Im := -C1.Im;
end; { procedure Conjugate }
function Modulus(var C1 : Complex) : Float;
begin
Modulus := Sqrt(Sqr(C1.Re) + Sqr(C1.Im));
end; { function Modulus }
procedure Add(C1, C2 : Complex; var C3 : Complex);
begin
C3.Re := C1.Re + C2.Re;
C3.Im := C1.Im + C2.Im;
end; { procedure Add }
procedure Sub(C1, C2 : Complex; var C3 : Complex);
begin
C3.Re := C1.Re - C2.Re;
C3.Im := C1.Im - C2.Im;
end; { procedure Sub }
procedure Mult(C1, C2 : Complex; var C3 : Complex);
begin
C3.Re := C1.Re * C2.Re - C1.Im * C2.Im;
C3.Im := C1.Im * C2.Re + C1.Re * C2.Im;
end; { procedure Mult }
procedure Divide(C1, C2 : Complex; var C3 : Complex);
var
Dum1, Dum2 : Complex;
E : Float;
begin
Conjugate(C2, Dum1);
Mult(C1, Dum1, Dum2);
E := Sqr(Modulus(C2));
C3.Re := Dum2.Re / E;
C3.Im := Dum2.Im / E;
end; { procedure Divide }
procedure SquareRoot(C1 : Complex; var C2 : Complex);
var
R, Theta : Float;
begin
R := Sqrt(Sqr(C1.Re) + Sqr(C1.Im));
if ABS(C1.Re) < NearlyZero then
begin
if C1.Im < 0 then
Theta := Pi / 2
else
Theta := -Pi / 2;
end
else
if C1.Re < 0 then
Theta := ArcTan(C1.Im / C1.Re) + Pi
else
Theta := ArcTan(C1.Im / C1.Re);
C2.Re := Sqrt(R) * Cos(Theta / 2);
C2.Im := Sqrt(R) * Sin(Theta / 2);
end; { procedure SquareRoot }
BEGIN
{$IFOPT N+}
NearlyZero := 1E-015;
{$ELSE}
NearlyZero := 1E-07;
{$ENDIF}
END. |
unit uFileConfiguration;
interface
uses System.IniFiles,System.SysUtils,Vcl.Forms;
//clase responsavel por efetuar a leitura e escrita dos dados usados para conexao com a base de dados
type
TFileConfiguration = class
portaTCP : String;
usuarioBancoDados :String;
senhaBancoDados : String;
// Objeto responsavel por criar arquivo ini
arquivoConfiguracao : TIniFile;
// funcao responsavel por escrever as configuracoes de um arquivo .ini onde são guardadas as configuracaoes
procedure escrever();
// funcao responsavek por ler as configuracoes do arquivo ini
procedure leitura();
constructor TFileCreate;
destructor TFileDestroy;
end;
var
fileDataBase : TFileConfiguration;
implementation
{ TFileDataBase }
procedure TFileConfiguration.leitura;
begin
arquivoConfiguracao.ReadString('BANCO_DADOS','USUARIO',usuarioBancoDados);
arquivoConfiguracao.ReadString('BANCO_DADOS','SENHA',senhaBancoDados);
arquivoConfiguracao.ReadString('BANCO_DADOS','USUARIO',portaTCP);
end;
constructor TFileConfiguration.TFileCreate;
begin
// criacao do arquivo ini no diretorio em que se encontra o arquivo exe
arquivoConfiguracao.Create(ExtractFilePath(Application.ExeName)+'config.ini');
end;
destructor TFileConfiguration.TFileDestroy;
begin
end;
procedure TFileConfiguration.escrever();
begin
// escrevo no arquivo ini
arquivoConfiguracao.WriteString('BANCO_DADOS','USUARIO',usuarioBancoDados);
arquivoConfiguracao.WriteString('BANCO_DADOS','SENHA',senhaBancoDados);
arquivoConfiguracao.WriteString('BANCO_DADOS','PORTA',portaTCP);
end;
end.
|
unit MonForm;
{ Interprocess Communication Demo
This program along with the Client.dpr project, demonstrate a number
of topics in Win32 programming. Threads, Events, Mutexes, and Shared
memory are all used to provide communication between this monitor and
it's clients, see IPCThrd.pas.
To Run, compile this project and the Client.dpr project. Run one
instance of the monitor and then run several instances of the client.
You can switch between clients by clicking on the Client's window or
by selecting it from the Client menu in the monitor.
Topics Covered:
Interprocess Communication
Threads
Events
Mutexes
Shared Memory
Single instance EXE.
}
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Typinfo, IPCThrd, Buttons, ComCtrls, ExtCtrls, Menus;
const
WM_SETTRACEDATA = WM_USER + 1;
WM_UPDATESTATUS = WM_USER + 2;
WM_UPDATEMENU = WM_USER + 3;
type
TWMTraceData = record
Msg: Cardinal;
X: Smallint;
Y: Smallint;
Flag: TClientFlag;
Result: Longint;
end;
TLabelRec = record
XLabel: TLabel;
YLabel: TLabel;
end;
TMonitorForm = class(TForm)
DownX: TLabel;
DownY: TLabel;
SizeX: TLabel;
SizeY: TLabel;
MoveX: TLabel;
MoveY: TLabel;
Bevel1: TBevel;
Panel1: TPanel;
PauseButton: TSpeedButton;
StatusBar: TStatusBar;
MouseMove: TCheckBox;
MouseDown: TCheckBox;
WindowSize: TCheckBox;
MainMenu: TMainMenu;
Options1: TMenuItem;
AutoClientSwitch1: TMenuItem;
PlaceHolder21: TMenuItem;
File1: TMenuItem;
miFileExit: TMenuItem;
miClients: TMenuItem;
PlaceHolder1: TMenuItem;
Help1: TMenuItem;
About1: TMenuItem;
ShowTraceButton: TSpeedButton;
ClearButton: TSpeedButton;
ExitButton: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ClientMenuClick(Sender: TObject);
procedure miClientsClick(Sender: TObject);
procedure SetTraceFlags(Sender: TObject);
procedure AutoClientSwitch1Click(Sender: TObject);
procedure miFileExitClick(Sender: TObject);
procedure ShowTraceButtonClick(Sender: TObject);
procedure PauseButtonClick(Sender: TObject);
procedure ClearButtonClick(Sender: TObject);
procedure ExitButtonClick(Sender: TObject);
procedure About1Click(Sender: TObject);
private
FTraceMsg: TWMTraceData;
IPCMonitor: TIPCMonitor;
TraceLabels: array[TClientFlag] of TLabelRec;
FClientData: TEventData;
FStatusText: string;
procedure ClearLabels;
procedure OnConnect(Sender: TIPCThread; Connecting: Boolean);
procedure OnDirectoryUpdate(Sender: TIPCThread);
procedure OnSignal(Sender: TIPCThread; Data: TEventData);
procedure SignalClientStatus;
procedure UpdateTraceData(var Msg: TWMTraceData); message WM_SETTRACEDATA;
procedure UpdateStatusBar(var Msg: TMessage); message WM_UPDATESTATUS;
procedure UpdateClientMenu(var Msg: TMessage); message WM_UPDATEMENU;
end;
var
MonitorForm: TMonitorForm;
implementation
uses TrcView, About;
{$R *.DFM}
{ Private Routines }
procedure TMonitorForm.ClearLabels;
var
Index: TClientFlag;
begin
for Index := Low(TClientFlag) to High(TClientFlag) do
begin
TraceLabels[Index].YLabel.Caption := '0';
TraceLabels[Index].XLabel.Caption := '0';
end;
end;
procedure TMonitorForm.OnConnect(Sender: TIPCThread; Connecting: Boolean);
begin
if Connecting then
begin
FStatusText := IPCMonitor.ClientName;
SignalClientStatus;
end
else
FStatusText := 'No Client';
PostMessage(Handle, WM_UPDATESTATUS, 0, 0);
end;
{ When a client starts or stops we need to update the client menu.
We do this by posting a message to the Monitor Form, which in turn causes
the UpdateClientMenu method to be invoked. We use this approach, rather than
calling UpdateClientMenu directly because this code is not being executed
by the main thread, but rather by the thread used in the TMonitorThread
class. We could also have used the TThread.Synchonize method, but since
there is no need for the IPC thread to wait for the monitor to update
the menu, this approach is more effecient. }
procedure TMonitorForm.OnDirectoryUpdate(Sender: TIPCThread);
begin
PostMessage(Handle, WM_UPDATEMENU, 0, 0);
end;
{ This event is triggered when the client has new data for us. As with
the OnDirectoryUpdate event above, we use PostMessage to get the main
thread to update the display. }
procedure TMonitorForm.OnSignal(Sender: TIPCThread; Data: TEventData);
begin
FTraceMsg.X := Data.X;
FTraceMsg.Y := Data.Y;
FTraceMsg.Flag := Data.Flag;
PostMessage(Handle, WM_SETTRACEDATA, TMessage(FTraceMsg).WPARAM,
TMessage(FTraceMsg).LPARAM);
end;
procedure TMonitorForm.SignalClientStatus;
begin
if PauseButton.Down then
IPCMonitor.SignalClient([]) else
IPCMonitor.SignalClient(FClientData.Flags);
end;
procedure TMonitorForm.UpdateTraceData(var Msg: TWMTraceData);
begin
with Msg do
if Flag in FClientData.Flags then
begin
TraceLabels[Flag].XLabel.Caption := IntToStr(X);
TraceLabels[Flag].YLabel.Caption := IntToStr(Y);
end
end;
procedure TMonitorForm.UpdateStatusBar(var Msg: TMessage);
begin
StatusBar.SimpleText := FStatusText;
ClearLabels;
end;
procedure TMonitorForm.UpdateClientMenu(var Msg: TMessage);
var
I, ID: Integer;
List: TStringList;
mi: TMenuItem;
begin
List := TStringList.Create;
try
IPCMonitor.GetClientNames(List);
while miClients.Count > 0 do miClients.Delete(0);
if List.Count < 1 then
miClients.Add(NewItem('(None)', 0, False, False, nil, 0, ''))
else
for I := 0 to List.Count - 1 do
begin
ID := Integer(List.Objects[I]);
mi := NewItem(List[I], 0, False, True, ClientMenuClick, 0, '');
mi.Tag := ID;
mi.RadioItem := True;
mi.GroupIndex := 1;
miClients.Add(MI);
end;
finally
List.Free;
end;
end;
{ Event Handlers }
procedure TMonitorForm.FormCreate(Sender: TObject);
procedure SetupLabelArray;
begin
TraceLabels[cfMouseMove].XLabel := MoveX;
TraceLabels[cfMouseMove].YLabel := MoveY;
TraceLabels[cfMouseDown].XLabel := DownX;
TraceLabels[cfMouseDown].YLabel := DownY;
TraceLabels[cfResize].XLabel := SizeX;
TraceLabels[cfResize].YLabel := SizeY;
end;
begin
IPCMonitor := TIPCMonitor.Create(Application.Handle, 'Monitor');
IPCMonitor.OnSignal := OnSignal;
IPCMonitor.OnConnect := OnConnect;
IPCMonitor.OnDirectoryUpdate := OnDirectoryUpdate;
IPCMonitor.Activate;
OnDirectoryUpdate(nil);
OnConnect(nil, False);
FClientData.Flags := [cfMouseMove, cfMouseDown, cfReSize];
SetupLabelArray;
end;
procedure TMonitorForm.FormDestroy(Sender: TObject);
begin
IPCMonitor.Free;
end;
procedure TMonitorForm.ClientMenuClick(Sender: TObject);
var
NewID: Integer;
begin
NewID := (Sender as TMenuItem).Tag;
if NewID <> IPCMonitor.ClientID then
IPCMonitor.ClientID := NewID;
end;
procedure TMonitorForm.miClientsClick(Sender: TObject);
var
I: Integer;
begin
if IPCMonitor.ClientID <> 0 then
for I := 0 to miClients.Count - 1 do
with miClients.Items[I] do
if Tag = IPCMonitor.ClientID then
begin
Checked := True;
System.Break;
end;
end;
procedure TMonitorForm.SetTraceFlags(Sender: TObject);
var
F: TClientFlag;
begin
with (Sender as TCheckBox) do
begin
F := TClientFlag(Tag);
if Checked then
Include(FClientData.Flags, F) else
Exclude(FClientData.Flags, F);
end;
SignalClientStatus;
end;
procedure TMonitorForm.AutoClientSwitch1Click(Sender: TObject);
begin
with (Sender as TMenuItem) do
begin
Checked := not Checked;
IPCMonitor.AutoSwitch := Checked;
end;
end;
procedure TMonitorForm.miFileExitClick(Sender: TObject);
begin
Close;
end;
procedure TMonitorForm.ShowTraceButtonClick(Sender: TObject);
begin
IPCMonitor.GetDebugInfo(TraceForm.TraceData.Items);
TraceForm.ShowModal;
end;
procedure TMonitorForm.PauseButtonClick(Sender: TObject);
begin
SignalClientStatus;
end;
procedure TMonitorForm.ClearButtonClick(Sender: TObject);
begin
IPCMonitor.ClearDebugInfo;
end;
procedure TMonitorForm.ExitButtonClick(Sender: TObject);
begin
Close;
end;
procedure TMonitorForm.About1Click(Sender: TObject);
begin
ShowAboutBox;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLPerlinPFX<p>
PFX particle effects revolving around the use of Perlin noise.<p>
<b>History : </b><font size=-1><ul>
<li>04/11/10 - DaStr - Restored Delphi5 and Delphi6 compatibility
<li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter
<li>22/01/10 - Yar - Added bmp32.Blank:=false for memory allocation
<li>30/03/07 - DaStr - Added $I GLScene.inc
<li>16/03/07 - DaStr - Added explicit pointer dereferencing
(thanks Burkhard Carstens) (Bugtracker ID = 1678644)
<li>15/04/04 - Mrqzzz - Fixed range check error suggested by Graham Kennedy
<li>15/04/04 - EG - Creation
</ul></font>
}
unit GLPerlinPFX;
interface
{$I GLScene.inc}
uses
System.Classes, System.Math,
//GLS
GLParticleFX, GLGraphics, GLCrossPlatform,
GLPerlinNoise3D, OpenGLTokens, GLVectorGeometry;
type
// TGLPerlinPFXManager
//
{: A sprite-based particles FX manager using perlin-based sprites.<p>
This PFX manager is more suited for smoke or fire effects, and with proper
tweaking of the texture and perlin parameters, may help render a convincing
effect with less particles.<p>
The sprite generate by this manager is the composition of a distance-based
intensity and a perlin noise. }
TGLPerlinPFXManager = class (TGLBaseSpritePFXManager)
private
{ Private Declarations }
FTexMapSize : Integer;
FNoiseSeed : Integer;
FNoiseScale : Integer;
FNoiseAmplitude : Integer;
FSmoothness : Single;
FBrightness, FGamma : Single;
protected
{ Protected Declarations }
procedure PrepareImage(bmp32 : TGLBitmap32; var texFormat : Integer); override;
procedure SetTexMapSize(const val : Integer);
procedure SetNoiseSeed(const val : Integer);
procedure SetNoiseScale(const val : Integer);
procedure SetNoiseAmplitude(const val : Integer);
procedure SetSmoothness(const val : Single);
procedure SetBrightness(const val : Single);
procedure SetGamma(const val : Single);
public
{ Public Declarations }
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
published
{ Published Declarations }
{: Underlying texture map size, as a power of two.<p>
Min value is 3 (size=8), max value is 9 (size=512). }
property TexMapSize : Integer read FTexMapSize write SetTexMapSize default 6;
{: Smoothness of the distance-based intensity.<p>
This value is the exponent applied to the intensity in the texture,
basically with a value of 1 (default) the intensity decreases linearly,
with higher values, it will remain 'constant' in the center then
fade-off more abruptly, and with values below 1, there will be a
sharp spike in the center. }
property Smoothness : Single read FSmoothness write SetSmoothness;
{: Brightness factor applied to the perlin texture intensity.<p>
Brightness acts as a scaling, non-saturating factor. Examples:<ul>
<li>Brightness = 1 : intensities in the [0; 1] range
<li>Brightness = 2 : intensities in the [0.5; 1] range
<li>Brightness = 0.5 : intensities in the [0; 0.5] range
</ul>Brightness is applied to the final texture (and thus affects
the distance based intensity). }
property Brightness : Single read FBrightness write SetBrightness;
property Gamma : Single read FGamma write SetGamma;
{: Random seed to use for the perlin noise. }
property NoiseSeed : Integer read FNoiseSeed write SetNoiseSeed default 0;
{: Scale applied to the perlin noise (stretching). }
property NoiseScale : Integer read FNoiseScale write SetNoiseScale default 100;
{: Amplitude applied to the perlin noise (intensity).<p>
This value represent the percentage of the sprite luminance affected by
the perlin texture. }
property NoiseAmplitude : Integer read FNoiseAmplitude write SetNoiseAmplitude default 50;
property ColorMode default scmInner;
property SpritesPerTexture default sptFour;
property ParticleSize;
property ColorInner;
property ColorOuter;
property LifeColors;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLPerlinPFXManager ------------------
// ------------------
// Create
//
constructor TGLPerlinPFXManager.Create(aOwner : TComponent);
begin
inherited;
FTexMapSize:=6;
FNoiseScale:=100;
FNoiseAmplitude:=50;
FSmoothness:=1;
FBrightness:=1;
FGamma:=1;
SpritesPerTexture:=sptFour;
ColorMode:=scmInner;
end;
// Destroy
//
destructor TGLPerlinPFXManager.Destroy;
begin
inherited Destroy;
end;
// SetTexMapSize
//
procedure TGLPerlinPFXManager.SetTexMapSize(const val : Integer);
begin
if val<>FTexMapSize then begin
FTexMapSize:=val;
if FTexMapSize<3 then FTexMapSize:=3;
if FTexMapSize>9 then FTexMapSize:=9;
NotifyChange(Self);
end;
end;
// SetNoiseSeed
//
procedure TGLPerlinPFXManager.SetNoiseSeed(const val : Integer);
begin
if val<>FNoiseSeed then begin
FNoiseSeed:=val;
NotifyChange(Self);
end;
end;
// SetNoiseScale
//
procedure TGLPerlinPFXManager.SetNoiseScale(const val : Integer);
begin
if val<>FNoiseScale then begin
FNoiseScale:=val;
NotifyChange(Self);
end;
end;
// SetNoiseAmplitude
//
procedure TGLPerlinPFXManager.SetNoiseAmplitude(const val : Integer);
begin
if val<>FNoiseAmplitude then begin
FNoiseAmplitude:=val;
if FNoiseAmplitude<0 then FNoiseAmplitude:=0;
if FNoiseAmplitude>100 then FNoiseAmplitude:=100;
NotifyChange(Self);
end;
end;
// SetSmoothness
//
procedure TGLPerlinPFXManager.SetSmoothness(const val : Single);
begin
if FSmoothness<>val then begin
FSmoothness:=ClampValue(val, 1e-3, 1e3);
NotifyChange(Self);
end;
end;
// SetBrightness
//
procedure TGLPerlinPFXManager.SetBrightness(const val : Single);
begin
if FBrightness<>val then begin
FBrightness:=ClampValue(val, 1e-3, 1e3);
NotifyChange(Self);
end;
end;
// SetGamma
//
procedure TGLPerlinPFXManager.SetGamma(const val : Single);
begin
if FGamma<>val then begin
FGamma:=ClampValue(val, 0.1, 10);
NotifyChange(Self);
end;
end;
// BindTexture
//
procedure TGLPerlinPFXManager.PrepareImage(bmp32 : TGLBitmap32; var texFormat : Integer);
procedure PrepareSubImage(dx, dy, s : Integer; noise : TGLPerlin3DNoise);
var
s2 : Integer;
x, y, d : Integer;
is2, f, fy, pf, nBase, nAmp, df, dfg : Single;
invGamma : Single;
scanLine : PGLPixel32Array;
gotIntensityCorrection : Boolean;
begin
s2:=s shr 1;
is2:=1/s2;
pf:=FNoiseScale*0.05*is2;
nAmp:=FNoiseAmplitude*(0.01);
nBase:=1-nAmp*0.5;
if Gamma<0.1 then
invGamma:=10
else invGamma:=1/Gamma;
gotIntensityCorrection:=(Gamma<>1) or (Brightness<>1);
for y:=0 to s-1 do begin
fy:=Sqr((y+0.5-s2)*is2);
scanLine:=bmp32.ScanLine[y+dy];
for x:=0 to s-1 do begin
f:=Sqr((x+0.5-s2)*is2)+fy;
if f<1 then begin
df:=nBase+nAmp*noise.Noise(x*pf, y*pf);
if gotIntensityCorrection then
df:=ClampValue(Power(df, InvGamma)*Brightness, 0, 1);
dfg:=Power((1-Sqrt(f)), FSmoothness);
d:=Trunc(df*255);
if d > 255 then d:=255;
with scanLine^[x+dx] do begin
r:=d;
g:=d;
b:=d;
a:=Trunc(dfg*255);
end;
end else PInteger(@scanLine[x+dx])^:=0;
end;
end;
end;
var
s, s2 : Integer;
noise : TGLPerlin3DNoise;
begin
s:=(1 shl TexMapSize);
bmp32.Width:=s;
bmp32.Height:=s;
bmp32.Blank := false;
texFormat:=GL_LUMINANCE_ALPHA;
noise:=TGLPerlin3DNoise.Create(NoiseSeed);
try
case SpritesPerTexture of
sptOne : PrepareSubImage(0, 0, s, noise);
sptFour : begin
s2:=s div 2;
PrepareSubImage(0, 0, s2, noise);
noise.Initialize(NoiseSeed+1);
PrepareSubImage(s2, 0, s2, noise);
noise.Initialize(NoiseSeed+2);
PrepareSubImage(0, s2, s2, noise);
noise.Initialize(NoiseSeed+3);
PrepareSubImage(s2, s2, s2, noise);
end;
else
Assert(False);
end;
finally
noise.Free;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterClasses([TGLPerlinPFXManager]);
end.
|
PROCEDURE Reverse;
var ch: char;
BEGIN (* Reverse *)
Read(ch);
if ch <> '' then begin
Reverse;
Write(ch);
end;
END; (* Reverse *) |
{$A-,B-,D+,E-,F-,G-,I-,L+,N-,O-,P-,Q-,R-,S-,T-,V-,X+,Y+,Use32+}
{様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様}
{ Streams }
{ Portable source code (tested on DOS and OS/2) }
{ Copyright (c) 1996 by Andrew Zabolotny, FRIENDS software }
{様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様}
Unit Streams;
Interface uses miscUtil;
const
steOK = 0;
steNoSuchFile = 1;
steCreateError = 2;
steInvalidFormat = 3;
steInvalidOpenMode = 4;
steReadError = 5;
steWriteError = 6;
steNoMemory = 7;
steSeekError = 8;
steNotApplicable = 9;
type
pStream = ^tStream;
tStream = object(tObject)
Error : Word16;
function Name : string; virtual;
function Put(var Data; bytes : word) : word; virtual;
function Get(var Data; bytes : word) : word; virtual;
procedure Skip(bytes : longint); virtual;
procedure Seek(newPos : longint); virtual;
function GetPos : longint; virtual;
function Size : longint; virtual;
function EOS : boolean; virtual;
procedure PutStr(var S : string);
function GetStr : string;
procedure PutZTstr(S : pChar);
function GetZTstr : pChar;
function CopyFrom(var S : tStream; bytes : longint) : longint;
end;
pFilter = ^tFilter;
tFilter = object(tStream)
ChainStream : pStream;
constructor Create(Chain : pStream);
function Name : string; virtual;
function Put(var Data; bytes : word) : word; virtual;
function Get(var Data; bytes : word) : word; virtual;
procedure Skip(bytes : longint); virtual;
function EOS : boolean; virtual;
end;
const
stmReadOnly = $0000; { ---- ---- ---- -000 }
stmWriteOnly = $0001; { ---- ---- ---- -001 }
stmReadWrite = $0002; { ---- ---- ---- -010 }
stmAccessMask = $0007; { ---- ---- ---- -111 }
stsDenyReadWrite = $0010; { ---- ---- -001 ---- }
stsDenyWrite = $0020; { ---- ---- -010 ---- }
stsDenyRead = $0030; { ---- ---- -011 ---- }
stsDenyNone = $0040; { ---- ---- -100 ---- }
stfNoInherit = $0080; { ---- ---- 1--- ---- }
stfNo_Locality = $0000; { ---- -000 ---- ---- }
stfSequential = $0100; { ---- -001 ---- ---- }
stfRandom = $0200; { ---- -010 ---- ---- }
stfRandomSequential = $0300; { ---- -011 ---- ---- }
stfNoCache = $1000; { ---1 ---- ---- ---- }
stfFailOnError = $2000; { --1- ---- ---- ---- }
stfWriteThrough = $4000; { -1-- ---- ---- ---- }
stfDASD = $8000; { 1--- ---- ---- ---- }
type
pFileStream = ^tFileStream;
tFileStream = object(tStream)
F : File;
constructor Create(const fName : string; openMode : Word);
function Name : string; virtual;
function Put(var Data; bytes : word) : word; virtual;
function Get(var Data; bytes : word) : word; virtual;
procedure Skip(bytes : longint); virtual;
procedure Seek(newPos : longint); virtual;
function GetPos : longint; virtual;
function Size : longint; virtual;
function EOS : boolean; virtual;
function GetTime : longint; virtual;
procedure SetTime(Time : longint); virtual;
function GetAttr : longint;
procedure SetAttr(Attr : longint);
procedure Truncate;
procedure Free; virtual;
destructor Erase;
end;
Implementation uses Dos, Strings;
function tStream.Name;
begin
Name := '';
end;
function tStream.Get;
begin
Get := 0;
if Error = steOK
then Error := steNotApplicable;
end;
function tStream.Put;
begin
Put := 0;
if Error = steOK
then Error := steNotApplicable;
end;
procedure tStream.Skip;
var
buff : Pointer;
bsz,I : Word;
begin
if Error = steOK
then begin
Seek(GetPos + bytes);
if Error <> steOK
then begin
Error := steOK;
bsz := minL(minL(maxAvail, $FFF0), bytes);
GetMem(buff, bsz);
if buff <> nil
then begin
While (Error = steOK) and (bytes > 0) do
begin
I := minL(bytes, bsz);
Dec(bytes, Get(buff^, I));
end;
FreeMem(buff, bsz);
end
else Error := steNoMemory;
end;
end;
end;
procedure tStream.Seek;
begin
if Error = steOK
then Error := steNotApplicable;
end;
function tStream.GetPos;
begin
GetPos := -1;
if Error = steOK
then Error := steNotApplicable;
end;
function tStream.Size;
begin
Size := -1;
if Error = steOK
then Error := steNotApplicable;
end;
function tStream.EOS;
begin
EOS := TRUE;
if Error = steOK
then Error := steNotApplicable;
end;
procedure tStream.PutStr;
begin
Put(S, succ(length(S)));
end;
function tStream.GetStr;
var
S : string;
begin
S := '';
Get(S[0], 1);
Get(S[1], length(S));
GetStr := S;
end;
procedure tStream.PutZTstr;
var
I : SmallWord;
begin
I := strLen(S);
Put(I, sizeOf(I));
Put(S^, I);
end;
function tStream.GetZTstr;
var
I : SmallWord;
S : pChar;
begin
Get(I, sizeOf(I));
if Error = steOK
then begin
GetMem(S, succ(I));
Get(S^, I);
pByteArray(S)^[I] := 0;
end
else S := nil;
GetZTstr := S;
end;
function tStream.CopyFrom;
var
Buff : Pointer;
bSz : Word;
i,rc : longint;
begin
CopyFrom := 0;
bSz := minL($FFF0, maxAvail);
GetMem(Buff, bSz);
if Buff = nil then begin Error := steNoMemory; exit; end;
rc := 0;
While (not S.EOS) and (bytes <> 0) and (Error = steOK) do
begin
if bytes = -1
then i := bSz
else i := minL(bytes, bSz);
i := S.Get(Buff^, i);
Put(Buff^, i);
if bytes <> -1
then Dec(bytes, i);
Inc(rc, i);
end;
FreeMem(Buff, bSz);
CopyFrom := rc;
end;
constructor tFilter.Create;
begin
inherited Create;
ChainStream := Chain;
end;
function tFilter.Name;
begin
if ChainStream <> nil
then Name := ChainStream^.Name
else Name := inherited Name;
end;
function tFilter.Get;
begin
if Error = steOK
then if ChainStream <> nil
then begin
Get := ChainStream^.Get(Data, bytes);
Error := ChainStream^.Error;
end
else Get := inherited Get(Data, bytes)
else Get := 0;
end;
function tFilter.Put;
begin
if Error = steOK
then if ChainStream <> nil
then begin
Put := ChainStream^.Put(Data, bytes);
Error := ChainStream^.Error;
end
else Put := inherited Put(Data, bytes)
else Put := 0;
end;
procedure tFilter.Skip;
begin
if Error = steOK
then if (ChainStream <> nil)
then begin
ChainStream^.Skip(bytes);
Error := ChainStream^.Error;
end
else inherited Skip(bytes);
end;
function tFilter.EOS;
begin
if ChainStream <> nil
then begin
EOS := ChainStream^.EOS;
Error := ChainStream^.Error;
end
else EOS := inherited EOS;
end;
constructor tFileStream.Create;
label
fCreate;
var
oldMode : Integer;
begin
inherited Create;
Assign(F, fName);
oldMode := FileMode;
FileMode := openMode;
case openMode and stmAccessMask of
stmReadOnly,
stmReadWrite : begin
Reset(F, 1);
if ioResult <> 0
then if openMode and stmAccessMask = stmReadWrite
then goto fCreate
else Error := steNoSuchFile;
end;
stmWriteOnly : begin
fCreate: Rewrite(F, 1);
if ioResult <> 0
then Error := steCreateError;
end;
else Error := steInvalidOpenMode;
end;
FileMode := oldMode;
end;
function tFileStream.Name;
begin
Name := strPas(FileRec(F).Name);
end;
function tFileStream.Put;
var
L : Word;
begin
Put := 0;
if Error = steOK
then begin
blockWrite(F, Data, bytes, L);
if ioResult <> 0 then Error := steWriteError;
Put := L;
end;
end;
function tFileStream.Get;
var
L : Word;
begin
Get := 0;
if Error = steOK
then begin
blockRead(F, Data, bytes, L);
if ioResult <> 0 then Error := steReadError;
Get := L;
end;
end;
procedure tFileStream.Skip;
begin
if Error = steOK
then begin
inOutRes := 0;
System.Seek(F, filePos(F) + bytes);
if ioResult <> 0 {not a random-access file}
then inherited Skip(bytes);
end;
end;
function tFileStream.GetPos;
begin
if Error = steOK
then begin
inOutRes := 0;
GetPos := FilePos(F);
if ioResult <> 0 then Error := steSeekError;
end
else GetPos := -1;
end;
procedure tFileStream.Seek;
begin
if Error = steOK
then begin
System.Seek(F, newPos);
if ioResult <> 0 then Error := steSeekError;
end;
end;
function tFileStream.Size;
begin
if Error = steOK
then begin
inOutRes := 0;
Size := System.FileSize(F);
if ioResult <> 0 then Error := steNotApplicable;
end
else Size := -1;
end;
function tFileStream.EOS;
begin
if Error = steOK
then begin
inOutRes := 0;
EOS := System.EOF(F);
if ioResult <> 0 then Error := steNotApplicable;
end
else EOS := TRUE;
end;
function tFileStream.GetTime;
var
L : longint;
begin
if Error = steOK
then begin
GetFTime(F, L);
GetTime := L;
if ioResult <> 0 then Error := steNotApplicable;
end
else GetTime := 0;
end;
procedure tFileStream.SetTime;
begin
if (Error = steOK) and (Time <> 0)
then begin
SetFTime(F, Time);
if ioResult <> 0 then Error := steNotApplicable;
end;
end;
function tFileStream.GetAttr;
var
W : word;
begin
if Error = steOK
then begin
GetFAttr(F, W);
GetAttr := W;
if ioResult <> 0 then Error := steNotApplicable;
end
else GetAttr := 0;
end;
procedure tFileStream.SetAttr;
begin
if (Error = steOK) and (Attr <> 0)
then begin
SetFAttr(F, Attr);
if ioResult <> 0 then Error := steNotApplicable;
end;
end;
procedure tFileStream.Truncate;
begin
if Error = steOK
then begin
System.Truncate(F);
if ioResult <> 0 then Error := steNotApplicable;
end;
end;
procedure tFileStream.Free;
begin
inOutRes := 0;
Close(F);
inOutRes := 0;
end;
destructor tFileStream.Erase;
begin
Free;
System.Erase(F);
inOutRes := 0;
end;
end.
|
unit try_finally_1;
interface
implementation
var
G: Int32;
procedure Test;
begin
try
G := 1;
Exit;
finally
G := G + 1;
end;
end;
initialization
Test();
finalization
Assert(G = 2);
end. |
{$H+}
unit Execfile;
interface
uses
WinTypes, WinProcs, Messages,
Classes;
type
TWindowStyle = ( wsNorm, wsMinimize, wsMaximize, wsHide,
wsMinNoActivate, wsShowNoActivate );
TWaitStyle = ( wRegular, wSuspend );
TPriorityClass = ( pcNormal, pcIdle, pcHigh, pcRealTime );
InString = String[255];
TExecFile = class(TComponent)
private
FStopWaiting: Boolean;
FMsg: TMsg;
FAss: Boolean;
FInstanceID: Integer;
FPriorityClass: TPriorityClass;
FPriorityValue: Integer;
FError: Integer;
FExitCode: Integer;
FIsWaiting: Boolean;
FWait: Boolean;
FWaitStyle: TWaitStyle; {Wait method}
FOnFail: TNotifyEvent;
FCommandLine: InString; {Command Line of Executable File}
FRCommandLine: InString;
FFParams: InString; {Parameters to send to Executable File}
FAssFName: String; {Name of associated executable}
FAssFDir: String; {Path of associated executable}
FWindowStyle: TWindowStyle; {Window style for Executable File}
StartUpInfo: TStartUpInfo;
ProcessInfo: TProcessInformation;
protected
procedure SetWindowStyle( Value: TWindowStyle );
procedure SetWaitStyle ( Value: TWaitStyle );
procedure SetPriorityClass ( Value: TPriorityClass );
public
function Execute: Boolean;
function Terminate: Boolean;
function IsWaiting: Boolean;
function StopWaiting: Boolean;
function ErrorCode: LongInt;
published
property Associate: Boolean read FAss write FAss;
property CommandLine: InString read FCommandLine write FCommandLine;
property Parameters: InString read FFParams write FFParams;
property Priority: TPriorityClass read FPriorityClass write SetPriorityClass default pcNormal;
property Wait: Boolean read FWait write FWait;
property WaitStyle: TWaitStyle read FWaitStyle write SetWaitStyle default wRegular;
property WindowStyle: TWindowStyle read FWindowStyle write SetWindowStyle default wsNorm;
property OnFail: TNotifyEvent read FOnFail write FOnFail;
end;
procedure Register;
implementation
uses ShellAPI;
procedure TExecFile.SetWindowStyle(Value : TWindowStyle);
begin FWindowStyle := Value;
end;
procedure TExecFile.SetWaitStyle(Value : TWaitStyle);
begin FWaitStyle := Value;
end;
procedure TExecFile.SetPriorityClass(Value : TPriorityClass);
begin FPriorityClass := Value;
end;
procedure Register;
begin RegisterComponents('Samples', [TExecFile]);
end;
function TExecFile.Execute: Boolean;
var zCommandLine: array[0..512] of Char;
zFAssFName: array[0..255] of Char;
zFAssFDir: array[0..255] of Char;
zFAssFDoc: array[0..255] of Char;
FSuccess: Boolean;
begin
FillChar(StartupInfo,Sizeof(StartupInfo),#0);
StartupInfo.cb := Sizeof(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
If FWindowStyle = wsNorm then StartupInfo.wShowWindow := SW_SHOWNORMAL;
If FWindowStyle = wsMinimize then StartupInfo.wShowWindow := SW_SHOWMINIMIZED;
If FWindowStyle = wsMaximize then StartupInfo.wShowWindow := SW_SHOWMAXIMIZED;
If FWindowStyle = wsHide then StartupInfo.wShowWindow := SW_HIDE;
If FWindowStyle = wsMinNoActivate then StartupInfo.wShowWindow := SW_SHOWMINNOACTIVE;
If FWindowStyle = wsShowNoActivate then StartupInfo.wShowWindow := SW_SHOWNA;
If FPriorityClass = pcHigh then FPriorityValue := HIGH_PRIORITY_CLASS;
If FPriorityClass = pcIdle then FPriorityValue := IDLE_PRIORITY_CLASS;
If FPriorityClass = pcNormal then FPriorityValue := NORMAL_PRIORITY_CLASS;
If FPriorityClass = pcRealTime then FPriorityValue := REALTIME_PRIORITY_CLASS;
StrPCopy(zCommandLine,FCommandLine+' '+FFParams);
FSuccess := CreateProcess(
nil,
zCommandLine, { pointer to command line string }
nil, { pointer to process security attributes }
nil, { pointer to thread security attributes }
false, { handle inheritance flag }
{CREATE_NEW_CONSOLE or} { creation flags }
FPriorityValue,
nil, { pointer to new environment block }
nil, { pointer to current directory name }
StartupInfo, { pointer to STARTUPINFO }
ProcessInfo);
If not FSuccess then begin
If FAss then begin StrPCopy(zFAssFDoc,FCommandLine);
If findExecutable(zFAssFDoc,zFAssFDir,zFAssFName)<32 then begin
FError := GetLastError(); If Assigned(FOnFail) then FOnFail(Self);
Result := False; exit;
end else begin FAssFName := zFAssFName;
StrPCopy(zCommandLine,FAssFName+' '+FCommandLine+' '+FFParams);
FSuccess := CreateProcess(nil,
zCommandLine, { pointer to command line string }
nil, { pointer to process security attributes }
nil, { pointer to thread security attributes }
false, { handle inheritance flag }
{CREATE_NEW_CONSOLE or} { creation flags }
FPriorityValue,
nil, { pointer to new environment block }
nil, { pointer to current directory name }
StartupInfo, { pointer to STARTUPINFO }
ProcessInfo);
end
end;
end;
If FSuccess then begin
If FWait then begin FIsWaiting := True; FStopWaiting := False;
If FWaitStyle = wRegular then begin
repeat
While PeekMessage(FMsg,0,0,0,PM_REMOVE) do begin
If FMsg.Message = WM_QUIT then halt(FMsg.wParam);
TranslateMessage(FMsg); DispatchMessage(FMsg); end;
If WaitforSingleObject(ProcessInfo.hProcess,0)<>WAIT_TIMEOUT then begin
FStopWaiting := True; {Application.ProcessMessages;}Sleep(20); end;
Until FStopWaiting; end
else begin
WaitForSingleObject(ProcessInfo.hProcess,INFINITE); end;
FIsWaiting := False; Result:= True; end;
end else begin
FError := GetLastError(); If Assigned(FOnFail) then FOnFail(Self);
Result := False; end;
end;
function TExecFile.Terminate: Boolean;
begin
GetExitCodeProcess(ProcessInfo.hProcess,FExitCode);
If TerminateProcess(ProcessInfo.hProcess,FExitCode) then Result := True;
end;
function TExecFile.IsWaiting: Boolean;
begin
Result := FIsWaiting;
end;
function TExecFile.StopWaiting: Boolean;
begin
FStopWaiting := True;
Result := True;
end;
function TExecFile.ErrorCode: LongInt;
begin
Result := FError;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Local Client DataSet - IB }
{ }
{ Copyright (c) 1997,01 Inprise Corporation }
{ }
{*******************************************************}
unit DBLocalI;
{$R-,T-,H+,X+}
interface
{$IFDEF MSWINDOWS}
uses Windows, SysUtils, Variants, Classes, Db, DBCommon, Midas,
IBQuery, IBDatabase, IB, DBClient, DBLocal, Provider;
{$ENDIF}
{$IFDEF LINUX}
uses Libc, SysUtils, Variants, Classes, DB, DBCommon, Midas,
IBCustomDataset, IBDatabase, IB, DBClient, DBLocal, Provider;
{$ENDIF}
type
{ TIBCDSDataset }
TIBCDSQuery = class(TIBQuery)
private
FKeyFields: string;
protected
function PSGetDefaultOrder: TIndexDef; override;
end;
{ TIBClientDataSet }
TIBClientDataSet = class(TCustomCachedDataSet)
private
FCommandText : String;
FDataSet: TIBCDSQuery;
FLocalParams: TParams;
FStreamedActive: Boolean;
procedure CheckMasterSourceActive(MasterSource: TDataSource);
procedure SetDetailsActive(Value: Boolean);
function GetConnection: TIBDatabase;
function GetMasterFields: String;
function GetMasterSource: TDataSource;
function GetTransaction: TIBTransaction;
procedure SetConnection(Value: TIBDatabase);
procedure SetDataSource(const Value: TDataSource);
procedure SetInternalCommandText(Value: string);
procedure SetLocalParams;
procedure SetMasterFields(const Value: String);
procedure SetParamsFromSQL(const Value: string);
procedure SetTransaction(const Value: TIBTransaction);
protected
function GetCommandText: String; override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetActive(Value: Boolean); override;
procedure SetCommandText(Value: string); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CloneCursor(Source: TCustomClientDataSet; Reset: Boolean;
KeepSettings: Boolean = False); override;
function GetQuoteChar: String;
published
property Active;
property CommandText: string read GetCommandText write SetCommandText;
property DBConnection: TIBDatabase read GetConnection write SetConnection;
property DBTransaction : TIBTransaction read GetTransaction write SetTransaction;
property MasterFields : String read GetMasterFields write SetMasterFields;
property MasterSource: TDataSource read GetMasterSource write SetDataSource;
end;
implementation
uses MidConst, IBUtils;
type
{ TIBCDSParams }
TIBCDSParams = class(TParams)
private
FFieldName: TStrings;
protected
procedure ParseSelect(SQL: string);
public
constructor Create(Owner: TPersistent);
Destructor Destroy; override;
end;
constructor TIBCDSParams.Create(Owner: TPersistent);
begin
inherited;
FFieldName := TStringList.Create;
end;
destructor TIBCDSParams.Destroy;
begin
FreeAndNil(FFieldName);
inherited;
end;
procedure TIBCDSParams.ParseSelect(SQL: string);
const
SSelect = 'select'; {Do not localize}
var
FWhereFound: Boolean;
Start: PChar;
FName, Value: string;
SQLToken, CurSection, LastToken: TSQLToken;
Params: Integer;
begin
if Pos(' ' + SSelect + ' ', LowerCase(string(PChar(SQL)+8))) > 1 then Exit; // can't parse sub queries
Start := PChar(ParseSQL(PChar(SQL), True));
CurSection := stUnknown;
LastToken := stUnknown;
FWhereFound := False;
Params := 0;
repeat
repeat
SQLToken := NextSQLToken(Start, FName, CurSection);
if SQLToken in [stWhere] then
begin
FWhereFound := True;
LastToken := stWhere;
end else if SQLToken in [stTableName] then
begin
{ Check for owner qualified table name }
if Start^ = '.' then {Do not localize}
NextSQLToken(Start, FName, CurSection);
end else
if (SQLToken = stValue) and (LastToken = stWhere) then
SQLToken := stFieldName;
if SQLToken in SQLSections then CurSection := SQLToken;
until SQLToken in [stFieldName, stEnd];
if FWhereFound and (SQLToken in [stFieldName]) then
repeat
SQLToken := NextSQLToken(Start, Value, CurSection);
if SQLToken in SQLSections then CurSection := SQLToken;
until SQLToken in [stEnd,stValue,stIsNull,stIsNotNull,stFieldName];
if Value='?' then {Do not localize}
begin
FFieldName.Add(FName);
Inc(Params);
end;
until (Params = Count) or (SQLToken in [stEnd]);
end;
{ TIBCDSQuery }
function TIBCDSQuery.PSGetDefaultOrder: TIndexDef;
begin
if FKeyFields = '' then
Result := inherited PSGetDefaultOrder
else
begin // detail table default order
Result := TIndexDef.Create(nil);
Result.Options := [ixUnique]; // keyfield is unique
Result.Name := StringReplace(FKeyFields, ';', '_', [rfReplaceAll]); {Do not localize}
Result.Fields := FKeyFields;
end;
end;
{ TIBClientDataSet }
constructor TIBClientDataSet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataSet := TIBCDSQuery.Create(nil);
FDataSet.Name := Self.Name + 'DataSet1'; {Do not localize}
Provider.DataSet := FDataSet;
SqlDBType := typeIBX;
FLocalParams := TParams.Create;
end;
destructor TIBClientDataSet.Destroy;
begin
inherited Destroy;
FDataSet.Close;
FreeAndNil(FDataSet);
FreeAndNil(FLocalParams);
end;
function TIBClientDataSet.GetCommandText: String;
begin
Result := FCommandText;
end;
procedure TIBClientDataSet.SetCommandText(Value: String);
begin
if Value <> CommandText then
begin
CheckInactive;
FCommandText := Value;
if not (csLoading in ComponentState) then
begin
FDataSet.FKeyFields := '';
IndexFieldNames := '';
MasterFields := '';
IndexName := '';
IndexDefs.Clear;
Params.Clear;
if (csDesigning in ComponentState) and (Value <> '') then
SetParamsFromSQL(Value);
end;
end;
end;
function TIBClientDataSet.GetConnection: TIBDatabase;
begin
Result := FDataSet.Database;
end;
procedure TIBClientDataSet.SetConnection(Value: TIBDatabase);
begin
if FDataSet.Database <> Value then
begin
CheckInactive;
FDataSet.Database := Value;
end;
end;
function TIBClientDataSet.GetQuoteChar: String;
begin
Result := '';
if Assigned(FDataSet.Database) then
if FDataSet.Database.SQLDialect = 3 then
Result := '"' {Do not localize}
end;
procedure TIBClientDataSet.SetTransaction(const Value: TIBTransaction);
begin
FDataSet.Transaction := Value;
end;
function TIBClientDataSet.GetTransaction: TIBTransaction;
begin
Result := FDataSet.Transaction;
end;
procedure TIBClientDataSet.CloneCursor(Source: TCustomClientDataSet; Reset,
KeepSettings: Boolean);
begin
if not (Source is TIBClientDataSet) then
DatabaseError(SInvalidClone);
Provider.DataSet := TIBClientDataSet(Source).Provider.DataSet;
DBConnection := TIBClientDataSet(Source).DBConnection;
DBTransaction := TIBClientDataSet(Source).DBTransaction;
CommandText := TIBClientDataSet(Source).CommandText;
inherited CloneCursor(Source, Reset, KeepSettings);
end;
procedure TIBClientDataSet.SetDetailsActive(Value: Boolean);
var
DetailList: TList;
I: Integer;
begin
DetailList := TList.Create;
try
GetDetailDataSets(DetailList);
for I := 0 to DetailList.Count -1 do
if TDataSet(DetailList[I]) is TIBClientDataSet then
TIBClientDataSet(TDataSet(DetailList[I])).Active := Value;
finally
DetailList.Free;
end;
end;
procedure TIBClientDataSet.CheckMasterSourceActive(
MasterSource: TDataSource);
begin
if Assigned(MasterSource) and Assigned(MasterSource.DataSet) then
if not MasterSource.DataSet.Active then
DatabaseError(SMasterNotOpen);
end;
function TIBClientDataSet.GetMasterSource: TDataSource;
begin
Result := inherited GetDataSource;
end;
procedure TIBClientDataSet.SetDataSource(const Value: TDataSource);
begin
inherited MasterSource := Value;
if Assigned(Value) then
begin
if PacketRecords = -1 then
PacketRecords := 0;
end
else
if PacketRecords = 0 then
PacketRecords := -1;
end;
function TIBClientDataSet.GetMasterFields: String;
begin
Result := inherited MasterFields;
end;
procedure TIBClientDataSet.SetMasterFields(const Value: String);
begin
inherited MasterFields := Value;
if Value <> '' then
IndexFieldNames := Value;
FDataSet.FKeyFields := '';
end;
procedure TIBClientDataSet.SetActive(Value: Boolean);
var
FCurrentCommand: string;
begin
if Value then
begin
if csLoading in ComponentState then
begin
FStreamedActive := True;
exit;
end;
if MasterFields <> '' then
begin
if not (csLoading in ComponentState) then
CheckMasterSourceActive(MasterSource);
SetLocalParams;
FCurrentCommand := AddIBParamSQLForDetail(FLocalParams, CommandText, false, FDataset.Database.SQLDialect);
SetInternalCommandText(FCurrentCommand);
Params := FLocalParams;
FetchParams;
end else
begin
SetInternalCommandText(FCommandText);
if Params.Count > 0 then
begin
FDataSet.Params := Params;
FetchParams;
end;
end;
end;
if Value and (FDataSet.ObjectView <> ObjectView) then
FDataSet.ObjectView := ObjectView;
inherited SetActive(Value);
SetDetailsActive(Value);
end;
procedure TIBClientDataSet.SetInternalCommandText(Value: string);
begin
if Assigned(Provider.DataSet) then
begin
if Assigned(TIBCDSQuery(Provider.DataSet).Database) and (Value <> TIBCDSQuery(Provider.DataSet).SQL.Text) then
begin
TIBCDSQuery(Provider.DataSet).SQL.Text := Value;
inherited SetCommandText(TIBCDSQuery(Provider.DataSet).SQL.Text);
end;
end
else
DataBaseError(SNoDataProvider);
end;
procedure TIBClientDataSet.SetParamsFromSQL(const Value: string);
var
DataSet: TIBCDSQuery;
TableName, TempQuery, Q: string;
List: TIBCDSParams;
I: Integer;
Field: TField;
begin
TableName := GetTableNameFromSQL(Value);
if TableName <> '' then
begin
TempQuery := Value;
List := TIBCDSParams.Create(Self);
try
List.ParseSelect(TempQuery);
List.AssignValues(Params);
for I := 0 to List.Count - 1 do
List[I].ParamType := ptInput;
DataSet := TIBCDSQuery.Create(FDataSet.Database);
try
if Assigned(FDataSet) then
Q := FDataSet.PSGetQuoteChar
else
Q := '';
DataSet.SQL.Add('select * from ' + Q + TableName + Q + ' where 0 = 1'); { do not localize }
try
DataSet.Open;
for I := 0 to List.Count - 1 do
begin
if List.FFieldName.Count > I then
begin
try
Field := DataSet.FieldByName(List.FFieldName[I]);
except
Field := nil;
end;
end else
Field := nil;
if Assigned(Field) then
begin
if Field.DataType <> ftString then
List[I].DataType := Field.DataType
else if TStringField(Field).FixedChar then
List[I].DataType := ftFixedChar
else
List[I].DataType := ftString;
end;
end;
except
// ignore all exceptions
end;
finally
DataSet.Free;
end;
finally
if List.Count > 0 then
Params.Assign(List);
List.Free;
end;
end;
end;
procedure TIBClientDataSet.Loaded;
begin
inherited Loaded;
if FStreamedActive then
begin
try
SetActive(True);
FStreamedActive := False;
except
if csDesigning in ComponentState then
InternalHandleException
else
Raise;
end;
end;
end;
procedure TIBClientDataSet.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if Operation = opRemove then
if AComponent = FDataset.Database then
begin
FDataSet.DataBase := nil;
SetActive(False);
end
else
if AComponent = FDataSet.Transaction then
begin
FDataSet.Transaction := nil;
SetActive(False);
end;
end;
procedure TIBClientDataSet.SetLocalParams;
procedure CreateParamsFromMasterFields(Create: Boolean);
var
I: Integer;
List: TStrings;
begin
List := TStringList.Create;
try
if Create then
FLocalParams.Clear;
FDataSet.FKeyFields := MasterFields;
List.CommaText := MasterFields;
for I := 0 to List.Count -1 do
begin
if Create then
FLocalParams.CreateParam( ftUnknown, MasterSource.DataSet.FieldByName(List[I]).FieldName,
ptInput);
FLocalParams[I].AssignField(MasterSource.DataSet.FieldByName(List[I]));
end;
finally
List.Free;
end;
end;
begin
if (MasterFields <> '') and Assigned(MasterSource) and Assigned(MasterSource.DataSet) then
CreateParamsFromMasterFields(True);
end;
end.
|
unit QuestionSelectFrame;
interface
uses
TestClasses,
Generics.Collections,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TfrmQuestionSelect = class(TFrame)
PanelQuestionSelect: TPanel;
lbQuestionSelect: TLabel;
cbNumberSelect: TComboBox;
procedure cbNumberSelectSelect(Sender: TObject);
private
function GetIndex: Integer;
function NullCheck: boolean;
function LastNumber: Integer;
function IndexInitialize: Integer;
{ Private declarations }
public
OnQuestionSelect: TNotifyEvent;
procedure NumberListing(List: TObjectList<TQuiz>);
property IsNull: boolean read NullCheck;
property TestIndex: Integer read GetIndex;
property Numbering: Integer read LastNumber;
property SetIndex: Integer read IndexInitialize;
end;
implementation
{$R *.dfm}
{ TfrmQuestionSelect }
function TfrmQuestionSelect.LastNumber: Integer;
begin
if cbNumberSelect.Items.Count < 1 then Result := 0
else Result := StrToInt(cbNumberSelect.Items[cbNumberSelect.Items.Count - 1]);
end;
function TfrmQuestionSelect.NullCheck: boolean;
begin
Result := cbNumberSelect.Text = '';
end;
procedure TfrmQuestionSelect.NumberListing(List: TObjectList<TQuiz>);
var
I: Integer;
begin
cbNumberSelect.Clear;
for I := 0 to List.Count - 1 do
cbNumberSelect.Items.AddObject(IntToStr(List.Items[I].QuizNumber), List.Items[I]);
cbNumberSelect.ItemIndex := 0;
cbNumberSelectSelect(List);
end;
procedure TfrmQuestionSelect.cbNumberSelectSelect(Sender: TObject);
begin
if Assigned(OnQuestionSelect) then
if cbNumberSelect.ItemIndex >= 0 then
OnQuestionSelect(cbNumberSelect.Items.Objects[cbNumberSelect.ItemIndex]);
end;
function TfrmQuestionSelect.GetIndex: Integer;
begin
Result := cbNumberSelect.ItemIndex;
end;
function TfrmQuestionSelect.IndexInitialize: Integer;
begin
cbNumberSelect.ItemIndex := -1;
end;
end.
|
unit progressdialog;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls,
ComCtrls;
type
{ ProgressBarDialog }
{ TProgressBarDialog }
TProgressBarDialog = class(TForm)
Label1: TLabel;
barLabel: TLabel;
ProgressBar1: TProgressBar;
private
{ private declarations }
public
{ public declarations }
addUnit: string;
constructor create(title,description:string;maxprogress:longint=100); reintroduce;
procedure setProgress(progress:longint);
procedure progressEvent(sender:TObject;progress,maxprogress:longint);
end;
implementation
{$R *.lfm}
constructor TProgressBarDialog.create(title,description: string; maxprogress: longint=100);
begin
inherited Create(Application);
Caption:=title;
Label1.Caption:=description;
ProgressBar1.Max:=maxprogress;
setProgress(0);
//BorderIcons:=[];
//FormStyle:=fsStayOnTop;
Show;
Application.ProcessMessages;
end;
procedure TProgressBarDialog.setProgress(progress: longint);
var
s: String;
begin
ProgressBar1.Position:=progress;
s:=IntToStr(progress)+addUnit+'/'+inttostr(ProgressBar1.max)+addUnit;
if ProgressBar1.max<>0 then s:=s+' ('+IntToStr(100*progress div ProgressBar1.max)+'%)';
barLabel.Caption:=s;
Application.ProcessMessages;
end;
procedure TProgressBarDialog.progressEvent(sender: TObject; progress,
maxprogress: longint);
begin
if ProgressBar1.Max<>maxprogress then
ProgressBar1.Max:=maxprogress;
setProgress(progress);
end;
end.
|
unit LanguagesU;
interface
uses
System.Generics.Collections;
type
TLanguage = class
Code: string;
Name: string;
private
constructor Create(aName, aCode: string);
end;
TLanguages = class
private
class var FList: TObjectList<TLanguage>;
public
class constructor Create;
class destructor Destroy;
class property List: TObjectList<TLanguage> read FList;
class function FromCode(aCode: String): TLanguage;
class function FromName(aName: String): TLanguage;
end;
implementation
{ TLanguages }
class constructor TLanguages.Create;
begin
FList := TObjectList<TLanguage>.Create;
FList.Add(TLanguage.Create('Afrikaans', 'af'));
FList.Add(TLanguage.Create('Albanian', 'sq'));
FList.Add(TLanguage.Create('Amharic', 'am'));
FList.Add(TLanguage.Create('Arabic', 'ar'));
FList.Add(TLanguage.Create('Armenian', 'hy'));
FList.Add(TLanguage.Create('Azeerbaijani', 'az'));
FList.Add(TLanguage.Create('Basque', 'eu'));
FList.Add(TLanguage.Create('Belarusian', 'be'));
FList.Add(TLanguage.Create('Bengali', 'bn'));
FList.Add(TLanguage.Create('Bosnian', 'bs'));
FList.Add(TLanguage.Create('Bulgarian', 'bg'));
FList.Add(TLanguage.Create('Catalan', 'ca'));
FList.Add(TLanguage.Create('Cebuano', 'ceb (ISO-639-2)'));
FList.Add(TLanguage.Create('Chinese (Simplified)', 'zh-CN'));
FList.Add(TLanguage.Create('Chinese (Traditional)', 'zh-TW'));
FList.Add(TLanguage.Create('Corsican', 'co'));
FList.Add(TLanguage.Create('Croatian', 'hr'));
FList.Add(TLanguage.Create('Czech', 'cs'));
FList.Add(TLanguage.Create('Danish', 'da'));
FList.Add(TLanguage.Create('Dutch', 'nl'));
FList.Add(TLanguage.Create('English', 'en'));
FList.Add(TLanguage.Create('Esperanto', 'eo'));
FList.Add(TLanguage.Create('Estonian', 'et'));
FList.Add(TLanguage.Create('Finnish', 'fi'));
FList.Add(TLanguage.Create('French', 'fr'));
FList.Add(TLanguage.Create('Frisian', 'fy'));
FList.Add(TLanguage.Create('Galician', 'gl'));
FList.Add(TLanguage.Create('Georgian', 'ka'));
FList.Add(TLanguage.Create('German', 'de'));
FList.Add(TLanguage.Create('Greek', 'el'));
FList.Add(TLanguage.Create('Gujarati', 'gu'));
FList.Add(TLanguage.Create('Haitian Creole', 'ht'));
FList.Add(TLanguage.Create('Hausa', 'ha'));
FList.Add(TLanguage.Create('Hawaiian', 'haw'));
FList.Add(TLanguage.Create('Hebrew', 'iw'));
FList.Add(TLanguage.Create('Hindi', 'hi'));
FList.Add(TLanguage.Create('Hmong', 'hmn'));
FList.Add(TLanguage.Create('Hungarian', 'hu'));
FList.Add(TLanguage.Create('Icelandic', 'is'));
FList.Add(TLanguage.Create('Igbo', 'ig'));
FList.Add(TLanguage.Create('Indonesian', 'id'));
FList.Add(TLanguage.Create('Irish', 'ga'));
FList.Add(TLanguage.Create('Italian', 'it'));
FList.Add(TLanguage.Create('Japanese', 'ja'));
FList.Add(TLanguage.Create('Javanese', 'jw'));
FList.Add(TLanguage.Create('Kannada', 'kn'));
FList.Add(TLanguage.Create('Kazakh', 'kk'));
FList.Add(TLanguage.Create('Khmer', 'km'));
FList.Add(TLanguage.Create('Korean', 'ko'));
FList.Add(TLanguage.Create('Kurdish', 'ku'));
FList.Add(TLanguage.Create('Kyrgyz', 'ky'));
FList.Add(TLanguage.Create('Lao', 'lo'));
FList.Add(TLanguage.Create('Latin', 'la'));
FList.Add(TLanguage.Create('Latvian', 'lv'));
FList.Add(TLanguage.Create('Lithuanian', 'lt'));
FList.Add(TLanguage.Create('Luxembourgish', 'lb'));
FList.Add(TLanguage.Create('Macedonian', 'mk'));
FList.Add(TLanguage.Create('Malagasy', 'mg'));
FList.Add(TLanguage.Create('Malay', 'ms'));
FList.Add(TLanguage.Create('Malayalam', 'ml'));
FList.Add(TLanguage.Create('Maltese', 'mt'));
FList.Add(TLanguage.Create('Maori', 'mi'));
FList.Add(TLanguage.Create('Marathi', 'mr'));
FList.Add(TLanguage.Create('Mongolian', 'mn'));
FList.Add(TLanguage.Create('Myanmar (Burmese)', 'my'));
FList.Add(TLanguage.Create('Nepali', 'ne'));
FList.Add(TLanguage.Create('Norwegian', 'no'));
FList.Add(TLanguage.Create('Nyanja (Chichewa)', 'ny'));
FList.Add(TLanguage.Create('Pashto', 'ps'));
FList.Add(TLanguage.Create('Persian', 'fa'));
FList.Add(TLanguage.Create('Polish', 'pl'));
FList.Add(TLanguage.Create('Portuguese (Portugal, Brazil)', 'pt'));
FList.Add(TLanguage.Create('Punjabi', 'pa'));
FList.Add(TLanguage.Create('Romanian', 'ro'));
FList.Add(TLanguage.Create('Russian', 'ru'));
FList.Add(TLanguage.Create('Samoan', 'sm'));
FList.Add(TLanguage.Create('Scots Gaelic', 'gd'));
FList.Add(TLanguage.Create('Serbian', 'sr'));
FList.Add(TLanguage.Create('Sesotho', 'st'));
FList.Add(TLanguage.Create('Shona', 'sn'));
FList.Add(TLanguage.Create('Sindhi', 'sd'));
FList.Add(TLanguage.Create('Sinhala (Sinhalese)', 'si'));
FList.Add(TLanguage.Create('Slovak', 'sk'));
FList.Add(TLanguage.Create('Slovenian', 'sl'));
FList.Add(TLanguage.Create('Somali', 'so'));
FList.Add(TLanguage.Create('Spanish', 'es'));
FList.Add(TLanguage.Create('Sundanese', 'su'));
FList.Add(TLanguage.Create('Swahili', 'sw'));
FList.Add(TLanguage.Create('Swedish', 'sv'));
FList.Add(TLanguage.Create('Tagalog (Filipino)', 'tl'));
FList.Add(TLanguage.Create('Tajik', 'tg'));
FList.Add(TLanguage.Create('Tamil', 'ta'));
FList.Add(TLanguage.Create('Telugu', 'te'));
FList.Add(TLanguage.Create('Thai', 'th'));
FList.Add(TLanguage.Create('Turkish', 'tr'));
FList.Add(TLanguage.Create('Ukrainian', 'uk'));
FList.Add(TLanguage.Create('Urdu', 'ur'));
FList.Add(TLanguage.Create('Uzbek', 'uz'));
FList.Add(TLanguage.Create('Vietnamese', 'vi'));
FList.Add(TLanguage.Create('Welsh', 'cy'));
FList.Add(TLanguage.Create('Xhosa', 'xh'));
FList.Add(TLanguage.Create('Yiddish', 'yi'));
FList.Add(TLanguage.Create('Yoruba', 'yo'));
FList.Add(TLanguage.Create('Zulu', 'zu'));
end;
class destructor TLanguages.Destroy;
begin
FList.Free;
end;
class function TLanguages.FromCode(aCode: String): TLanguage;
var
Language: TLanguage;
begin
for Language in FList do
if Language.Code = aCode then
exit(Language);
exit(nil);
end;
class function TLanguages.FromName(aName: String): TLanguage;
var
Language: TLanguage;
begin
for Language in FList do
if Language.Name = aName then
exit(Language);
exit(nil);
end;
{ TLanguage }
constructor TLanguage.Create(aName, aCode: string);
begin
Code := aCode;
Name := aName;
end;
end.
|
unit ufk_colors;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, LCLIntf, lclType;
function Darker(MyColor:TColor; Percent:Byte):TColor;
function Lighter(MyColor:TColor; Percent:Byte):TColor;
function IsLightColor(const AColor: TColor): Boolean;
function DisabledColor(AColor: TColor; APercent: Integer): TColor;
function HotColor(AColor: TColor; const APercent: Integer): TColor;
implementation
function Darker(MyColor:TColor; Percent:Byte):TColor;
var r,g,b:Byte;
begin
MyColor:=ColorToRGB(MyColor);
r:=GetRValue(MyColor);
g:=GetGValue(MyColor);
b:=GetBValue(MyColor);
r:=r-muldiv(r,Percent,100); //Percent% closer to black
g:=g-muldiv(g,Percent,100);
b:=b-muldiv(b,Percent,100);
result:=RGB(r,g,b);
end;
function Lighter(MyColor:TColor; Percent:Byte):TColor;
var r,g,b:Byte;
begin
MyColor:=ColorToRGB(MyColor);
r:=GetRValue(MyColor);
g:=GetGValue(MyColor);
b:=GetBValue(MyColor);
r:=r+muldiv(255-r,Percent,100); //Percent% closer to white
g:=g+muldiv(255-g,Percent,100);
b:=b+muldiv(255-b,Percent,100);
result:=RGB(r,g,b);
end;
function IsLightColor(const AColor: TColor): Boolean;
var
r, g, b, yiq: integer;
begin
r := GetRValue(AColor);
g := GetGValue(AColor);
b := GetBValue(AColor);
yiq := ((r*299)+(g*587)+(b*114)) div 1000;
if (yiq >= 128) then
result := True
else
result := False;
end;
function DisabledColor(AColor: TColor; APercent: Integer): TColor;
begin
if IsLightColor(AColor) then
Result := Darker(AColor, APercent)
else
Result := Lighter(AColor, APercent);
end;
function HotColor(AColor: TColor; const APercent: Integer): TColor;
begin
if IsLightColor(AColor) then
Result := Lighter(AColor, APercent)
else
Result := Darker(AColor, APercent);
end;
end.
|
unit AConfiguracaoFilial;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, Buttons, StdCtrls, Mask,
DBCtrls, Tabela, Localizacao, Db, DBTables, ComCtrls, BotaoCadastro, DBClient;
type
TFConfiguracaoFilial = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
BotaoAlterar1: TBotaoAlterar;
BotaoGravar1: TBotaoGravar;
BotaoCancelar1: TBotaoCancelar;
Fechar: TBitBtn;
PageControl: TPageControl;
PCotacao: TTabSheet;
DataFiliais: TDataSource;
localiza: TConsultaPadrao;
CadFiliais: TSQL;
PProduto: TTabSheet;
CCondicaoPagamentoCotacao: TDBCheckBox;
CadFiliaisC_FIN_COT: TWideStringField;
CodigoTabela: TDBEditLocaliza;
ETabelaServico: TDBEditLocaliza;
CadFiliaisI_COD_TAB: TFMTBCDField;
CadFiliaisI_TAB_SER: TFMTBCDField;
Label1: TLabel;
Label2: TLabel;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
Label3: TLabel;
Label4: TLabel;
CadFiliaisI_COD_EMP: TFMTBCDField;
CExcluiFinaceiroCotacao: TDBCheckBox;
CadFiliaisC_EXC_FIC: TWideStringField;
CRegerarFinanceiroQuandoAltera: TDBCheckBox;
CadFiliaisC_FIN_ACO: TWideStringField;
PFinanceiro: TTabSheet;
EContaPadrao: TDBEditLocaliza;
Label29: TLabel;
SpeedButton4: TSpeedButton;
Label38: TLabel;
CadFiliaisC_CON_BAN: TWideStringField;
CadFiliaisC_CON_BOL: TWideStringField;
Label17: TLabel;
SpeedButton11: TSpeedButton;
Label18: TLabel;
EContaBoletoPadrao: TDBEditLocaliza;
TabSheet1: TTabSheet;
CEmiteECF: TDBCheckBox;
CadFiliaisC_IND_ECF: TWideStringField;
CCorFiscal: TDBCheckBox;
CadFiliaisC_EST_FIS: TWideStringField;
PFiscal: TTabSheet;
CadFiliaisN_PER_ISQ: TFMTBCDField;
DBEditColor1: TDBEditColor;
Label5: TLabel;
PContratos: TTabSheet;
DBEditLocaliza1: TDBEditLocaliza;
Label6: TLabel;
Label7: TLabel;
SpeedButton3: TSpeedButton;
CadFiliaisC_CON_CON: TWideStringField;
CadFiliaisN_VAL_CHA: TFMTBCDField;
CadFiliaisN_VAL_DKM: TFMTBCDField;
PAssistenciaTecnica: TTabSheet;
EValChamado: TDBEditNumerico;
EValKM: TDBEditNumerico;
Label8: TLabel;
Label9: TLabel;
CadFiliaisC_IND_CLA: TWideStringField;
CUtilizarClassificacao: TDBCheckBox;
CadFiliaisC_IND_NSU: TWideStringField;
DBCheckBox2: TDBCheckBox;
CadFiliaisC_SIM_FED: TWideStringField;
PCRM: TTabSheet;
Label10: TLabel;
DBEditColor2: TDBEditColor;
DBMemoColor1: TDBMemoColor;
CadFiliaisC_EMA_COM: TWideStringField;
CadFiliaisL_ROD_EMA: TWideStringField;
Label11: TLabel;
Label52: TLabel;
Label53: TLabel;
DBEditColor8: TDBEditColor;
DBEditColor9: TDBEditColor;
CadFiliaisC_CRM_CES: TWideStringField;
CadFiliaisC_CRM_CCL: TWideStringField;
DBCheckBox3: TDBCheckBox;
CadFiliaisC_COB_FRM: TWideStringField;
DBCheckBox4: TDBCheckBox;
CadFiliaisC_COT_BEC: TWideStringField;
CadFiliaisC_COT_COM: TWideStringField;
DBCheckBox5: TDBCheckBox;
DBEditColor3: TDBEditColor;
Label12: TLabel;
CadFiliaisC_SEN_EMC: TWideStringField;
TabSheet2: TTabSheet;
CadFiliaisL_OBS_COM: TWideStringField;
DBMemoColor2: TDBMemoColor;
Label13: TLabel;
CadFiliaisC_CAB_EMA: TWideStringField;
CadFiliaisC_MEI_EMA: TWideStringField;
DBMemoColor3: TDBMemoColor;
Label14: TLabel;
DBMemoColor4: TDBMemoColor;
Label15: TLabel;
CadFiliaisN_PER_CSS: TFMTBCDField;
DBEditColor5: TDBEditColor;
CadFiliaisC_DIR_ECF: TWideStringField;
Label19: TLabel;
PNFE: TTabSheet;
GroupBox4: TGroupBox;
Label20: TLabel;
DBComboBoxColor1: TDBComboBoxColor;
DBCheckBox6: TDBCheckBox;
DBCheckBox7: TDBCheckBox;
CadFiliaisC_UFD_NFE: TWideStringField;
CadFiliaisC_AMH_NFE: TWideStringField;
CadFiliaisC_MOM_NFE: TWideStringField;
RDANFE: TDBRadioGroup;
DBEditColor6: TDBEditColor;
Label21: TLabel;
CadFiliaisC_DAN_NFE: TWideStringField;
CadFiliaisC_CER_NFE: TWideStringField;
CadFiliaisC_IND_NFE: TWideStringField;
DBCheckBox8: TDBCheckBox;
ENotaPAdrao: TDBEditLocaliza;
Label23: TLabel;
SpeedButton5: TSpeedButton;
Label24: TLabel;
DBMemoColor5: TDBMemoColor;
Label25: TLabel;
CadFiliaisC_DAD_ADI: TWideStringField;
CadFiliaisC_TEX_RED: TWideStringField;
DBMemoColor6: TDBMemoColor;
Label26: TLabel;
DBEditColor10: TDBEditColor;
Label27: TLabel;
DBEditColor11: TDBEditColor;
Label28: TLabel;
CadFiliaisC_SER_NOT: TWideStringField;
CadFiliaisC_SER_SER: TWideStringField;
PanelColor2: TPanelColor;
DBCheckBox1: TDBCheckBox;
Label16: TLabel;
DBEditColor4: TDBEditColor;
CadFiliaisI_DOC_NOT: TFMTBCDField;
DBCheckBox10: TDBCheckBox;
CadFiliaisC_NOT_CON: TWideStringField;
PSpedFiscal: TTabSheet;
PanelColor3: TPanelColor;
Label22: TLabel;
EPerfilSped: TDBComboBoxColor;
Label30: TLabel;
EIndicadorAtividadeSped: TComboBoxColor;
CadFiliaisC_PER_SPE: TWideStringField;
CadFiliaisI_ATI_SPE: TFMTBCDField;
CadFiliaisI_CON_SPE: TFMTBCDField;
CadFiliaisC_CPC_SPE: TWideStringField;
CadFiliaisC_CRC_SPE: TWideStringField;
Label31: TLabel;
EContabilidade: TDBEditLocaliza;
SpeedButton7: TSpeedButton;
Label32: TLabel;
CadFiliaisC_NCO_SPE: TWideStringField;
DBEditColor7: TDBEditColor;
Label33: TLabel;
DBEditCPF1: TDBEditCPF;
Label34: TLabel;
DBEditColor12: TDBEditColor;
Label35: TLabel;
DBCheckBox9: TDBCheckBox;
CadFiliaisC_IND_SPE: TWideStringField;
CadFiliaisN_PER_COF: TFMTBCDField;
CadFiliaisN_PER_PIS: TFMTBCDField;
CadFiliaisC_CST_IPI: TWideStringField;
Label36: TLabel;
DBEditColor13: TDBEditColor;
Label37: TLabel;
DBEditColor14: TDBEditColor;
DBEditColor15: TDBEditColor;
Label39: TLabel;
CadFiliaisD_ULT_ALT: TSQLTimeStampField;
PanelColor4: TPanelColor;
PanelColor5: TPanelColor;
PanelColor6: TPanelColor;
PanelColor7: TPanelColor;
PanelColor8: TPanelColor;
PanelColor9: TPanelColor;
PanelColor10: TPanelColor;
PanelColor11: TPanelColor;
PanelColor12: TPanelColor;
PanelColor13: TPanelColor;
CadFiliaisC_EMA_NFE: TWideStringField;
Label40: TLabel;
DBEditColor16: TDBEditColor;
CadFiliaisC_COD_REC: TWideStringField;
CadFiliaisI_DIA_VIC: TFMTBCDField;
Label41: TLabel;
DBEditColor17: TDBEditColor;
Label42: TLabel;
DBEditColor18: TDBEditColor;
CadFiliaisC_COT_CSP: TWideStringField;
DBCheckBox16: TDBCheckBox;
CadFiliaisC_DES_IPI: TWideStringField;
DBCheckBox11: TDBCheckBox;
Label43: TLabel;
DBEditColor19: TDBEditColor;
CadFiliaisC_COP_ENF: TWideStringField;
DBCheckBox12: TDBCheckBox;
CadFiliaisI_EMP_FIL: TFMTBCDField;
CadFiliaisI_COD_FIL: TFMTBCDField;
CadFiliaisC_NOM_FIL: TWideStringField;
CadFiliaisC_END_FIL: TWideStringField;
CadFiliaisI_NUM_FIL: TFMTBCDField;
CadFiliaisC_BAI_FIL: TWideStringField;
CadFiliaisC_CID_FIL: TWideStringField;
CadFiliaisC_EST_FIL: TWideStringField;
CadFiliaisI_CEP_FIL: TFMTBCDField;
CadFiliaisC_CGC_FIL: TWideStringField;
CadFiliaisC_INS_FIL: TWideStringField;
CadFiliaisC_GER_FIL: TWideStringField;
CadFiliaisC_DIR_FIL: TWideStringField;
CadFiliaisC_FON_FIL: TWideStringField;
CadFiliaisC_FAX_FIL: TWideStringField;
CadFiliaisC_OBS_FIL: TWideStringField;
CadFiliaisD_DAT_MOV: TSQLTimeStampField;
CadFiliaisC_WWW_FIL: TWideStringField;
CadFiliaisC_END_ELE: TWideStringField;
CadFiliaisD_DAT_INI_ATI: TSQLTimeStampField;
CadFiliaisD_DAT_FIM_ATI: TSQLTimeStampField;
CadFiliaisC_NOM_FAN: TWideStringField;
CadFiliaisC_PIC_CLA: TWideStringField;
CadFiliaisC_PIC_PRO: TWideStringField;
CadFiliaisCOD_CIDADE: TFMTBCDField;
CadFiliaisC_CEP_FIL: TWideStringField;
CadFiliaisC_NOT_PAD: TFMTBCDField;
CadFiliaisD_ULT_FEC: TSQLTimeStampField;
CadFiliaisI_SEQ_ROM: TFMTBCDField;
CadFiliaisC_JUN_COM: TWideStringField;
CadFiliaisC_CPF_RES: TWideStringField;
CadFiliaisI_NRO_NSU: TFMTBCDField;
CadFiliaisD_DAT_SNG: TSQLTimeStampField;
CadFiliaisI_COD_FIS: TFMTBCDField;
CadFiliaisC_COD_CNA: TWideStringField;
CadFiliaisC_INS_MUN: TWideStringField;
CadFiliaisI_ULT_PED: TFMTBCDField;
CadFiliaisI_ULT_SEN: TFMTBCDField;
CadFiliaisC_MEN_BOL: TWideStringField;
Label44: TLabel;
DBEditColor20: TDBEditColor;
CadFiliaisI_ULT_REC: TFMTBCDField;
CadFiliaisI_ULT_COM: TFMTBCDField;
CadFiliaisD_DAT_CER: TSQLTimeStampField;
DBRadioGroup1: TDBRadioGroup;
CadFiliaisC_MOT_NFE: TWideStringField;
ScrollBox1: TScrollBox;
Label45: TLabel;
DBEditColor21: TDBEditColor;
CadFiliaisC_END_COT: TWideStringField;
DBCheckBox13: TDBCheckBox;
CadFiliaisC_ROM_ABE: TWideStringField;
DBCheckBox14: TDBCheckBox;
CadFiliaisC_CRM_EPC: TWideStringField;
Label46: TLabel;
DBEditColor22: TDBEditColor;
Label47: TLabel;
DBEditColor23: TDBEditColor;
Label48: TLabel;
DBEditColor24: TDBEditColor;
Label49: TLabel;
DBEditColor25: TDBEditColor;
Label50: TLabel;
DBEditColor26: TDBEditColor;
CadFiliaisC_CST_IPE: TWideStringField;
CadFiliaisC_CST_PIS: TWideStringField;
CadFiliaisC_CST_PIE: TWideStringField;
CadFiliaisC_CST_COS: TWideStringField;
CadFiliaisC_CST_COE: TWideStringField;
DBEditColor27: TDBEditColor;
Label100: TLabel;
CadFiliaisD_ULT_RPS: TSQLTimeStampField;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FecharClick(Sender: TObject);
procedure CodigoTabelaSelect(Sender: TObject);
procedure ETabelaServicoSelect(Sender: TObject);
procedure EContaPadraoSelect(Sender: TObject);
procedure EIndicadorAtividadeSpedClick(Sender: TObject);
procedure CadFiliaisAfterPost(DataSet: TDataSet);
procedure CadFiliaisBeforePost(DataSet: TDataSet);
procedure PanelColor5Click(Sender: TObject);
procedure DBEditColor7Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FConfiguracaoFilial: TFConfiguracaoFilial;
implementation
uses APrincipal, FunSql, Constantes,funobjeto, UnSistema;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFConfiguracaoFilial.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
AdicionaSQLAbreTabela(CadFiliais,'Select * from CADFILIAIS '+
' Where I_EMP_FIL = '+ IntToStr(varia.CodigoEmpFil));
PageControl.ActivePageIndex := 0;
EIndicadorAtividadeSped.ItemIndex := Varia.TipoAtividadeSped;
InicializaVerdadeiroeFalsoCheckBox(PanelColor1,'T','F');
AtualizaLocalizas([ETabelaServico,CodigoTabela,EContaPadrao,EContaBoletoPadrao,EContabilidade]);
end;
procedure TFConfiguracaoFilial.PanelColor5Click(Sender: TObject);
begin
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFConfiguracaoFilial.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
CadFiliais.Close;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFConfiguracaoFilial.FecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFConfiguracaoFilial.CadFiliaisAfterPost(DataSet: TDataSet);
begin
Sistema.MarcaTabelaParaImportar('CADFILIAIS');
end;
{******************************************************************************}
procedure TFConfiguracaoFilial.CadFiliaisBeforePost(DataSet: TDataSet);
begin
CadFiliaisD_ULT_ALT.AsDateTime := Sistema.RDataServidor;
end;
{******************************************************************************}
procedure TFConfiguracaoFilial.CodigoTabelaSelect(Sender: TObject);
begin
CodigoTabela.ASelectValida.Clear;
CodigoTabela.ASelectValida.Add(' select I_cod_tab, c_nom_tab from cadtabelapreco ' +
' where i_cod_emp = ' + CadFiliais.fieldByname('i_cod_emp').asstring +
' and i_cod_tab = @' );
CodigoTabela.ASelectLocaliza.Clear;
CodigoTabela.ASelectLocaliza.Add(' select I_cod_tab, c_nom_tab from cadtabelapreco '+
' where i_cod_emp = ' + CadFiliais.fieldByname('i_cod_emp').asstring +
' and i_cod_tab like ''@%''');
end;
procedure TFConfiguracaoFilial.DBEditColor7Change(Sender: TObject);
begin
end;
{******************************************************************************}
procedure TFConfiguracaoFilial.ETabelaServicoSelect(Sender: TObject);
begin
ETabelaServico.ASelectValida.Clear;
ETabelaServico.ASelectValida.Add(' select I_cod_tab, c_nom_tab from cadtabelapreco ' +
' where i_cod_emp = ' + CadFiliais.fieldByname('i_cod_emp').asstring +
' and i_cod_tab = @' );
ETabelaServico.ASelectLocaliza.Clear;
ETabelaServico.ASelectLocaliza.Add(' select I_cod_tab, c_nom_tab from cadtabelapreco '+
' where i_cod_emp = ' + CadFiliais.fieldByname('i_cod_emp').asstring +
' and i_cod_tab like ''@%''');
end;
{******************************************************************************}
procedure TFConfiguracaoFilial.EContaPadraoSelect(Sender: TObject);
begin
TDBEditLocaliza(sender).ASelectLocaliza.Text := 'Select * from cadbancos Ban, CadContas Co'+
' where Ban.I_COD_BAN = Co.I_COD_BAN '+
// ' and CO.I_EMP_FIL = '+IntTostr(varia.CodigoempFil)+
' and Co.C_NRO_CON like ''@%'''+
' AND CO.C_IND_ATI = ''T''';
TDBEditLocaliza(sender).ASelectValida.Text := 'Select * from cadbancos Ban, CadContas Co'+
' where Ban.I_COD_BAN = Co.I_COD_BAN '+
// ' and CO.I_EMP_FIL = '+IntTostr(varia.CodigoempFil)+
' and Co.C_NRO_CON = ''@'''+
' AND CO.C_IND_ATI = ''T''';
end;
{******************************************************************************}
procedure TFConfiguracaoFilial.EIndicadorAtividadeSpedClick(Sender: TObject);
begin
IF CadFiliais.State in [dsedit,dsinsert] then
begin
Varia.TipoAtividadeSped := EIndicadorAtividadeSped.ItemIndex;
CadFiliaisI_ATI_SPE.AsInteger := Varia.TipoAtividadeSped;
end
else
EIndicadorAtividadeSped.ItemIndex := Varia.TipoAtividadeSped;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFConfiguracaoFilial]);
end.
|
unit MCheckListBox;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, CheckLst, Menus;
type
{ TMCheckListBox }
TMCheckListBox = class(TCheckListBox)
FPopup : TPopupMenu;
FSelectAll : TMenuItem;
FDeSelectAll : TMenuItem;
FInvertSelect : TMenuItem;
public
constructor Create(AOwner: TComponent); override;
destructor destroy; override;
procedure SetCheckedAll ( Sender: TObject );
procedure SetUnCheckedAll( Sender: TObject );
procedure SetInvertSelect( Sender: TObject );
end;
procedure Register;
implementation
resourcestring
sFCapSelAll = '&Select All';
sFCapDeselAll = '&Deselect All';
sFInvert = '&Invert selection';
procedure Register;
begin
RegisterComponents('xPL Components', [TMCheckListBox]);
end;
constructor TMCheckListBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPopUp := TPopupMenu.Create( self );
FSelectAll := TMenuItem.Create( FPopUp );
FSelectAll.Caption := sFCapSelAll;
FSelectAll.OnClick := @SetCheckedAll;
FDeSelectAll := TMenuItem.Create( FPopUp );
FDeSelectAll.Caption := sFCapDeselAll;
FDeSelectAll.OnClick := @SetUnCheckedAll;
FInvertSelect := TMenuItem.Create( FPopUp );
FInvertSelect.Caption := sfInvert;
FInvertSelect.OnClick := @SetInvertSelect;
FPopUp.Items.Add(FSelectAll );
FPopUp.Items.Add(FDeSelectAll );
FPopUp.Items.Add(FInvertSelect);
PopupMenu := FPopUp;
Font.Size := 10;
end;
destructor TMCheckListBox.destroy;
begin
FSelectAll.Free;
FDeSelectAll.Free;
FInvertSelect.Free;
FPopup.Free;
inherited destroy;
end;
procedure TMCheckListBox.SetCheckedAll( Sender : TObject );
var i:integer;
begin
for i:=0 to Items.Count -1 do Checked[i]:= true;
end;
procedure TMCheckListBox.SetUnCheckedAll( Sender: TObject );
var i : integer;
begin
for i:=0 to Items.Count-1 do Checked[i] := false;
end;
procedure TMCheckListBox.SetInvertSelect(Sender: TObject);
var i : integer;
begin
for i:=0 to Items.Count-1 do Checked[i] := not Checked[i];
end;
end.
|
unit Thread.Download.Helper;
interface
uses
SysUtils, Classes, Windows, IdHttp, IdComponent,
MeasureUnit.DataSize, MeasureUnit.Time, OS.DeleteDirectory, Getter.WebPath,
Component.ProgressSection, Global.LanguageString;
type
TDownloadModelStrings = record
Download: String;
Cancel: String;
end;
TDownloadRequest = record
Source: TDownloadFile;
Destination: TDownloadFile;
DownloadModelStrings: TDownloadModelStrings;
end;
TDownloader = class
private
type
TRAWDownloadRequest = record
Source: String;
Destination: String;
end;
private
ThreadToSynchronize: TThread;
OriginalRequest: TDownloadRequest;
RAWRequest: TRAWDownloadRequest;
Aborted: Boolean;
DestinationFileStream: TFileStream;
Downloader: TIdHttp;
SourceSize: Int64;
ProgressSynchronizer: TProgressSection;
LastTick: Cardinal;
LastWorkCount: Int64;
procedure SetRAWDownloadRequest;
procedure SetMainformCaption;
procedure SynchronizedSetMainformCaption;
procedure CreateDownloader;
procedure CreateDestinationFileStream;
procedure FreeDownloader;
procedure FreeDestinationFileStream;
procedure TryToDownload;
procedure DownloaderWork(Sender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
procedure CreateProgressSynchronizer;
procedure FreeProgressSynchronizer;
function GetElapsedTick: Cardinal;
function GetAddedByte(CurrentWorkCount: Int64): Cardinal;
function GetProgressCaption(CurrentWorkCount: Int64): String;
function GetLeftTimeInSecond(RemainingByte, BytePerSecond: Int64):
Int64;
function GetBytePerSecond(AddedByte, ElapsedTick: Int64): Int64;
procedure StartDownload;
procedure PrepareDownload;
procedure SetCancelAbort;
procedure SynchronizedSetCancelAbort;
public
procedure DownloadFile(DownloadRequest: TDownloadRequest;
ThreadToSynchronize: TThread);
procedure Abort(Sender: TObject);
end;
implementation
uses
Form.Main;
procedure TDownloader.SetRAWDownloadRequest;
begin
RAWRequest.Source := GetDownloadPath(OriginalRequest.Source);
RAWRequest.Destination := GetDownloadPath(OriginalRequest.Destination);
end;
procedure TDownloader.SetMainformCaption;
begin
if ThreadToSynchronize <> nil then
TThread.Queue(ThreadToSynchronize, SynchronizedSetMainformCaption)
else
SynchronizedSetMainformCaption;
end;
procedure TDownloader.SynchronizedSetMainformCaption;
begin
fMain.lDownload.Caption := OriginalRequest.DownloadModelStrings.Download;
fMain.bCancel.Caption := OriginalRequest.DownloadModelStrings.Cancel;
end;
procedure TDownloader.Abort(Sender: TObject);
begin
Aborted := true;
Downloader.Disconnect;
FreeDestinationFileStream;
DeleteFile(PChar(RAWRequest.Destination));
DeleteDirectory(ExtractFileDir(RAWRequest.Destination));
end;
procedure TDownloader.CreateDestinationFileStream;
begin
DestinationFileStream := TFileStream.Create(RAWRequest.Destination,
fmCreate or fmShareExclusive);
end;
procedure TDownloader.CreateDownloader;
begin
Downloader := TIdHttp.Create;
Downloader.Request.UserAgent := 'Naraeon SSD Tools';
Downloader.HandleRedirects := true;
end;
procedure TDownloader.CreateProgressSynchronizer;
begin
ProgressSynchronizer := TProgressSection.Create(ThreadToSynchronize);
end;
procedure TDownloader.FreeProgressSynchronizer;
begin
FreeAndNil(ProgressSynchronizer);
end;
procedure TDownloader.TryToDownload;
begin
Aborted := false;
SourceSize := 0;
LastTick := 0;
LastWorkCount := 0;
Downloader.OnWork := DownloaderWork;
Downloader.Head(RAWRequest.Source);
SourceSize := Downloader.response.ContentLength;
ProgressSynchronizer.ShowProgress;
Downloader.Get(RAWRequest.Source, DestinationFileStream);
ProgressSynchronizer.HideProgress;
end;
procedure TDownloader.PrepareDownload;
begin
SetRAWDownloadRequest;
SetMainformCaption;
SetCancelAbort;
CreateDestinationFileStream;
CreateDownloader;
CreateProgressSynchronizer;
end;
procedure TDownloader.StartDownload;
begin
try
TryToDownload;
finally
FreeDestinationFileStream;
FreeDownloader;
FreeProgressSynchronizer;
end;
end;
procedure TDownloader.DownloadFile(DownloadRequest: TDownloadRequest;
ThreadToSynchronize: TThread);
begin
self.OriginalRequest := DownloadRequest;
self.ThreadToSynchronize := ThreadToSynchronize;
PrepareDownload;
StartDownload;
end;
procedure TDownloader.SynchronizedSetCancelAbort;
begin
fMain.bCancel.OnClick := Abort;
end;
procedure TDownloader.SetCancelAbort;
begin
TThread.Synchronize(ThreadToSynchronize, SynchronizedSetCancelAbort);
end;
procedure TDownloader.FreeDestinationFileStream;
begin
if DestinationFileStream <> nil then
FreeAndNil(DestinationFileStream);
end;
procedure TDownloader.FreeDownloader;
begin
FreeAndNil(Downloader);
end;
function TDownloader.GetElapsedTick: Cardinal;
var
CurrentTick: Cardinal;
begin
CurrentTick := GetTickCount;
if CurrentTick < LastTick then
result := 1
else
result := CurrentTick - LastTick;
LastTick := CurrentTick;
end;
function TDownloader.GetAddedByte(CurrentWorkCount: Int64): Cardinal;
begin
if CurrentWorkCount < LastWorkCount then
result := 1
else
result := CurrentWorkCount - LastWorkCount;
LastWorkCount := CurrentWorkCount;
end;
function TDownloader.GetProgressCaption(CurrentWorkCount: Int64): String;
var
BinaryBtoMB: TDatasizeUnitChangeSetting;
begin
BinaryBtoMB.FNumeralSystem := Binary;
BinaryBtoMB.FFromUnit := ByteUnit;
BinaryBtoMB.FToUnit := MegaUnit;
result := CapProg1[CurrLang];
result := result +
Format('%.1fMB', [ChangeDatasizeUnit(CurrentWorkCount, BinaryBtoMB)]) +
' / ';
result := result +
Format('%.1fMB', [ChangeDatasizeUnit(SourceSize, BinaryBtoMB)]);
result := result +
' (' + IntToStr(Round((CurrentWorkCount / SourceSize) * 100)) + '%)';
end;
function TDownloader.GetBytePerSecond(AddedByte, ElapsedTick: Int64):
Int64;
const
TickToSecond = 1000;
begin
if ElapsedTick > 0 then
result := round(AddedByte / (ElapsedTick / TickToSecond))
else
result := 0;
end;
function TDownloader.GetLeftTimeInSecond(RemainingByte, BytePerSecond: Int64):
Int64;
begin
result := 0;
if BytePerSecond > 0 then
result :=
round((SourceSize - RemainingByte) / BytePerSecond);
end;
procedure TDownloader.DownloaderWork(Sender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
var
ProgressToApply: TProgressToApply;
BytePerSecond: Int64;
RemainingCount: Int64;
ElapsedTick: Int64;
LeftTimeInSecond: Double;
begin
if (AWorkMode <> wmRead) then
exit;
ProgressToApply.ProgressValue := Round((AWorkCount / SourceSize) * 100);
ProgressToApply.ProgressCaption := GetProgressCaption(AWorkCount);
ElapsedTick := GetElapsedTick;
BytePerSecond := GetBytePerSecond(GetAddedByte(AWorkCount), ElapsedTick);
if (ElapsedTick <= 0) or (BytePerSecond <= 0) then
exit;
RemainingCount := SourceSize - AWorkCount;
LeftTimeInSecond := GetLeftTimeInSecond(RemainingCount, BytePerSecond);
ProgressToApply.SpeedCaption := CapTime[CurrLang] +
FormatTimeInSecond(LeftTimeInSecond);
ProgressSynchronizer.ChangeProgress(ProgressToApply);
end;
end.
|
unit DateTimeVisualizer;
interface
procedure Register;
implementation
uses
Classes, Forms, SysUtils, ToolsAPI;
resourcestring
sDateTimeVisualizerName = 'TDateTime/TDate/TTime Visualizer for Delphi and C++';
sDateTimeVisualizerDescription = 'Displays TDateTime, TDate and TTime instances in a human-readable date and time format rather than as a floating-point value';
type
TDebuggerDateTimeVisualizer = class(TInterfacedObject, IOTADebuggerVisualizer,
IOTADebuggerVisualizerValueReplacer, IOTAThreadNotifier, IOTAThreadNotifier160)
private
FNotifierIndex: Integer;
FCompleted: Boolean;
FDeferredResult: string;
public
{ IOTADebuggerVisualizer }
function GetSupportedTypeCount: Integer;
procedure GetSupportedType(Index: Integer; var TypeName: string;
var AllDescendants: Boolean);
function GetVisualizerIdentifier: string;
function GetVisualizerName: string;
function GetVisualizerDescription: string;
{ IOTADebuggerVisualizerValueReplacer }
function GetReplacementValue(const Expression, TypeName, EvalResult: string): string;
{ IOTAThreadNotifier }
procedure EvaluteComplete(const ExprStr: string; const ResultStr: string;
CanModify: Boolean; ResultAddress: Cardinal; ResultSize: Cardinal;
ReturnCode: Integer);
procedure ModifyComplete(const ExprStr: string; const ResultStr: string;
ReturnCode: Integer);
procedure ThreadNotify(Reason: TOTANotifyReason);
procedure AfterSave;
procedure BeforeSave;
procedure Destroyed;
procedure Modified;
{ IOTAThreadNotifier160 }
procedure EvaluateComplete(const ExprStr: string; const ResultStr: string;
CanModify: Boolean; ResultAddress: TOTAAddress; ResultSize: LongWord;
ReturnCode: Integer);
end;
TTypeLang = (tlDelphi, tlCpp);
TDateTimeType = (dttDateTime, dttDate, dttTime);
TDateTimeVisualizerType = record
TypeName: string;
TypeLang: TTypeLang;
DateTimeType: TDateTimeType;
end;
const
DateTimeVisualizerTypes: array[0..7] of TDateTimeVisualizerType =
(
(TypeName: 'TDateTime'; TypeLang: tlDelphi; DateTimeType: dttDateTime;),
(TypeName: 'TDate'; TypeLang: tlDelphi; DateTimeType: dttDate;),
(TypeName: 'TTime'; TypeLang: tlDelphi; DateTimeType: dttTime;),
(TypeName: 'function: TDateTime'; TypeLang: tlDelphi; DateTimeType: dttDateTime;),
(TypeName: 'function: TDate'; TypeLang: tlDelphi; DateTimeType: dttDate;),
(TypeName: 'function: TTime'; TypeLang: tlDelphi; DateTimeType: dttTime;),
(TypeName: 'System::TDateTime'; TypeLang: tlCpp; DateTimeType: dttDateTime;),
(TypeName: 'System::TDateTime &'; TypeLang: tlCpp; DateTimeType: dttDateTime;)
//the C++ evaluator currently doesn't differentiate between TDateTime, TDate and TTime
// (TypeName: 'System::TDate'; TypeLang: tlCpp; DateTimeType: dttDate;),
// (TypeName: 'System::TTime'; TypeLang: tlCpp; DateTimeType: dttTime;)
);
{ TDebuggerDateTimeVisualizer }
procedure TDebuggerDateTimeVisualizer.AfterSave;
begin
// don't care about this notification
end;
procedure TDebuggerDateTimeVisualizer.BeforeSave;
begin
// don't care about this notification
end;
procedure TDebuggerDateTimeVisualizer.Destroyed;
begin
// don't care about this notification
end;
procedure TDebuggerDateTimeVisualizer.Modified;
begin
// don't care about this notification
end;
procedure TDebuggerDateTimeVisualizer.ModifyComplete(const ExprStr,
ResultStr: string; ReturnCode: Integer);
begin
// don't care about this notification
end;
procedure TDebuggerDateTimeVisualizer.EvaluteComplete(const ExprStr,
ResultStr: string; CanModify: Boolean; ResultAddress, ResultSize: Cardinal;
ReturnCode: Integer);
begin
EvaluateComplete(ExprStr, ResultStr, CanModify, TOTAAddress(ResultAddress),
LongWord(ResultSize), ReturnCode);
end;
procedure TDebuggerDateTimeVisualizer.EvaluateComplete(const ExprStr,
ResultStr: string; CanModify: Boolean; ResultAddress: TOTAAddress; ResultSize: LongWord;
ReturnCode: Integer);
begin
FCompleted := True;
if ReturnCode = 0 then
FDeferredResult := ResultStr;
end;
procedure TDebuggerDateTimeVisualizer.ThreadNotify(Reason: TOTANotifyReason);
begin
// don't care about this notification
end;
function TDebuggerDateTimeVisualizer.GetReplacementValue(
const Expression, TypeName, EvalResult: string): string;
var
Lang: TTypeLang;
DateTimeType: TDateTimeType;
I: Integer;
CurProcess: IOTAProcess;
CurThread: IOTAThread;
ResultStr: array[0..255] of Char;
CanModify: Boolean;
ResultAddr, ResultSize, ResultVal: LongWord;
EvalRes: TOTAEvaluateResult;
DebugSvcs: IOTADebuggerServices;
function FormatResult(const LEvalResult: string; DTType: TDateTimeType; out ResStr: string): Boolean;
var
Dbl: Double;
begin
Result := True;
try
if not TryStrToFloat(LEvalResult, Dbl) then
Result := False
else
case DTType of
dttDateTime: ResStr := DateTimeToStr(TDateTime(Dbl));
dttDate: ResStr := DateToStr(TDate(Dbl));
dttTime: ResStr := TimeToStr(TTime(Dbl));
end;
except
Result := False;
end;
end;
begin
Lang := TTypeLang(-1);
DateTimeType := TDateTimeType(-1);
for I := Low(DateTimeVisualizerTypes) to High(DateTimeVisualizerTypes) do
begin
if TypeName = DateTimeVisualizerTypes[I].TypeName then
begin
Lang := DateTimeVisualizerTypes[I].TypeLang;
DateTimeType := DateTimeVisualizerTypes[I].DateTimeType;
Break;
end;
end;
if Lang = tlDelphi then
begin
if not FormatResult(EvalResult, DateTimeType, Result) then
Result := EvalResult;
end else if Lang = tlCpp then
begin
Result := EvalResult;
if Supports(BorlandIDEServices, IOTADebuggerServices, DebugSvcs) then
CurProcess := DebugSvcs.CurrentProcess;
if CurProcess <> nil then
begin
CurThread := CurProcess.CurrentThread;
if CurThread <> nil then
begin
EvalRes := CurThread.Evaluate(Expression+'.Val', @ResultStr, Length(ResultStr),
CanModify, eseAll, '', ResultAddr, ResultSize, ResultVal, '', 0);
if EvalRes = erOK then
begin
if FormatSettings.DecimalSeparator <> '.' then
begin
for I := 0 to Length(ResultStr) - 1 do
begin
if ResultStr[I] = '.' then
begin
ResultStr[I] := FormatSettings.DecimalSeparator;
break;
end;
end;
end;
if not FormatResult(ResultStr, DateTimeType, Result) then
Result := EvalResult;
end else if EvalRes = erDeferred then
begin
FCompleted := False;
FDeferredResult := '';
FNotifierIndex := CurThread.AddNotifier(Self);
while not FCompleted do
DebugSvcs.ProcessDebugEvents;
CurThread.RemoveNotifier(FNotifierIndex);
FNotifierIndex := -1;
if (FDeferredResult = '') or not FormatResult(FDeferredResult, DateTimeType, Result) then
Result := EvalResult;
end;
end;
end;
end;
end;
function TDebuggerDateTimeVisualizer.GetSupportedTypeCount: Integer;
begin
Result := Length(DateTimeVisualizerTypes);
end;
procedure TDebuggerDateTimeVisualizer.GetSupportedType(Index: Integer; var TypeName: string;
var AllDescendants: Boolean);
begin
AllDescendants := False;
TypeName := DateTimeVisualizerTypes[Index].TypeName;
end;
function TDebuggerDateTimeVisualizer.GetVisualizerDescription: string;
begin
Result := sDateTimeVisualizerDescription;
end;
function TDebuggerDateTimeVisualizer.GetVisualizerIdentifier: string;
begin
Result := ClassName;
end;
function TDebuggerDateTimeVisualizer.GetVisualizerName: string;
begin
Result := sDateTimeVisualizerName;
end;
var
DateTimeVis: IOTADebuggerVisualizer;
procedure Register;
begin
DateTimeVis := TDebuggerDateTimeVisualizer.Create;
(BorlandIDEServices as IOTADebuggerServices).RegisterDebugVisualizer(DateTimeVis);
end;
procedure RemoveVisualizer;
var
DebuggerServices: IOTADebuggerServices;
begin
if Supports(BorlandIDEServices, IOTADebuggerServices, DebuggerServices) then
begin
DebuggerServices.UnregisterDebugVisualizer(DateTimeVis);
DateTimeVis := nil;
end;
end;
initialization
finalization
RemoveVisualizer;
end.
|
unit ZLibConst;
interface
resourcestring
sTargetBufferTooSmall = 'ZLib error: target buffer may be too small';
sInvalidStreamOp = 'Invalid stream operation';
sError = 'Error';
implementation
end.
|
unit BodyVariationsJedecQuery;
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,
BodyVariationJedecQuery, BaseEventsQuery, DSWrap;
type
TBodyVariationsJedecW = class(TDSWrap)
private
FIDBodyVariation: TParamWrap;
FIDJEDEC: TFieldWrap;
FJEDEC: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
procedure LoadJEDEC(const AFileName: String);
property IDBodyVariation: TParamWrap read FIDBodyVariation;
property IDJEDEC: TFieldWrap read FIDJEDEC;
property JEDEC: TFieldWrap read FJEDEC;
end;
TQueryBodyVariationsJedec = class(TQueryBaseEvents)
private
FIDBodyVariations: TArray<Integer>;
FqBodyVariationJedec: TQueryBodyVariationJedec;
FW: TBodyVariationsJedecW;
function GetqBodyVariationJedec: TQueryBodyVariationJedec;
{ Private declarations }
protected
procedure ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
procedure ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
procedure ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
function CreateDSWrap: TDSWrap; override;
procedure DoAfterOpen(Sender: TObject);
property qBodyVariationJedec: TQueryBodyVariationJedec
read GetqBodyVariationJedec;
public
constructor Create(AOwner: TComponent); override;
function SearchByIDBodyVariations(AIDBodyVariations: string): Integer;
property W: TBodyVariationsJedecW read FW;
{ Public declarations }
end;
implementation
uses
StrHelper, System.Generics.Collections, System.IOUtils, NotifyEvents;
{$R *.dfm}
constructor TQueryBodyVariationsJedec.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TBodyVariationsJedecW;
// На сервер ничего сохранять не будем!
FDQuery.OnUpdateRecord := W.FDQueryUpdateRecordOnClient;
// Будем накапливать изменения, чтобы понять, есть-ли изменения
FDQuery.CachedUpdates := True;
TNotifyEventWrap.Create(W.AfterOpen, DoAfterOpen, W.EventList);
end;
procedure TQueryBodyVariationsJedec.ApplyDelete(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
var
AIDBodyVariation: Integer;
begin
for AIDBodyVariation in FIDBodyVariations do
begin
qBodyVariationJedec.SearchByIDJEDEC(AIDBodyVariation,
W.IDJEDEC.F.AsInteger, 1);
qBodyVariationJedec.FDQuery.Delete;
end;
end;
procedure TQueryBodyVariationsJedec.ApplyInsert(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
var
AIDBodyVariation: Integer;
begin
Assert(ASender = FDQuery);
for AIDBodyVariation in FIDBodyVariations do
begin
if not qBodyVariationJedec.FDQuery.Active then
qBodyVariationJedec.SearchByIDBodyVariation(AIDBodyVariation);
qBodyVariationJedec.W.TryAppend;
qBodyVariationJedec.W.IDBodyVariation.F.Value := AIDBodyVariation;
qBodyVariationJedec.W.IDJEDEC.F.Value := W.IDJEDEC.F.Value;
qBodyVariationJedec.W.TryPost;
end;
FetchFields([W.IDJEDEC.FieldName], [W.IDJEDEC.F.Value], ARequest, AAction,
AOptions);
end;
procedure TQueryBodyVariationsJedec.ApplyUpdate(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
var
AIDBodyVariation: Integer;
begin
Assert(ASender = FDQuery);
for AIDBodyVariation in FIDBodyVariations do
begin
qBodyVariationJedec.SearchByIDJEDEC(AIDBodyVariation,
W.IDJEDEC.F.OldValue, 1);
qBodyVariationJedec.W.TryEdit;
qBodyVariationJedec.W.IDJEDEC.F.Value := W.IDJEDEC.F.Value;
qBodyVariationJedec.W.TryPost;
end;
end;
function TQueryBodyVariationsJedec.CreateDSWrap: TDSWrap;
begin
Result := TBodyVariationsJedecW.Create(FDQuery);
end;
procedure TQueryBodyVariationsJedec.DoAfterOpen(Sender: TObject);
begin
W.SetFieldsReadOnly(False);
end;
function TQueryBodyVariationsJedec.GetqBodyVariationJedec
: TQueryBodyVariationJedec;
begin
if FqBodyVariationJedec = nil then
begin
FqBodyVariationJedec := TQueryBodyVariationJedec.Create(Self);
end;
Result := FqBodyVariationJedec;
end;
function TQueryBodyVariationsJedec.SearchByIDBodyVariations(AIDBodyVariations
: string): Integer;
var
AStipulation: string;
I: Integer;
L: TList<Integer>;
m: TArray<String>;
begin
Assert(not AIDBodyVariations.IsEmpty);
m := AIDBodyVariations.Split([',']);
L := TList<Integer>.Create;
try
for I := Low(m) to High(m) do
begin
L.Add(m[I].Trim.ToInteger);
end;
FIDBodyVariations := L.ToArray;
finally
FreeAndNil(L);
end;
AStipulation := Format('%s in (%s)', [W.IDBodyVariation.FieldName,
AIDBodyVariations]);
// Меняем в запросе условие
FDQuery.SQL.Text := ReplaceInSQL(SQL, AStipulation, 0);
// Ищем
W.RefreshQuery;
Result := FDQuery.RecordCount;
end;
constructor TBodyVariationsJedecW.Create(AOwner: TComponent);
begin
inherited;
FIDJEDEC := TFieldWrap.Create(Self, 'IDJEDEC', '', True);
FJEDEC := TFieldWrap.Create(Self, 'JEDEC');
// Параметры SQL запроса
FIDBodyVariation := TParamWrap.Create(Self, 'bvj.IDBodyVariation');
end;
procedure TBodyVariationsJedecW.LoadJEDEC(const AFileName: String);
var
S: string;
begin
Assert(not AFileName.IsEmpty);
Assert(DataSet.RecordCount > 0);
// В БД храним имя файла без расширения и всё
S := TPath.GetFileNameWithoutExtension(AFileName);
TryEdit;
JEDEC.F.AsString := S;
TryPost;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
private
hrc: HGLRC;
{позиция курсора}
xpos : GLfloat;
ypos : GLfloat;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
var
i : 1..40;
begin
wglMakeCurrent(Canvas.Handle, hrc);
glViewPort (0, 0, ClientWidth, ClientHeight);
glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета
For i := 1 to 40 do begin
glColor3f (random, random, random);
glPointSize (random (10));
glBegin (GL_POINTS);
glVertex2f (xpos + 0.2 * random * sin (random (360)),
ypos + 0.2 * random * cos (random (360)));
glEnd;
end;
SwapBuffers(Canvas.Handle); // содержимое буфера - на экран
wglMakeCurrent(0, 0);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
Randomize;
SetDCPixelFormat(Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
end;
{=======================================================================
Обрабока движения курсора}
procedure TfrmGL.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
xpos := 2 * X / ClientWidth - 1;
ypos := 2 * (ClientHeight - Y) / ClientHeight - 1;
Refresh; // перерисовка окна при каждом движении курсора
end;
end.
|
{*******************************************************************************
Developer: josking Date﹕ 2009/11/26
Coding standard version NO. :1.0
Copyright(gbm ems) ,All right reserved
*******************************************************************************}
unit clsGlobal;
interface
uses clsDataConnect, clsUser, clsSysparameter, clsClientDtSet, Forms, SysUtils,midaslib;
type
TGlobal = class(Tobject)
public
objDataConnect: TDataConnect;
objUser: TclsUser;
ObjSysParameter: TSysParameter;
dtSetMain: TClientDtSet;
gLoginCancel: boolean;
isDelShow: boolean;
gApplication: TApplication;
gScreen: TScreen;
PFormFreeCallBack: Pointer;
gCallType: integer; //用于標示常規或DLL調用
gLongFomatDateTime: string;
gShortFomatDateTime: string;
gMultiLanguage: integer; //用于標示目前用戶選擇的語言
gCaseName: string; //用于標示當前打開的Case的名稱
gDBType: integer; //用于標示目前所用數據庫的類型
gRunning: Boolean; //用于自動登出機制控制﹕子窗體是否正在Running
gNoActiveTime: Integer; //用于自動登出機制控制﹕主程式未激活累計時間
gOption01, gOption02, gOption03: integer; //擴展參數 integer﹔
gParam01, gParam02, gParam03: string; //擴展參數 string﹔
objDaStProvideName,objSPProvideName:string;//provide name .
constructor Create;
destructor Destroy; override;
end;
function GetCurrentDateTime: TDateTime;
var
objGlobal: TGlobal;
implementation
{ TForever }
constructor TGlobal.Create;
begin
objDataConnect := TdataConnect.Create;
objUser := TclsUser.Create;
dtSetMain := TClientDtSet.Create(nil);
objUser.FID := 'A001';
objUser.FName := 'Default User';
ObjSysParameter := TSysParameter.Create;
ObjSysParameter.FmajorComGroup := 1; // 0:不用此欄位 1:需此欄位 ; Default:0
ObjSysParameter.FdisplayMode := 'MES';
ObjSysParameter.FdisplayLayer := 'MES';
objDaStProvideName:='OraDataSetProQuery';
objSPProvideName:='OraDataSetProSP';
isDelShow := true;
gApplication := Application;
gScreen := Screen;
gCallType := 0; //默認0﹕為常規調用﹐為1﹕則為DLL調用
gLongFomatDateTime := 'yyyy/mm/dd hh:nn:ss';
gShortFomatDateTime := 'yyyy/mm/dd';
gMultiLanguage := 1033; //多國語言參數﹐默認1033為英語(美國)﹔1028 為中文(繁體)﹔2052為中文(簡體)
gCaseName := '';
gDBType := 0; //0:SQL Server;1:Oracle;2:DB2;3:SysBase;4:Infomix;
gRunning := False;
gNoActiveTime := 0;
end;
destructor TGlobal.Destroy;
begin
objDataConnect.Free;
objDataConnect := nil;
objUser.Free;
objUser := nil;
dtSetMain.Free;
ObjSysParameter.Free;
ObjSysParameter := nil;
inherited Destroy;
end;
function GetCurrentDateTime: TDateTime;
var
sql: string;
FtmpDt: TClientDtSet;
begin
case objGlobal.gDBType of
0: begin
sql := 'select getDate() as FDate ';
end;
1: begin
sql := 'select sysdate as FDate from dual ';
end;
end;
FtmpDt := objGlobal.objDataConnect.DataQuery(sql);
Result := FtmpDt.FieldByName('FDate').AsDateTime;
FtmpDt.Free;
FtmpDt := nil;
end;
end.
|
unit WiseAppLock;
interface
uses
SysUtils, Windows, Dialogs;
const
lockDir: string = 'C:\Locks';
crlf: string = #10#13;
(*
** Creates a 'single application instance' lock-file.
** The file's path is C:\Locks\<app-name>.lock, where <app-name>
** is provided at object Create time.
** If the application dies or is killed, the lock is removed by the Windows.
*)
type TWiseAppLock = class
private appName: string;
private fileName: string;
private fileHandle: THandle;
private fileSize: integer;
public
function tryLock: boolean;
procedure unlock;
function path: string;
constructor Create(appName: string);
end;
implementation
constructor TWiseAppLock.Create(appName: string);
begin
if not DirectoryExists(lockDir) then
ForceDirectories(lockDir);
Self.appName := appName;
Self.fileName := lockDir + '\' + appName + '.lock';
end;
function TWiseAppLock.tryLock: boolean;
begin
Result := False;
try
Self.fileHandle := CreateFile(PChar(Self.fileName),GENERIC_READ, 0, nil, OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
Self.fileSize := GetFileSize(Self.fileHandle, nil);
if LockFile(Self.fileHandle,0,0,Self.fileSize,0) then
Result := True;
except
end;
if Result = False then
ShowMessage(
crlf +
'Cannot lock "' + Self.fileName + '"!' + crlf +
crlf +
'There may be another "' + Self.appName + '" running! ' + crlf
);
end;
procedure TWiseAppLock.unlock;
begin
UnlockFile(Self.fileHandle,0,0,Self.fileSize,0);
CloseHandle(Self.fileHandle);
end;
function TWiseAppLock.path: string;
begin
Result := Self.fileName;
end;
end.
|
(* StringRotation: MM, 2020-03-20 *)
(* ------ *)
(* A Program to rotate find rotations in certain strings *)
(* ========================================================================= *)
PROGRAM StringRotation;
FUNCTION KnutMorrisPratt2(s, p: STRING): INTEGER;
VAR next: ARRAY[1..255] OF INTEGER;
sLen, pLen: INTEGER;
i, j: INTEGER;
PROCEDURE InitNext;
BEGIN (* InitNext *)
i := 1;
j := 0;
next[1] := 0;
WHILE (i < pLen) DO BEGIN
IF ((j = 0) OR (p[i] = p[j])) THEN BEGIN
Inc(i);
Inc(j);
IF (NOT (p[i] = p[j])) THEN
next[i] := j
ELSE
next[i] := next[j];
END ELSE BEGIN
j := next[j];
END; (* IF *)
END; (* WHILE *)
END; (* InitNext *)
BEGIN (* KnutMorrisPratt2 *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
KnutMorrisPratt2 := 0;
END ELSE BEGIN
InitNext;
i := 1;
j := 1;
REPEAT
IF (j = 0) OR (s[i] = p[j]) THEN BEGIN
Inc(i);
Inc(j);
END ELSE BEGIN
j := next[j];
END; (* IF *)
UNTIL ((j > pLen) OR (i > sLen)); (* REPEAT *)
IF (j > pLen) THEN BEGIN
KnutMorrisPratt2 := i - pLen;
END ELSE BEGIN
KnutMorrisPratt2 := 0;
END; (* IF *)
END; (* IF *)
END; (* KnutMorrisPratt2 *)
FUNCTION ConcatRotation(a, b: STRING): BOOLEAN;
BEGIN (* ConcatRotation *)
IF (Length(a) = Length(b)) THEN BEGIN
a := a + a;
ConcatRotation := KnutMorrisPratt2(a, b) <> 0;
END ELSE BEGIN
ConcatRotation := FALSE;
END; (* IF *)
END; (* ConcatRotation *)
FUNCTION IsRotation(a, b: STRING): BOOLEAN;
VAR aLen, bLen: INTEGER;
initialB: STRING;
BEGIN (* IsRotation *)
aLen := Length(a);
bLen := Length(b);
initialB := b;
IF (aLen = bLen) THEN BEGIN
Repeat
b := b + b[1];
Delete(b, 1, 1);
UNTIL ((a = b) OR (b = initialB))
END; (* IF *)
IsRotation := (a = b);
END; (* IsRotation *)
VAR a, b: STRING;
BEGIN (* StringRotation *)
REPEAT
Write('Enter a > ');
ReadLn(a);
Write('Enter b > ');
ReadLn(b);
WriteLn('Is ', b, ' a rotation of ', a, '? ', ConcatRotation(a, b), ' (Concat-Rotation)');
WriteLn('Is ', b, ' a rotation of ', a, '? ', IsRotation(a, b), ' (Rotation)');
UNTIL ((a = '') OR (b = '')); (* REPEAT *)
END. (* StringRotation *) |
unit ClientCommunication;
interface
uses SysUtils, Classes, Windows,
IdContext, IdTCPClient, IdBaseComponent, IdComponent;
procedure addClient(ip_port: string; context: TIdContext);
procedure deleteClient(ip_port:string);
function countClients:integer;
procedure disconnectAllClients;
procedure updateClientsCounter;
procedure broadcastToClients(action:string; tool:string = ''; data:string = ''; forwardedPaint:boolean=false);
procedure tellServer(action:string;tool:string = ''; data:string = '');
type
TClientThread=class(TThread)
procedure phase_first;
procedure phase_last;
procedure readImage;
procedure got_image;
procedure update;
procedure drawStuff;
procedure drawEffects;
protected
procedure execute; override;
end;
implementation
uses main;
procedure tellServer(action:string; tool: string = ''; data: string = '');
var colors, brush: string;
begin
colors := IntToStr(foreColor) + ',' + IntToStr(backColor);
brush := IntToStr(ord(brushStyle)) + ',' + IntToStr(ord(penStyle));
TCP_Client.IOHandler.WriteLn(action+tool + ':' + colors + ',' + brush + ',' + DATA);
end;
procedure broadcastToClients(action: string; tool: string = '';data:string = ''; forwardedPaint: boolean = false);
var i: integer;
colors, brush: string;
begin
colors := '';
brush := '';
if not forwardedPaint then
begin
colors := IntToStr(foreColor) + ',' + IntToStr(backColor) + ',';
brush := IntToStr(ord(brushStyle)) + ',' + IntToStr(ord(penStyle)) + ',';
end;
for i := 1 to 255 do
if (clients[i].ip_port <> '') and (clients[i].ip_port <> skipClient) then
if action = 'IMAGE' then
form1.WriteImage(clients[i].context)
else
clients[i].context.Connection.IOHandler.WriteLn(action+tool + ':' + colors+brush+DATA);
end;
procedure deleteClient(ip_port: string);
var i: integer;
begin
for i := 1 to 255 do
if clients[i].ip_port=ip_port then
begin
clients[i].ip_port := '';
clients[i].context := nil;
end;
end;
function countClients:integer;
var i, cnt: integer;
begin
cnt := 0;
for i := 1 to 255 do
if clients[i].ip_port<>'' then
inc(cnt);
result := cnt;
end;
procedure disconnectAllClients;
var i: integer;
begin
for i := 1 to 255 do
if clients[i].ip_port <> '' then
begin
clients[i].context.Connection.IOHandler.WriteLn('OKBYE');
clients[i].context.Connection.Disconnect;
clients[i].ip_port := '';
clients[i].context := nil;
end;
end;
procedure addClient(ip_port: string; context: TIdContext);
var i: integer;
begin
for i := 1 to 255 do
if clients[i].ip_port = '' then
begin
clients[i].ip_port := ip_port;
clients[i].context := context;
break;
end;
end;
// TClientThread
procedure TClientThread.drawEffects;
var effect:string;
begin
effect := TCP_Client.IOHandler.ReadLn;
form1.drawEffects_core(effect);
end;
procedure TClientThread.drawStuff;
var client: TIdTCPClient;
tmp, toolstr: string;
begin
client := TCP_Client;
tmp := client.IOHandler.ReadLn;
toolstr := copy(tmp, 1, pos(':', tmp)-1);
delete(tmp, 1, length(toolstr) + 1);
updstr := 'DRAW ' + toolstr + ' @ ' + tmp;
Synchronize(update);
form1.drawStuff_core(tmp, toolstr);
end;
procedure TClientThread.update;
begin
//form1.client_log.Lines.Add(updstr);
end;
procedure TClientThread.phase_last;
begin
form1.connect_to_server.Enabled := true;
form1.connect_to_server.Caption := 'Connect';
form1.TCP_ClientDisconnected(nil);
form1.update_info_bars;
end;
procedure TClientThread.phase_first;
begin
form1.connect_to_server.Enabled := true;
form1.connect_to_server.Caption := 'Disconnect';
form1.update_info_bars;
end;
procedure TClientThread.execute;
var client: TIdTCPClient;
tmp: string;
error: boolean;
label done;
begin
FreeOnTerminate := true;
client := TCP_Client;
try
client.Connect;
except
updstr := 'There was an error while connecting';
Synchronize(update);
Synchronize(phase_last);
exit;
end;
while not connected do sleep(100);
Synchronize(phase_first);
error := false;
while not terminated do
begin
try
tmp := '';
tmp := client.IOHandler.ReadString(5);
except
error := true;
end;
if error then goto done;
if tmp<>'' then
begin
updstr := 'GOT: ' + tmp;
Synchronize(update);
if tmp = 'IMAGE' then readImage
else if tmp = 'DRAW_' then Synchronize(drawStuff)
else if tmp = 'EFECT' then Synchronize(drawEffects)
else if tmp = 'OKBYE' then Terminate;
end;
end;
done:
try
client.IOHandler.ReadLn;
client.Disconnect;
connected := false;
client.Socket.Free;
client.IOHandler.Free;
ClientThread := nil;
finally
Synchronize(phase_last);
end;
end;
procedure TClientThread.got_image;
begin
Form1.Image1.Picture.Bitmap.LoadFromStream(imageStream);
saved := false;
updstr := 'Image received';
update;
end;
procedure TClientThread.readImage;
var size: integer;
tmp: string;
begin
updstr := 'Reading image';
Synchronize(update);
TCP_Client.IOHandler.readLn; //go to next line
tmp := TCP_Client.IOHandler.readLn;
size := StrToInt(tmp);
imageStream.Clear;
imageStream.Size := size;
tmp := TCP_Client.IOHandler.ReadString(size);
CopyMemory(imageStream.Memory, @tmp[1], size);
Synchronize(got_image);
end;
procedure updateClientsCounter;
begin
form1.client_count.Caption := IntToStr(countClients) + ' clients';
end;
end.
|
{
this file is part of Ares
Aresgalaxy ( http://aresgalaxy.sourceforge.net )
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
}
{
Description:
localized vars, used to display multilanguage strings in the UI
}
unit vars_localiz;
interface
uses
classes,sysutils,helper_unicode,registry,const_ares,helper_strings,helper_diskio,
windows{,cometPageView,ufrm_settings};
const
MIN_TRANSLATIONTABLE_INDEX=108;
MAX_TRANSLATIONTABLE_INDEX=833;
type
Tdb_language=array[MIN_TRANSLATIONTABLE_INDEX..MAX_TRANSLATIONTABLE_INDEX] of widestring;
const
db_english_lang:array[MIN_TRANSLATIONTABLE_INDEX..MAX_TRANSLATIONTABLE_INDEX] of string = (
{108}'Filter Executable files and potentially dangerous file types',
{109}'Send',
{110}'Load',
{111}'Clear',
{112}'Avatar',
{113}'Display chat event''s date/time',
{114}'When you are away, you may activate away status. '+const_ares.appname+' replies to private chat requests with an away message. Here you may configure your custom away message.',
{115}'Block all private messages',
{116}'Reply with an away message to private chats',
{117}'Start server',
{118}'Stop server',
{119}'Filesharing',
{120}'Block Emotes',
{121}'Choked',
{122}'Optimistic Unchoke',
{123}'Interested',
{124}'Personal message',
{125}'Keep connection Alive',
{126}'Accept incoming connections on port:',
{127}'upload(s) allowed at once',
{128}'upload(s) per user (0=no limit)',
{129}'Upload bandwidth (kb/s 0=no limit)',
{130}'Increase on Idle',
{131}'Download bandwidth (kb/s 0=no limit)',
{132}'',
{133}'Downloads are saved into folder:',
{134}'Change folder',
{135}'Restore to default folder',
{136}' Hit ''Start scan'' to scan your system',
{137}'Start scan',
{138}'Stop scan',
{139}'Check all',
{140}'Uncheck all',
{141}'Check folder(s) you want to share with online comunity.',
{142}'Legend',
{143}'This folder isn''t shared, but other child folders are shared.',
{144}'Folder is shared, all files in this folder are shared.',
{145}'',
{146}'My computer is behind a firewall or can''t accept incoming connections',
{147}'',
{148}'',
{149}'Load '+const_ares.appname+' when windows starts',
{150}'Auto-connect to network when I start '+const_ares.appname,
{151}'Start '+const_ares.appname+' minimized',
{152}'Exit '+const_ares.appname+' when I click on close button',
{153}'This screen allows you to select which folder you would like to share, making it available for other comunity''s users. Other users cannot modify content of these folders.',
{154}'',
{155}'',
{156}'',
{157}'',
{158}'Show taskbar button',
{159}'Show ''What I''m listening to'' on MSN',
{160}'Show status on main window''s caption',
{161}'Show transfer percentage',
{162}'Block large hints',
{163}'Pause video when moving between tabs',
{164}'Ask for confirmation when cancelling downloads',
{165}'',
{166}'',
{167}'',
{168}'',
{169}'',
{170}'',
{171}'',
{172}'',
{173}'',
{174}'',
{175}'',
{176}'',
{177}'',
{178}'',
{179}'',
{180}'',
{181}'',
{182}'',
{183}'',
{184}'',
{185}'',
{186}'',
{187}'',
{188}'',
{189}'',
{190}'',
{191}'',
{192}'',
{193}'Nickname:',
{194}'',
{195}'Ok',
{196}'Cancel',
{197}'Apply',
{198}'',
{199}'Close',
{200}'Search for text',
{201}'Audio Files',
{202}'Video Files',
{203}'Playlist Files',
{204}'Any File',
{205}'Clear Search History',
{206}'Advanced search',
{207}'',
{208}'Simple search',
{209}'',
{210}'Found',
{211}'Main',
{212}'Connect',
{213}'Disconnect',
{214}'Preferences',
{215}'',
{216}'',
{217}'Search Field',
{218}'',
{219}'',
{220}'',
{221}'',
{222}'',
{223}'',
{224}'',
{225}'',
{226}'',
{227}'',
{228}'',
{229}'',
{230}'Library',
{231}'Share and Organize your Media',
{232}'Search',
{233}'Search for Files on '+const_ares.appname+' Network',
{234}'Transfer',
{235}'Progress of Downloads and Uploads',
{236}'Web',
{237}'Browse the Internet',
{238}'Screen',
{239}'Play your Media',
{240}'Chat',
{241}'Meet new friends in '+const_ares.appname+' chat',
{242}'Fullscreen',
{243}'Set fullscreen mode',
{244}'',
{245}'',
{246}'',
{247}'',
{248}'Original size',
{249}'Fit to screen/Set to original video size',
{250}'Exit channel',
{251}'Refresh list',
{252}'Join channel',
{253}'Send a private message',
{254}'Browse user''s files',
{255}'Host your Channel',
{256}'Share Settings - Click here to configure shared folders',
{257}'Rescan your library',
{258}'Folders',
{259}'Show/Hide folders',
{260}'Details',
{261}'Show/Hide details',
{262}'Share/Unshare',
{263}'Delete file',
{264}'Add file to playlist',
{265}'Reconnect to host',
{266}'File',
{267}'Send File',
{268}'Accept Incoming Files',
{269}'Show Transfers',
{270}'Hide Transfers',
{271}'Edit',
{272}'Select All',
{273}'Copy',
{274}'Save to disk',
{275}'',
{276}'Set me Away',
{277}'Block this Host',
{278}'Cancell All',
{279}'Connecting to host, please wait...',
{280}'Connection established',
{281}'Connection closed by remote peer',
{282}'Remote host unreachable',
{283}'Ok open it!',
{284}'Generating preview',
{285}'Copying file',
{286}'Mute',
{287}'',
{288}'',
{289}'Cancel',
{290}'Cancel selected transfer',
{291}'Pause/Resume',
{292}'Pause/Resume selected download',
{293}'Play/Preview',
{294}'Play/Preview selected file',
{295}'Locate file',
{296}'Locate selected file/Open incoming file folder',
{297}'Clear Idle',
{298}'Clear completed/cancelled transfers',
{299}'Add file to playlist',
{300}'Add folder to playlist',
{301}'Remove selected file',
{302}'Clear playlist',
{303}'Load/Save playlist',
{304}'',
{305}'Load playlist',
{306}'Save playlist',
{307}'Remove All',
{308}'Remove Selected',
{309}'Sort',
{310}'Alpha-sort ascending',
{311}'Alpha-sort descending',
{312}'Shuffle list',
{313}'',
{314}'Shuffle',
{315}'Repeat',
{316}'New search',
{317}'Make a new search',
{318}'Download',
{319}'Download selected file',
{320}'',
{321}'Show/Hide Search Field',
{322}'Back',
{323}'Forward',
{324}'Stop',
{325}'Refresh',
{326}'Play',
{327}'Pause',
{328}'Previous',
{329}'Next',
{330}'Volume',
{331}'Show playlist',
{332}'Close playlist',
{333}'',
{334}'',
{335}'Playlist',
{336}'Hide details',
{337}'Shared',
{338}'Hide folders',
{339}'Check to share file, uncheck to unshare this file',
{340}'in queue',
{341}'Try also',
{342}'Personal details',
{343}'',
{344}'',
{345}'',
{346}'',
{347}'',
{348}'Transfer',
{349}'',
{350}'Chat',
{351}'Private messages',
{352}'Not connected',
{353}'File posting',
{354}'Private messages',
{355}'Fileshare',
{356}'Auto-scan',
{357}'Manual configure',
{358}'Download folder',
{359}'General',
{360}'Network',
{361}'connected as',
{362}'',
{363}'Files',
{364}'files',
{365}'Unable to connect',
{366}'Last seen',
{367}'Availability',
{368}'Connecting',
{369}'Connecting to network',
{370}'',
{371}'',
{372}'Connected, handshaking...',
{373}' Browse failed',
{374}'',
{375}'Handshake error, blocking connection',
{376}'no directories found',
{377}'Scan completed',
{378}'directory found',
{379}'Performing search, please wait...',
{380}'Search finished without any result',
{381}'Would you like to choose your nickname now?',
{382}'',
{383}'Are you sure you want to erase search history?',
{384}'Erase search history',
{385}'',
{386}'',
{387}'',
{388}'',
{389}'',
{390}'Your chat party wants to send you one or more files, would you like to start the file session?',
{391}'Incoming file session',
{392}'',
{393}'',
{394}'',
{395}'',
{396}'',
{397}'',
{398}'Are you sure you want to cancel download?',
{399}'Cancel Download',
{400}'',
{401}'',
{402}'',
{403}'',
{404}'',
{405}'',
{406}'',
{407}'directories found',
{408}'Handshake error, connection reset by peer',
{409}'Handshake error, timeout waiting for peer reply',
{410}'Disconnected',
{411}'Disconnected, buffer overflow',
{412}'Logged in, retrieving user''s list...',
{413}'Topic changed',
{414}'sharing',
{415}'files, has joined',
{416}'has parted',
{417}'Disconnected, send timeout',
{418}'You are muzzled',
{419}'Images & Videos',
{420}'Downloaded',
{421}'Hosted channel',
{422}'Channel',
{423}'Shared size',
{424}'Total size',
{425}'queued',
{426}'Queued',
{427}'',
{428}'Channel name:',
{429}'Wrong name',
{430}'Please choose one with at least 4 character',
{431}'',
{432}'',
{433}'',
{434}'Connecting to remote channel',
{435}'Free slots',
{436}'KB/sec',
{437}'You are already hosting a chat channel called',
{438}'FILE NOT SHARED',
{439}'There''s no undo feature',
{440}'WARNING, harddisk file erase',
{441}'Delete file',
{442}'Delete files',
{443}'Transmitted',
{444}'File transfer already in progress',
{445}'Please take a look to transfer tab',
{446}'Duplicated request',
{447}'Selected file is already in your library',
{448}'Please take a look to library tab',
{449}'Duplicated file',
{450}'This media type is filtered',
{451}'Filtered Media',
{452}'Hide '+const_ares.appname,
{453}'Show '+const_ares.appname,
{454}'result for',
{455}'results for',
{456}'my shared folder',
{457}'',
{458}'please wait...',
{459}'*THIS FILE IS ALREADY IN YOUR LIBRARY*',
{460}'*YOU ARE ALREADY DOWNLOADING THIS FILE*',
{461}'Processing',
{462}'Paused',
{463}'',
{464}'Leech Paused',
{465}'Cancelled',
{466}'Completed',
{467}'Downloading',
{468}'Idle',
{469}'Searching',
{470}'Connecting',
{471}'WARNING',
{472}'Searching',
{473}'Users',
{474}'Connecting to remote user',
{475}'Chat - connecting to remote host',
{476}'You',
{477}'banned (it will be unbanned when you restart the program)',
{478}' Searching for',
{479}'anything',
{480}'Hash priority',
{481}'Server queue',
{482}'Highest',
{483}'Higher',
{484}'Normal',
{485}'Lower',
{486}'Lowest',
{487}'Ignore/Unignore',
{488}'Muzzle',
{489}'Unmuzzle',
{490}'Ban',
{491}'Unban',
{492}'Kill',
{493}'',
{494}'Share Settings',
{495}'Open/Play',
{496}'Open External',
{497}'Locate File',
{498}'Search for files containing text:',
{499}'Find more from the same',
{500}'Pause All/Unpause All',
{501}'View Playlist',
{502}'Quit '+const_ares.appname,
{503}'',
{504}'Block User',
{505}'Unshare File',
{506}'Fit to Screen',
{507}'',
{508}'Stop Search',
{509}'Select All',
{510}'Copy to Clipboard',
{511}'Save to disk',
{512}'Search Now',
{513}'Date',
{514}'Show queue',
{515}'See who''s in your queue',
{516}'Show upload',
{517}'See uploads',
{518}'Filter',
{519}'Regular View',
{520}'Virtual View',
{521}'Show the library in virtual view',
{522}'Show the library in regular view',
{523}'User',
{524}'Title',
{525}'Artist',
{526}'Quality',
{527}'Year',
{528}'Version',
{529}'Filetype',
{530}'Colours',
{531}'Author',
{532}'Folder',
{533}'Length',
{534}'received',
{535}'sent',
{536}'Resolution',
{537}'Media Type',
{538}'Language',
{539}'Category',
{540}'Download',
{541}'Scan in progress',
{542}'Upload',
{543}'Uploads',
{544}'Downloads',
{545}'Album',
{546}'Company',
{547}'Date',
{548}'Requested size',
{549}'File size',
{550}'Size',
{551}'Format',
{552}'Filename',
{553}'URL',
{554}'Name',
{555}'Topic',
{556}'Welcome to the ',
{557}' channel',
{558}'Speed',
{559}'Group by Album',
{560}'Group by Author',
{561}'Group by Artist',
{562}'Group by Category',
{563}'Group by Company',
{564}'Group by Genre',
{565}'All',
{566}'Audio',
{567}'Video',
{568}'Image',
{569}'Document',
{570}'Other',
{571}'Software',
{572}'',
{573}'',
{574}'',
{575}'',
{576}'',
{577}'',
{578}'',
{579}'',
{580}'',
{581}'Shared virtual folders',
{582}'Shared folders',
{583}'Shared files',
{584}'Your library',
{585}'Search for Video files',
{586}'Search for Audio files',
{587}'Search for generic media',
{588}'Search for Image files',
{589}'Search for Documents',
{590}'Search for Softwares',
{591}'',
{592}'',
{593}'',
{594}'Type',
{595}'File',
{596}'Uploaded',
{597}'Status',
{598}'Media Type',
{599}'Location',
{600}'Requested',
{601}'today',
{602}'total',
{603}'Genre',
{604}'Remaining',
{605}'Progress',
{606}'Total transfer speed',
{607}'Comments',
{608}'Estimated time remaining',
{609}'Volume transmitted',
{610}'Volume downloaded',
{611}'Number of sources',
{612}'sources',
{613}'source',
{614}'Bandwidth',
{615}'Unknown',
{616}'unknown',
{617}'of',
{618}'Uploading',
{619}'',
{620}'',
{621}'',
{622}'',
{623}'',
{624}'',
{625}'',
{626}'',
{627}'',
{628}'',
{629}'',
{630}'',
{631}'on',
{632}'from',
{633}'',
{634}'',
{635}'',
{636}'',
{637}'',
{638}'',
{639}'',
{640}'',
{641}'',
{642}'',
{643}'',
{644}'',
{645}'',
{646}'',
{647}'',
{648}'',
{649}'',
{650}'',
{651}'',
{652}'',
{653}'',
{654}'',
{655}'',
{656}'',
{657}'',
{658}'',
{659}'',
{660}'',
{661}'',
{662}'',
{663}'',
{664}'',
{665}'',
{666}'',
{667}'',
{668}'',
{669}'',
{670}'',
{671}'',
{672}'',
{673}'',
{674}'',
{675}'',
{676}'',
{677}'',
{678}'',
{679}'',
{680}'',
{681}'',
{682}'',
{683}'Clear screen',
{684}'',
{685}'',
{686}'',
{687}'',
{688}'',
{689}'',
{690}'',
{691}'',
{692}'',
{693}'Age',
{694}'Sex',
{695}'Country',
{696}'State/City',
{697}'Male',
{698}'Female',
{699}'Preferred Language',
{700}'Channels',
{701}'Shared',
{702}'',
{703}'Retrieving list, please wait...',
{704}'List empty, please try later',
{705}'Scanning',
{706}'',
{707}'',
{708}'sharing',
{709}'files',
{710}'connected as',
{711}'Hide search field',
{712}'Available space',
{713}'Browse in progress:',
{714}'Browse completed:',
{715}'Poor',
{716}'Average',
{717}'Good',
{718}'Very good',
{719}'Scanning is now taking place in your '+const_ares.appname+' program.'+CRLF+CRLF+'When '+const_ares.appname+' finds new media in your shared folders, it must compute an unique Hash identifier for each new file.'+
'This operation may take a while, depending on the size of files to be hashed and speed of your computer.'+CRLF+CRLF+'You can see which file is being hashed right above here.'+
'You can also modify the priority '+const_ares.appname+' gives to hashing.'+CRLF+'Be aware that chosing high thread priority shorten time needed to compute hash values, but may slow down your computer.'+CRLF+
'We are glad you have chosen '+const_ares.appname+' as your peer to peer program.',
{720}'Hash calculation in progress',
{721}'Media search in progress ',
{722}'',
{723}'',
{724}'Cancel upload',
{725}'Other',
{726}'Audio',
{727}'Software',
{728}'Video',
{729}'Document',
{730}'Image',
{731}'Started',
{732}'Available sources',
{733}'Actual progress',
{734}'Total tries',
{735}'Retry interval',
{736}'Last request',
{737}'',
{738}'Expiration',
{739}'',
{740}'',
{741}'Save As',
{742}'At least',
{743}'At best',
{744}'Equal to',
{745}'Circa',
{746}'Longer than',
{747}'Shorter than',
{748}'Smaller than',
{749}'Bigger than',
{750}'Locally paused',
{751}'download(s) allowed at once',
{752}'Unknown command',
{753}'Proxy',
{754}'',
{755}'Don''t use proxy',
{756}'Use Sock4 proxy',
{757}'Use Sock5 proxy',
{758}'Proxy server address',
{759}'Username',
{760}'Password',
{761}'Remote user is browsing your library',
{762}'Allow browse of my library',
{763}'',
{764}'',
{765}'',
{766}'Direct chat',
{767}'Send folder',
{768}'Offline',
{769}'Channel Search',
{770}'Grant slot',
{771}'Browse failed, list unavailable',
{772}'Shareable File Types',
{773}'',
{774}'',
{775}'Download HashLink',
{776}'Insert HashLink here',
{777}'Export HashLink',
{778}'File Corrupted',
{779}'File Access Error',
{780}'',
{781}'',
{782}'',
{783}'',
{784}'',
{785}'Grant browse',
{786}'',
{787}'Downloaded on',
{788}'Recent downloads',
{789}'Allow regular folder browse',
{790}'Open folder',
{791}'Auto accept files',
{792}'',
{793}'',
{794}'',
{795}'Hashlinks',
{796}'Handle Ed2k links',
{797}'Handle Magnet links',
{798}'',
{799}'Control Panel',
{800}'Configure and control your '+const_ares.appname,
{801}'Check connection',
{802}'Testing...',
{803}'Test failed',
{804}'Test passed',
{805}'Proxy bouncer',
{806}'Currently using',
{807}'Load list',
{808}'Save list',
{809}'Use multiple proxy servers',
{810}'New tab',
{811}'Go',
{812}'Show Join/Part notice',
{813}'Favorites',
{814}'Add to Favorites',
{815}'Last',
{816}'Search for Other files',
{817}'Disconnect source',
{818}'You are about to open a potentially dangerous file type. The file may contain a virus or trojan.'+CRLF+'Are you sure you want to continue?',
{819}'Busy',
{820}'Chatroom',
{821}'Pushing',
{822}'Waiting for peer',
{823}'Requesting',
{824}'Auto Join',
{825}'Connected',
{826}'Auto add to favorites',
{827}'Make '+const_ares.appname+' my default torrent client',
{828}'Active',
{829}'Save to Disk',
{830}'New Radio',
{831}'Handle m3u and pls files',
{832}'Directory', {shoutcast stations}
{833}''
);
STR_FILTERPOTENTIALYDANGEROUS=108;
STR_SEND_DIRECTCHAT=109;
STR_LOAD=110;
STR_CLEAR=111;
STR_AVATAR=112;
STR_CONF_CHATTIME=113;
STR_CONF_PVT_TIP=114;
STR_CONF_BLOCK_PVT=115;
STR_CONF_PVTAWAY=116;
STR_CONF_CHAT_STARTSERVER=117;
STR_CONF_CHAT_STOPSERVER=118;
STR_FILESHARING=119;
STR_CONF_BLOCK_EMOTES=120;
STR_TORRENT_CHOKED=121;
STR_TORRENT_OPTUNCHOKE=122;
STR_TORRENT_INTERESTED=123;
STR_PERSONAL_MESSAGE=124;
STR_KEEP_ALIVE_CONNECTION=125;
STR_CONF_ACCEPTPORT=126;
STR_CONF_UPATONCE=127;
STR_CONF_UPPERUSER=128;
STR_CONF_UPBAND=129;
STR_CONF_INCREASEONIDLE=130;
STR_CONF_DLBAND=131;
STR_CONF_SAVEINFOLD=133;
STR_CONF_CHANGEFOLD=134;
STR_CONF_RESTOREDETAULDLFOLDER=135;
STR_HIT_START_TOBEGIN=136;
STR_CONF_START_SCAN=137;
STR_CONF_STOP_SCAN=138;
STR_CONF_CHECKALL=139;
STR_CONF_UNCHECKALL=140;
STR_CONF_MANUALFILESHARE_TIP=141;
STR_CONF_LEGEND=142;
STR_CONF_THISFOLDERNOTSHARE=143;
STR_CONF_THISFOLDERSHARED=144;
STR_CONF_CANTSUPERNODE=146;
STR_CONF_GENERAL_TIP=148;
STR_CONF_HKEYSETTINGS=149;
STR_CONF_AUTOCONNECT=150;
STR_CONF_STARTMINIM=151;
STR_CONF_CLOSEARESWHENSHUT=152;
STR_CONF_FILESHARE_TIP=153;
STR_CONT_SHOWCHATTASKBTN=158;
STR_CONF_MSNSONG=159;
STR_CONF_SHOWSPECCAPT=160;
STR_CONF_SHOWTRANPERCENT=161;
STR_CONF_BLOCKLARGEHINTS=162;
STR_CONF_PAUSEVIDEOWHENMOVING=163;
STR_CONF_ASKWHENCANCELLINGDL=164;
STR_CONF_NICKNAME=193;
STR_OK=195;
STR_CANCEL=196;
STR_APPLY=197;
STR_CLOSE=199;
STR_SEARCHFORTEXT=200;
STR_AUDIO_FILES=201;
STR_VIDEO_FILES=202;
STR_PLAYLIST_FILES=203;
STR_ANY_FILE=204;
PURGE_SEARCH_STR=205;
MORE_SEARCH_OPTION_STR=206;
LESS_SEARCH_OPTION_STR=208;
STR_FOUND=210;
STR_MAIN_MENU=211;
STR_MAIN_CONNECT_MENU=212;
STR_MAIN_DISCONNECT_MENU=213;
STR_MAIN_PREFERENCES_MENU=214;
STR_VIEW_SEARCHFIELD_MENU=217;
STR_LIBRARY=230;
STR_HINT_BTN_LIBRARY=231;
STR_SEARCH=232;
STR_HINT_BTN_SEARCH=233;
STR_TRANSFER=234;
STR_HINT_BTN_TRANSFER=235;
STR_WEB=236;
STR_HINT_BTN_WEB=237;
STR_SCREEN=238;
STR_HINT_BTN_SCREEN=239;
STR_CHAT=240;
STR_HINT_CHAT_BTN=241;
STR_FULLSCREEN=242;
STR_HINT_FULLSCREEN=243;
STR_ACTUALSIZE=248;
STR_HINT_ACTUALSIZE=249;
STR_EXIT_CHANNEL=250;
STR_REFRESH_LIST=251;
STR_JOIN_CHANNEL=252;
STR_PVT_HINT=253;
STR_BRS_HINT=254;
STR_HOST_A_CHANNEL=255;
STR_HINT_SHARESETTING=256;
STR_HINT_REFRESH_LIBRARY=257;
STR_FOLDERS=258;
STR_HINT_FOLDERS=259;
STR_DETAILS=260;
STR_HINT_DETAILS=261;
STR_HINT_SHAREUN=262;
STR_HINT_DELETEFILE=263;
STR_HINT_ADDTOPLAYLIST=264;
STR_RECONNECTTOHOST_MENU=265;
STR_FILE_MENU=266;
STR_SENDFILE_MENU=267;
STR_ACCEPTINCOMIN_MENU=268;
STR_SHOWTRANSFERS_MENU=269;
STR_HIDETRANSFERS_MENU=270;
STR_EDIT_MENU=271;
STR_SELECTALL_MENU=272;
STR_COPY_MENU=273;
STR_OPENINNOTEPAD_MENU=274;
STR_SETMEAWAY_MENU=276;
STR_BLOCKTHISHOST_MENU=277;
STR_CANCELLALL_MENU=278;
STR_CONNECTING_PLEASE_WAIT=279;
STR_CONNECTION_ESTABLISHED=280;
STR_CONNECTIONCLOSED=281;
STR_FEAILED_TO_CONNECT=282;
STR_OKOPENIT=283;
STR_GENERATING_PREVIEW=284;
STR_COPYINGFILE=285;
STR_MUTE=286;
STR_CANCEL_TRANSFER=289;
STR_HINT_CANCEL_TRANSFER=290;
STR_PAUSE_RESUME=291;
STR_HINT_PAUSE_RESUME=292;
STR_PLAYPREVIEW=293;
STR_HINT_PLAYPREVIEW=294;
STR_LOCATE_FILE=295;
STR_HINT_LOCATE_FILE=296;
STR_CLEARIDLE=297;
STR_HINT_CLEARIDLE=298;
STR_ADD_FILETOPLAYLIST=299;
STR_ADD_FOLDERTOPLAYLIST=300;
STR_DELETEFILEFROMPLAYLIST=301;
STR_CLEARPLAYLIST=302;
STR_LOADSAVEPLAYLIST=303;
STR_LOADPLAYLIST=305;
STR_SAVEPLAYLIST=306;
STR_REMOVEALL=307;
STR_REMOVESELECTED=308;
STR_SORT=309;
STR_ALPHASORTASCENDING=310;
STR_ALPHASORTDESCENDING=311;
STR_SHUFFLELIST=312;
STR_SHUFFLE=314;
STR_REPEAT=315;
STR_NEW_SEARCH=316;
STR_HINT_NEW_SEARCH=317;
STR_DOWNLOAD_BTN=318;
STR_HINT_DOWNLOAD_BTN=319;
STR_HINT_SEARCHFIELD_BTN=321;
STR_BACK=322;
STR_FORWARD=323;
STR_STOP=324;
STR_REFRESH=325;
STR_PLAY=326;
STR_PAUSE=327;
STR_PREVIOUS=328;
STR_NEXT=329;
STR_VOLUME=330;
STR_SHOW_PLAYLIST=331;
STR_CLOSE_PLAYLIST=332;
STR_PLAYLIST=335;
STR_HIDE_DETAILS=336;
STR_SHARED=337;
STR_HIDE_FOLDERS=338;
STR_IN_QUEUE=340;
STR_RELATED_ARTISTS=341;
STR_CONFIG_PERSONAL_DETAIL=342;
STR_CONFIG_TRANSFER=348;
STR_CONFIG_CHAT=350;
STR_NOT_CONNECTED=352;
STR_CONFIG_PRIVATE_MSG=354;
STR_CONFIG_FILESHARE=355;
STR_CONFIG_SHARE_SYSTEMSCAN=356;
STR_CONFIG_SHARE_MANUAL=357;
STR_CONFIG_SHARE_DOWNLOAD_FOLDER=358;
STR_CONFIG_GENERAL=359;
STR_CONFIG_NETWORK=360;
STR_FILES_CHAT=363;
STR_FILES_STAT=364;
STR_UNABLE_TO_CONNECT=365;
STR_LAST_SEEN=366;
STR_AVAILIBILITY=367;
STR_CONNECTING_TO_NETWORK=368;
STR_CONNECTING_TO_SUPERNODE=369;
STR_CONNECTED_HANDSHAKING=372;
STR_BROWSE_FAILED=373;
STR_SOCKET_CANALE_FAILED_HANDSHAKE_BLOCKING=375;
STR_NO_DIR_FOUND=376;
STR_SCAN_COMPLETED=377;
STR_DIRECTORY_FOUND=378;
STR_SEARCHING_THE_NET=379;
STR_SEARCHING_THE_NET_NO_RESULT=380;
STR_WOULD_YOU_LIKE_TO_CHOSE_NICK=381;
STR_CHOSE_YOUR_NICK=382;
STR_SURE_TO_ERASE_HISTORY=383;
STR_ERASE_HISTORY=384;
STR_WARNING_INCOMING_FILE=390;
STR_INCOMING_FILE=391;
STR_ARES_YOU_SURETOCANCEL=398;
STR_CANCEL_DL=399;
STR_DIRECTORY_FOUNDS=407;
STR_SOCKET_CANALE_FAILED_HANDSHAKE_RESET=408;
STR_SOCKET_CANALE_FAILED_HANDSHAKE_TIMEOUT=409;
STR_DISCONNECTED=410;
STR_DISCONNECTED_OVERFLOW=411;
STR_LOGGED_IN_RETRIEVING_LIST=412;
STR_TOPIC_CHANGED=413;
STR_SHARING_CHAT=414;
STR_FILES_HAS_JOINED=415;
STR_HAS_PARTED=416;
STR_DISCONNECTED_SEND_TIMEOUT=417;
STR_YOUR_ARE_MUZZLED=418;
STR_IMAGE_AND_VIDEOS=419;
STR_DOWNLOADED=420;
STR_HOSTED_CHANNEL=421;
STR_CHANNEL=422;
STR_SHARED_SIZE=423;
STR_TOTAL_SIZE=424;
STR_QUEUED_HINT=425;
STR_QUEUED_STATUS=426;
STR_CHANNEL_NAME=428;
STR_WRONG_NAME=429;
STR_PLEASE_CHOSE_ANOTHER_NAME=430;
STR_CONNECTING_TO_REMOTE_CHAN=434;
STR_KB_SEC=436;
STR_YOUR_ARE_ALREADY_HOSTING=437;
STR_THERES_NO_UNDO=439;
STR_WARNING_HD_ERASE=440;
STR_DELETE_FILE=441;
STR_DELETE_FILES=442;
STR_TRANSMITTED=443;
STR_TRANSFER_ALREADY_IN_PROGRESS=444;
STR_TAKE_A_LOOK_TO_TRANSFER_TAB=445;
STR_DUPLICATE_REQUEST=446;
STR_FILE_ALREADY_IN_LIBRARY=447;
STR_TAKE_A_LOOK_TO_YOUR_LIBRARY=448;
STR_DUPLICATE_FILE=449;
STR_ARES_IS_CONFIGURED_TO_BLOCK_THIS=450;
STR_FILTERED_MEDIATYPE=451;
STR_HIDE_ARES=452;
STR_SHOW_ARES=453;
STR_RESULT_FOR=454;
STR_RESULTS_FOR=455;
STR_PLEASE_WAIT=458;
STR_ALREADY_IN_LIB=459;
STR_ALREADY_DOWNLOADING=460;
STR_PROCESSING=461;
STR_PAUSED=462;
STR_LEECH_PAUSED=464;
STR_CANCELLED=465;
STR_COMPLETED=466;
STR_DOWNLOADING=467;
STR_IDLE=468;
STR_SEARCHING=469;
STR_CONNECTING=470;
STR_WARNING=471;
STR_MORE_SOURCES_NEEDED=47;
STR_USERS=473;
STR_CONNECTING_TO_REMOTE_USER=474;
STR_CHAT_CONNECTING=475;
STR_YOU=476;
STR_BANNED_HINT=477;
STR_SEARCHING_FOR=478;
STR_ANYTHING=479;
STR_HASH_PRIORITY=480;
STR_SERVER_QUEUE=481;
STR_HIGHEST=482;
STR_HIGHER=483;
STR_NORMAL=484;
STR_LOWER=485;
STR_LOWERST=486;
STR_IGNOREUN=487;
STR_MUZZLE=488;
STR_UNMUZZLE=489;
STR_BAN=490;
STR_UNBAN=491;
STR_KILL=492;
STR_SHARESETTING=494;
STR_OPENPLAY=495;
STR_OPENEXTERNAL=496;
STR_LOCATEFILE=497;
STR_FORTEXT=498;
STR_FINDMOREOFTHESAME=499;
STR_PAUSE_RESUMEALL=500;
STR_VIEW_PLAYLIST=501;
STR_QUITARES=502;
STR_BLOCKUSER=504;
STR_UNSHAREFILE=505;
STR_FITTOSCREEN=506;
STR_STOPSEARCH=508;
STR_SELECTALL_POPUP=509;
STR_COPYTOCLIP_POPUP=510;
STR_OPENINNOTEPAD_POPUP=511;
STR_SEARCHNOW=512;
STR_DATE=513;
STR_SHOW_QUEUE=514;
STR_HINT_SHOW_QUEUE=515;
STR_SHOW_UPLOAD=516;
STR_SHOW_UPLOAD_HINT=517;
STR_FILTER=518;
STR_REGULAR_VIEW=519;
STR_VIRTUAL_VIEW=520;
STR_VIRTUAL_VIEW_HINT=521;
STR_REGULAR_VIEW_HINT=522;
STR_USER=523;
STR_TITLE=524;
STR_ARTIST=525;
STR_QUALITY=526;
STR_YEAR=527;
STR_VERSION=528;
STR_FILETYPE=529;
STR_COLOURS=530;
STR_AUTHOR=531;
STR_FOLDER=532;
STR_LENGTH=533;
STR_RECEIVED=534;
STR_SENT=535;
STR_RESOLUTION=536;
STR_MEDIATYPE=537;
STR_LANGUAGE=538;
STR_CATEGORY=539;
STR_DOWNLOAD=540;
STR_SCAN_IN_PROGRESS=541;
STR_UPLOAD=542;
STR_UPLOADS=543;
STR_DOWNLOADS=544;
STR_ALBUM=545;
STR_COMPANY=546;
STR_DATE_COLUMN=547;
STR_REQUESTED_SIZE=548;
STR_FILE_SIZE=549;
STR_SIZE=550;
STR_FORMAT=551;
STR_FILENAME=552;
STR_URL=553;
STR_NAME=554;
STR_TOPIC=555;
STR_WELCOME_CHANNEL_TOPIC1=556;
STR_WELCOME_CHANNEL_TOPIC2=557;
STR_SPEED=558;
STR_GROUP_BY_ALBUM=559;
STR_GROUP_BY_AUTHOR=560;
STR_GROUP_BY_ARTIST=561;
STR_GROUP_BY_CATEGORY=562;
STR_GROUP_BY_COMPANY=563;
STR_GROUP_BY_GENRE=564;
STR_ALL=565;
STR_AUDIO=566;
STR_VIDEO=567;
STR_IMAGE=568;
STR_DOCUMENT=569;
STR_OTHER=570;
STR_SOFTWARE=571;
STR_SHARED_VIRTUAL_FOLDERS=581;
STR_SHARED_FOLDERS=582;
STR_SHARED_FILES=583;
STR_YOUR_LIBRARY=584;
STR_SEARCH_FOR_VIDEO_FILES=585;
STR_SEARCH_FOR_AUDIO_FILES=586;
STR_SEARCH_FOR_GENERIC_MEDIA=587;
STR_SEARCH_FOR_IMAGE_FILES=588;
STR_SEARCH_FOR_DOCUMENTS=589;
STR_SEARCH_FOR_SOFTWARES=590;
STR_TYPE=594;
STR_FILE=595;
STR_UPLOADED=596;
STR_STATUS=597;
STR_MEDIA_TYPE=598;
STR_LOCATION=599;
STR_REQUESTED=600;
STR_TODAY=601;
STR_TOTAL=602;
STR_GENRE=603;
STR_REMAINING=604;
STR_PROGRESS=605;
STR_TOTAL_TRANSFER_SPEED=606;
STR_COMMENT=607;
STR_ESTIMATED_TIME_REMAINING=608;
STR_VOLUME_TRANSMITTED=609;
STR_VOLUME_DOWNLOADED=610;
STR_NUMBER_OF_SOURCES=611;
STR_SOURCES=612;
STR_SOURCE=613;
STR_BANDWIDTH=614;
STR_UNKNOWN=615;
STR_UNKNOW_LOWER=616;
STR_OF=617;
STR_UPLOADING=618;
STR_ON=631;
STR_FROM=632;
STR_CLEARSSCREEN=683;
STR_AGE=693;
STR_SEX=694;
STR_COUNTRY=695;
STR_STATECITY=696;
STR_MALE=697;
STR_FEMALE=698;
STR_CONF_PREFERRED_LANGUAGE=699;
STR_CHANNELS=700;
STR_SHARED_PLUR=701;
STR_RETRIEVINGLIST_PLEASEWAIT=703;
//STR_LISTEMPTY_TRYLATER=704;
STR_SCANNING=705;
STR_SHARING=708;
STR_FILES=709;
STR_CONNECTED_AS=710;
STR_HIDESEARCHFIELD=711;
STR_AVAILABLE_SPACE=712;
STR_BROWSEINPROGRESS=713;
STR_BROWSECOMPLETED=714;
STR_POOR=715;
STR_AVERAGE=716;
STR_GOOD=717;
STR_VERYGOOD=718;
STR_HASH_HINT=719;
STR_HASH_CALCULATIONINPROGRESS=720;
STR_MEDIASEARCHINPROGRESS=721;
STR_CANCELUPLOAD=724;
STR_OTHERMIME=725;
STR_AUDIOMIME=726;
STR_SOFTWAREMIME=727;
STR_VIDEOMIME=728;
STR_DOCUMENTMIME=729;
STR_IMAGEMIME=730;
STR_STARTED=731;
STR_SOURCES_AVAILABLE=732;
STR_ACTUALPROGRESS=733;
STR_TOTALTRIES=734;
STR_RETRYINTERVAL=735;
STR_LASTREQUESTED=736;
STR_EXPIRATION=738;
STR_SAVEAS=741;
STR_ATLEAST=742;
STR_ATBEST=743;
STR_EQUALTO=744;
STR_CIRCA=745;
STR_LONGERTHAN=746;
STR_SHORTERTHAN=747;
STR_SMALLERTHAN=748;
STR_BIGGERTHAN=749;
STR_LOCAL_PAUSED=750;
STR_CONF_DLATONCE=751;
STR_UNKNOWNCOMMAND=752;
STR_CONFIG_PROXY=753; //proxy
STR_CONFIG_PROXY_NOTUSINGPROXY=755;
STR_CONFIG_PROXY_USING_SOCK4=756;
STR_CONFIG_PROXY_USING_SOCK5=757;
STR_CONFIG_PROXY_SOCKSADDR=758;
STR_CONFIG_PROXY_USERNAME=759;
STR_CONFIG_PROXY_PASSWORD=760;
STR_USERISBROWSINGYOU=761;
STR_DISALLOWPVTBROWSE=762;
STR_CHAT_WITH_USER=766;
STR_SENDFOLDER_MENU=767;
STR_OFFLINE=768;
STR_CHAT_SEARCH=769;
STR_GRANT_SLOT=770;
STR_BROWSE_FAILED_USER_OFFLINE=771;
STR_CHATROOM_SHAREABLE_TYPES=772;
STR_DOWNLOAD_HASHLINK=775;
STR_EXPORT_HASHLINK=777;
STR_ERROR_FILECORRUPTED=778;
STR_ERROR_FILELOCKED=779;
STR_GRANTBROWSE_MENU=785;
STR_DOWNLOADED_ON=787;
STR_RECENT_DOWNLOADS=788;
STR_SENDFULLPATH_BROWSE=789;
STR_OPENFOLDER=790;
STR_AUTOACCEPTFILES=791;
STR_CONFIG_HASHLINKS=795;
STR_CONFIGINCLUDEMAGNETLINKS=797;
STR_MAIN_CONTROL_PANEL=799;
STR_MAIN_CONTROL_PANEL_HINT=800;
STR_CONFIG_CHECKPROXY=801;
STR_CHECKPROXY_TESTING=802;
STR_CHECKPROXY_FAILED=803;
STR_CHECKPROXY_SUCCEDED=804;
STR_ANON_PROXY=805;
STR_ACTUAL_ANONPROXY=806;
STR_LOAD_PROXYIES=807;
STR_SAVE_LIST=808;
STR_USEMULTIPLEPROXIES=809;
STR_NEW_WINDOW=810;
STR_GO=811;
STR_CONF_SHOW_JP=812;
STR_FAVORITES=813;
STR_ADD_TOFAVORITES=814;
STR_LAST_JOINED=815;
STR_SEARCH_FOR_OTHERS=816;
STR_REMOVE_SOURCE=817;//2956+
STR_WARN_DANGEROUS_FILEEXT=818; //2961+
STR_BUSY=819;
STR_CONFIG_CHATROOM=820;
STR_PUSHING=821;
STR_WAITINGFORPEERACK=822;
STR_REQUESTING=823;
STR_AUTOJOIN=824;
STR_CONNECTED=825;
STR_AUTOADD_TO_FAVORITES=826;
STR_BITTORRENT_ASSOCIATION=827;
STR_ACTIVE=828;
STR_RIPTODISK=829;
STR_TUNEIN=830;
STR_HANDLE_M3UANDPLS=831;
STR_DIRECTORY_SHOUTCAST=832;
//STR_CONF_AUTOCLOSEROOM=834;
country_strings:array[1..233] of string = (
'Afghanistan',
'Albania',
'Algeria',
'Andorra',
'Angola',
'Anguilla',
'Antarctica',
'Antigua and Barbuda',
'Argentina',
'Armenia',
'Aruba',
'Australia',
'Austria',
'Azerbaijan',
'Bahamas',
'Bahrain',
'Bangladesh',
'Barbados',
'Belarus',
'Belgium',
'Belize',
'Benin',
'Bermuda',
'Bhutan',
'Bolivia',
'Bosnia and Herzegovina',
'Botswana',
'Brazil',
'Brunei',
'Bulgaria',
'Burkina Faso',
'Burundi',
'Cambodia',
'Cameroon',
'Canada',
'Cape Verde',
'Cayman Islands',
'Central African Republic',
'Chad',
'Chile',
'China',
'Christmas Islands',
'Cocos Islands',
'Colombia',
'Comoros',
'Congo',
'Congo',
'Cook Islands',
'Costa Rica',
'Croatia',
'Cuba',
'Cyprus',
'Czech Republic',
'Denmark',
'Djibouti',
'Dominica',
'Dominican Republic',
'Dutch antilles',
'EastTimor',
'Ecuador',
'Egypt',
'El Salvador',
'Equatorial Guinea',
'Eritrea',
'Estonia',
'Ethiopia',
'Falkland Islands',
'Faroe Islands',
'Fiji Islands',
'Finland',
'France',
'French Polynesia',
'Gabon',
'Gambia',
'Gaza',
'Georgia',
'Germany',
'Ghana',
'Gibraltar',
'Greece',
'Greenland',
'Grenada',
'Guadaloupe',
'Guatemala',
'Guernsey',
'Guinea',
'Guinea-Bissau',
'Guyana',
'Guyana',
'Haiti',
'Honduras',
'Hong Kong',
'Hungary',
'Iceland',
'India',
'Indonesia',
'Iran',
'Iraq',
'Ireland',
'Isle of Man',
'Israel',
'Italy',
'Ivory coast',
'Jamaica',
'Japan',
'Jersey',
'Jordan',
'Kazakhstan',
'Kenya',
'Kiribati',
'Kuwait',
'Kyrgyzstan',
'Laos',
'Latvia',
'Lebanon',
'Lesotho',
'Liberia',
'Libya',
'Liechtenstein',
'Lithuania',
'Luxembourg',
'Macao',
'Macedonia',
'Madagascar',
'Malawi',
'Malaysia',
'Maldives',
'Mali',
'Malta',
'Marshall Islands',
'Martinique',
'Mauritania',
'Mauritius',
'Mayotte',
'Mexico',
'Micronesia',
'Moldova',
'Monaco',
'Mongolia',
'Montserrat',
'Morocco',
'Mozambique',
'Myanmar',
'Namibia',
'Nauru',
'Nepal',
'Netherlands',
'New Caledonia',
'New Zealand',
'Nicaragua',
'Niger',
'Nigeria',
'Niue',
'Norfolk Island',
'North Korea',
'Norway',
'Oman',
'Pakistan',
'Palau',
'Panama',
'Papua New-Guinea',
'Paraguay',
'Peru',
'Philippines',
'Pitcairn island',
'Poland',
'Portugal',
'Puerto Rico',
'Qatar',
'Reunion',
'Romania',
'Russia',
'Rwanda',
'Samoa',
'San Marino',
'Sao Tome and Principe',
'Saudi Arabia',
'Senegal',
'Seychelles',
'Sierra Leone',
'Singapore',
'Slovakia',
'Slovenia',
'Solomon island',
'Somalia',
'South Africa',
'South Georgia Island and South Sandwich Islands',
'South Korea',
'Spain',
'Sri Lanka',
'St Helens',
'St Kitts and Nevis',
'St Lucia',
'St Pierre and Miquelon',
'St Vincent and the Grenadines',
'Sudan',
'Suriname',
'Svalbard',
'Swaziland',
'Sweden',
'Switzerland',
'Syria',
'Taiwan',
'Tajikistan',
'Tanzania',
'Thailand',
'Togo',
'Tokelau',
'Tonga',
'Trinidad and Tobago',
'Tunisia',
'Turkey',
'Turkmenistan',
'Turks and Caicos Islands',
'Tuvalu',
'Uganda',
'Ukraine',
'United Arab Emirates',
'United Kingdom',
'United States',
'Uruguay',
'Uzbekistan',
'Vanuatu',
'Venezuela',
'Vietnam',
'Virgin Islands',
'Wallis and Futuna',
'West Bank',
'Western Sahara',
'Yemen',
'Yugoslavia',
'Zambia',
'Zimbabwe'
);
//function parse_lines_lang(superwstr:widestring):integer;
procedure localiz_loadlanguage;
//procedure load_default_language_english;
//procedure mainGui_apply_language;
//procedure mainGui_apply_languageFirst;
//procedure mainGui_update_localiz_headers;
function GetLangStringA(LangStrId:integer):string;
function GetLangStringW(LangStrId:integer):widestring;
procedure FreeLanguageDb;
procedure CreateLanguageDb;
procedure InitLanguageDb;
function getDefLang:widestring;
function GetOsLanguage:string;
//procedure mainGui_enumlangs;
//procedure SetCurrentLanguage_Index;
var
db_language:^Tdb_Language=nil;
implementation
uses
vars_global,{ufrmmain,}
helper_registry;
function GetLangStringA(LangStrId:integer):string;
begin
result:='';
if ((LangStrId>MAX_TRANSLATIONTABLE_INDEX) or
(LangStrId<MIN_TRANSLATIONTABLE_INDEX)) then exit;
if ((defLangEnglish) or (db_language=nil)) then result:=db_english_lang[LangStrId]
else begin
result:=widestrtoutf8str(db_language[LangStrId]);
if length(result)=0 then result:=db_english_lang[LangStrId];
end;
end;
function GetLangStringW(LangStrId:integer):widestring;
begin
result:='';
if ((LangStrId>MAX_TRANSLATIONTABLE_INDEX) or
(LangStrId<MIN_TRANSLATIONTABLE_INDEX)) then exit;
if ((defLangEnglish) or (db_language=nil)) then result:=db_english_lang[LangStrId]
else begin
result:=db_language[LangStrId];
if length(Result)=0 then result:=db_english_lang[LangStrId];
end;
end;
{
procedure mainGui_update_localiz_headers;
var
i,h:integer;
precord_chat:precord_canale_chat_visual;
pvt:precord_pvt_chat_visual;
begin
with ares_frmmain do begin
with treeview_download.header do begin
columns[0].text:=GetLangStringW(STR_FILE);
columns[1].text:=GetLangStringW(STR_TYPE);
columns[2].text:=GetLangStringW(STR_USER);
columns[3].text:=GetLangStringW(STR_STATUS);
columns[4].text:=GetLangStringW(STR_PROGRESS);
columns[5].text:=GetLangStringW(STR_SPEED);
columns[6].text:=GetLangStringW(STR_REMAINING);
columns[7].text:=GetLangStringW(STR_DOWNLOADED);
end;
with treeview_upload.header do begin
columns[0].text:=GetLangStringW(STR_FILE);
columns[1].text:=GetLangStringW(STR_TYPE);
columns[2].text:=GetLangStringW(STR_USER);
columns[3].text:=GetLangStringW(STR_STATUS);
columns[4].text:=GetLangStringW(STR_PROGRESS);
columns[5].text:=GetLangStringW(STR_SPEED);
columns[6].text:=GetLangStringW(STR_REMAINING);
columns[7].text:=GetLangStringW(STR_UPLOADED);
end;
with treeview_queue.header do begin
columns[0].text:=GetLangStringW(STR_USER);
columns[1].text:=GetLangStringW(STR_FILE);
columns[2].text:=GetLangStringW(STR_SIZE);
end;
with listview_chat_channel.Header do
if columns[0].text<>'' then begin
columns[0].text:=GetLangStringW(STR_NAME);
columns[1].text:=GetLangStringW(STR_LANGUAGE);
columns[2].text:=GetLangStringW(STR_USERS);
columns[3].text:=GetLangStringW(STR_TOPIC);
end;
with treeview_chat_favorites.header do begin
columns[0].text:=GetLangStringW(STR_NAME);
columns[1].text:=GetLangStringW(STR_LAST_JOINED);
columns[2].text:=GetLangStringW(STR_TOPIC);
end;
end;
if vars_global.list_chatchan_visual<>nil then
for i:=0 to vars_global.list_chatchan_visual.count-1 do begin
precord_chat:=vars_global.list_chatchan_visual[i];
with precord_chat^.listview.header do begin
Columns[0].text:=GetLangStringW(STR_USER);
Columns[1].text:=GetLangStringW(STR_FILES_CHAT);
Columns[2].text:=GetLangStringW(STR_SPEED);
end;
precord_chat^.buttonToggleTask.hint:=GetLangStringA(STR_CONT_SHOWCHATTASKBTN);
precord_chat^.urlPanel.CaptionLeft:=precord_chat^.buttonToggleTask.left+precord_chat^.buttonToggleTask.width+6;
if precord_chat^.lista_pvt<>nil then
for h:=0 to precord_chat^.lista_pvt.count-1 do begin
pvt:=precord_chat^.lista_pvt[h];
pvt^.buttonToggleTask.hint:=precord_chat^.buttonToggleTask.caption;
end;
end;
end;
procedure mainGui_apply_languageFirst;
var
pnl:TCometPagePanel;
begin
with ares_frmmain do begin
pnl:=tabs_pageview.panels[IDTAB_LIBRARY];
pnl.btncaption:=GetLangStringW(STR_LIBRARY);
pnl:=tabs_pageview.panels[IDTAB_SCREEN];
pnl.btncaption:=GetLangStringW(STR_SCREEN);
pnl:=tabs_pageview.panels[IDTAB_SEARCH];
pnl.btncaption:=GetLangStringW(STR_SEARCH);
pnl:=tabs_pageview.panels[IDTAB_TRANSFER];
pnl.btncaption:=GetLangStringW(STR_TRANSFER);
pnl:=tabs_pageview.panels[IDTAB_CHAT];
pnl.btncaption:=GetLangStringW(STR_CHAT);
pnl:=tabs_pageview.panels[IDTAB_OPTION];
pnl.btncaption:=GetLangStringW(STR_MAIN_CONTROL_PANEL);
btn_start_search.caption:=GetLangStringW(STR_SEARCHNOW);
btn_stop_search.caption:=GetLangStringW(STR_STOPSEARCH);
lbl_srcmime_all.caption:=GetLangStringW(STR_ALL);
lbl_srcmime_audio.caption:=GetLangStringW(STR_AUDIO);
lbl_srcmime_video.caption:=GetLangStringW(STR_VIDEO);
lbl_srcmime_image.caption:=GetLangStringW(STR_IMAGE);
lbl_srcmime_document.caption:=GetLangStringW(STR_DOCUMENT);
lbl_srcmime_software.caption:=GetLangStringW(STR_SOFTWARE);
lbl_srcmime_other.caption:=GetLangStringW(STR_OTHER);
helper_search_gui.searchpanel_invalidatemimeicon(0);
lbl_capt_search.caption:=GetLangStringW(STR_SEARCH_FOR_GENERIC_MEDIA);
end;
end;
procedure mainGui_apply_language;
var
pnl:TCometPagePanel;
begin
ares_FrmMain.caption:=' '+appname+' '+versioneares;
mainGui_update_localiz_headers;
with ares_frmmain do begin
pnl:=tabs_pageview.panels[IDTAB_LIBRARY];
pnl.btncaption:=GetLangStringW(STR_LIBRARY);
pnl:=tabs_pageview.panels[IDTAB_SCREEN];
pnl.btncaption:=GetLangStringW(STR_SCREEN);
pnl:=tabs_pageview.panels[IDTAB_SEARCH];
pnl.btncaption:=GetLangStringW(STR_SEARCH);
pnl:=tabs_pageview.panels[IDTAB_TRANSFER];
pnl.btncaption:=GetLangStringW(STR_TRANSFER);
pnl:=tabs_pageview.panels[IDTAB_CHAT];
pnl.btncaption:=GetLangStringW(STR_CHAT);
pnl:=tabs_pageview.panels[IDTAB_OPTION];
pnl.btncaption:=GetLangStringW(STR_MAIN_CONTROL_PANEL);
//options
btn_opt_connect.caption:=GetLangStringA(STR_MAIN_CONNECT_MENU);
btn_opt_connect.hint:=GetLangStringA(STR_MAIN_CONNECT_MENU);
btn_opt_disconnect.caption:=GetLangStringA(STR_MAIN_DISCONNECT_MENU);
btn_opt_disconnect.Hint:=GetLangStringA(STR_MAIN_DISCONNECT_MENU);
if frm_settings<>nil then frm_settings.apply_language;
//chat btns
btn_chat_refchanlist.caption:=GetLangStringA(STR_REFRESH_LIST);
btn_chat_refchanlist.hint:=btn_chat_refchanlist.caption;
btn_chat_join.caption:=GetLangStringA(STR_JOIN_CHANNEL);
btn_chat_join.hint:=btn_chat_join.caption;
btn_chat_host.caption:=GetLangStringA(STR_HOST_A_CHANNEL);
btn_chat_host.hint:=btn_chat_host.caption;
btn_chat_fav.caption:=GetLangStringA(STR_FAVORITES);
btn_chat_fav.hint:=btn_chat_fav.caption;
pnl_chat_fav.capt:=GetLangStringW(STR_FAVORITES);
(panel_chat.Panels[0] as TCometPagePanel).btncaption:=GetLangStringW(STR_CHANNELS);
with combo_chat_srctypes do begin
with items do begin
clear;
add(GetLangStringW(STR_ALL));
add(GetLangStringW(STR_AUDIO));
add(GetLangStringW(STR_VIDEO));
add(GetLangStringW(STR_IMAGE));
add(GetLangStringW(STR_DOCUMENT));
add(GetLangStringW(STR_SOFTWARE));
add(GetLangStringW(STR_OTHER));
end;
itemindex:=0;
end;
btn_chat_search.caption:=GetLangStringA(STR_SEARCH);
btn_chat_search.hint:=GetLangStringA(STR_CHAT_SEARCH);
//screen
//library
btn_lib_virtual_view.caption:=GetLangStringA(STR_VIRTUAL_VIEW);
btn_lib_virtual_view.hint:=GetLangStringA(STR_VIRTUAL_VIEW_HINT);
btn_lib_regular_view.caption:=GetLangStringA(STR_REGULAR_VIEW);
btn_lib_regular_view.hint:=GetLangStringA(STR_REGULAR_VIEW_HINT);
btn_lib_regular_view.left:=btn_lib_virtual_view.left+btn_lib_virtual_view.width+5;
btn_lib_refresh.caption:='';
btn_lib_refresh.hint:=GetLangStringA(STR_HINT_REFRESH_LIBRARY);
btn_lib_toggle_folders.caption:=GetLangStringA(STR_FOLDERS);
btn_lib_toggle_folders.hint:=GetLangStringA(STR_HINT_FOLDERS);
btn_lib_toggle_details.caption:=GetLangStringA(STR_DETAILS);
btn_lib_toggle_details.hint:=GetLangStringA(STR_HINT_DETAILS);
btn_lib_delete.caption:='';
btn_lib_delete.hint:=GetLangStringA(STR_HINT_DELETEFILE);
btn_lib_addtoplaylist.caption:='';
btn_lib_addtoplaylist.hint:=GetLangStringA(STR_HINT_ADDTOPLAYLIST);
openfolder1.caption:=GetLangStringW(STR_OPENFOLDER);
//transfer
btn_tran_cancel.caption:=GetLangStringA(STR_CANCEL_TRANSFER);
btn_tran_cancel.hint:=GetLangStringA(STR_HINT_CANCEL_TRANSFER);
btn_tran_play.caption:=GetLangStringA(STR_PLAYPREVIEW);
btn_tran_play.hint:=GetLangStringA(STR_HINT_PLAYPREVIEW);
btn_tran_locate.caption:=GetLangStringA(STR_LOCATE_FILE);
btn_tran_locate.hint:=GetLangStringA(STR_HINT_LOCATE_FILE);
btn_tran_clearidle.caption:=GetLangStringA(STR_CLEARIDLE);
btn_tran_clearidle.hint:=GetLangStringA(STR_HINT_CLEARIDLE);
//search
// panel_search.Headercaption:=' '+GetLangStringW(STR_SEARCH);
//btn_src_hide.hint:=GetLangStringA(STR_HIDESEARCHFIELD);
pnl:=pagesrc.panels[0];
pnl.btncaption:=GetLangStringW(STR_NEW_SEARCH);
with combo_sel_quality.items do begin
clear;
add('');
add(GetLangStringW(STR_ATBEST));
add(GetLangStringW(STR_EQUALTO));
add(GetLangStringW(STR_ATLEAST));
end;
with combo_sel_duration.items do begin
clear;
add('');
add(GetLangStringW(STR_SHORTERTHAN));
add(GetLangStringW(STR_CIRCA));
add(GetLangStringW(STR_LONGERTHAN));
end;
with combo_sel_size.items do begin
clear;
add('');
add(GetLangStringW(STR_SMALLERTHAN));
add(GetLangStringW(STR_CIRCA));
add(GetLangStringW(STR_BIGGERTHAN));
end;
//vari
btn_playlist_close.hint:=GetLangStringA(STR_CLOSE_PLAYLIST);
// panel_details_library.HeaderCaption:=' '+GetLangStringW(STR_DETAILS);
// btn_lib_hidedetails.hint:=GetLangStringA(STR_HIDE_DETAILS);
btn_tran_toggle_queup.caption:=GetLangStringA(STR_SHOW_QUEUE);
btn_tran_toggle_queup.hint:=GetLangStringA(STR_HINT_SHOW_QUEUE);
lbl_lib_fileshared.caption:=GetLangStringW(STR_SHARED);
//popups chat
Sendaprivatemessage1.caption:=GetLangStringW(STR_CHAT_WITH_USER);
SendPrivateMessage1.caption:=GetLangStringW(STR_PVT_HINT);
Chat4.caption:=Sendaprivatemessage1.caption;
Chat5.caption:=Sendaprivatemessage1.caption;
SendPrivate2.caption:=SendPrivateMessage1.caption;
Sendprivate1.caption:=SendPrivateMessage1.caption;
Browse1.caption:=GetLangStringW(STR_BRS_HINT);
Browse2.Caption:=Browse1.caption;
All1.caption:=GetLangStringW(STR_ALL);
Audio1.caption:=GetLangStringW(STR_AUDIO);
Video1.caption:=GetLangStringW(STR_VIDEO);
Image1.caption:=GetLangStringW(STR_IMAGE);
Document1.caption:=GetLangStringW(STR_DOCUMENT);
Software1.caption:=GetLangStringW(STR_SOFTWARE);
other1.caption:=GetLangStringW(STR_OTHER);
All2.caption:=All1.caption;
Audio2.caption:=audio1.caption;
Video2.caption:=Video1.caption;
Image3.caption:=Image1.caption;
Document2.caption:=Document1.caption;
Software2.caption:=Software1.caption;
other2.caption:=Other1.caption;
IgnoreUnignore1.caption:=GetLangStringW(STR_IGNOREUN);
Muzzle1.caption:=GetLangStringW(STR_MUZZLE);
UnMuzzle1.caption:=GetLangStringW(STR_UNMUZZLE);
Ban1.caption:=GetLangStringW(STR_BAN);
Ban2.caption:=ban1.caption;
Ban3.caption:=ban1.caption;
copynickname1.caption:=GetLangStringW(STR_COPY_MENU);
Unban1.caption:=GetLangStringW(STR_UNBAN);
Disconnect2.caption:=GetLangStringW(STR_KILL);
Kill1.caption:=Disconnect2.caption;
Kill2.caption:=disconnect2.caption;
//popup library popup1
AddRemovefolderstosharelist2.caption:=GetLangStringW(STR_SHARESETTING);
ShareUn1.caption:=GetLangStringW(STR_HINT_SHAREUN);
OpenPlay1.caption:=GetLangStringW(STR_OPENPLAY);
Openwithexternalplayer2.caption:=GetLangStringW(STR_OPENEXTERNAL);
Locate1.caption:=GetLangStringW(STR_LOCATEFILE);
DeleteFile2.caption:=GetLangStringW(STR_HINT_DELETEFILE);
AddtoPlaylist4.caption:=GetLangStringW(STR_ADD_FOLDERTOPLAYLIST);//add to playlist da treeview1
AddtoPlaylist5.caption:=AddtoPlaylist4.caption;
Addtoplaylist1.caption:=GetLangStringW(STR_HINT_ADDTOPLAYLIST);
Findmoreofthesameartist1.caption:=GetLangStringW(STR_FINDMOREOFTHESAME);
Artist1.caption:=GetLangStringW(STR_ARTIST);
Genre1.caption:=GetLangStringW(STR_GENRE);
ExportHashLink1.caption:=GetLangStringW(STR_EXPORT_HASHLINK);
ExportHashlink2.caption:=ExportHashLink1.caption;
ExportHashlink3.caption:=ExportHashLink1.caption;
ExportHashlink4.caption:=ExportHashLink1.caption;
//popup download popup3
chat2.caption:=GetLangStringW(STR_CHAT_WITH_USER);
OpenPreview2.caption:=GetLangStringW(STR_PLAYPREVIEW);
Openexternal1.caption:=GetLangStringW(STR_OPENEXTERNAL);
Addtoplaylist2.caption:=GetLangStringW(STR_HINT_ADDTOPLAYLIST);
Locate2.caption:=GetLangStringW(STR_LOCATEFILE);
Findmorefromthesame2.caption:=GetLangStringW(STR_FINDMOREOFTHESAME);
Artist3.caption:=GetLangStringW(STR_ARTIST);
Genre3.caption:=GetLangStringW(STR_GENRE);
PauseResume1.caption:=GetLangStringW(STR_PAUSE_RESUME);
PauseallUnpauseAll1.caption:=GetLangStringW(STR_PAUSE_RESUMEALL);
Cancel2.caption:=GetLangStringW(STR_CANCEL_TRANSFER);
ClearIdle2.caption:=GetLangStringW(STR_CLEARIDLE);
RemoveSource1.caption:=GetLangStringW(STR_REMOVE_SOURCE);
//popup tray popup17
tray_Play.caption:=GetLangStringW(STR_PLAY);
tray_Pause.caption:=GetLangStringW(STR_PAUSE);
tray_Stop.caption:=GetLangStringW(STR_STOP);
tray_showPlaylist.caption:=GetLangStringW(STR_VIEW_PLAYLIST);
tray_quit.caption:=GetLangStringW(STR_QUITARES);
if vars_global.app_minimized then tray_Minimize.caption:=GetLangStringW(STR_SHOW_ARES)
else tray_Minimize.caption:=GetLangStringW(STR_HIDE_ARES);
//popup menu lista canali popupmenu_list_channel
Joinchannel1.caption:=GetLangStringW(STR_JOIN_CHANNEL);
saveas1.caption:=GetLangStringW(STR_OPENINNOTEPAD_MENU);
Exporthashlink5.caption:=GetLangStringW(STR_EXPORT_HASHLINK);
AddtoFavorites1.caption:=GetLangStringW(STR_ADD_TOFAVORITES);
//popup chat favorites
Remove1.caption:=GetLangStringW(STR_REMOVESELECTED);
Join1.caption:=GetLangStringW(STR_JOIN_CHANNEL);
autojoin1.caption:=GetLangStringW(STR_AUTOJOIN);
Exporthashlink6.caption:=GetLangStringW(STR_EXPORT_HASHLINK);
//popupmenu caption player
OpenExternal3.caption:=GetLangStringW(STR_OPENEXTERNAL);
Locate3.caption:=GetLangStringW(STR_LOCATEFILE);
Addtoplaylist6.caption:=GetLangStringW(STR_HINT_ADDTOPLAYLIST);
new1.caption:=GetLangStringW(STR_TUNEIN);
Riptodisk1.caption:=GetLangStringW(STR_RIPTODISK);
Locate4.caption:=Locate3.caption;
Enable1.caption:=GetLangStringW(STR_ACTIVE);
ExportHashlink7.caption:=ExportHashLink1.caption;
directory1.caption:=GetLangStringW(STR_DIRECTORY_SHOUTCAST);
//queued menu PopupMenu7
Blockhost1.caption:=GetLangStringW(STR_BLOCKUSER);
Chatwithuser1.caption:=GetLangStringW(STR_CHAT_WITH_USER);
GrantSlot1.caption:=GetLangStringW(STR_GRANT_SLOT);
MenuItem8.caption:=GetLangStringW(STR_OPENPLAY);
MenuItem9.caption:=GetLangStringW(STR_OPENEXTERNAL);
MenuItem10.caption:=GetLangStringW(STR_LOCATEFILE);
MenuItem11.caption:=GetLangStringW(STR_HINT_ADDTOPLAYLIST);
//PopupMenuvideo
Fullscreen2.caption:=GetLangStringW(STR_FULLSCREEN);
fittoscreen1.caption:=GetLangStringW(STR_FITTOSCREEN);
Originalsize1.caption:=GetLangStringW(STR_ACTUALSIZE);
Play1.caption:=GetLangStringW(STR_PLAY);
Pause1.caption:=GetLangStringW(STR_PAUSE);
Stop2.caption:=GetLangStringW(STR_STOP);
Volume1.caption:=GetLangStringW(STR_VOLUME);
//FlatButton6.caption:=STR_CLOSE;
// popup uploads PopupMenu5
Chat1.caption:=GetLangStringW(STR_CHAT_WITH_USER);
GrantSlot2.caption:=GetLangStringW(STR_GRANT_SLOT);
RemoveSource2.caption:=RemoveSource1.caption;
OpenPlay2.caption:=GetLangStringW(STR_OPENPLAY);
OpenExternal2.caption:=GetLangStringW(STR_OPENEXTERNAL);
LocateFile1.caption:=GetLangStringW(STR_LOCATEFILE);
Addtoplaylist3.caption:=GetLangStringW(STR_HINT_ADDTOPLAYLIST);
Cancel1.caption:=GetLangStringW(STR_CANCELUPLOAD);
BanUser1.caption:=GetLangStringW(STR_BLOCKUSER);
ClearIdle1.caption:=GetLangStringW(STR_CLEARIDLE);
//poup search view PopupMenu2
Play3.caption:=GetLangStringW(STR_PLAY);
Download1.caption:=GetLangStringW(STR_DOWNLOAD);
Findmorefromthesame1.caption:=GetLangStringW(STR_FINDMOREOFTHESAME);
Artist2.caption:=GetLangStringW(STR_ARTIST);
Genre2.caption:=GetLangStringW(STR_GENRE);
NewSearch1.caption:=GetLangStringW(STR_NEW_SEARCH);
Stopsearch1.caption:=GetLangStringW(STR_STOPSEARCH);
//popup chat room PopupMenu_chat_memo
SelectAll1.caption:=GetLangStringW(STR_SELECTALL_POPUP);
CopytoClipboard1.caption:=GetLangStringW(STR_COPYTOCLIP_POPUP);
Openinnotepad1.caption:=GetLangStringW(STR_OPENINNOTEPAD_POPUP);
ClearScreen1.caption:=GetLangStringW(STR_CLEARSSCREEN);
Download2.caption:=GetLangStringW(STR_DOWNLOAD);
Grantupslot1.caption:=GetLangStringW(STR_GRANT_SLOT);
//chat browse listview
Findmoreofthesame1.caption:=GetLangStringW(STR_FINDMOREOFTHESAME);
Artist4.caption:=GetLangStringW(STR_ARTIST);
Genre4.caption:=GetLangStringW(STR_GENRE);
//chat popoup folder dl
Download3.caption:=GetLangStringW(STR_DOWNLOAD);
Download4.caption:=Download3.caption;
Download5.caption:=download3.Caption;
//pannello search
lbl_srcmime_all.caption:=GetLangStringW(STR_ALL);
lbl_srcmime_audio.caption:=GetLangStringW(STR_AUDIO);
lbl_srcmime_video.caption:=GetLangStringW(STR_VIDEO);
lbl_srcmime_image.caption:=GetLangStringW(STR_IMAGE);
lbl_srcmime_document.caption:=GetLangStringW(STR_DOCUMENT);
lbl_srcmime_software.caption:=GetLangStringW(STR_SOFTWARE);
lbl_srcmime_other.caption:=GetLangStringW(STR_OTHER);
Btn_start_search.caption:=GetLangStringW(STR_SEARCHNOW);
btn_stop_search.caption:=GetLangStringW(STR_STOPSEARCH);
//lbl_src_hint.caption:=GetLangStringW(STR_FORTEXT);
label_back_src.caption:=GetLangStringW(STR_BACK);
end;
ufrmmain.ares_frmmain.radiosearchmimeclick(nil);
//details library
with ares_frmmain do begin
lbl_title_detlib.caption:=GetLangStringW(STR_TITLE);
lbl_descript_detlib.caption:=GetLangStringW(STR_COMMENT);
lbl_url_detlib.caption:=GetLangStringW(STR_URL);
lbl_categ_detlib.caption:=GetLangStringW(STR_CATEGORY);
lbl_author_detlib.caption:=GetLangStringW(STR_AUTHOR);
lbl_album_detlib.caption:=GetLangStringW(STR_ALBUM);
lbl_language_detlib.caption:=GetLangStringW(STR_LANGUAGE);
lbl_year_detlib.caption:=GetLangStringW(STR_DATE);
//filtro in library narrow list
edit_lib_search.glyphindex:=12;
if edit_lib_search.text='' then edit_lib_search.text:=GetLangStringW(STR_SEARCH);
if edit_src_filter.text='' then edit_src_filter.text:=GetLangStringW(STR_FILTER);
// lbl_chat_filter.caption:=GetLangStringW(STR_FILTER)+':';
end;
mainGui_sizectrls;
end;
procedure SetCurrentLanguage_Index;
var
Ind:integer;
deflang:widestring;
reg:tregistry;
begin
reg:=tregistry.create;
with reg do begin
openkey(areskey,true);
deflang:=utf8strtowidestr(hexstr_to_bytestr(ReadString('General.Language')));
//if lowercase(deflang)='spanishla' then deflang:='Spanish';
closekey;
destroy;
end;
if deflang='' then deflang:='English';
ind:=frm_settings.Combo_opt_gen_gui_lang.items.indexof(deflang);
if ind<>-1 then frm_settings.Combo_opt_gen_gui_lang.itemindex:=ind
else begin
ind:=frm_settings.Combo_opt_gen_gui_lang.items.indexof('English');
if ind<>-1 then frm_settings.Combo_opt_gen_gui_lang.itemindex:=ind;
end;
end;
procedure mainGui_enumlangs;
var
doserror:integer;
dirinfo:ares_types.tsearchrecW;
str:widestring;
begin
//get available langs
with frm_settings do begin
Combo_opt_gen_gui_lang.items.clear;
Combo_opt_gen_gui_lang.items.add('English');
doserror:=helper_diskio.findfirstW(app_path+'\Lang\*.txt',FAANYFILE,dirinfo);
while (doserror=0) do begin
str:=dirinfo.name;
delete(str,length(str)-3,4); //remove ext .txt
if Combo_opt_gen_gui_lang.items.indexof(str)=-1 then Combo_opt_gen_gui_lang.items.add(str);
doserror:=helper_diskio.findnextW(dirinfo);
end;
helper_diskio.findcloseW(dirinfo);
combo_opt_gen_gui_lang.Sorted:=true;
SetCurrentLanguage_Index;
end;
end;
}
function GetOsLanguage:string;
function PRIMARYLANGID(lgid : Word) : LongInt;
begin
result := lgid and $3FF;
end;
function SUBLANGID(lgid : Word) : LongInt;
begin
result := lgid shr 10;
end;
function MAKELANGID(sPrimaryLanguage : Word; sSubLanguage : Word) : Word;
begin
result := (sSubLanguage shl 10) or
sPrimaryLanguage;
end;
var
ID:LangID;
lang,
sub:longint;
begin
result:='English';
try
ID := GetSystemDefaultLangID;
lang:=PRIMARYLANGID(id);
sub:=SUBLANGID(id);
case lang of
$01:result:='Arabic';
$04:result:='Chinese';
$05:result:='Czech';
$06:result:='Dansk';
$13:result:='Dutch';
$0b:result:='Finnish';
$0c:result:='French';
$07:result:='German';
$10:result:='Italian';
$11:result:='Japanese';
$40:result:='Kyrgyz';
$15:result:='Polish';
$16:result:='Portugues';
$1b:result:='Slovak';
$0a:if sub=1 then result:='Spanish'
else result:='Spanish';//'SpanishLa';
$1d:result:='Swedish';
$1f:result:='Turkish'
else result:='English';
end;
except
end;
end;
function getDefLang:widestring;
var
reg:tregistry;
stream:THandleStream;
begin
reg:=tregistry.create;
with reg do begin
openkey(areskey,true);
result:=utf8strtowidestr(hexstr_to_bytestr(ReadString('General.Language')));
//if lowercase(deflang)='spanishla' then deflang:='Spanish';
closekey;
destroy;
end;
if result='' then begin
result:=GetOsLanguage;
set_regstring('General.Language',bytestr_to_hexstr(result));
exit;
end;
if not FileExists(app_path+'\Lang\'+result+'.txt') then begin
result:='English';
exit;
end;
stream:=helper_diskio.myfileopen(app_path+'\Lang\'+result+'.txt',ARES_READONLY_BUT_SEQUENTIAL);
if stream=nil then begin
result:='English';
exit;
end;
FreeHandleStream(stream);
end;
procedure localiz_loadlanguage;
var
stream:thandlestream;
buffer:array[0..2047] of char;
previous_len:integer;
utf8str:string;
len:integer;
deflang:widestring;
begin
//deflang:=ares_frmmmain.Combo_opt_gen_gui_lang.text;
try
deflang:=getDefLang;
if lowercase(deflang)='english' then begin
defLangEnglish:=true;
// load_default_language_english;
exit;
end;
stream:=helper_diskio.myfileopen(app_path+'\Lang\'+deflang+'.txt',ARES_READONLY_BUT_SEQUENTIAL);
if stream=nil then begin
// load_default_language_english;
defLangEnglish:=true;
exit;
end;
utf8str:='';
try
defLangEnglish:=false;
CreateLanguageDb;
with stream do begin
while (position+1<size) do begin
len:=read(buffer,sizeof(buffer));
if len<1 then break;
previous_len:=length(utf8str);
setlength(utf8str,previous_len+len);
move(buffer,utf8str[previous_len+1],len);
end;
end;
FreeHandleStream(Stream);
// parse_lines_lang(utf8strtowidestr(utf8str));
except
FreeHandleStream(Stream);
end;
except
end;
end;
{
function parse_lines_lang(superwstr:widestring):integer;
var
trovato:boolean;
i:integer;
linea:widestring;
cmd:integer;
str,fontn:string;
fonts:integer;
begin
fonts:=8;
if ((ares_frmmain.font.name<>'Tahoma') or (ares_frmmain.font.size<>8)) then begin
ares_frmmain.font.name:='Tahoma';
ares_frmmain.font.size:=8;
vars_global.font_chat.name:='Verdana';
vars_global.font_chat.size:=10;
mainGui_applyfont;
end;
result:=length(superwstr);
while (length(superwstr)>0) do begin
trovato:=false;
for i:=1 to length(superwstr)-1 do begin
if ((integer(superwstr[i])=13) and (integer(superwstr[i+1])=10)) then begin
setlength(linea,i-1);
linea:=copy(superwstr,1,i-1);
delete(superwstr,1,i+1);
result:=length(superwstr);
trovato:=true;
break;
end;
end;
if not trovato then break;
if length(linea)<4 then continue;
if linea[4]<>'|' then begin //FONT?
str:=widestrtoutf8str(linea);
if pos('FONT NAME="',str)=1 then begin
delete(str,1,11);
fontn:=copy(str,1,pos('"',str)-1);
delete(str,1,pos('"',str));
if pos(' SIZE="',str)=1 then begin
delete(str,1,7);
fonts:=strtointdef(copy(str,1,pos('"',str)-1),8);
delete(str,1,pos('"',str));
end;
try
ares_FrmMain.Font.Name:=fontn;
ares_FrmMain.font.size:=fonts;
except
ares_FrmMain.font.name:='Tahoma';
ares_FrmMain.font.size:=8;
end;
if pos(' FONT_CHAT NAME="',str)=1 then begin
delete(str,1,17);
fontn:=copy(str,1,pos('"',str)-1);
delete(str,1,pos('"',str));
if pos(' SIZE="',str)=1 then begin
delete(str,1,7);
fonts:=strtointdef(copy(str,1,pos('"',str)-1),8);
end;
try
vars_global.Font_Chat.Name:=fontn;
vars_global.font_chat.size:=fonts;
except
vars_global.font_chat.name:='Verdana';
vars_global.font_chat.size:=10;
end;
end;
mainGui_applyfont;
end;
continue;
end;
cmd:=strtointdef(string(copy(linea,1,3)),0);
if cmd=0 then break;
delete(linea,1,4);
linea:=strip_nl(linea);
if ((cmd>=MIN_TRANSLATIONTABLE_INDEX) and (cmd<=MAX_TRANSLATIONTABLE_INDEX)) then db_language[cmd]:=linea;
end;
end;
procedure load_default_language_english;
begin
try
ares_frmmain.font.name:='Tahoma';
ares_frmmain.font.size:=8;
vars_global.font_chat.name:='Verdana';
vars_global.font_chat.size:=10;
helper_gui_misc.mainGui_applyfont;
except
end;
FreeLanguageDb;
end;
}
procedure InitLanguageDb;
var
i:integer;
begin
if db_language=nil then exit;
for i:=MIN_TRANSLATIONTABLE_INDEX to MAX_TRANSLATIONTABLE_INDEX do db_language[i]:='';
end;
procedure CreateLanguageDb;
begin
if db_language<>nil then exit;
db_language:=AllocMem(sizeof(Tdb_Language));
end;
procedure FreeLanguageDb;
begin
if db_language=nil then exit;
InitLanguageDb;
FreeMem(db_language,sizeof(Tdb_Language));
db_language:=nil;
end;
end.
|
unit usave;
{Menyimpan array of ADT masing-masing ke dalam file csv, contoh: array of ADT Buku}
{REFERENSI : http://wiki.freepascal.org/File_Handling_In_Pascal
https://www.youtube.com/watch?v=AOYbfHHh4bE (Reading & Writing to CSV Files in Pascal by Holly Billinghurst)}
interface
uses
k03_kel3_utils,
ubook,
uuser,
udate;
{PUBLIC FUNCTIONS, PROCEDURE}
procedure savebook(filename: string; ptr: pbook);
procedure saveuser(filename: string; ptr: puser);
procedure saveborrow(filename: string; ptr: pborrow);
procedure savereturn(filename: string; ptr: preturn);
procedure savemissing(filename: string; ptr: pmissing);
implementation
{FUNGSI dan PROSEDUR}
procedure savebook(filename: string; ptr: pbook);
{DESKRIPSI : Menyimpan ADT array of Book ke dalam file csv}
{I.S. : pointer pbook terdefinisi, array tbook terdefinisi}
{F.S. : file csv terbentuk/terupdate di direktori}
{Proses : meminta input nama file, lalu menyimpan ADT array of Book ke dalam file csv}
{KAMUS LOKAL}
var
row : integer;
f : text;
{ALGORITMA}
begin
{memuat file ke variabel f}
assign(f, filename);
rewrite(f);
writeln(f, 'ID_Buku,Judul_Buku,Author,Jumlah_Buku,Tahun_Penerbit,Kategori');
for row:= 1 to bookNeff do begin
write(f, IntToStr(ptr^[row].id) + delimiter);
write(f, ptr^[row].title + delimiter);
write(f, ptr^[row].author + delimiter);
write(f, IntToStr(ptr^[row].qty) + delimiter);
write(f, IntToStr(ptr^[row].year) + delimiter);
writeln(f, ptr^[row].category);;
end;
close(f);
end;
procedure saveuser(filename: string; ptr: puser);
{DESKRIPSI : Menyimpan ADT array of User ke dalam file csv}
{I.S. : pointer pUser terdefinisi, array tUser terdefinisi}
{F.S. : file csv terbentuk/terupdate di direktori}
{Proses : meminta input nama file, lalu menyimpan ADT array of User ke dalam file csv}
{KAMUS LOKAL}
var
row : integer;
f : text;
{ALGORITMA}
begin
{memuat file ke variabel f}
system.assign(f, filename);
system.rewrite(f);
writeln(f, 'Nama,Alamat,Username,Password,Role');
for row:= 1 to userNeff do begin
write(f, ptr^[row].fullname + delimiter);
write(f, ptr^[row].address + delimiter);
write(f, ptr^[row].username + delimiter);
write(f, ptr^[row].password + delimiter);
if ptr^[row].isAdmin then begin
writeln(f, 'Admin');
end else begin
writeln(f, 'Pengunjung');
end;
end;
close(f);
end;
procedure saveborrow(filename: string; ptr: pborrow);
{DESKRIPSI : Menyimpan ADT array of BorrowHistory ke dalam file csv}
{I.S. : pointer pBorrow terdefinisi, array tBorrow terdefinisi}
{F.S. : file csv terbentuk/terupdate di direktori}
{Proses : meminta input nama file, lalu menyimpan ADT array of BorrowHistory ke dalam file csv}
{KAMUS LOKAL}
var
row : integer;
f : text;
{ALGORITMA}
begin
{memuat file ke variabel f}
system.assign(f, filename);
system.rewrite(f);
writeln(f, 'Username,ID_Buku,Tanggal_Peminjaman,Tanggal_Batas_Pengembalian,Status_Pengembalian');
for row:= 1 to borrowNeff do begin
write(f, ptr^[row].username + delimiter);
write(f, IntToStr(ptr^[row].id) + delimiter);
write(f, DateToStr(ptr^[row].borrowDate) + delimiter);
write(f, DateToStr(ptr^[row].returnDate) + delimiter);
if ptr^[row].isBorrowed then begin
writeln(f, 'belum');
end else begin
writeln(f, 'sudah');
end;
end;
close(f);
end;
procedure savereturn(filename: string; ptr: preturn);
{DESKRIPSI : Menyimpan ADT array of ReturnHistory ke dalam file csv}
{I.S. : pointer pReturn terdefinisi, array tReturn terdefinisi}
{F.S. : file csv terbentuk/terupdate di direktori}
{Proses : meminta input nama file, lalu menyimpan ADT array of ReturnHistory ke dalam file csv}
{KAMUS LOKAL}
var
row : integer;
f : text;
{ALGORITMA}
begin
{memuat file ke variabel f}
system.assign(f, filename);
system.rewrite(f);
writeln(f, 'Username,ID_Buku,Tanggal_Pengembalian');
for row:= 1 to returnNeff do begin
write(f, ptr^[row].username + delimiter);
write(f, IntToStr(ptr^[row].id) + delimiter);
writeln(f, DateToStr(ptr^[row].returnDate));
end;
close(f);
end;
procedure savemissing(filename: string; ptr: pmissing);
{DESKRIPSI : Menyimpan ADT array of MissingBook ke dalam file csv}
{I.S. : pointer pMissing terdefinisi, array tMissing terdefinisi}
{F.S. : file csv terbentuk/terupdate di direktori}
{Proses : meminta input nama file, lalu menyimpan ADT array of MissingBook ke dalam file csv}
{KAMUS LOKAL}
var
row : integer;
f : text;
{ALGORITMA}
begin
{memuat file ke variabel f}
system.assign(f, filename);
system.rewrite(f);
writeln(f, 'Username,ID_Buku_Hilang,Tanggal_Laporan');
for row:= 1 to missingNeff do begin
write(f, ptr^[row].username, delimiter);
write(f, IntToStr(ptr^[row].id), delimiter);
writeln(f, DateToStr(ptr^[row].reportDate));
end;
close(f);
end;
end.
|
unit fSurgeryView;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ORFN,
StdCtrls, ExtCtrls, ORCtrls, ComCtrls, ORDtTm, Spin, rSurgery, fBase508Form,
VA508AccessibilityManager;
type
TfrmSurgeryView = class(TfrmBase508Form)
pnlBase: TORAutoPanel;
lblBeginDate: TLabel;
calBeginDate: TORDateBox;
lblEndDate: TLabel;
calEndDate: TORDateBox;
cmdOK: TButton;
cmdCancel: TButton;
lblMaxDocs: TLabel;
edMaxDocs: TCaptionEdit;
grpTreeView: TGroupBox;
lblGroupBy: TOROffsetLabel;
cboGroupBy: TORComboBox;
radTreeSort: TRadioGroup;
cmdClear: TButton;
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure cmdClearClick(Sender: TObject);
private
FChanged: Boolean;
FBeginDate: string;
FFMBeginDate: TFMDateTime;
FEndDate: string;
FFMEndDate: TFMDateTime;
FOpProc: string;
FMaxDocs: integer;
FGroupBy: string;
FTreeAscending: Boolean;
FCurrentContext: TSurgCaseContext;
end;
function SelectSurgeryView(FontSize: Integer; ShowForm: Boolean; CurrentContext: TSurgCaseContext;
var SurgeryContext: TSurgCaseContext): boolean ;
implementation
{$R *.DFM}
uses rCore, uCore;
const
TX_DATE_ERR = 'Enter valid beginning and ending dates or press Cancel.';
TX_DATE_ERR_CAP = 'Error in Date Range';
function SelectSurgeryView(FontSize: Integer; ShowForm: Boolean; CurrentContext: TSurgCaseContext;
var SurgeryContext: TSurgCaseContext): boolean ;
var
frmSurgeryView: TfrmSurgeryView;
W, H: Integer;
begin
frmSurgeryView := TfrmSurgeryView.Create(Application);
try
with frmSurgeryView do
begin
Font.Size := FontSize;
W := ClientWidth;
H := ClientHeight;
ResizeToFont(FontSize, W, H);
ClientWidth := W; pnlBase.Width := W;
ClientHeight := H; pnlBase.Height := H;
FChanged := False;
FCurrentContext := CurrentContext;
calBeginDate.Text := CurrentContext.BeginDate;
calEndDate.Text := CurrentContext.EndDate;
if calEndDate.Text = '' then calEndDate.Text := 'TODAY';
if CurrentContext.MaxDocs > 0 then
edMaxDocs.Text := IntToStr(CurrentContext.MaxDocs)
else
edMaxDocs.Text := '';
FMaxDocs := StrToIntDef(edMaxDocs.Text, 0);
radTreeSort.ItemIndex := 0;
cboGroupBy.SelectByID(CurrentContext.GroupBy);
if ShowForm then ShowModal else cmdOKClick(frmSurgeryView);
with SurgeryContext do
begin
Changed := FChanged;
OpProc := FOpProc;
BeginDate := FBeginDate;
FMBeginDate := FFMBeginDate;
EndDate := FEndDate;
FMEndDate := FFMEndDate;
MaxDocs := FMaxDocs;
GroupBy := FGroupBy;
TreeAscending := FTreeAscending;
Result := Changed ;
end;
end; {with frmSurgeryView}
finally
frmSurgeryView.Release;
end;
end;
procedure TfrmSurgeryView.cmdOKClick(Sender: TObject);
var
bdate, edate: TFMDateTime;
begin
if calBeginDate.Text <> '' then
bdate := StrToFMDateTime(calBeginDate.Text)
else
bdate := 0 ;
if calEndDate.Text <> '' then
edate := StrToFMDateTime(calEndDate.Text)
else
edate := 0 ;
if (bdate <= edate) then
begin
FBeginDate := calBeginDate.Text;
FFMBeginDate := bdate;
FEndDate := calEndDate.Text;
FFMEndDate := edate;
end
else
begin
InfoBox(TX_DATE_ERR, TX_DATE_ERR_CAP, MB_OK or MB_ICONWARNING);
Exit;
end;
FTreeAscending := (radTreeSort.ItemIndex = 0);
FMaxDocs := StrToIntDef(edMaxDocs.Text, 0);
if cboGroupBy.ItemID <> '' then
FGroupBy := cboGroupBy.ItemID
else
FGroupBy := '';
FChanged := True;
Close;
end;
procedure TfrmSurgeryView.cmdCancelClick(Sender: TObject);
begin
FChanged := False;
Close;
end;
procedure TfrmSurgeryView.cmdClearClick(Sender: TObject);
begin
cboGroupBy.ItemIndex := -1;
radTreeSort.ItemIndex := 0;
end;
end.
|
{
"HTTP Server Provider (WinSock)" - Copyright (c) Danijel Tkalcec
@html(<br>)
Using TRtcWSockServerProvider to implement a HTTP Server provider.
@exclude
}
unit rtcWSockHttpSrvProv;
{$INCLUDE rtcDefs.inc}
interface
uses
Classes,
SysUtils,
rtcLog,
rtcConn,
rtcConnProv,
rtcFastStrings,
rtcWSockSrvProv;
type
TRtcWSockHttpServerProvider = class(TRtcWSockServerProvider)
private
FOnInvalidRequest:TRtcEvent;
FMaxHeaderSize:integer;
FMaxRequestSize:integer;
FRequest:TRtcServerRequest;
FResponse:TRtcServerResponse;
FRequestBuffer:TRtcHugeString;
FRequestWaiting:boolean; // will be set when request is waiting to be read.
FChunked:boolean;
FChunkState:byte;
FRequestLine:boolean; // request line received
InBuffer:string; // data received, including HTTP header (header will be stripped when read)
FHaveRequest:boolean; // request header accepted, receiving request data.
LenToRead:int64; // number of bytes left to read from last Request
LenToWrite:int64; // number of bytes to write out using inherited Write()
LenToSend:int64; // number of bytes left to send out (DataOut event)
FHeaderOut:boolean;
procedure ClearRequest;
public
constructor Create; override;
destructor Destroy; override;
procedure TriggerDisconnect; override;
procedure TriggerDataReceived; override;
procedure TriggerDataSent; override;
procedure TriggerDataOut; override;
procedure TriggerInvalidRequest; virtual;
procedure SetTriggerInvalidRequest(Event:TRtcEvent);
procedure WriteHeader(SendNow:boolean=True); overload;
procedure WriteHeader(const Header_Text:string; SendNow:boolean=True); overload;
procedure Write(const ResultData:string; SendNow:boolean=True); override;
// 1. On DataReceived, read client request info using this:
function Read:string; override;
property Request:TRtcServerRequest read FRequest write FRequest;
property Response:TRtcServerResponse read FResponse write FResponse;
property MaxRequestSize:integer read FMaxRequestSize write FMaxRequestSize;
property MaxHeaderSize:integer read FMaxHeaderSize write FMaxHeaderSize;
end;
implementation
const
CRLF = #13#10;
END_MARK = CRLF+CRLF;
{ TRtcWSockHttpServerProvider }
procedure TRtcWSockHttpServerProvider.SetTriggerInvalidRequest(Event: TRtcEvent);
begin
FOnInvalidRequest:=Event;
end;
procedure TRtcWSockHttpServerProvider.TriggerInvalidRequest;
begin
if assigned(FOnInvalidRequest) then
FOnInvalidRequest;
end;
constructor TRtcWSockHttpServerProvider.Create;
begin
inherited;
FRequestBuffer:=TRtcHugeString.Create;
InBuffer:='';
LenToWrite:=0;
LenToSend:=0;
FHeaderOut:=False;
FRequestLine:=False;
FRequest:=nil;
FResponse:=nil;
FChunked:=False;
FChunkState:=0;
end;
destructor TRtcWSockHttpServerProvider.Destroy;
begin
FRequestBuffer.Free;
InBuffer:='';
LenToWrite:=0;
LenToSend:=0;
FRequestLine:=False;
FHeaderOut:=False;
inherited;
end;
procedure TRtcWSockHttpServerProvider.ClearRequest;
begin
FRequestBuffer.Clear;
FRequestLine:=False;
FRequest.Clear;
FResponse.Clear;
LenToRead:=0;
end;
procedure TRtcWSockHttpServerProvider.TriggerDisconnect;
begin
inherited;
FRequestBuffer.Clear;
InBuffer:='';
LenToWrite:=0;
LenToSend:=0;
FHeaderOut:=False;
FRequestLine:=False;
ClearRequest;
end;
procedure TRtcWSockHttpServerProvider.TriggerDataReceived;
var
s,
StatusLine,
HeadStr:string;
HeadLen,
MyPos:integer;
function HexToInt(s:string):integer;
var
i,len:integer;
c:char;
begin
Result:=0;
len:=length(s);
i:=1;
while len>0 do
begin
c:=s[len];
if c in ['1'..'9'] then
Result:=Result+i*(Ord(c)-Ord('0'))
else if s[len] in ['A'..'F'] then
Result:=Result+i*(Ord(c)-Ord('A')+10)
else if s[len] in ['a'..'f'] then
Result:=Result+i*(Ord(c)-Ord('a')+10);
i:=i*16;Dec(len);
end;
end;
procedure RequestError;
begin
FRequestLine:=False;
TriggerInvalidRequest;
end;
begin
if Request.Complete and not Response.Done then
begin
if assigned(CryptPlugin) then
begin
// Read string from buffer
InBuffer:=InBuffer + inherited Read;
if InBuffer='' then
begin
FRequestWaiting:=True;
Exit;
end
else
FRequestWaiting:=False;
end
else
begin
FRequestWaiting:=True;
Exit;
end;
end
else
FRequestWaiting:=False;
// Read string from buffer
InBuffer:=InBuffer + inherited Read;
while InBuffer<>'' do
begin
if not FHaveRequest then // Don't have the header yet ...
begin
if not FRequestLine then
begin
MyPos:=Pos(CRLF,InBuffer);
if (MaxRequestSize>0) and
( (MyPos>MaxRequestSize+1) or
((MyPos<=0) and (length(InBuffer)>MaxRequestSize+length(CRLF))) ) then
begin
ClearRequest;
Request.FileName:=InBuffer;
RequestError;
Exit;
end
else if (MyPos>0) then
begin
ClearRequest;
StatusLine:=Copy(InBuffer,1,MyPos-1);
Delete(InBuffer,1,MyPos+length(CRLF)-1);
MyPos:=Pos(' HTTP/', UpperCase(StatusLine));
if MyPos<=0 then
MyPos:=Pos(' HTTPS/', UpperCase(StatusLine));
if MyPos<=0 then
begin
Request.FileName:=StatusLine;
RequestError;
Exit;
end
else
begin
Request.Started:=True;
Request.Active:=True;
// Request Method
MyPos:=Pos(' ',StatusLine);
if MyPos<=0 then
begin
Request.FileName:=StatusLine;
RequestError;
Exit;
end;
Request.Method:=Trim(Copy(StatusLine,1,MyPos-1));
Delete(StatusLine,1,MyPos);
// Request FileName
MyPos:=Pos(' ',StatusLine);
if MyPos<=0 then
begin
Request.FileName:=StatusLine;
RequestError;
Exit;
end;
Request.FileName:=Copy(StatusLine,1,MyPos-1);
Delete(StatusLine,1,MyPos);
// Request HTTP type
MyPos:=Pos('/',StatusLine);
if MyPos<=0 then
begin
RequestError;
Exit;
end;
if Copy(StatusLine,MyPos+1,3)='1.0' then
Request.Close:=True;
MyPos:=Pos('?',Request.FileName);
if MyPos>0 then
begin
Request.Query.Text:=Copy(Request.FileName,MyPos+1,length(Request.FileName)-MyPos);
Request.FileName:=Copy(Request.FileName,1,MyPos-1);
end
else
Request.Query.Clear;
FRequestLine:=True;
end;
end;
end;
if FRequestLine then
begin
// See if we can get the whole header ...
HeadLen:=Pos(CRLF, InBuffer);
if HeadLen<>1 then
HeadLen:=Pos(END_MARK, InBuffer);
if HeadLen=1 then
begin
Delete(InBuffer,1,2);
FHaveRequest:=True;
end
else if (MaxHeaderSize>0) and
( (HeadLen>MaxHeaderSize) or
((HeadLen<=0) and (length(InBuffer)>MaxHeaderSize+length(END_MARK))) ) then
begin
RequestError;
Exit;
end
else if HeadLen>0 then
begin
// Separate header from the body
HeadStr:=Copy(InBuffer, 1, HeadLen+length(END_MARK)-1);
Delete(InBuffer,1,HeadLen+length(END_MARK)-1);
FHaveRequest:=True;
// Scan for all header attributes ...
MyPos:=Pos(CRLF, HeadStr);
while (MyPos>1) do // at least 1 character inside line
begin
StatusLine:=Copy(HeadStr,1,MyPos-1);
Delete(HeadStr,1,MyPos+Length(CRLF)-1);
MyPos:=Pos(':',StatusLine);
if MyPos>0 then
begin
s:=Trim(Copy(StatusLine,1,MyPos-1));
Delete(StatusLine,1,MyPos);
StatusLine:=Trim(StatusLine);
if CompareText(s,'CONTENT-LENGTH')=0 then
begin
LenToRead:=StrToInt64Def(StatusLine,0);
Request.ContentLength:=LenToRead;
end
else
Request[s]:=StatusLine;
end;
MyPos:=Pos(CRLF, HeadStr);
end;
if CompareText(Request['CONNECTION'],'CLOSE')=0 then
Request.Close:=True;
if CompareText(Request['TRANSFER-ENCODING'],'CHUNKED')=0 then
begin
FChunked:=True;
FChunkState:=0;
end
else
FChunked:=False;
if CompareText(Copy(Request.ContentType,1,19),'MULTIPART/FORM-DATA')=0 then
begin
MyPos:=Pos('BOUNDARY=',UpperCase(Request.ContentType));
if MyPos>0 then
// Get MULTIPART Boundary (Params.Delimiter)
begin
Request.Params.Delimiter:=
Copy(Request.ContentType, MyPos+9, length(Request.ContentType)-MyPos-8);
if (Copy(Request.Params.Delimiter,1,1)='"') and
(Copy(Request.Params.Delimiter,
length(Request.Params.Delimiter),1)='"') then
begin
Request.Params.Delimiter:=
Copy(Request.Params.Delimiter, 2, length(Request.Params.Delimiter)-2);
end;
end;
end;
StatusLine:='';
HeadStr:='';
end;
end;
end;
if FHaveRequest then // Processing a request ...
begin
if FChunked then // Read data as chunks
begin
if (FChunkState=0) and (InBuffer<>'') then // 1.step = read chunk size
begin
MyPos:=Pos(CRLF,InBuffer);
if MyPos>0 then
begin
StatusLine:=Trim(Copy(InBuffer,1,MyPos-1));
Delete(InBuffer,1,MyPos+1);
LenToRead:=HexToInt(StatusLine);
FChunkState:=1; // ready to read data
end;
end;
if (FChunkState=1) and (InBuffer<>'') then // 2.step = read chunk data
begin
if (LenToRead>length(InBuffer)) then // need more than we have
begin
Request.ContentIn:=Request.ContentIn+length(InBuffer);
if LenToRead>0 then
Dec(LenToRead, length(InBuffer));
FRequestBuffer.Add(InBuffer);
InBuffer:='';
inherited TriggerDataReceived;
Request.Started:=False;
end
else
begin
if LenToRead>0 then
begin
Request.ContentIn:=Request.ContentIn+LenToRead;
FRequestBuffer.Add(Copy(InBuffer,1,LenToRead));
Delete(InBuffer,1,LenToRead);
LenToRead:=0;
FChunkState:=2; // this is not the last chunk, ready to read CRLF
end
else
FChunkState:=3; // this was last chunk, ready to read CRLF
end;
end;
if (FChunkState>=2) and (length(InBuffer)>=2) then // 3.step = close chunk
begin
LenToRead:=-1;
Delete(InBuffer,1,2); // Delete CRLF
if FChunkState=2 then // not the last chunk
begin
FChunkState:=0; // will continue with next chunk
end
else
begin
Request.Complete:=True;
FHaveRequest:=False; // get ready for next request
FRequestLine:=False;
end;
inherited TriggerDataReceived;
Request.Started:=False;
end;
end
else
begin
if LenToRead>0 then
begin
if LenToRead>length(InBuffer) then // need more than we have
begin
Request.ContentIn:=Request.ContentIn + length(InBuffer);
FRequestBuffer.Add(InBuffer);
Dec(LenToRead, length(InBuffer));
InBuffer:='';
end
else
begin
Request.ContentIn:=Request.ContentIn + LenToRead;
FRequestBuffer.Add(Copy(InBuffer,1,LenToRead));
Delete(InBuffer,1,LenToRead);
LenToRead:=0;
Request.Complete:=True;
FHaveRequest:=False; // get ready for next request
FRequestLine:=False;
end;
end
else
begin
Request.Complete:=True;
FHaveRequest:=False; // get ready for next request
FRequestLine:=False;
end;
inherited TriggerDataReceived;
Request.Started:=False;
end;
if Request.Complete and not Response.Done then
begin
FRequestWaiting:=InBuffer<>'';
Break; // need to wait for the request to be processed, before we can go to the next one.
end;
end
else
Break; // Failing to fetch a header will break the loop.
end;
end;
procedure TRtcWSockHttpServerProvider.WriteHeader(SendNow:boolean=True);
var
s:string;
begin
if FHeaderOut then
raise Exception.Create('Last header intercepted with new header, before data sent out.');
s:='HTTP/1.1 '+IntToStr(Response.StatusCode)+' '+Response.StatusText+CRLF+
Response.HeaderText;
if Request.Close then s:=s+'Connection: close'+CRLF;
s:=s+CRLF;
Response.Sending:=True;
Response.Started:=True;
if Response.SendContent and
(Response['CONTENT-LENGTH']='') then // streaming data
begin
LenToWrite:=-1;
LenToSend:=-1;
end
else
begin
if not Response.SendContent then
Response['CONTENT-LENGTH']:='';
LenToWrite:=Response.ContentLength;
LenToSend:=length(s) + Response.ContentLength;
end;
Response.Sent:=LenToWrite=0;
if Response.Sent then
TriggerLastWrite;
FHeaderOut:=True;
inherited Write(s, SendNow or (LenToWrite<=0));
end;
procedure TRtcWSockHttpServerProvider.WriteHeader(const Header_Text:string; SendNow:boolean=True);
var
s:string;
begin
if FHeaderOut then
raise Exception.Create('Last header intercepted with new header, before data sent out.');
if Header_Text<>'' then
begin
Response.HeaderText:=Header_Text;
s:='HTTP/1.1 '+IntToStr(Response.StatusCode)+' '+Response.StatusText+CRLF+
Response.HeaderText;
if Request.Close then s:=s+'Connection: close'+CRLF;
s:=s+CRLF;
end
else
begin
s:='';
Request.Close:=True;
end;
Response.Sending:=True;
Response.Started:=True;
if Response.SendContent and
(Response['CONTENT-LENGTH']='') then // streaming data
begin
LenToWrite:=-1;
LenToSend:=-1;
end
else
begin
if not Response.SendContent then
Response['CONTENT-LENGTH']:='';
LenToWrite:=Response.ContentLength;
LenToSend:=length(s) + Response.ContentLength;
end;
Response.Sent:=LenToWrite=0;
if Response.Sent then
TriggerLastWrite;
FHeaderOut:=True;
inherited Write(s, SendNow or (LenToWrite<=0));
end;
procedure TRtcWSockHttpServerProvider.Write(const ResultData: string; SendNow:boolean=True);
begin
if length(ResultData)=0 then Exit;
if not FHeaderOut then
raise Exception.Create('Trying to send Data without Header. Call WriteHeader before Write.');
if LenToWrite>=0 then
begin
if length(ResultData)>LenToWrite then
raise Exception.Create('Trying to send more Data out than specified in Header.');
Dec(LenToWrite, length(ResultData));
end;
Response.Sent:=LenToWrite=0;
Response.ContentOut:=Response.ContentOut + length(ResultData);
if Response.Sent then
TriggerLastWrite;
inherited Write(ResultData,SendNow);
end;
function TRtcWSockHttpServerProvider.Read: string;
begin
if FRequestBuffer.Size>0 then
begin
Result:=FRequestBuffer.Get;
FRequestBuffer.Clear;
end
else
Result:='';
end;
procedure TRtcWSockHttpServerProvider.TriggerDataSent;
begin
if Response.Sending then
Response.Started:=False;
inherited TriggerDataSent;
if Response.Done then
begin
ClearRequest;
if FRequestWaiting then
TriggerDataReceived;
end;
end;
procedure TRtcWSockHttpServerProvider.TriggerDataOut;
begin
if Response.Sending then
begin
if LenToSend>=0 then
begin
Dec(LenToSend, DataOut);
Response.Done := LenToSend=0;
end;
if Response.Done then
begin
Request.Started:=False;
Request.Active:=False;
Response.Started:=False;
Response.Sending:=False;
FHeaderOut:=False;
end;
end;
inherited TriggerDataOut;
end;
end.
|
unit SIBGlobals;
// SuperIB
// Copyright © 1999 David S. Becker
// dhbecker@jps.net
// www.jps.net/dhbecker/superib
interface
uses SysUtils;
const
SIB_MAX_EVENT_BLOCK = 15; // maximum events handled per block by InterBase
SIB_MAX_EVENT_LENGTH = 128; // maximum event name length
type
ESIBError = class(Exception);
resourcestring
SIB_RS_NOT_REGISTERED = 'Events not registered';
SIB_RS_ALREADY_REGISTERED = 'Events already registered';
SIB_RS_EMPTY_STRINGS = 'Can not assign empty strings as events. ';
SIB_RS_TOO_LONG = 'Some event were longer than %d and were truncated. ';
SIB_RS_FIB_SET_NATIVEHANDLE = 'SIBfibEventAlerter does not allow you to set the NativeHandle property';
SIB_RS_FIB_NO_DATABASE = 'Cannot register events, no database assigned or database not connected';
implementation
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ XML Transform Components }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Datasnap.Xmlxform;
interface
uses
Datasnap.DBClient, Datasnap.Provider, System.Classes, System.Types, Xml.XmlTransform;
type
{ TXMLTransformProvider }
{ This component takes data in an arbitrary XML data file and provides it to a
DataSnap client. It also takes updates to the data from the DataSnap client and
modifies the original XML data file.
Properties:
CacheData
Indicates if data is cached by the provider after the GetRecords
method is called by the client. Caching the data will speed
the update process, but will consume additional resources.
XMLDataFile
XML File containing data to be returned to the client. This can be
in any format that can be transformed into a DataSnap compatible format.
Updates are written back to this file.
TransformRead.TransformationFile
Transform file for for converting from XMLDataFile format into a
DataSnap format. This file must be created using the XMLMapper program.
TransformWrite.TransformationFile
Transform file for for converting from a DataSnap format into the
XMLDataFile format. This file must be created using the XMLMapper
program.
}
TXMLTransformProvider = class(TCustomProvider)
private
FDataCache: TClientDataSet;
FResolver: TDataSetProvider;
FTransformRead: TXMLTransform;
FTransformWrite: TXMLTransform;
FCacheData: Boolean;
function GetXMLDataFile: string;
procedure SetXMLDataFile(const Value: string);
protected
function InternalApplyUpdates(const Delta: OleVariant; MaxErrors: Integer;
out ErrorCount: Integer): OleVariant; override;
function InternalGetRecords(Count: Integer; out RecsOut: Integer;
Options: TGetRecordOptions; const CommandText: OleStr;
var Params: OleVariant): OleVariant; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property TransformRead: TXMLTransform read FTransformRead ;
property TransformWrite: TXMLTransform read FTransformWrite ;
property XMLDataFile: string read GetXMLDataFile write SetXMLDataFile;
property CacheData: Boolean read FCacheData write FCacheData default False;
property BeforeApplyUpdates;
property AfterApplyUpdates;
property BeforeGetRecords;
property AfterGetRecords;
property BeforeRowRequest;
property AfterRowRequest;
property OnDataRequest;
end;
{ Transform Client }
{ This component takes data returned from a DataSnap AppServer and transforms
it into an external XML data file (GetXML method). The format of the XML is
determined by the TransformGetData TransformationFile.
It also allows inserting and deleting data on the AppServer by calling the
calling ApplyUpdates method, passing an XML file with the data to
insert/delete, and also a reference to a file containing the
relavant transformation info. }
TXMLTransformClient = class(TComponent)
private
FDataCache: TClientDataSet;
FSetParamsDataCache: TClientDataSet;
FLocalAppServer: TLocalAppServer;
FTransformGetData: TXMLTransform;
FTransformApplyUpdates: TXMLTransform;
FTransformSetParams: TXMLTransform;
function GetProviderName: string;
function GetRemoteServer: TCustomRemoteServer;
procedure SetProviderName(const Value: string);
procedure SetRemoteServer(const Value: TCustomRemoteServer);
protected
procedure SetupAppServer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetDataAsXml(const PublishTransformFile: string): string; virtual;
function ApplyUpdates(const UpdateXML, UpdateTransformFile: string; MaxErrors: Integer): Integer; virtual;
procedure SetParams(const ParamsXml, ParamsTransformFile: string);
published
property RemoteServer: TCustomRemoteServer read GetRemoteServer write SetRemoteServer;
property ProviderName: string read GetProviderName write SetProviderName;
property TransformGetData: TXMLTransform read FTransformGetData ;
property TransformApplyUpdates: TXMLTransform read FTransformApplyUpdates;
property TransformSetParams: TXMLTransform read FTransformSetParams ;
end;
implementation
uses
Data.DB, Datasnap.DSIntf, System.SysUtils, System.Variants, Xml.Xmldom, Xml.xmlutil;
{ Utility Functions }
// Helpers to reduce explicit casts
function VariantArrayToString(const V: OleVariant): string;
var
LByteArray: TBytes;
begin
LByteArray := Datasnap.DSIntf.VariantArrayToBytes(V);
Result := TMarshal.ReadStringAsUtf8(TPtrWrapper.Create(LByteArray), Length(LByteArray) - 1);
end;
function StringToVariantArray(const S: string): OleVariant;
const
CP_UTF8 = 65001;
var
LArray: TArray<Byte>;
Len: Integer;
M: TMarshaller;
begin
Len := LocaleCharsFromUnicode(CP_UTF8, 0, PWideChar(S), S.Length, nil, 0, nil, nil);
SetLength(LArray, Len);
Move(M.AsUtf8(S).ToPointer^, PByte(LArray)^, Len);
Result := Datasnap.DSIntf.BytesToVariantArray(LArray);
end;
procedure StringToFile(const S, FileName: string);
begin
with TStringList.Create do
try
Text := S;
SaveToFile(FileName);
finally
Free;
end;
end;
function GetXMLData(DataSet: TClientDataSet): string;
var
Stream: TStringStream;
begin
Stream := TStringStream.Create('');
try
DataSet.SaveToStream(Stream, dfXML);
Result := Stream.DataString;
finally
Stream.Free;
end;
end;
function CreateNestedTransform(Owner: TComponent; const Name: string): TXMLTransform;
begin
Result := TXMLTransform.Create(Owner);
Result.SetSubComponent(True);
Result.Name := Name;
end;
{ TXMLTransformProvider }
constructor TXMLTransformProvider.Create(AOwner: TComponent);
begin
FTransformRead := CreateNestedTransform(Self, 'DataTransformRead'); // Do not localize
FTransformWrite := CreateNestedTransform(Self, 'DataTransformWrite'); // Do not localize
FDataCache := TClientDataSet.Create(Self);
inherited;
end;
destructor TXMLTransformProvider.Destroy;
begin
inherited;
end;
function TXMLTransformProvider.InternalGetRecords(Count: Integer;
out RecsOut: Integer; Options: TGetRecordOptions;
const CommandText: OleStr; var Params: OleVariant): OleVariant;
begin
Result := StringtoVariantArray(FTransformRead.Data);
if CacheData then
FDataCache.Data := Result;
end;
function TXMLTransformProvider.InternalApplyUpdates(const Delta: OleVariant;
MaxErrors: Integer; out ErrorCount: Integer): OleVariant;
var
S: string;
begin
if not Assigned(FResolver) then
begin
FResolver := TDataSetProvider.Create(Self);
FResolver.DataSet := FDataCache;
FResolver.ResolveToDataSet := True;
FResolver.UpdateMode := upWhereAll; //upWhereKeyOnly;
end;
if not FCacheData or not FDataCache.Active then
FDataCache.Data := StringToVariantArray(FTransformRead.Data);
Result := FResolver.ApplyUpdates(Delta, MaxErrors, ErrorCount);
FDataCache.MergeChangeLog;
S := FTransformWrite.TransformXML(GetXMLData(FDataCache));
if FTransformWrite.ResultDocument <> nil then
begin
SetEncoding(FTransformWrite.ResultDocument, FTransformRead.Encoding, False);
if FTransformRead.SourceXmlFile <> '' then
(FTransformWrite.ResultDocument as IDOMPersist).save(FTransformRead.SourceXmlFile);
end
else if S <> '' then
StringToFile(S, FTransformRead.SourceXmlFile);
if not FCacheData then
FDataCache.Data := Null;
end;
function TXMLTransformProvider.GetXMLDataFile: string;
begin
Result := FTransformRead.SourceXMLFile
end;
procedure TXMLTransformProvider.SetXMLDataFile(const Value: string);
begin
FTransformRead.SourceXMLFile := Value;
end;
{ TXMLTransformClient }
constructor TXMLTransformClient.Create(AOwner: TComponent);
begin
FTransformGetData := CreateNestedTransform(Self, 'TransformGetData'); // Do not localize
FTransformApplyUpdates := CreateNestedTransform(Self, 'TransformApplyUpdates'); // Do not localize
FTransformSetParams := CreateNestedTransform(Self, 'TransformSetParams'); // Do not localize
FDataCache := TClientDataSet.Create(Self);
inherited;
end;
destructor TXMLTransformClient.Destroy;
begin
inherited;
FLocalAppServer.Free;
end;
procedure TXMLTransformClient.SetupAppServer;
var
ProvComp: TComponent;
begin
if not Assigned(FDataCache.RemoteServer) or not FDataCache.HasAppServer then
begin
ProvComp := Owner.FindComponent(ProviderName);
if Assigned(ProvComp) and (ProvComp is TCustomProvider) then
FDataCache.AppServer := TLocalAppServer.Create(TCustomProvider(ProvComp));
end;
end;
function TXMLTransformClient.GetDataAsXml(const PublishTransformFile: string): string;
var
RecsOut: Integer;
Params, OwnerData, VarPacket: OleVariant;
TransFileName, XmlData: string;
Options: TGetRecordOptions;
begin
SetupAppServer;
if FDataCache.Params.Count > 0 then
Params := PackageParams(FDataCache.Params);
Options := [grMetaData, grXML];
VarPacket := FDataCache.AppServer.AS_GetRecords(GetProviderName, -1,
RecsOut, Byte(Options), '', Params, OwnerData);
XmlData := VariantArrayToString(VarPacket);
if PublishTransformFile <> '' then
TransFileName := PublishTransformFile else
TransFileName := FTransformGetData.TransformationFile;
Result := FTransformGetData.TransformXML(XMLData, TransFileName);
if (Result <> '') and (FTransformGetData.ResultDocument <> nil) and
(FTransformGetData.EncodingTrans <> '') then
SetEncoding(FTransformGetData.ResultDocument,
FTransformGetData.EncodingTrans, True);
end;
function TXMLTransformClient.ApplyUpdates(const UpdateXML, UpdateTransformFile: string;
MaxErrors: Integer): Integer;
var
Delta: Variant;
OwnerData: OleVariant;
TransFileName: string;
begin
SetupAppServer;
if UpdateTransformFile <> '' then
TransFileName := UpdateTransformFile else
TransFileName := FTransformApplyUpdates.TransformationFile;
Delta := FTransformApplyUpdates.TransformXML(UpdateXML, TransFileName);
try
FDataCache.AppServer.AS_ApplyUpdates(GetProviderName,
StringToVariantArray(Delta), MaxErrors, Result, OwnerData);
except
end;
end;
function TXMLTransformClient.GetProviderName: string;
begin
Result := FDataCache.ProviderName;
end;
procedure TXMLTransformClient.SetProviderName(const Value: string);
begin
FDataCache.ProviderName := Value;
end;
function TXMLTransformClient.GetRemoteServer: TCustomRemoteServer;
begin
Result := FDataCache.RemoteServer;
end;
procedure TXMLTransformClient.SetRemoteServer(const Value: TCustomRemoteServer);
begin
FDataCache.RemoteServer := Value;
end;
procedure TXMLTransformClient.SetParams(const ParamsXml, ParamsTransformFile: string);
var
I: Integer;
Field: TField;
Param: TParam;
S: string;
begin
if FSetParamsdataCache = nil then
FSetParamsdataCache := TClientDataSet.Create(Self);
with FSetParamsdataCache do
begin
Active := False;
S := FTransformSetParams.TransformXML(ParamsXML, ParamsTransformFile);
Data := StringToVariantArray(S);
if (Active) and (Fields.Count > 0) then
begin
First;
if not EOF then
for I := 0 to Fields.Count -1 do
begin
Field := Fields[I];
Param := FDataCache.Params.FindParam(Field.FieldName);
if Param = nil then
Param := FDataCache.Params.CreateParam(Field.DataType, Field.FieldName, ptInput);
Param.Value := Field.Value;
end;
end;
end;
end;
end.
|
unit uROR_GridView;
{$I Components.inc}
interface
uses
ComCtrls, Controls, Classes, Graphics, Variants, uROR_Utilities,
uROR_CustomListView, Messages, CommCtrl, OvcFiler;
type
TCCRGridView = class;
TCCRGridDataType = (gftUnknown, gftString, gftInteger, gftDateTime,
gftDouble, gftFMDate, gftBoolean, gftMUMPS);
//----------------------------- TCCRGridField(s) -----------------------------
TCCRGridField = class(TCollectionItem)
private
fAlignment: TAlignment;
fAllowResize: Boolean;
fAllowSort: Boolean;
fAutoSize: Boolean;
fCaption: String;
fColIndex: Integer;
fDataType: TCCRGridDataType;
fFMDTOptions: TFMDateTimeMode;
fFormat: String;
fMaxWidth: Integer;
fMinWidth: Integer;
fTag: Longint;
fVisible: Boolean;
fWidth: Integer;
protected
function GetDisplayName: String; override;
function getGridView: TCCRGridView;
procedure setAlignment(const aValue: TAlignment); virtual;
procedure setAutoSize(const aValue: Boolean); virtual;
procedure setCaption(const aValue: String); virtual;
procedure setDataType(const aValue: TCCRGridDataType); virtual;
procedure setFMDTOptions(const aValue: TFMDateTimeMode); virtual;
procedure setFormat(const aValue: String); virtual;
procedure setMaxWidth(const aValue: Integer); virtual;
procedure setMinWidth(const aValue: Integer); virtual;
procedure setTag(const aValue: Longint); virtual;
procedure setVisible(const aValue: Boolean); virtual;
procedure setWidth(const aValue: Integer); virtual;
function validColumn(const aColumnIndex: Integer): Boolean;
property ColIndex: Integer read fColIndex
write fColIndex;
public
constructor Create(aCollection: TCollection); override;
procedure Assign(Source: TPersistent); override;
procedure AssignTo(aDest: TPersistent); override;
property GridView: TCCRGridView read getGridView;
published
property Alignment: TAlignment read fAlignment
write setAlignment
default taLeftJustify;
property AllowResize: Boolean read fAllowResize
write fAllowResize
default True;
property AllowSort: Boolean read fAllowSort
write fAllowSort
default True;
property AutoSize: Boolean read fAutoSize
write setAutoSize;
property Caption: String read fCaption
write setCaption;
property DataType: TCCRGridDataType read fDataType
write setDataType
default gftString;
property FMDTOptions: TFMDateTimeMode read fFMDTOptions
write setFMDTOptions
default fmdtShortDateTime;
property Format: String read fFormat
write setFormat;
property MaxWidth: Integer read fMaxWidth
write setMaxWidth;
property MinWidth: Integer read fMinWidth
write setMinWidth;
property Tag: Longint read fTag
write setTag;
property Visible: Boolean read fVisible
write setVisible
default True;
property Width: Integer read fWidth
write setWidth
default 50;
end;
TCCRGridFieldClass = class of TCCRGridField;
TCCRGridFields = class(TOwnedCollection)
protected
function GetItem(anIndex: Integer): TCCRGridField;
function getGridView: TCCRGridView;
procedure Notify(anItem: TCollectionItem; anAction: TCollectionNotification); override;
procedure Update(anItem: TCollectionItem); override;
public
constructor Create(anOwner: TCCRGridView;
anItemClass: TCCRGridFieldClass = nil);
function GetColumn(aColumnIndex: Integer): TListColumn;
property GridView: TCCRGridView read getGridView;
property Items[anIndex: Integer]: TCCRGridField read GetItem; default;
end;
//------------------------------ TCCRGridItem(s) -----------------------------
TCCRFieldData = record
VString: String;
MType: TCCRGridDataType;
case TCCRGridDataType of
gftBoolean: (VBoolean: Boolean);
gftDateTime: (VDateTime: TDateTime);
gftDouble: (VDouble: Double);
gftInteger: (VInteger: Integer);
end;
TCCRFieldDataArray = array of TCCRFieldData;
PCCRFieldDataArray = ^TCCRFieldDataArray;
TCCRGridItem = class(TCCRCustomListItem)
private
fFieldData: array of TCCRFieldData;
function getListView: TCCRGridView;
protected
function formatFieldValue(aFieldIndex: Integer): String;
function getAsBoolean(aFieldIndex: Integer): Boolean;
function getAsDateTime(aFieldIndex: Integer): TDateTime;
function getAsDouble(aFieldIndex: Integer): Double;
function getAsInteger(aFieldIndex: Integer): Integer;
function getAsString(aFieldIndex: Integer): String;
function getFieldValue(const aFieldIndex: Integer;
var anInternalValue: Variant): String; override;
function getFormatted(aFieldIndex: Integer): String;
procedure setAsBoolean(aFieldIndex: Integer; const aValue: Boolean);
procedure setAsDateTime(aFieldIndex: Integer; const aValue: TDateTime);
procedure setAsDouble(aFieldIndex: Integer; const aValue: Double);
procedure setAsInteger(aFieldIndex: Integer; const aValue: Integer);
procedure setAsString(aFieldIndex: Integer; const aValue: String);
public
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure AssignRawData(const RawData: String; anIndexList: array of Integer;
const Separator: String = '^');
function GetDataType(aFieldIndex: Integer): TCCRGridDataType;
function GetRawData(anIndexList: array of Integer;
const Separator: String = '^'): String;
procedure UpdateStringValues(const aFieldIndex: Integer); override;
property AsBoolean[anIndex: Integer]: Boolean read getAsBoolean
write setAsBoolean;
property AsDateTime[anIndex: Integer]: TDateTime read getAsDateTime
write setAsDateTime;
property AsDouble[anIndex: Integer]: Double read getAsDouble
write setAsDouble;
property AsInteger[anIndex: Integer]: Integer read getAsInteger
write setAsInteger;
property AsString[anIndex: Integer]: String read getAsString
write setAsString;
property Formatted[anIndex: Integer]: String read getFormatted;
property ListView: TCCRGridView read getListView;
end;
TCCRGridItems = class(TCCRCustomListItems)
private
function getItem(anIndex: Integer): TCCRGridItem;
procedure setItem(anIndex: Integer; const aValue: TCCRGridItem);
public
function Add: TCCRGridItem;
function AddItem(anItem: TCCRGridItem; anIndex: Integer = -1): TCCRGridItem;
procedure AppendRawData(RawData: TStrings; anIndexList: array of Integer;
const Separator: String = '^'; const numStrPerItem: Integer = 1);
procedure AssignRawData(RawData: TStrings; anIndexList: array of Integer;
const Separator: String = '^');
procedure GetRawData(RawData: TStrings; anIndexList: array of Integer;
const Separator: String = '^');
function Insert(anIndex: Integer): TCCRGridItem;
property Item[anIndex: Integer]: TCCRGridItem read getItem
write setItem;
default;
end;
//------------------------------- TCCRGridView -------------------------------
TCCRColumnResizeEvent = procedure(aSender: TCCRGridView;
aColumn: TListColumn) of object;
TCCRFormatFieldValueEvent = procedure (aSender: TObject; anItem: TCCRGridItem;
const aFieldIndex: Integer; var aResult: String; var Default: Boolean) of object;
TCCRGridView = class(TCCRCustomListView)
private
fFields: TCCRGridFields;
fOnFieldValueFormat: TCCRFormatFieldvalueEvent;
fOnColumnResize: TCCRColumnResizeEvent;
function getItemFocused: TCCRGridItem;
function getItems: TCCRGridItems;
function getSelected: TCCRGridItem;
procedure setItemFocused(aValue: TCCRGridItem);
procedure setSelected(aValue: TCCRGridItem);
protected
procedure CompareItems(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer); override;
function CreateListItem: TListItem; override;
function CreateListItems: TListItems; override;
procedure CreateWnd; override;
procedure DoOnColumnResize(aColumn: TListColumn); virtual;
function getSortColumn: Integer; override;
procedure setFields(const aValue: TCCRGridFields); virtual;
procedure UpdateColumns(const aClrFlg: Boolean); virtual;
procedure WMNotify(var Msg: TWMNotify); message WM_NOTIFY;
property Columns;
public
constructor Create(anOwner: TComponent); override;
destructor Destroy; override;
function ColumnIndex(const aFieldIndex: Integer;
const SortableOnly: Boolean = False): Integer; override;
function FieldIndex(const aColumnIndex: Integer;
const SortableOnly: Boolean = False): Integer; override;
function GetNextItem(StartItem: TCCRCustomListItem;
Direction: TSearchDirection; States: TItemStates): TCCRGridItem;
procedure LoadLayout(aStorage: TOvcAbstractStore; const aSection: String); virtual;
procedure SaveLayout(aStorage: TOvcAbstractStore; const aSection: String); virtual;
property ItemFocused: TCCRGridItem read getItemFocused
write setItemFocused;
property Items: TCCRGridItems read getItems;
property Selected: TCCRGridItem read getSelected
write setSelected;
property SortColumn;
published
property Action;
property Align;
property AllocBy;
property Anchors;
property BevelEdges;
property BevelInner;
property BevelKind default bkNone;
property BevelOuter;
property BevelWidth;
property BiDiMode;
property BorderStyle;
property BorderWidth;
property Checkboxes;
property Color;
property ColumnClick;
//property Columns;
property Constraints;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FlatScrollBars;
property Font;
//property FullDrag;
property GridLines default True;
property HideSelection;
property HotTrack;
property HotTrackStyles;
property HoverTime;
property IconOptions;
property LargeImages;
property MultiSelect;
property OwnerData;
property OwnerDraw;
property ParentBiDiMode;
property ParentColor default False;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly default False;
property RowSelect default True;
property ShowColumnHeaders default True;
property ShowHint;
property ShowWorkAreas;
property SmallImages;
//property SortType;
property StateImages;
property TabOrder;
property TabStop default True;
//property ViewStyle;
property Visible;
property OnAdvancedCustomDraw;
property OnAdvancedCustomDrawItem;
property OnAdvancedCustomDrawSubItem;
property OnChange;
property OnChanging;
property OnClick;
property OnColumnClick;
//property OnColumnDragged;
property OnColumnRightClick;
//property OnCompare;
property OnContextPopup;
property OnCustomDraw;
property OnCustomDrawItem;
property OnCustomDrawSubItem;
property OnData;
property OnDataFind;
property OnDataHint;
property OnDataStateChange;
property OnDblClick;
property OnDeletion;
property OnDragDrop;
property OnDragOver;
property OnDrawItem;
property OnEdited;
property OnEditing;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetImageIndex;
property OnGetSubItemImage;
property OnInfoTip;
property OnInsert;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnSelectItem;
property OnStartDock;
property OnStartDrag;
property SortDescending;
property SortField;
property Fields: TCCRGridFields read fFields
write setFields;
property OnColumnResize: TCCRColumnResizeEvent read fOnColumnResize
write fOnColumnResize;
property OnFieldValueFormat: TCCRFormatFieldValueEvent
read fOnFieldValueFormat
write fOnFieldValueFormat;
end;
implementation
uses
uROR_Resources, SysUtils;
//////////////////////////////// TCCRGridField \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
constructor TCCRGridField.Create(aCollection: TCollection);
begin
fAlignment := taLeftJustify;
fAllowResize := True;
fAllowSort := True;
fColIndex := -1;
fDataType := gftString;
fFMDTOptions := fmdtShortDateTime;
fVisible := True;
fWidth := 50;
inherited;
end;
procedure TCCRGridField.Assign(Source: TPersistent);
begin
if Source is TCCRGridField then
with TCCRGridField(Source) do
begin
Self.Alignment := Alignment;
Self.AllowResize := AllowResize;
Self.AllowSort := AllowSort;
Self.AutoSize := AutoSize;
Self.Caption := Caption;
Self.ColIndex := ColIndex;
Self.DataType := DataType;
Self.FMDTOptions := FMDTOptions;
Self.Format := Format;
Self.MaxWidth := MaxWidth;
Self.MinWidth := MinWidth;
Self.Tag := Tag;
Self.Visible := Visible;
Self.Width := Width;
end
else if Source is TListColumn then
with TListColumn(Source) do
begin
Self.Alignment := Alignment;
Self.AutoSize := AutoSize;
Self.MaxWidth := MaxWidth;
Self.MinWidth := MinWidth;
Self.Width := Width;
Self.Caption := Caption;
end
else
inherited;
end;
procedure TCCRGridField.AssignTo(aDest: TPersistent);
var
wdc: Boolean;
begin
if aDest is TListColumn then
with TListColumn(aDest) do
begin
wdc := (Self.Width <> Width);
Alignment := Self.Alignment;
AutoSize := Self.AutoSize;
MaxWidth := Self.MaxWidth;
MinWidth := Self.MinWidth;
Tag := Self.Index;
Width := Self.Width;
Caption := Self.Caption;
if wdc and Assigned(GridView) then
GridView.DoOnColumnResize(TListColumn(aDest));
end
else
inherited;
end;
function TCCRGridField.GetDisplayName: String;
begin
if fCaption <> '' then
Result := Caption
else
Result := inherited GetDisplayName;
end;
function TCCRGridField.getGridView: TCCRGridView;
begin
if Assigned(Collection) then
Result := TCCRGridFields(Collection).GridView
else
Result := nil;
end;
procedure TCCRGridField.setAlignment(const aValue: TAlignment);
begin
if aValue <> fAlignment then
begin
fAlignment := aValue;
if validColumn(ColIndex) then
GridView.Columns[ColIndex].Alignment := aValue;
Changed(False);
end;
end;
procedure TCCRGridField.setAutoSize(const aValue: Boolean);
begin
if aValue <> fAutoSize then
begin
fAutoSize := aValue;
if validColumn(ColIndex) then
GridView.Columns[ColIndex].AutoSize := aValue;
Changed(False);
end;
end;
procedure TCCRGridField.setCaption(const aValue: String);
begin
if aValue <> fCaption then
begin
fCaption := aValue;
if validColumn(ColIndex) then
GridView.Columns[ColIndex].Caption := aValue;
Changed(False);
end;
end;
procedure TCCRGridField.setDataType(const aValue: TCCRGridDataType);
begin
if aValue <> fDataType then
begin
fDataType := aValue;
Changed(False);
end;
end;
procedure TCCRGridField.setFMDTOptions(const aValue: TFMDateTimeMode);
begin
if aValue <> fFMDTOptions then
begin
fFMDTOptions := aValue;
Changed(False);
end;
end;
procedure TCCRGridField.setFormat(const aValue: String);
begin
if aValue <> fFormat then
begin
fFormat := aValue;
Changed(False);
end;
end;
procedure TCCRGridField.setMaxWidth(const aValue: Integer);
begin
if aValue <> fmaxWidth then
begin
fMaxWidth := aValue;
if validColumn(ColIndex) then
GridView.Columns[ColIndex].MaxWidth := aValue;
Changed(False);
end;
end;
procedure TCCRGridField.setMinWidth(const aValue: Integer);
begin
if aValue <> fMinWidth then
begin
fMinWidth := aValue;
if validColumn(ColIndex) then
GridView.Columns[ColIndex].MinWidth := aValue;
Changed(False);
end;
end;
procedure TCCRGridField.setTag(const aValue: Longint);
begin
if aValue <> fTag then
begin
fTag := aValue;
Changed(False);
end;
end;
procedure TCCRGridField.setVisible(const aValue: Boolean);
begin
if aValue <> fVisible then
begin
fVisible := aValue;
Changed(True);
end;
end;
procedure TCCRGridField.setWidth(const aValue: Integer);
begin
if aValue <> fWidth then
begin
fWidth := aValue;
if validColumn(ColIndex) then
with GridView do
begin
Columns[ColIndex].Width := aValue;
DoOnColumnResize(Columns[ColIndex]);
end;
Changed(False);
end;
end;
function TCCRGridField.validColumn(const aColumnIndex: Integer): Boolean;
begin
if Assigned(GridView) then
Result := (aColumnIndex >= 0) and (aColumnIndex < GridView.Columns.Count)
else
Result := False;
end;
///////////////////////////////// TCCRGridFields \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
constructor TCCRGridFields.Create(anOwner: TCCRGridView;
anItemClass: TCCRGridFieldClass);
begin
if Assigned(anItemClass) then
inherited Create(anOwner, anItemClass)
else
inherited Create(anOwner, TCCRGridField);
end;
function TCCRGridFields.GetColumn(aColumnIndex: Integer): TListColumn;
begin
Result := nil;
if Assigned(GridView) then
if (aColumnIndex >= 0) and (aColumnIndex < GridView.Columns.Count) then
Result := GridView.Columns[aColumnIndex];
end;
function TCCRGridFields.getGridView: TCCRGridView;
begin
Result := TCCRGridView(Owner);
end;
function TCCRGridFields.GetItem(anIndex: Integer): TCCRGridField;
begin
Result := TCCRGridField(inherited GetItem(anIndex));
end;
procedure TCCRGridFields.Notify(anItem: TCollectionItem;
anAction: TCollectionNotification);
var
col: TListColumn;
fld: TCCRGridField;
begin
inherited;
fld := TCCRGridField(anItem);
case anAction of
cnAdded:
if fld.Visible and Assigned(GridView) then
begin
col := GridView.Columns.Add;
col.Assign(fld);
fld.ColIndex := col.Index;
end;
cnDeleting, cnExtracting:
if Assigned(GridView) then
begin
col := GetColumn(fld.ColIndex);
if Assigned(col) then
GridView.Columns.Delete(col.Index);
fld.ColIndex := -1;
end;
end;
end;
procedure TCCRGridFields.Update(anItem: TCollectionItem);
begin
inherited;
if (anItem = nil) and Assigned(GridView) then
GridView.UpdateColumns(True);
end;
////////////////////////////////// TCCRGridItem \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
destructor TCCRGridItem.Destroy;
var
i: Integer;
begin
for i:=0 to High(fFieldData) do
fFieldData[i].VString := '';
SetLength(fFieldData, 0);
fFieldData := nil;
inherited;
end;
procedure TCCRGridItem.Assign(Source: TPersistent);
var
i: Integer;
si: TCCRGridItem;
begin
inherited;
if Source is TCCRGridItem then
begin
si := TCCRGridItem(Source);
SetLength(fFieldData, High(si.fFieldData)+1);
for i:=0 to High(fFieldData) do
fFieldData[i] := si.fFieldData[i];
end
end;
procedure TCCRGridItem.AssignRawData(const RawData: String;
anIndexList: array of Integer; const Separator: String);
var
i, ip, n: Integer;
begin
n := ListView.Fields.Count - 1;
if n > High(anIndexList) then n := High(anIndexList);
BeginUpdate;
try
for i:=0 to n do
begin
ip := anIndexList[i];
if ip > 0 then
AsString[i] := Piece(RawData, Separator, ip);
end;
finally
EndUpdate;
end;
end;
function TCCRGridItem.formatFieldValue(aFieldIndex: Integer): String;
var
dt: TCCRGridDataType;
defaultFormat: Boolean;
begin
Result := '';
dt := GetDataType(aFieldIndex);
if (dt = gftUnknown) or (aFieldIndex > High(fFieldData)) then Exit;
with ListView do
begin
//--- Get the custom-formatted external value (if possible)
if Assigned(OnFieldValueFormat) then
begin
defaultFormat := False;
OnFieldValueFormat(ListView, Self, aFieldIndex, Result, defaultFormat);
end
else
defaultFormat := True;
//--- Get the default external value of the field
if defaultFormat then
case dt of
gftBoolean:
Result := BooleanToString(
fFieldData[aFieldIndex].VBoolean,
Fields[aFieldIndex].Format);
gftDateTime:
if fFieldData[aFieldIndex].VDateTime > 0 then
Result := FormatDateTime(
Fields[aFieldIndex].Format,
fFieldData[aFieldIndex].VDateTime);
gftDouble:
Result := FormatFloat(
Fields[aFieldIndex].Format,
fFieldData[aFieldIndex].VDouble);
gftFMDate:
if fFieldData[aFieldIndex].VDouble > 0 then
Result := FMDateTimeStr(
FloatToStr(fFieldData[aFieldIndex].VDouble),
Fields[aFieldIndex].FMDTOptions);
gftInteger:
if Fields[aFieldIndex].Format <> '' then
Result := Format(
Fields[aFieldIndex].Format,
[fFieldData[aFieldIndex].VInteger])
else
Result := IntToStr(fFieldData[aFieldIndex].VInteger);
gftString, gftMUMPS:
if Fields[aFieldIndex].Format <> '' then
Result := Format(
Fields[aFieldIndex].Format,
[fFieldData[aFieldIndex].VString])
else
Result := fFieldData[aFieldIndex].VString;
end;
end;
end;
function TCCRGridItem.getAsBoolean(aFieldIndex: Integer): Boolean;
var
dt: TCCRGridDataType;
begin
Result := False;
if aFieldIndex <= High(fFieldData) then
begin
dt := GetDataType(aFieldIndex);
if dt = gftMUMPS then
dt := fFieldData[aFieldIndex].MType;
case dt of
gftBoolean:
Result := fFieldData[aFieldIndex].VBoolean;
gftDateTime:
Result := (fFieldData[aFieldIndex].VDateTime > 0);
gftDouble:
Result := (fFieldData[aFieldIndex].VDouble <> 0);
gftFMDate:
Result := (fFieldData[aFieldIndex].VDouble > 0);
gftInteger:
Result := (fFieldData[aFieldIndex].VInteger <> 0);
gftString:
Result := StrToBoolDef(fFieldData[aFieldIndex].VString, False);
end;
end;
end;
function TCCRGridItem.getAsDateTime(aFieldIndex: Integer): TDateTime;
var
dt: TCCRGridDataType;
begin
Result := 0;
if aFieldIndex <= High(fFieldData) then
begin
dt := GetDataType(aFieldIndex);
if dt = gftMUMPS then
dt := fFieldData[aFieldIndex].MType;
case dt of
gftBoolean:
Result := -1;
gftDateTime:
Result := fFieldData[aFieldIndex].VDateTime;
gftDouble, gftFMDate:
Result := fFieldData[aFieldIndex].VDouble;
gftInteger:
Result := fFieldData[aFieldIndex].VInteger;
gftString:
Result := StrToFloatDef(fFieldData[aFieldIndex].VString, 0);
end;
end;
if Result < 0 then
raise EConvertError.Create(RSC0020);
end;
function TCCRGridItem.getAsDouble(aFieldIndex: Integer): Double;
var
dt: TCCRGridDataType;
begin
Result := 0;
if aFieldIndex <= High(fFieldData) then
begin
dt := GetDataType(aFieldIndex);
if dt = gftMUMPS then
dt := fFieldData[aFieldIndex].MType;
case dt of
gftBoolean:
if fFieldData[aFieldIndex].VBoolean then
Result := 1
else
Result := 0;
gftDateTime:
Result := fFieldData[aFieldIndex].VDateTime;
gftDouble, gftFMDate:
Result := fFieldData[aFieldIndex].VDouble;
gftInteger:
Result := fFieldData[aFieldIndex].VInteger;
gftString:
Result := StrToFloatDef(fFieldData[aFieldIndex].VString, 0);
end;
end;
end;
function TCCRGridItem.getAsInteger(aFieldIndex: Integer): Integer;
var
dt: TCCRGridDataType;
begin
Result := 0;
if aFieldIndex <= High(fFieldData) then
begin
dt := GetDataType(aFieldIndex);
if dt = gftMUMPS then
dt := fFieldData[aFieldIndex].MType;
case dt of
gftBoolean:
if fFieldData[aFieldIndex].VBoolean then
Result := 1
else
Result := 0;
gftDateTime:
Result := Trunc(fFieldData[aFieldIndex].VDateTime);
gftDouble, gftFMDate:
Result := Trunc(fFieldData[aFieldIndex].VDouble);
gftInteger:
Result := fFieldData[aFieldIndex].VInteger;
gftString:
Result := StrToIntDef(fFieldData[aFieldIndex].VString, 0);
end;
end;
end;
function TCCRGridItem.getAsString(aFieldIndex: Integer): String;
begin
Result := '';
if (aFieldIndex >= 0) and (aFieldIndex <= High(fFieldData)) then
Result := fFieldData[aFieldIndex].VString;
end;
function TCCRGridItem.GetDataType(aFieldIndex: Integer): TCCRGridDataType;
begin
Result := gftUnknown;
if Assigned(ListView) then
with ListView do
if (aFieldIndex >= 0) and (aFieldIndex < Fields.Count) then
Result := Fields[aFieldIndex].DataType;
end;
function TCCRGridItem.getFieldValue(const aFieldIndex: Integer;
var anInternalValue: Variant): String;
var
dt: TCCRGridDataType;
begin
Result := '';
dt := GetDataType(aFieldIndex);
if dt = gftMUMPS then
dt := fFieldData[aFieldIndex].MType;
case dt of
gftBoolean:
begin
anInternalValue := fFieldData[aFieldIndex].VBoolean;
Result := fFieldData[aFieldIndex].VString;
end;
gftDateTime:
begin
anInternalValue := fFieldData[aFieldIndex].VDateTime;
Result := fFieldData[aFieldIndex].VString;
end;
gftDouble, gftFMDate:
begin
anInternalValue := fFieldData[aFieldIndex].VDouble;
Result := fFieldData[aFieldIndex].VString;
end;
gftInteger:
begin
anInternalValue := fFieldData[aFieldIndex].VInteger;
Result := fFieldData[aFieldIndex].VString;
end;
gftString:
begin
anInternalValue := fFieldData[aFieldIndex].VString;
Result := anInternalValue;
end;
end;
end;
function TCCRGridItem.getFormatted(aFieldIndex: Integer): String;
begin
if (aFieldIndex < 0) or (aFieldIndex >= ListView.Fields.Count) then
Result := ''
else if ListView.Fields[aFieldIndex].Visible then
Result := StringValues[ListView.ColumnIndex(aFieldIndex)]
else
Result := formatFieldValue(aFieldIndex);
end;
function TCCRGridItem.getListView: TCCRGridView;
begin
Result := inherited ListView as TCCRGridView;
end;
function TCCRGridItem.GetRawData(anIndexList: array of Integer;
const Separator: String): String;
var
i, ifld, lastFld: Integer;
begin
Result := '';
lastFld := ListView.Fields.Count - 1;
for i:=0 to High(anIndexList) do
begin
ifld := anIndexList[i];
if (ifld >= 0) and (ifld <= lastFld) then
Result := Result + AsString[ifld] + Separator
else
Result := Result + Separator;
end;
end;
procedure TCCRGridItem.setAsBoolean(aFieldIndex: Integer; const aValue: Boolean);
var
dt: TCCRGridDataType;
begin
dt := GetDataType(aFieldIndex);
if dt = gftUnknown then Exit;
with ListView do
begin
if aFieldIndex > High(fFieldData) then
SetLength(fFieldData, aFieldIndex+1);
if dt = gftMUMPS then
begin
fFieldData[aFieldIndex].MType := gftDouble;
dt := gftDouble;
end;
case dt of
gftBoolean:
fFieldData[aFieldIndex].VBoolean := aValue;
gftDateTime, gftFMDate:
raise EConvertError.Create(RSC0020);
gftDouble:
if aValue then
fFieldData[aFieldIndex].VDouble := 1
else
fFieldData[aFieldIndex].VDouble := 0;
gftInteger:
if aValue then
fFieldData[aFieldIndex].VInteger := 1
else
fFieldData[aFieldIndex].VInteger := 0;
gftString:
fFieldData[aFieldIndex].VString := BoolToStr(aValue);
end;
UpdateStringValues(aFieldIndex);
end;
end;
procedure TCCRGridItem.setAsDateTime(aFieldIndex: Integer; const aValue: TDateTime);
begin
setAsDouble(aFieldIndex, aValue);
end;
procedure TCCRGridItem.setAsDouble(aFieldIndex: Integer; const aValue: Double);
var
dt: TCCRGridDataType;
begin
dt := GetDataType(aFieldIndex);
if dt = gftUnknown then Exit;
with ListView do
begin
if aFieldIndex > High(fFieldData) then
SetLength(fFieldData, aFieldIndex+1);
if dt = gftMUMPS then
begin
fFieldData[aFieldIndex].MType := gftDouble;
dt := gftDouble;
end;
case dt of
gftBoolean:
fFieldData[aFieldIndex].VBoolean := (aValue <> 0);
gftDateTime:
fFieldData[aFieldIndex].VDateTime := aValue;
gftDouble, gftFMDate:
fFieldData[aFieldIndex].VDouble := aValue;
gftInteger:
fFieldData[aFieldIndex].VInteger := Trunc(aValue);
gftString:
fFieldData[aFieldIndex].VString := FloatToStr(aValue);
end;
UpdateStringValues(aFieldIndex);
end;
end;
procedure TCCRGridItem.setAsInteger(aFieldIndex: Integer; const aValue: Integer);
var
dt: TCCRGridDataType;
begin
dt := GetDataType(aFieldIndex);
if dt = gftUnknown then Exit;
with ListView do
begin
if aFieldIndex > High(fFieldData) then
SetLength(fFieldData, aFieldIndex+1);
if dt = gftMUMPS then
begin
fFieldData[aFieldIndex].MType := gftDouble;
dt := gftDouble;
end;
case dt of
gftBoolean:
fFieldData[aFieldIndex].VBoolean := (aValue <> 0);
gftDateTime:
fFieldData[aFieldIndex].VDateTime := aValue;
gftDouble, gftFMDate:
fFieldData[aFieldIndex].VDouble := aValue;
gftInteger:
fFieldData[aFieldIndex].VInteger := aValue;
gftString:
fFieldData[aFieldIndex].VString := IntToStr(aValue);
end;
UpdateStringValues(aFieldIndex);
end;
end;
procedure TCCRGridItem.setAsString(aFieldIndex: Integer; const aValue: String);
var
dt: TCCRGridDataType;
begin
dt := GetDataType(aFieldIndex);
if dt = gftUnknown then Exit;
with ListView do
begin
if aFieldIndex > High(fFieldData) then
SetLength(fFieldData, aFieldIndex+1);
case dt of
gftBoolean:
fFieldData[aFieldIndex].VBoolean := StrToBoolDef(aValue, False);
gftDateTime:
fFieldData[aFieldIndex].VDateTime := StrToDateTimeDef(aValue, 0);
gftDouble, gftFMDate:
fFieldData[aFieldIndex].VDouble := StrToFloatDef(aValue, 0);
gftInteger:
fFieldData[aFieldIndex].VInteger := StrToIntDef(aValue, 0);
gftMUMPS:
try
fFieldData[aFieldIndex].VDouble := StrToFloat(aValue);
fFieldData[aFieldIndex].MType := gftDouble;
except
fFieldData[aFieldIndex].VString := aValue;
fFieldData[aFieldIndex].MType := gftString;
end;
gftString:
fFieldData[aFieldIndex].VString := aValue;
end;
UpdateStringValues(aFieldIndex);
end;
end;
procedure TCCRGridItem.UpdateStringValues(const aFieldIndex: Integer);
var
i, n: Integer;
procedure update_field(const aFieldIndex: Integer);
var
dt: TCCRGridDataType;
begin
dt := GetDataType(aFieldIndex);
if (dt = gftUnknown) or (aFieldIndex > High(fFieldData)) then Exit;
//--- Update the internal string value of the field
with fFieldData[aFieldIndex] do
begin
if dt = gftMUMPS then
dt := MType;
case dt of
gftBoolean:
VString := BoolToStr(VBoolean);
gftDateTime:
VString := FloatToStr(VDateTime);
gftDouble, gftFMDate:
VString := FloatToStr(VDouble);
gftInteger:
VString := IntToStr(VInteger);
end;
end;
//--- Update the Caption or SubItem if the field is visible
with ListView do
if Fields[aFieldIndex].Visible then
StringValues[ColumnIndex(aFieldIndex)] := formatFieldValue(aFieldIndex);
end;
begin
if UpdateLock = 0 then
if aFieldIndex >= 0 then
update_field(aFieldIndex)
else
begin
SubItems.BeginUpdate;
try
n := ListView.Fields.Count - 1;
for i:=0 to n do
update_field(i);
finally
SubItems.EndUpdate;
end;
end;
end;
////////////////////////////////// TCCRGridItems \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function TCCRGridItems.Add: TCCRGridItem;
begin
Result := TCCRGridItem(inherited Add);
end;
function TCCRGridItems.AddItem(anItem: TCCRGridItem; anIndex: Integer): TCCRGridItem;
begin
Result := TCCRGridItem(inherited AddItem(anItem, anIndex));
end;
procedure TCCRGridItems.AppendRawData(RawData: TStrings; anIndexList: array of Integer;
const Separator: String; const numStrPerItem: Integer);
var
i, j: Integer;
buf: String;
gi : TCCRGridItem;
begin
BeginUpdate;
try
i := 0;
while i < RawData.Count do
begin
buf := RawData[i];
Inc(i);
for j:=2 to numStrPerItem do
begin
if i >= RawData.Count then
Break;
buf := buf + Separator + RawData[i];
Inc(i);
end;
gi := Add;
if Assigned(gi) then
gi.AssignRawData(buf, anIndexList, Separator);
end;
finally
EndUpdate;
end;
end;
procedure TCCRGridItems.AssignRawData(RawData: TStrings;
anIndexList: array of Integer; const Separator: String);
begin
BeginUpdate;
try
Clear;
AppendRawData(RawData, anIndexList, Separator);
finally
EndUpdate;
end;
end;
function TCCRGridItems.getItem(anIndex: Integer): TCCRGridItem;
begin
Result := inherited Item[anIndex] as TCCRGridItem;
end;
procedure TCCRGridItems.GetRawData(RawData: TStrings; anIndexList: array of Integer;
const Separator: String);
var
i, numItems: Integer;
buf: String;
begin
RawData.BeginUpdate;
try
RawData.Clear;
numItems := Count - 1;
for i:=0 to numItems do
begin
buf := Item[i].GetRawData(anIndexList, Separator);
RawData.Add(buf);
end;
finally
RawData.EndUpdate;
end;
end;
function TCCRGridItems.Insert(anIndex: Integer): TCCRGridItem;
begin
Result := TCCRGridItem(inherited Insert(anIndex));
end;
procedure TCCRGridItems.setItem(anIndex: Integer; const aValue: TCCRGridItem);
begin
Item[anIndex].Assign(aValue);
end;
////////////////////////////////// TCCRGridView \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
constructor TCCRGridView.Create(anOwner: TComponent);
begin
inherited;
BevelKind := bkNone;
GridLines := True;
ParentColor := False;
ReadOnly := False;
RowSelect := True;
ShowColumnHeaders := True;
TabStop := True;
ViewStyle := vsReport;
fFields := TCCRGridFields.Create(Self);
fOnColumnResize := nil;
fOnFieldValueFormat := nil;
end;
destructor TCCRGridView.Destroy;
begin
FreeAndNil(fFields);
inherited;
end;
function TCCRGridView.ColumnIndex(const aFieldIndex: Integer;
const SortableOnly: Boolean): Integer;
begin
if (aFieldIndex >= 0) and (aFieldIndex < Fields.Count) then
begin
if Fields[aFieldIndex].AllowSort then
begin
Result := Fields[aFieldIndex].ColIndex;
if (Result < 0) or (Result >= Columns.Count) then
Result := -1;
end
else
Result := -1;
end
else
Result := -1;
end;
procedure TCCRGridView.CompareItems(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
var
dt1, dt2, dt: TCCRGridDataType;
iv1, iv2: Integer;
dv1, dv2: Double;
bv1, bv2: Boolean;
begin
if (SortField < 0) or (SortField >= Fields.Count) then Exit;
Compare := 0;
dt := Fields[SortField].DataType;
if dt = gftMUMPS then
begin
//--- Get the actual data types
dt1 := TCCRGridItem(Item1).fFieldData[SortField].MType;
dt2 := TCCRGridItem(Item2).fFieldData[SortField].MType;
//--- If they are different, perform MUMPS-like comparison.
//--- Otherwise, skip to the regular comparison of values.
if dt1 <> dt2 then
begin
//--- Item1
if TCCRGridItem(Item1).getAsString(SortField) = '' then
Dec(Compare, 1)
else if dt1 = gftDouble then
Inc(Compare, 1)
else if dt1 = gftString then
Inc(Compare, 2);
//--- Item2
if TCCRGridItem(Item2).getAsString(SortField) = '' then
Inc(Compare, 1)
else if dt2 = gftDouble then
Dec(Compare, 1)
else if dt2 = gftString then
Dec(Compare, 2);
{
dv1\dv2 | empty | number | string
--------+-------+--------+---------
empty | 0 | -2 | -3
--------+-------+--------+---------
number | 2 | cmp. | -1
--------+-------+--------+---------
string | 3 | 1 | cmp.
}
if Compare < -1 then
Compare := -1;
if Compare > 1 then
Compare := 1;
end
else
dt := dt1;
end;
//--- Regular comparison of field values
case dt of
gftBoolean:
begin
bv1 := TCCRGridItem(Item1).getAsBoolean(SortField);
bv2 := TCCRGridItem(Item2).getAsBoolean(SortField);
if bv1 > bv2 then Compare := 1
else if bv1 < bv2 then Compare := -1;
end;
gftDateTime, gftDouble, gftFMDate:
begin
dv1 := TCCRGridItem(Item1).getAsDouble(SortField);
dv2 := TCCRGridItem(Item2).getAsDouble(SortField);
if dv1 > dv2 then Compare := 1
else if dv1 < dv2 then Compare := -1;
end;
gftInteger:
begin
iv1 := TCCRGridItem(Item1).getAsInteger(SortField);
iv2 := TCCRGridItem(Item2).getAsInteger(SortField);
if iv1 > iv2 then Compare := 1
else if iv1 < iv2 then Compare := -1;
end;
gftString:
Compare := CompareStr(
TCCRGridItem(Item1).getAsString(SortField),
TCCRGridItem(Item2).getAsString(SortField));
end;
//--- Reverse the sort order if necessary
if SortDescending then
Compare := -Compare;
end;
function TCCRGridView.CreateListItem: TListItem;
var
LClass: TListItemClass;
begin
LClass := TCCRGridItem;
if Assigned(OnCreateItemClass) then
OnCreateItemClass(Self, LClass);
Result := LClass.Create(Items);
end;
function TCCRGridView.CreateListItems: TListItems;
begin
Result := TCCRGridItems.Create(self);
end;
procedure TCCRGridView.CreateWnd;
begin
inherited;
UpdateColumns(False);
end;
procedure TCCRGridView.DoOnColumnResize(aColumn: TListColumn);
begin
if Assigned(OnColumnResize) then
OnColumnResize(Self, aColumn);
end;
function TCCRGridView.FieldIndex(const aColumnIndex: Integer;
const SortableOnly: Boolean): Integer;
begin
if (aColumnIndex >= 0) and (aColumnIndex < Columns.Count) then
begin
Result := Columns[aColumnIndex].Tag;
if (Result < 0) or (Result >= Fields.Count) then
Result := -1
else if not Fields[Result].AllowSort then
Result := -1;
end
else
Result := -1;
end;
function TCCRGridView.getItemFocused: TCCRGridItem;
begin
Result := inherited ItemFocused as TCCRGridItem;
end;
function TCCRGridView.getItems: TCCRGridItems;
begin
Result := inherited Items as TCCRGridItems;
end;
function TCCRGridView.GetNextItem(StartItem: TCCRCustomListItem;
Direction: TSearchDirection; States: TItemStates): TCCRGridItem;
begin
Result := TCCRGridItem(inherited GetNextItem(StartItem, Direction, States));
end;
function TCCRGridView.getSelected: TCCRGridItem;
begin
Result := inherited Selected as TCCRGridItem;
end;
function TCCRGridView.getSortColumn: Integer;
begin
if (SortField >= 0) and (SortField < Fields.Count) then
Result := Fields[SortField].ColIndex
else
Result := -1;
end;
procedure TCCRGridView.LoadLayout(aStorage: TOvcAbstractStore; const aSection: String);
var
i, n, wd: Integer;
begin
try
aStorage.Open;
try
n := Fields.Count - 1;
for i:=0 to n do
begin
wd := aStorage.ReadInteger(aSection, Fields[i].GetNamePath, -1);
if wd >= 0 then Fields[i].Width := wd;
end;
finally
aStorage.Close;
end;
except
end;
end;
procedure TCCRGridView.SaveLayout(aStorage: TOvcAbstractStore; const aSection: String);
var
i, n: Integer;
begin
try
aStorage.Open;
try
n := Fields.Count - 1;
for i:=0 to n do
aStorage.WriteInteger(aSection, Fields[i].GetNamePath, Fields[i].Width);
finally
aStorage.Close;
end;
except
end;
end;
procedure TCCRGridView.setFields(const aValue: TCCRGridFields);
begin
try
fFields.Free;
Columns.Clear;
except
end;
fFields := aValue;
end;
procedure TCCRGridView.setItemFocused(aValue: TCCRGridItem);
begin
inherited ItemFocused := aValue;
end;
procedure TCCRGridView.setSelected(aValue: TCCRGridItem);
begin
inherited Selected := aValue;
end;
procedure TCCRGridView.UpdateColumns(const aClrFlg: Boolean);
var
i, n: Integer;
col: TListColumn;
begin
if aClrFlg then
Clear;
Columns.BeginUpdate;
try
Columns.Clear;
n := Fields.Count - 1;
for i:=0 to n do
if Fields[i].Visible then
begin
col := Columns.Add;
if Assigned(col) then
begin
col.Assign(Fields[i]);
Fields[i].ColIndex := col.Index;
end;
end;
UpdateSortField;
finally
Columns.EndUpdate;
end;
end;
procedure TCCRGridView.WMNotify(var Msg: TWMNotify);
var
colNdx, colWidth, fldNdx: Integer;
begin
if csDesigning in ComponentState then
begin
inherited;
Exit;
end;
if (Msg.NMHdr^.code = HDN_BEGINTRACKA) or (Msg.NMHdr^.code = HDN_BEGINTRACKW) then
begin
colNdx := FindColumnIndex(Msg.NMHdr);
fldNdx := FieldIndex(colNdx);
if fldNdx >= 0 then
if not Fields[fldNdx].AllowResize then
begin
Msg.Result := 1; // Disable resizing the column
Exit;
end;
end;
inherited;
case Msg.NMHdr^.code of
HDN_ENDTRACK:
begin
colNdx := FindColumnIndex(Msg.NMHdr);
colWidth := FindColumnWidth(Msg.NMHdr);
//--- Update the width of field
fldNdx := FieldIndex(colNdx);
if (fldNdx >= 0) and (colWidth >= 0) then
Fields[fldNdx].fWidth := colWidth;
//--- Call the event handler (if assigned)
DoOnColumnResize(Columns[colNdx]);
end;
//HDN_BEGINTRACK:
//HDN_TRACK: ;
end;
end;
end.
|
{_______________________________________________________________
FRAKVOSS.PAS Accompanies "Mimicking Mountains," by Tom Jeffery,
BYTE, December 1987, page 337
______________________________________________________________}
unit fracsurf
interface
{$N+}
VAR
size : longint { compute size x size surface. 64 is recommended }
datafile : string {file to store array in}
program fractalVoss;
const
size = 64; {Maximum index of array}
datafile = 'D:SURFACE.FKL';
type
AlgorithmType = (Voss, FFC);
var
row, col, n, step, st : longint;
srf : array[0..size, 0..size] of longint; {The surface file}
srfile : file of longint;
H : extended; {Roughness factor}
stepfactor : extended;
BadInput : BOOLEAN;
function gauss : extended;
{Returns a gaussian variable with mean = 0, variance = 1}
{Polar method due to Knuth, vol. 2, pp. 104, 113 }
{but found in "Smalltalk-80, Language and Implementation",}
{Goldberg and Robinson, p. 437.}
var
i : integer;
sum, v1, v2, s : extended;
begin
sum := 0;
repeat
v1 := (random / maxint);
v2 := (random / maxint);
s := sqr(v1) + sqr(v2);
until s < 1;
s := sqrt(-2 * ln(s) / s) * v1;
gauss := s;
end;
procedure horintpol (row : longint);
{Interpolates midpoints for 1 row}
var
i, col : longint;
begin
col := 0;
while col < size do
begin
srf[row, col + step] := (srf[row, col] + srf[row, col
+ 2 * step]) div 2; {New point}
col := col + 2 * step;
end;
end;
procedure verintpol (col : longint);
{Interpolates midpoints for 1 column}
var
i, row : longint;
begin
row := 0;
while row < size do
begin
srf[row + step, col] := (srf[row, col]
+ srf[row + 2 * step, col]) div 2; {New point}
row := row + 2 * step;
end;
end;
procedure centintpol (row : longint);
{Interpolates center points for all cells in a row}
var
i, col : longint;
begin
col := step;
while col < size do
begin
srf[row, col] := (srf[row, col - step] + srf[row, col + step]
+ srf[row - step, col] + srf[row + step, col]) div 4;
{New point}
col := col + 2 * step;
end;
end;
procedure intpol;
{Interpolates all midpoints at current step size}
var
i, row, col : longint;
begin
row := 0;
col := 0;
while row <= size do
begin
horintpol(row);
row := row + 2 * step;
end;
while col <= size do
begin
verintpol(col);
col := col + 2 * step;
end;
row := step;
while row <= size - step do
begin
centintpol(row);
row := row + 2 * step;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++}
procedure hordetail (row : longint);
{Calculates new points for one row}
var
disp, i, col : longint;
begin
col := 0;
while col < size do
begin
disp := Round(100 * (gauss * stepfactor)); {Random displacement}
srf[row, col + step] :=
(srf[row, col] + srf[row, col + 2 * step]) div 2; {Midpoint}
srf[row, col + step] := srf[row, col + step] + disp;{New point}
col := col + 2 * step;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++}
procedure verdetail (col : longint);
{Calculates new points for one column}
var
disp, i, row : longint;
begin
row := 0;
while row < size do
begin
disp := Round(100 * (gauss * stepfactor)); {Random displacement}
srf[row + step, col] :=
(srf[row, col] + srf[row + 2 * step, col]) div 2; {Midpoint}
srf[row + step, col] := srf[row + step, col] + disp; {New point}
row := row + 2 * step;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++}
procedure centdetail (row : longint);
{Calculates new points for centers of all cells in a row}
var
disp, i, col : longint;
begin
col := step;
while col < size do
begin
disp := Round(100 * (gauss * stepfactor)); {Random displacement}
srf[row, col] :=
(srf[row, col - step] + srf[row, col + step]
+ srf[row - step, col]
+ srf[row + step, col]) div 4; {Center Point}
srf[row, col] := srf[row, col] + disp; {New point}
col := col + 2 * step;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++}
procedure FFCDetail;
{Calculates new points at current step size}
var
i, row, col : longint;
begin
row := 0;
col := 0;
while row <= size do
begin
hordetail(row);
row := row + 2 * step;
end;
while col <= size do
begin
verdetail(col);
col := col + 2 * step;
end;
row := step;
while row <= size - step do
begin
centdetail(row);
row := row + 2 * step;
end;
end;
{+++++++++++++++++++++++++++++++++++++++++++++++++}
procedure VossDetail;
{Adds random displacement to all points at current step size}
var
r, c, disp : longint;
begin
r := 0;
while r <= size do
begin
c := 0;
while c <= size do
begin
disp := Round(100 * (gauss * stepfactor));
srf[r, c] := srf[r, c] + disp;
c := c + step;
end;
r := r + step;
end;
end;
procedure newsurface(Algo : AlgorithmType);
begin
step := size;
stepfactor := exp(2 * H * ln(step));
srf[0, 0] := Round(100 * (gauss * stepfactor));
srf[0, size] := Round(100 * (gauss * stepfactor));
srf[size, 0] := Round(100 * (gauss * stepfactor));
srf[size, size] := Round(100 * (gauss * stepfactor));
repeat
step := step div 2; {Go to smaller scale}
write('step = ');
writeln(step);
stepfactor := exp(2 * H * ln(step)); {Factor proportional to step size}
if Algo = Voss then
begin
intpol;
VossDetail;
end
else FFCDetail;
until step = 1;
end;
begin
repeat
write('H = ?'); {Set roughness}
{$I-}
readln(H);
{$I+}
BadInput := (IOResult <> 0);
if BadInput then writeln('Wrong form. Enter in the form 0.n.');
until not BadInput;
assign(srfile, datafile);
rewrite(srfile);
Randomize;
newsurface(Voss); {Calculate surface}
for row := 0 to size do
for col := 0 to size do
write(srfile, srf[row, col]); {Store surface in file}
close(srfile);
end.
|
unit Ntapi.ntpsapi;
{$WARN SYMBOL_PLATFORM OFF}
{$MINENUMSIZE 4}
interface
uses
Winapi.WinNt, Ntapi.ntdef, Ntapi.ntpebteb, Ntapi.ntrtl;
const
// Processes
// ProcessDebugFlags info class
PROCESS_DEBUG_INHERIT = $00000001;
PROCESS_TERMINATE = $0001;
PROCESS_CREATE_THREAD = $0002;
PROCESS_SET_SESSIONID = $0004;
PROCESS_VM_OPERATION = $0008;
PROCESS_VM_READ = $0010;
PROCESS_VM_WRITE = $0020;
PROCESS_DUP_HANDLE = $0040;
PROCESS_CREATE_PROCESS = $0080;
PROCESS_SET_QUOTA = $0100;
PROCESS_SET_INFORMATION = $0200;
PROCESS_QUERY_INFORMATION = $0400;
PROCESS_SUSPEND_RESUME = $0800;
PROCESS_QUERY_LIMITED_INFORMATION = $1000;
PROCESS_SET_LIMITED_INFORMATION = $2000;
PROCESS_ALL_ACCESS = STANDARD_RIGHTS_ALL or SPECIFIC_RIGHTS_ALL;
ProcessAccessMapping: array [0..13] of TFlagName = (
(Value: PROCESS_TERMINATE; Name: 'Terminate'),
(Value: PROCESS_CREATE_THREAD; Name: 'Create threads'),
(Value: PROCESS_SET_SESSIONID; Name: 'Set session ID'),
(Value: PROCESS_VM_OPERATION; Name: 'Modify memory'),
(Value: PROCESS_VM_READ; Name: 'Read memory'),
(Value: PROCESS_VM_WRITE; Name: 'Write memory'),
(Value: PROCESS_DUP_HANDLE; Name: 'Duplicate handles'),
(Value: PROCESS_CREATE_PROCESS; Name: 'Create process'),
(Value: PROCESS_SET_QUOTA; Name: 'Set quota'),
(Value: PROCESS_SET_INFORMATION; Name: 'Set information'),
(Value: PROCESS_QUERY_INFORMATION; Name: 'Query information'),
(Value: PROCESS_SUSPEND_RESUME; Name: 'Suspend/resume'),
(Value: PROCESS_QUERY_LIMITED_INFORMATION; Name: 'Query limited information'),
(Value: PROCESS_SET_LIMITED_INFORMATION; Name: 'Set limited information')
);
ProcessAccessType: TAccessMaskType = (
TypeName: 'process';
FullAccess: PROCESS_ALL_ACCESS;
Count: Length(ProcessAccessMapping);
Mapping: PFlagNameRefs(@ProcessAccessMapping);
);
// Flags for NtCreateProcessEx and NtCreateUserProcess
PROCESS_CREATE_FLAGS_BREAKAWAY = $00000001;
PROCESS_CREATE_FLAGS_NO_DEBUG_INHERIT = $00000002;
PROCESS_CREATE_FLAGS_INHERIT_HANDLES = $00000004;
PROCESS_CREATE_FLAGS_OVERRIDE_ADDRESS_SPACE = $00000008;
PROCESS_CREATE_FLAGS_LARGE_PAGES = $00000010;
// ProcessFlags for NtCreateUserProcess
PROCESS_CREATE_FLAGS_LARGE_PAGE_SYSTEM_DLL = $00000020;
PROCESS_CREATE_FLAGS_PROTECTED_PROCESS = $00000040;
PROCESS_CREATE_FLAGS_CREATE_SESSION = $00000080;
PROCESS_CREATE_FLAGS_INHERIT_FROM_PARENT = $00000100;
PROCESS_CREATE_FLAGS_SUSPENDED = $00000200;
// Threads
THREAD_TERMINATE = $0001;
THREAD_SUSPEND_RESUME = $0002;
THREAD_ALERT = $0004;
THREAD_GET_CONTEXT = $0008;
THREAD_SET_CONTEXT = $0010;
THREAD_SET_INFORMATION = $0020;
THREAD_QUERY_INFORMATION = $0040;
THREAD_SET_THREAD_TOKEN = $0080;
THREAD_IMPERSONATE = $0100;
THREAD_DIRECT_IMPERSONATION = $0200;
THREAD_SET_LIMITED_INFORMATION = $0400;
THREAD_QUERY_LIMITED_INFORMATION = $0800;
THREAD_RESUME = $1000;
THREAD_ALL_ACCESS = STANDARD_RIGHTS_ALL or SPECIFIC_RIGHTS_ALL;
ThreadAccessMapping: array [0..12] of TFlagName = (
(Value: THREAD_TERMINATE; Name: 'Terminate'),
(Value: THREAD_SUSPEND_RESUME; Name: 'Suspend/resume'),
(Value: THREAD_ALERT; Name: 'Alert'),
(Value: THREAD_GET_CONTEXT; Name: 'Get context'),
(Value: THREAD_SET_CONTEXT; Name: 'Set context'),
(Value: THREAD_SET_INFORMATION; Name: 'Set information'),
(Value: THREAD_QUERY_INFORMATION; Name: 'Query information'),
(Value: THREAD_SET_THREAD_TOKEN; Name: 'Set token'),
(Value: THREAD_IMPERSONATE; Name: 'Impersonate'),
(Value: THREAD_DIRECT_IMPERSONATION; Name: 'Direct impersonation'),
(Value: THREAD_SET_LIMITED_INFORMATION; Name: 'Set limited information'),
(Value: THREAD_QUERY_LIMITED_INFORMATION; Name: 'Query limited information'),
(Value: THREAD_RESUME; Name: 'Resume')
);
ThreadAccessType: TAccessMaskType = (
TypeName: 'thread';
FullAccess: THREAD_ALL_ACCESS;
Count: Length(ThreadAccessMapping);
Mapping: PFlagNameRefs(@ThreadAccessMapping);
);
// User processes and threads
// CreateFlags for NtCreateThreadEx
THREAD_CREATE_FLAGS_CREATE_SUSPENDED = $00000001;
THREAD_CREATE_FLAGS_SKIP_THREAD_ATTACH = $00000002;
THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER = $00000004;
THREAD_CREATE_FLAGS_HAS_SECURITY_DESCRIPTOR = $00000010;
THREAD_CREATE_FLAGS_ACCESS_CHECK_IN_TARGET = $00000020;
THREAD_CREATE_FLAGS_INITIAL_THREAD = $00000080;
// Jobs
JOB_OBJECT_ASSIGN_PROCESS = $0001;
JOB_OBJECT_SET_ATTRIBUTES = $0002;
JOB_OBJECT_QUERY = $0004;
JOB_OBJECT_TERMINATE = $0008;
JOB_OBJECT_SET_SECURITY_ATTRIBUTES = $0010;
JOB_OBJECT_IMPERSONATE = $0020;
JOB_OBJECT_ALL_ACCESS = STANDARD_RIGHTS_ALL or $3F;
JobAccessMapping: array [0..5] of TFlagName = (
(Value: JOB_OBJECT_ASSIGN_PROCESS; Name: 'Assign process'),
(Value: JOB_OBJECT_SET_ATTRIBUTES; Name: 'Set attributes'),
(Value: JOB_OBJECT_QUERY; Name: 'Query'),
(Value: JOB_OBJECT_TERMINATE; Name: 'Terminate'),
(Value: JOB_OBJECT_SET_SECURITY_ATTRIBUTES; Name: 'Set security attributes'),
(Value: JOB_OBJECT_IMPERSONATE; Name: 'Impersonate')
);
JobAccessType: TAccessMaskType = (
TypeName: 'job object';
FullAccess: JOB_OBJECT_ALL_ACCESS;
Count: Length(JobAccessMapping);
Mapping: PFlagNameRefs(@JobAccessMapping);
);
JOB_OBJECT_UILIMIT_HANDLES = $00000001;
JOB_OBJECT_UILIMIT_READCLIPBOARD = $00000002;
JOB_OBJECT_UILIMIT_WRITECLIPBOARD = $00000004;
JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS = $00000008;
JOB_OBJECT_UILIMIT_DISPLAYSETTINGS = $00000010;
JOB_OBJECT_UILIMIT_GLOBALATOMS = $00000020;
JOB_OBJECT_UILIMIT_DESKTOP = $00000040;
JOB_OBJECT_UILIMIT_EXITWINDOWS = $00000080;
JOB_OBJECT_TERMINATE_AT_END_OF_JOB = 0;
JOB_OBJECT_POST_AT_END_OF_JOB = 1;
NtCurrentProcess: THandle = THandle(-1);
NtCurrentThread: THandle = THandle(-2);
// Not NT, but useful
function NtCurrentProcessId: NativeUInt;
function NtCurrentThreadId: NativeUInt;
type
// Processes
TProcessInfoClass = (
ProcessBasicInformation = 0, // q: TProcessBasinInformation
ProcessQuotaLimits = 1, // q, s: TQuotaLimits
ProcessIoCounters = 2, // q: TIoCounters
ProcessVmCounters = 3,
ProcessTimes = 4,
ProcessBasePriority = 5, // s: KPRIORITY
ProcessRaisePriority = 6,
ProcessDebugPort = 7,
ProcessExceptionPort = 8,
ProcessAccessToken = 9, // s: TProcessAccessToken
ProcessLdtInformation = 10,
ProcessLdtSize = 11,
ProcessDefaultHardErrorMode = 12,
ProcessIoPortHandlers = 13,
ProcessPooledUsageAndLimits = 14,
ProcessWorkingSetWatch = 15,
ProcessUserModeIOPL = 16,
ProcessEnableAlignmentFaultFixup = 17,
ProcessPriorityClass = 18,
ProcessWx86Information = 19,
ProcessHandleCount = 20, // q: Cardinal
ProcessAffinityMask = 21,
ProcessPriorityBoost = 22,
ProcessDeviceMap = 23,
ProcessSessionInformation = 24, // q: Cardinal
ProcessForegroundInformation = 25,
ProcessWow64Information = 26, // q: PPeb32
ProcessImageFileName = 27, // q: UNICODE_STRING
ProcessLUIDDeviceMapsEnabled = 28,
ProcessBreakOnTermination = 29,
ProcessDebugObjectHandle = 30, // q: THandle
ProcessDebugFlags = 31, // q, s: Cardinal (PROCESS_DEBUG_INHERIT)
ProcessHandleTracing = 32,
ProcessIoPriority = 33,
ProcessExecuteFlags = 34,
ProcessResourceManagement = 35,
ProcessCookie = 36,
ProcessImageInformation = 37, // q: TSectionImageInformation
ProcessCycleTime = 38,
ProcessPagePriority = 39,
ProcessInstrumentationCallback = 40,
ProcessThreadStackAllocation = 41,
ProcessWorkingSetWatchEx = 42,
ProcessImageFileNameWin32 = 43, // q: UNICODE_STRING
ProcessImageFileMapping = 44,
ProcessAffinityUpdateMode = 45,
ProcessMemoryAllocationMode = 46,
ProcessGroupInformation = 47,
ProcessTokenVirtualizationEnabled = 48,
ProcessConsoleHostProcess = 49,
ProcessWindowInformation = 50,
ProcessHandleInformation = 51, // q: TProcessHandleSnapshotInformation
ProcessMitigationPolicy = 52,
ProcessDynamicFunctionTableInformation = 53,
ProcessHandleCheckingMode = 54,
ProcessKeepAliveCount = 55,
ProcessRevokeFileHandles = 56,
ProcessWorkingSetControl = 57,
ProcessHandleTable = 58,
ProcessCheckStackExtentsMode = 59,
ProcessCommandLineInformation = 60 // q: UNICODE_STRING
);
TProcessBasinInformation = record
ExitStatus: NTSTATUS;
PebBaseAddress: PPeb;
AffinityMask: NativeUInt;
BasePriority: KPRIORITY;
UniqueProcessId: NativeUInt;
InheritedFromUniqueProcessId: NativeUInt;
end;
PProcessBasinInformation = ^TProcessBasinInformation;
TProcessAccessToken = record
Token: THandle; // needs TOKEN_ASSIGN_PRIMARY
Thread: THandle; // currently unused, was THREAD_QUERY_INFORMATION
end;
TProcessHandleTableEntryInfo = record
HandleValue: THandle;
HandleCount: NativeUInt;
PointerCount: NativeUInt;
GrantedAccess: Cardinal;
ObjectTypeIndex: Cardinal;
HandleAttributes: Cardinal;
Reserved: Cardinal;
end;
PProcessHandleTableEntryInfo = ^TProcessHandleTableEntryInfo;
TProcessHandleSnapshotInformation = record
NumberOfHandles: NativeUInt;
Reserved: NativeUInt;
Handles: array [ANYSIZE_ARRAY] of TProcessHandleTableEntryInfo;
end;
PProcessHandleSnapshotInformation = ^TProcessHandleSnapshotInformation;
// Threads
TInitialTeb = record
OldStackBase: Pointer;
OldStackLimit: Pointer;
StackBase: Pointer;
StackLimit: Pointer;
StackAllocationBase: Pointer;
end;
PInitialTeb = ^TInitialTeb;
TThreadInfoClass = (
ThreadBasicInformation = 0, // q: TThreadBasicInformation
ThreadTimes = 1,
ThreadPriority = 2,
ThreadBasePriority = 3,
ThreadAffinityMask = 4,
ThreadImpersonationToken = 5, // s: THandle
ThreadDescriptorTableEntry = 6,
ThreadEnableAlignmentFaultFixup = 7,
ThreadEventPair = 8,
ThreadQuerySetWin32StartAddress = 9,
ThreadZeroTlsCell = 10,
ThreadPerformanceCount = 11,
ThreadAmILastThread = 12,
ThreadIdealProcessor = 13,
ThreadPriorityBoost = 14,
ThreadSetTlsArrayAddress = 15,
ThreadIsIoPending = 16,
ThreadHideFromDebugger = 17,
ThreadBreakOnTermination = 18,
ThreadSwitchLegacyState = 19,
ThreadIsTerminated = 20, // q: LongBool
ThreadLastSystemCall = 21,
ThreadIoPriority = 22,
ThreadCycleTime = 23,
ThreadPagePriority = 24,
ThreadActualBasePriority = 25,
ThreadTebInformation = 26, // q: TThreadTebInformation
ThreadCSwitchMon = 27,
ThreadCSwitchPmu = 28,
ThreadWow64Context = 29,
ThreadGroupInformation = 30,
ThreadUmsInformation = 31,
ThreadCounterProfiling = 32,
ThreadIdealProcessorEx = 33
);
TThreadBasicInformation = record
ExitStatus: NTSTATUS;
TebBaseAddress: PTeb;
ClientId: TClientId;
AffinityMask: NativeUInt;
Priority: KPRIORITY;
BasePriority: Integer;
end;
PThreadBasicInformation = ^TThreadBasicInformation;
TThreadTebInformation = record
TebInformation: Pointer;
TebOffset: Cardinal;
BytesToRead: Cardinal;
end;
PThreadTebInformation = ^TThreadTebInformation;
TPsApcRoutine = procedure (ApcArgument1, ApcArgument2, ApcArgument3: Pointer);
stdcall;
// User processes and threads
TPsAttribute = record
Attribute: NativeUInt;
Size: NativeUInt;
Value: NativeUInt;
ReturnLength: PNativeUInt;
end;
PPsAttribute = ^TPsAttribute;
TPsAttributeList = record
TotalLength: NativeUInt;
Attributes: array [ANYSIZE_ARRAY] of TPsAttribute;
end;
PPsAttributeList = ^TPsAttributeList;
TPsCreateState = (
PsCreateInitialState,
PsCreateFailOnFileOpen,
PsCreateFailOnSectionCreate,
PsCreateFailExeFormat,
PsCreateFailMachineMismatch,
PsCreateFailExeName,
PsCreateSuccess
);
TPsCreateInfo = record
Size: NativeUInt;
case State: TPsCreateState of
PsCreateInitialState: (
InitFlags: Cardinal;
AdditionalFileAccess: TAccessMask;
);
PsCreateFailOnSectionCreate: (
FileHandleFail: THandle;
);
PsCreateFailExeFormat: (
DllCharacteristics: Word;
);
PsCreateFailExeName: (
IFEOKey: THandle;
);
PsCreateSuccess: (
OutputFlags: Cardinal;
FileHandleSuccess: THandle;
SectionHandle: THandle;
UserProcessParametersNative: UInt64;
UserProcessParametersWow64: Cardinal;
CurrentParameterFlags: Cardinal;
PebAddressNative: UInt64;
PebAddressWow64: Cardinal;
ManifestAddress: UInt64;
ManifestSize: Cardinal;
);
end;
// Jobs
TJobObjectInfoClass = (
JobObjectReserved = 0,
JobObjectBasicAccountingInformation = 1, // q: TJobBasicAccountingInfo
JobObjectBasicLimitInformation = 2, // q, s: TJobBasicLimitInfo
JobObjectBasicProcessIdList = 3, // q: TJobBasicProcessIdList
JobObjectBasicUIRestrictions = 4, // q, s: Cardinal (UI flags)
JobObjectSecurityLimitInformation = 5, // not supported
JobObjectEndOfJobTimeInformation = 6, // s: Cardinal (EndOfJobTimeAction)
JobObjectAssociateCompletionPortInformation = 7, // s: TJobAssociateCompletionPort
JobObjectBasicAndIoAccountingInformation = 8, // q: TJobBasicAndIoAccountingInfo
JobObjectExtendedLimitInformation = 9, // q, s: TJobExtendedLimitInfo
JobObjectJobSetInformation = 10, // q: Cardinal (MemberLevel)
JobObjectGroupInformation = 11, // q, s: Word
JobObjectNotificationLimitInformation = 12, // q, s: TJobNotificationLimitInfo
JobObjectLimitViolationInformation = 13, //
JobObjectGroupInformationEx = 14, // q, s:
JobObjectCpuRateControlInformation = 15 // q, s: TJobCpuRateControlInfo
);
TJobBasicAccountingInfo = record
TotalUserTime: TLargeInteger;
TotalKernelTime: TLargeInteger;
ThisPeriodTotalUserTime: TLargeInteger;
ThisPeriodTotalKernelTime: TLargeInteger;
TotalPageFaultCount: Cardinal;
TotalProcesses: Cardinal;
ActiveProcesses: Cardinal;
TotalTerminatedProcesses: Cardinal;
end;
PJobBasicAccountingInfo = ^TJobBasicAccountingInfo;
TJobBasicLimitInfo = record
PerProcessUserTimeLimit: TLargeInteger;
PerJobUserTimeLimit: TLargeInteger;
LimitFlags: Cardinal;
MinimumWorkingSetSize: NativeUInt;
MaximumWorkingSetSize: NativeUInt;
ActiveProcessLimit: Cardinal;
Affinity: NativeUInt;
PriorityClass: Cardinal;
SchedulingClass: Cardinal;
end;
PJobBasicLimitInfo = ^TJobBasicLimitInfo;
TJobBasicProcessIdList = record
NumberOfAssignedProcesses: Cardinal;
NumberOfProcessIdsInList: Cardinal;
ProcessIdList: array [ANYSIZE_ARRAY] of NativeUInt;
end;
PJobBasicProcessIdList = ^TJobBasicProcessIdList;
TJobObjectMsg = (
JobObjectMsgEndOfJobTime = 1,
JobObjectMsgEndOfProcessTime = 2,
JobObjectMsgActiveProcessLimit = 3,
JobObjectMsgActiveProcessZero = 4,
JobObjectMsgNewProcess = 6,
JobObjectMsgExitProcess = 7,
JobObjectMsgAbnormalExitProcess = 8,
JobObjectMsgProcessMemoryLimit = 9,
JobObjectMsgJobMemoryLimit = 10,
JobObjectMsgNotificationLimit = 11,
JobObjectMsgJobCycleTimeLimit = 12,
JobObjectMsgSiloTerminated = 13
);
TJobAssociateCompletionPort = record
CompletionKey: Pointer;
CompletionPort: THandle;
end;
PJobAssociateCompletionPort = ^TJobAssociateCompletionPort;
TJobBasicAndIoAccountingInfo = record
BasicInfo: TJobBasicAccountingInfo;
IoInfo: TIoCounters;
end;
PJobBasicAndIoAccountingInfo = ^TJobBasicAndIoAccountingInfo;
TJobExtendedLimitInfo = record
BasicLimitInformation: TJobBasicLimitInfo;
IoInfo: TIoCounters;
ProcessMemoryLimit: NativeUInt;
JobMemoryLimit: NativeUInt;
PeakProcessMemoryUsed: NativeUInt;
PeakJobMemoryUsed: NativeUInt;
end;
PJobExtendedLimitInfo = ^TJobExtendedLimitInfo;
TJobRateControlTolerance = (
ToleranceLow = 1,
ToleranceMedium,
ToleranceHigh
);
TJobRateControlToleranceInterval = (
ToleranceIntervalShort = 1,
ToleranceIntervalMedium,
ToleranceIntervalLong
);
TJobNotificationLimitInfo = record
IoReadBytesLimit: UInt64;
IoWriteBytesLimit: UInt64;
PerJobUserTimeLimit: TLargeInteger;
JobMemoryLimit: UInt64;
RateControlTolerance: TJobRateControlTolerance;
RateControlToleranceInterval: TJobRateControlToleranceInterval;
LimitFlags: Cardinal;
end;
PJobNotificationLimitInfo = ^TJobNotificationLimitInfo;
TJobCpuRateControlInfo = record
ControlFlags: Cardinal;
case Integer of
0: (CpuRate: Cardinal);
1: (Weight: Cardinal);
2: (MinRate: Word; MaxRate: Word);
end;
PJobCpuRateControlInfo = ^TJobCpuRateControlInfo;
// Processes
function NtCreateProcess(out ProcessHandle: THandle; DesiredAccess: TAccessMask;
ObjectAttributes: PObjectAttributes; ParentProcess: THandle;
InheritObjectTable: Boolean; SectionHandle: THandle; DebugPort: THandle;
ExceptionPort: THandle): NTSTATUS; stdcall; external ntdll;
function NtCreateProcessEx(out ProcessHandle: THandle; DesiredAccess:
TAccessMask; ObjectAttributes: PObjectAttributes; ParentProcess: THandle;
Flags: Cardinal; SectionHandle: THandle; DebugPort: THandle; ExceptionPort:
THandle; JobMemberLevel: Cardinal): NTSTATUS; stdcall; external ntdll;
function NtOpenProcess(out ProcessHandle: THandle; DesiredAccess: TAccessMask;
const ObjectAttributes: TObjectAttributes; const ClientId: TClientId):
NTSTATUS; stdcall; external ntdll;
function NtTerminateProcess(ProcessHandle: THandle; ExitStatus: NTSTATUS):
NTSTATUS; stdcall; external ntdll;
function NtSuspendProcess(ProcessHandle: THandle): NTSTATUS; stdcall;
external ntdll;
function NtResumeProcess(ProcessHandle: THandle): NTSTATUS; stdcall;
external ntdll;
function NtQueryInformationProcess(ProcessHandle: THandle;
ProcessInformationClass: TProcessInfoClass; ProcessInformation: Pointer;
ProcessInformationLength: Cardinal; ReturnLength: PCardinal): NTSTATUS;
stdcall; external ntdll;
// Absent in ReactOS
function NtGetNextProcess(ProcessHandle: THandle; DesiredAccess: TAccessMask;
HandleAttributes: Cardinal; Flags: Cardinal; out NewProcessHandle: THandle):
NTSTATUS; stdcall; external ntdll delayed;
// Absent in ReactOS
function NtGetNextThread(ProcessHandle: THandle; ThreadHandle: THandle;
DesiredAccess: TAccessMask; HandleAttributes: Cardinal; Flags: Cardinal;
out NewThreadHandle: THandle): NTSTATUS; stdcall; external ntdll delayed;
function NtSetInformationProcess(ProcessHandle: THandle;
ProcessInformationClass: TProcessInfoClass; ProcessInformation: Pointer;
ProcessInformationLength: Cardinal): NTSTATUS; stdcall; external ntdll;
// Threads
function NtCreateThread(out ThreadHandle: THandle; DesiredAccess: TAccessMask;
ObjectAttributes: PObjectAttributes; ProcessHandle: THandle; out ClientId:
TClientId; const ThreadContext: TContext; const InitialTeb: TInitialTeb;
CreateSuspended: Boolean): NTSTATUS; stdcall; external ntdll;
function NtOpenThread(out ThreadHandle: THandle; DesiredAccess: TAccessMask;
const ObjectAttributes: TObjectAttributes; const ClientId: TClientId):
NTSTATUS; stdcall; external ntdll;
function NtTerminateThread(ThreadHandle: THandle; ExitStatus: NTSTATUS):
NTSTATUS; stdcall; external ntdll;
function NtSuspendThread(ThreadHandle: THandle; PreviousSuspendCount:
PCardinal = nil): NTSTATUS; stdcall; external ntdll;
function NtResumeThread(ThreadHandle: THandle; PreviousSuspendCount:
PCardinal = nil): NTSTATUS; stdcall; external ntdll;
function NtGetCurrentProcessorNumber: Cardinal; stdcall; external ntdll;
function NtGetContextThread(ThreadHandle: THandle; ThreadContext: PContext):
NTSTATUS; stdcall; external ntdll;
function NtSetContextThread(ThreadHandle: THandle; ThreadContext: PContext):
NTSTATUS; stdcall; external ntdll;
function NtQueryInformationThread(ThreadHandle: THandle;
ThreadInformationClass: TThreadInfoClass; ThreadInformation: Pointer;
ThreadInformationLength: Cardinal; ReturnLength: PCardinal): NTSTATUS;
stdcall; external ntdll;
function NtSetInformationThread(ThreadHandle: THandle;
ThreadInformationClass: TThreadInfoClass; ThreadInformation: Pointer;
ThreadInformationLength: Cardinal): NTSTATUS; stdcall; external ntdll;
function NtAlertThread(ThreadHandle: THandle): NTSTATUS; stdcall;
external ntdll;
function NtAlertResumeThread(ThreadHandle: THandle; PreviousSuspendCount:
PCardinal): NTSTATUS; stdcall; external ntdll;
function NtImpersonateThread(ServerThreadHandle: THandle;
ClientThreadHandle: THandle; const SecurityQos: TSecurityQualityOfService):
NTSTATUS; stdcall; external ntdll;
function NtQueueApcThread(ThreadHandle: THandle; ApcRoutine: TPsApcRoutine;
ApcArgument1, ApcArgument2, ApcArgument3: Pointer): NTSTATUS; stdcall;
external ntdll;
// User processes and threads
function NtCreateUserProcess(out ProcessHandle: THandle; out ThreadHandle:
THandle; ProcessDesiredAccess: TAccessMask; ThreadDesiredAccess: TAccessMask;
ProcessObjectAttributes: PObjectAttributes; ThreadObjectAttributes:
PObjectAttributes; ProcessFlags: Cardinal; ThreadFlags: Cardinal;
ProcessParameters: PRtlUserProcessParameters; var CreateInfo: TPsCreateInfo;
AttributeList: PPsAttributeList): NTSTATUS; stdcall; external ntdll;
function NtCreateThreadEx(out ThreadHandle: THandle; DesiredAccess: TAccessMask;
ObjectAttributes: PObjectAttributes; ProcessHandle: THandle; StartRoutine:
TUserThreadStartRoutine; Argument: Pointer; CreateFlags: Cardinal; ZeroBits:
NativeUInt; StackSize: NativeUInt; MaximumStackSize: NativeUInt;
AttributeList: PPsAttributeList): NTSTATUS; stdcall; external ntdll;
// Job objects
function NtCreateJobObject(out JobHandle: THandle; DesiredAccess: TAccessMask;
ObjectAttributes: PObjectAttributes): NTSTATUS; stdcall; external ntdll;
function NtOpenJobObject(out JobHandle: THandle; DesiredAccess: TAccessMask;
const ObjectAttributes: TObjectAttributes): NTSTATUS; stdcall; external ntdll;
function NtAssignProcessToJobObject(JobHandle: THandle; ProcessHandle: THandle):
NTSTATUS; stdcall; external ntdll;
function NtTerminateJobObject(JobHandle: THandle; ExitStatus: NTSTATUS):
NTSTATUS; stdcall; external ntdll;
function NtIsProcessInJob(ProcessHandle: THandle;
JobHandle: THandle): NTSTATUS; stdcall; external ntdll;
function NtQueryInformationJobObject(JobHandle: THandle;
JobObjectInformationClass: TJobObjectInfoClass; JobObjectInformation: Pointer;
JobObjectInformationLength: Cardinal; ReturnLength: PCardinal): NTSTATUS;
stdcall; external ntdll;
function NtSetInformationJobObject(JobHandle: THandle;
JobObjectInformationClass: TJobObjectInfoClass; JobObjectInformation: Pointer;
JobObjectInformationLength: Cardinal): NTSTATUS; stdcall; external ntdll;
implementation
function NtCurrentProcessId: NativeUInt;
begin
Result := NtCurrentTeb.ClientId.UniqueProcess;
end;
function NtCurrentThreadId: NativeUInt;
begin
Result := NtCurrentTeb.ClientId.UniqueThread;
end;
end.
|
unit uComandos;
interface
const
SYS_START = $21; //! SISTEMA INCIADO C -> S
CMD_OPEN = $61; //a COMANDO PARA COLOCAR O SERVO NA POSIÇÃO DE 180 GRAUS S -> C/C -> S (ECHO)
CMD_CLOSE = $62; //b COMANDO PARA COLOCAR O SERVO NA POSIÇÃO DE 0 GRAU S -> C/C -> S (ECHO)
CMD_NOTIFY = $63; //c COMANDO DE NOTIFICAÇÃO DA HORA DO REMÉDIO S -> C/C -> S (RECEBENDO ESTE COMANDO O S VAI ENVIAR A QUANTIDADE)
CMD_QUANT = $64; // 0x64 FF //COMANDO QUE RECEBERAR A QUANTIDADE [HEADER, VALOR INTEIRO]
CMD_ERROR = $FF; //255 RESPOSTA DE ERROR C -> C
CMD_RESET = $65; //e COMANDO PARA RESETAR O SISTEMA.
CMD_DISCONNECT = $66;
RES_SYS_START = $22;
RES_OPEN = $41;
RES_CLOSE = $42;
RES_NOTIFY = $43;
RES_QUANT = $44;
RES_TERMINATED = $60;
implementation
end.
|
unit u_plugin;
interface
uses
Winapi.Windows,
System.SysUtils,
System.Classes,
System.Net.URLClient,
System.Net.HttpClient,
System.Net.HttpClientComponent,
u_ext_info, u_obimp_const, u_params;
type
// Uptime plugin class
TUptimePlugin = class(TInterfacedObject, IExtensionPG)
private
FTick: Integer;
public
EventsPG : IEventsPG;
constructor Create(AEventsPG: IEventsPG);
destructor Destroy; override;
{==== Interface functions ====}
procedure TimerTick; stdcall;
procedure NotifyTextMsg(const ExtPlugTextMsg: TExtPlugTextMsg); stdcall;
end;
implementation
{ TUptimePlugin }
constructor TUptimePlugin.Create(AEventsPG: IEventsPG);
var
srvInfo: TExtServerInfo;
sFileLog, sLogStr: string;
begin
FTick:= 0;
//save events interface, will be used for plugin callbacks
EventsPG := AEventsPG;
//get server info, there we can find logs folder path
EventsPG.GetServerInfo(srvInfo);
InitConfig(EventsPG);
sFileLog:= IncludeTrailingPathDelimiter(srvInfo.PathLogFiles) + 'uptime_' + FormatDateTime('yyyy"-"mm"-"dd', Now) + '.txt';
sLogStr:= Format('Bimoid server: %d.%d.%d.%d', [srvInfo.VerMajor, srvInfo.VerMinor, srvInfo.VerRelease, srvInfo.VerBuild]);
sLogStr:= sLogStr + sLineBreak + Format('%s %s %s %d %s',
[
config.token,
config.url,
config.path,
config.updateTime,
BoolToStr(config.enable, true)
]);
//write log to file
LogToFile(sFileLog, sLogStr);
end;
destructor TUptimePlugin.Destroy;
begin
inherited;
end;
procedure TUptimePlugin.TimerTick;
var
data: String;
http: TNetHTTPClient;
begin
// Вызов каждые 100мс
Inc(FTick);
if(FTick > config.updateTime * 10) then begin
if (config.enable) then begin
data:= Format('%s?token=%s&startTime=%d&startFtTime=%d&ver=%s',
[config.url, config.token, config.startTime, getPIdBimFtSrv, config.srvVer]);
http:= TNetHTTPClient.Create(nil);
if Assigned(http) then try
http.Get(data);
finally
http.Free;
end;
end;
FTick:= 0;
end;
end;
procedure TUptimePlugin.NotifyTextMsg(const ExtPlugTextMsg: TExtPlugTextMsg);
begin
end;
end.
|
unit BodyTypesForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
DictonaryForm, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus,
System.Actions, Vcl.ActnList, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls,
GridFrame, BodyTypesView, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue;
type
TfrmBodyTypes = class(TfrmDictonary)
private
FViewBodyTypes: TViewBodyTypes;
{ Private declarations }
protected
procedure ApplyUpdates; override;
procedure CancelUpdates; override;
procedure ClearFormVariable; override;
function HaveAnyChanges: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
property ViewBodyTypes: TViewBodyTypes read FViewBodyTypes;
{ Public declarations }
end;
var
frmBodyTypes: TfrmBodyTypes;
implementation
{$R *.dfm}
constructor TfrmBodyTypes.Create(AOwner: TComponent);
begin
inherited;
FViewBodyTypes := TViewBodyTypes.Create(Self);
FViewBodyTypes.Parent := Panel1;
FViewBodyTypes.Align := alClient;
end;
procedure TfrmBodyTypes.ApplyUpdates;
begin
ViewBodyTypes.UpdateView;
ViewBodyTypes.actCommit.Execute;
end;
procedure TfrmBodyTypes.CancelUpdates;
begin
ViewBodyTypes.UpdateView;
ViewBodyTypes.actRollback.Execute;
end;
procedure TfrmBodyTypes.ClearFormVariable;
begin
frmBodyTypes := nil;
end;
function TfrmBodyTypes.HaveAnyChanges: Boolean;
begin
Result := ViewBodyTypes.BodyTypesGroup.HaveAnyChanges;
end;
end.
|
unit xClientControl;
interface
uses System.Classes, System.SysUtils, xClientType, xStudentInfo, xTCPClient,
xFunction, xDataDictionary;
type
TClientControl = class
private
FStudentInfo: TStudentInfo;
FStartTime: TDateTime;
FClientState: TClientState;
FEndTime: TDateTime;
FSubList: TStringList;
FOnStateChange: TNotifyEvent;
FConnState: TClientConnState;
FLoginState: TLoginState;
FWorkState: TClientWorkState;
FOnStopExam: TNotifyEvent;
FOnStuReady: TStuReadyEvent;
FOnStartExam: TNotifyEvent;
FOnStuProgress: TStuProgressEvent;
FOnStuLogin: TNotifyEvent;
FOnConnected: TNotifyEvent;
FOnDisconnect: TNotifyEvent;
FTCPClient : TTCPClient;
FOnLog: TGetStrProc;
FExamName: string;
FExamTimes: Integer;
procedure ReadINI;
procedure WriteINI;
procedure StateChange;
procedure SetClientState(const Value: TClientState);
procedure SetConnState(const Value: TClientConnState);
procedure SetLoginState(const Value: TLoginState);
procedure SetWorkState(const Value: TClientWorkState);
/// <summary>
/// 客户端基本状态改变
/// </summary>
procedure ClientStateChange;
procedure TCPConnect(Sender: TObject);
procedure TCPDisconnect(Sender: TObject);
procedure StuLogin(Sender: TObject);
procedure StuReady( nTotalCount : Integer);
procedure StuProgress( nReadyCount, nTotalCount : Integer);
procedure StartExam(Sender: TObject);
procedure StopExam(Sender: TObject);
procedure TCPLog(const S: string);
procedure TCPPacksLog( aPacks: TBytes; bSend : Boolean);
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 客户端连接状态
/// </summary>
property ConnState : TClientConnState read FConnState write SetConnState;
/// <summary>
/// 登录状态
/// </summary>
property LoginState : TLoginState read FLoginState write SetLoginState;
/// <summary>
/// 工作状态
/// </summary>
property WorkState : TClientWorkState read FWorkState write SetWorkState;
/// <summary>
/// 客户端状态
/// </summary>
property ClientState : TClientState read FClientState write SetClientState;
/// <summary>
/// 考生信息
/// </summary>
property StudentInfo : TStudentInfo read FStudentInfo write FStudentInfo;
/// <summary>
/// 考生的考题列表
/// </summary>
property SubList : TStringList read FSubList write FSubList;
/// <summary>
/// 开始考试时间
/// </summary>
property StartTime : TDateTime read FStartTime write FStartTime;
/// <summary>
/// 结束考试时间
/// </summary>
property EndTime : TDateTime read FEndTime write FEndTime;
/// <summary>
/// 考试名称
/// </summary>
property ExamName : string read FExamName write FExamName;
/// <summary>
/// 考试时间 分钟
/// </summary>
property ExamTimes : Integer read FExamTimes write FExamTimes;
public
property TCPClient : TTCPClient read FTCPClient;
/// <summary>
/// 考生登录
/// </summary>
function SendStuLogin(nStuID : Integer) : Boolean;
/// <summary>
/// 发送考生状态
/// </summary>
procedure SendStuState(AState : TClientState);
/// <summary>
/// 学员机准备考试
/// </summary>
procedure StuReadyExam;
public
/// <summary>
/// 状态改变
/// </summary>
property OnStateChange : TNotifyEvent read FOnStateChange write FOnStateChange;
/// <summary>
/// 连接事件
/// </summary>
property OnConnected : TNotifyEvent read FOnConnected write FOnConnected;
/// <summary>
/// 断开连接事件
/// </summary>
property OnDisconnect : TNotifyEvent read FOnDisconnect write FOnDisconnect;
/// <summary>
/// 学员登录事件
/// </summary>
property OnStuLogin : TNotifyEvent read FOnStuLogin write FOnStuLogin;
/// <summary>
/// 学员准备事件
/// </summary>
property OnStuReady : TStuReadyEvent read FOnStuReady write FOnStuReady;
/// <summary>
/// 学员准备进度事件
/// </summary>
property OnStuProgress : TStuProgressEvent read FOnStuProgress write FOnStuProgress;
/// <summary>
/// 开始考试事件
/// </summary>
property OnStartExam : TNotifyEvent read FOnStartExam write FOnStartExam;
/// <summary>
/// 停止考试事件
/// </summary>
property OnStopExam : TNotifyEvent read FOnStopExam write FOnStopExam;
/// <summary>
/// 通讯记录
/// </summary>
property OnLog : TGetStrProc read FOnLog write FOnLog;
end;
var
ClientControl : TClientControl;
implementation
{ TClientControl }
procedure TClientControl.ClientStateChange;
begin
if FConnState = ccsDisConn then
begin
ClientState := esDisconn;
if FLoginState = lsLogin then
begin
ClientState := esLogin;
end
else
begin
ClientState := esConned;
end;
end
else
begin
case FWorkState of
cwsNot :
begin
if FLoginState = lsLogin then
begin
ClientState := esLogin;
end
else
begin
ClientState := esConned;
end;
end;
cwsTrain :
begin
ClientState := esTrain;
end;
cwsPractise:
begin
ClientState := esPractise;
end;
cwsExamReady:
begin
ClientState := esWorkReady;
end;
cwsExamDoing:
begin
ClientState := esWorking;
end;
cwsExamFinished:
begin
ClientState := esWorkFinished;
end;
end;
end;
end;
constructor TClientControl.Create;
begin
FExamName:= '默认考试';
FExamTimes:= 30;
FSubList:= TStringList.Create;
FClientState := esDisconn;
FStudentInfo:= TStudentInfo.Create;
FConnState:= ccsDisConn;
FLoginState:= lsLogOut;
FWorkState:= cwsNot;
FTCPClient := TTCPClient.Create;
FTCPClient.OnConnected := TCPConnect;
FTCPClient.OnDisconnect := TCPDisconnect;
FTCPClient.OnLog := TCPLog;
FTCPClient.OnSendRevPack := TCPPacksLog;
FTCPClient.OnStuLogin := StuLogin;
FTCPClient.OnStuReady := StuReady;
FTCPClient.OnStuProgress := StuProgress;
FTCPClient.OnStartExam := StartExam;
FTCPClient.OnStopExam := StopExam;
ReadINI;
end;
destructor TClientControl.Destroy;
begin
WriteINI;
FStudentInfo.Free;
FTCPClient.Free;
FSubList.Free;
inherited;
end;
procedure TClientControl.ReadINI;
begin
end;
function TClientControl.SendStuLogin(nStuID: Integer): Boolean;
begin
Result := FTCPClient.StuLogin(nStuID);
end;
procedure TClientControl.SendStuState(AState: TClientState);
begin
FTCPClient.SendStuState(AState);
end;
procedure TClientControl.SetClientState(const Value: TClientState);
begin
if FClientState <> Value then
begin
FClientState := Value;
StateChange;
FTCPClient.SendStuState(FClientState);
end;
end;
procedure TClientControl.SetConnState(const Value: TClientConnState);
begin
if FConnState <> Value then
begin
FConnState := Value;
ClientStateChange;
end;
end;
procedure TClientControl.SetLoginState(const Value: TLoginState);
begin
if FLoginState <> Value then
begin
FLoginState := Value;
ClientStateChange;
FTCPClient.StuLogin(FStudentInfo.stuNumber);
end;
end;
procedure TClientControl.SetWorkState(const Value: TClientWorkState);
begin
if FWorkState <> Value then
begin
FWorkState := Value;
ClientStateChange;
end;
end;
procedure TClientControl.StartExam(Sender: TObject);
begin
if Assigned(FOnStartExam) then
begin
FStartTime := Now;
FOnStartExam(Self);
end;
end;
procedure TClientControl.StateChange;
begin
if Assigned(FOnStateChange) then
FOnStateChange(Self);
end;
procedure TClientControl.StopExam(Sender: TObject);
begin
if Assigned(FOnStopExam) then
begin
EndTime := Now;
FOnStopExam(Self);
end;
end;
procedure TClientControl.StuLogin(Sender: TObject);
begin
if Assigned(FOnStuLogin) then
begin
FOnStuLogin(Self);
end;
end;
procedure TClientControl.StuProgress(nReadyCount, nTotalCount: Integer);
begin
if Assigned(FOnStuProgress) then
begin
FOnStuProgress(nReadyCount, nTotalCount);
end;
end;
procedure TClientControl.StuReady(nTotalCount: Integer);
begin
if Assigned(FOnStuReady) then
begin
FOnStuReady(nTotalCount);
FSubList.Text := DataDict.Dictionary['考题列表'].Text;
FExamName := DataDict.Dictionary['考试名称'].Text;
trystrtoint(DataDict.Dictionary['考试时间'].Text, fexamtimes);
end;
end;
procedure TClientControl.StuReadyExam;
begin
FTCPClient.StuReadyExam;
end;
procedure TClientControl.TCPConnect(Sender: TObject);
begin
if Assigned(FOnConnected) then
begin
FOnConnected(Sender);
end;
end;
procedure TClientControl.TCPDisconnect(Sender: TObject);
begin
if Assigned(FOnDisconnect) then
begin
FOnDisconnect(Sender);
end;
end;
procedure TClientControl.TCPLog(const S: string);
begin
if Assigned(FOnLog) then
begin
FOnLog(s);
end;
end;
procedure TClientControl.TCPPacksLog(aPacks: TBytes; bSend: Boolean);
var
s : string;
begin
if bsend then
s := '发送'
else
s := '接收';
TCPLog(FormatDateTime('hh:mm:ss:zzz', Now) + s + ' ' + BCDPacksToStr(aPacks) );
end;
procedure TClientControl.WriteINI;
begin
end;
end.
|
unit MediaStream.Framer.Picture;
interface
uses Windows,SysUtils,Classes,MediaProcessing.Definitions,MediaStream.Framer;
type
TStreamFramerPicture = class (TStreamFramer)
private
FFrameInterval: cardinal;
public
constructor Create; override;
//Интервал между кадрами
property FrameInterval: cardinal read FFrameInterval write FFrameInterval;
end;
implementation
const DefaultFrameInterval = 5000;
{ TStreamFramerPicture }
constructor TStreamFramerPicture.Create;
begin
inherited;
FFrameInterval:=DefaultFrameInterval;
end;
end.
|
{-------------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: SynHighlighterASM.pas, released 2000-04-18.
The Original Code is based on the nhAsmSyn.pas file from the
mwEdit component suite by Martin Waldenburg and other developers, the Initial
Author of this file is Nick Hoddinott.
All Rights Reserved.
Contributors to the SynEdit and mwEdit projects are listed in the
Contributors.txt file.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
$Id: SynHighlighterAsm.pas,v 1.12 2003/09/24 05:06:14 etrusco Exp $
You may retrieve the latest version of this file at the SynEdit home page,
located at http://SynEdit.SourceForge.net
Known Issues:
-------------------------------------------------------------------------------}
{
@abstract(Provides a x86 Assembler highlighter for SynEdit)
@author(Nick Hoddinott <nickh@conceptdelta.com>, converted to SynEdit by David Muir <david@loanhead45.freeserve.co.uk>)
@created(7 November 1999, converted to SynEdit April 18, 2000)
@lastmod(April 18, 2000)
The SynHighlighterASM unit provides SynEdit with a x86 Assembler (.asm) highlighter.
The highlighter supports all x86 op codes, Intel MMX and AMD 3D NOW! op codes.
Thanks to Martin Waldenburg, Hideo Koiso.
}
{$IFNDEF QSYNHIGHLIGHTERASM}
unit uSynHighlighteri8008ASM;
{$ENDIF}
{$I SynEdit.inc}
interface
uses
{$IFDEF SYN_CLX}
QGraphics,
QSynEditTypes,
QSynEditHighlighter,
QSynHighlighterHashEntries,
{$ELSE}
Graphics,
SynEditTypes,
SynEditHighlighter,
SynHighlighterHashEntries,
{$ENDIF}
SysUtils,
Classes;
type
TtkTokenKind = (tkComment, tkIdentifier, tkKey, tkNull, tkNumber, tkSpace,
tkString, tkSymbol, tkUnknown);
TProcTableProc = procedure of object;
type
Ti8008ASMSyn = class(TSynCustomHighlighter)
private
fLine: PChar;
fLineNumber: Integer;
fProcTable: array[#0..#255] of TProcTableProc;
Run: LongInt;
fStringLen: Integer;
fToIdent: PChar;
fTokenPos: Integer;
fTokenID: TtkTokenKind;
fCommentAttri: TSynHighlighterAttributes;
fIdentifierAttri: TSynHighlighterAttributes;
fKeyAttri: TSynHighlighterAttributes;
fNumberAttri: TSynHighlighterAttributes;
fSpaceAttri: TSynHighlighterAttributes;
fStringAttri: TSynHighlighterAttributes;
fSymbolAttri: TSynHighlighterAttributes;
fKeywords: TSynHashEntryList;
function KeyHash(ToHash: PChar): Integer;
function KeyComp(const aKey: String): Boolean;
procedure CommentProc;
procedure CRProc;
procedure GreaterProc;
procedure IdentProc;
procedure LFProc;
procedure LowerProc;
procedure NullProc;
procedure NumberProc;
procedure SlashProc;
procedure SpaceProc;
procedure StringProc;
procedure SingleQuoteStringProc;
procedure SymbolProc;
procedure UnknownProc;
procedure DoAddKeyword(AKeyword: string; AKind: integer);
function IdentKind(MayBe: PChar): TtkTokenKind;
procedure MakeMethodTables;
protected
function GetIdentChars: TSynIdentChars; override;
function GetSampleSource: string; override;
function IsFilterStored: Boolean; override;
public
{$IFNDEF SYN_CPPB_1} class {$ENDIF} //mh 2000-07-14
function GetLanguageName: string; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
override;
function GetEol: Boolean; override;
function GetTokenID: TtkTokenKind;
procedure SetLine(NewValue: String; LineNumber:Integer); override;
function GetToken: String; override;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetTokenKind: integer; override;
function GetTokenPos: Integer; override;
procedure Next; override;
published
property CommentAttri: TSynHighlighterAttributes read fCommentAttri
write fCommentAttri;
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri
write fIdentifierAttri;
property KeyAttri: TSynHighlighterAttributes read fKeyAttri write fKeyAttri;
property NumberAttri: TSynHighlighterAttributes read fNumberAttri
write fNumberAttri;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri
write fSpaceAttri;
property StringAttri: TSynHighlighterAttributes read fStringAttri
write fStringAttri;
property SymbolAttri: TSynHighlighterAttributes read fSymbolAttri
write fSymbolAttri;
end;
implementation
uses
{$IFDEF SYN_CLX}
QSynEditStrConst;
{$ELSE}
SynEditStrConst;
{$ENDIF}
var
Identifiers: array[#0..#255] of ByteBool;
mHashTable: array[#0..#255] of Integer;
const
OpCodes: string = 'mov,mvi,inr,dcr,add,adc,sub,sbb,adi,aci,sui,sbi,'+
'ana,xra,ora,cmp,ani,xri,ori,cpi,jmp,jnc,jnz,jp,'+
'jpo,jc,jz,jm,jpe,call,cnc,cnz,cp,cpo,cc,cz,cm,'+
'cpe,rst,ret,rnc,rnz,rp,rpo,rc,rz,rm,rpe,rlc,rrc'+
'ral,rar,in,out';
procedure MakeIdentTable;
var
c: char;
begin
FillChar(Identifiers, SizeOf(Identifiers), 0);
for c := 'a' to 'z' do
Identifiers[c] := TRUE;
for c := 'A' to 'Z' do
Identifiers[c] := TRUE;
for c := '0' to '9' do
Identifiers[c] := TRUE;
Identifiers['_'] := TRUE;
FillChar(mHashTable, SizeOf(mHashTable), 0);
for c := 'a' to 'z' do
mHashTable[c] := 1 + Ord(c) - Ord('a');
for c := 'A' to 'Z' do
mHashTable[c] := 1 + Ord(c) - Ord('A');
for c := '0' to '9' do
mHashTable[c] := 27 + Ord(c) - Ord('0');
end;
function Ti8008ASMSyn.KeyHash(ToHash: PChar): Integer;
begin
Result := 0;
while Identifiers[ToHash^] do begin
{$IFOPT Q-}
Result := 7 * Result + mHashTable[ToHash^];
{$ELSE}
Result := (7 * Result + mHashTable[ToHash^]) and $FFFFFF;
{$ENDIF}
inc(ToHash);
end;
Result := Result and $3FF;
fStringLen := ToHash - fToIdent;
end;
function Ti8008ASMSyn.KeyComp(const aKey: String): Boolean;
var
i: integer;
pKey1, pKey2: PChar;
begin
pKey1 := fToIdent;
// Note: fStringLen is always > 0 !
pKey2 := pointer(aKey);
for i := 1 to fStringLen do
begin
if mHashTable[pKey1^] <> mHashTable[pKey2^] then
begin
Result := FALSE;
exit;
end;
Inc(pKey1);
Inc(pKey2);
end;
Result := TRUE;
end;
procedure Ti8008ASMSyn.DoAddKeyword(AKeyword: string; AKind: integer);
var
HashValue: integer;
begin
HashValue := KeyHash(PChar(AKeyword));
fKeywords[HashValue] := TSynHashEntry.Create(AKeyword, AKind);
end;
function Ti8008ASMSyn.IdentKind(MayBe: PChar): TtkTokenKind;
var
Entry: TSynHashEntry;
begin
fToIdent := MayBe;
Entry := fKeywords[KeyHash(MayBe)];
while Assigned(Entry) do begin
if Entry.KeywordLen > fStringLen then
break
else if Entry.KeywordLen = fStringLen then
if KeyComp(Entry.Keyword) then begin
Result := TtkTokenKind(Entry.Kind);
exit;
end;
Entry := Entry.Next;
end;
Result := tkIdentifier;
end;
procedure Ti8008ASMSyn.MakeMethodTables;
var
I: Char;
begin
for I := #0 to #255 do
case I of
#0 : fProcTable[I] := NullProc;
#10 : fProcTable[I] := LFProc;
#13 : fProcTable[I] := CRProc;
#34 : fProcTable[I] := StringProc;
#39 : fProcTable[I] := SingleQuoteStringProc;
'>' : fProcTable[I] := GreaterProc;
'<' : fProcTable[I] := LowerProc;
'/' : fProcTable[I] := SlashProc;
'A'..'Z', 'a'..'z', '_':
fProcTable[I] := IdentProc;
'0'..'9':
fProcTable[I] := NumberProc;
#1..#9, #11, #12, #14..#32:
fProcTable[I] := SpaceProc;
'#', ';':
fProcTable[I] := CommentProc;
'.', ':', '&', '{', '}', '=', '^', '-', '+', '(', ')', '*':
fProcTable[I] := SymbolProc;
else
fProcTable[I] := UnknownProc;
end;
end;
constructor Ti8008ASMSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fKeywords := TSynHashEntryList.Create;
fCommentAttri := TSynHighlighterAttributes.Create(SYNS_AttrComment);
fCommentAttri.Style := [fsItalic];
AddAttribute(fCommentAttri);
fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier);
AddAttribute(fIdentifierAttri);
fKeyAttri := TSynHighlighterAttributes.Create(SYNS_AttrReservedWord);
fKeyAttri.Style := [fsBold];
AddAttribute(fKeyAttri);
fNumberAttri := TSynHighlighterAttributes.Create(SYNS_AttrNumber);
AddAttribute(fNumberAttri);
fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace);
AddAttribute(fSpaceAttri);
fStringAttri := TSynHighlighterAttributes.Create(SYNS_AttrString);
AddAttribute(fStringAttri);
fSymbolAttri := TSynHighlighterAttributes.Create(SYNS_AttrSymbol);
AddAttribute(fSymbolAttri);
MakeMethodTables;
EnumerateKeywords(Ord(tkKey), OpCodes, IdentChars, DoAddKeyword);
SetAttributesOnChange(DefHighlightChange);
fDefaultFilter := SYNS_FilterX86Assembly;
end;
destructor Ti8008ASMSyn.Destroy;
begin
fKeywords.Free;
inherited Destroy;
end;
procedure Ti8008ASMSyn.SetLine(NewValue: String; LineNumber:Integer);
begin
fLine := PChar(NewValue);
Run := 0;
fLineNumber := LineNumber;
Next;
end;
procedure Ti8008ASMSyn.CommentProc;
begin
fTokenID := tkComment;
repeat
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end;
procedure Ti8008ASMSyn.CRProc;
begin
fTokenID := tkSpace;
Inc(Run);
if fLine[Run] = #10 then Inc(Run);
end;
procedure Ti8008ASMSyn.GreaterProc;
begin
Inc(Run);
fTokenID := tkSymbol;
if fLine[Run] = '=' then Inc(Run);
end;
procedure Ti8008ASMSyn.IdentProc;
begin
fTokenID := IdentKind((fLine + Run));
inc(Run, fStringLen);
while Identifiers[fLine[Run]] do inc(Run);
end;
procedure Ti8008ASMSyn.LFProc;
begin
fTokenID := tkSpace;
inc(Run);
end;
procedure Ti8008ASMSyn.LowerProc;
begin
Inc(Run);
fTokenID := tkSymbol;
if fLine[Run] in ['=', '>'] then Inc(Run);
end;
procedure Ti8008ASMSyn.NullProc;
begin
fTokenID := tkNull;
end;
procedure Ti8008ASMSyn.NumberProc;
begin
inc(Run);
fTokenID := tkNumber;
// while FLine[Run] in ['0'..'9', '.', 'e', 'E'] do inc(Run);
while FLine[Run] in ['0'..'9', '.', 'a'..'f', 'h', 'A'..'F', 'H'] do //ek 2000-09-23
Inc(Run);
end;
procedure Ti8008ASMSyn.SlashProc;
begin
Inc(Run);
if fLine[Run] = '/' then begin
fTokenID := tkComment;
repeat
Inc(Run);
until fLine[Run] in [#0, #10, #13];
end else
fTokenID := tkSymbol;
end;
procedure Ti8008ASMSyn.SpaceProc;
begin
fTokenID := tkSpace;
repeat
Inc(Run);
until (fLine[Run] > #32) or (fLine[Run] in [#0, #10, #13]);
end;
procedure Ti8008ASMSyn.StringProc;
begin
fTokenID := tkString;
if (FLine[Run + 1] = #34) and (FLine[Run + 2] = #34) then
inc(Run, 2);
repeat
case FLine[Run] of
#0, #10, #13: break;
end;
inc(Run);
until FLine[Run] = #34;
if FLine[Run] <> #0 then inc(Run);
end;
procedure Ti8008ASMSyn.SingleQuoteStringProc;
begin
fTokenID := tkString;
if (FLine[Run + 1] = #39) and (FLine[Run + 2] = #39) then
inc(Run, 2);
repeat
case FLine[Run] of
#0, #10, #13: break;
end;
inc(Run);
until FLine[Run] = #39;
if FLine[Run] <> #0 then inc(Run);
end;
procedure Ti8008ASMSyn.SymbolProc;
begin
inc(Run);
fTokenID := tkSymbol;
end;
procedure Ti8008ASMSyn.UnknownProc;
begin
{$IFDEF SYN_MBCSSUPPORT}
if FLine[Run] in LeadBytes then
Inc(Run,2)
else
{$ENDIF}
inc(Run);
fTokenID := tkIdentifier;
end;
procedure Ti8008ASMSyn.Next;
begin
fTokenPos := Run;
fProcTable[fLine[Run]];
end;
function Ti8008ASMSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
begin
case Index of
SYN_ATTR_COMMENT: Result := fCommentAttri;
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
SYN_ATTR_KEYWORD: Result := fKeyAttri;
SYN_ATTR_STRING: Result := fStringAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
SYN_ATTR_SYMBOL: Result := fSymbolAttri;
else
Result := nil;
end;
end;
function Ti8008ASMSyn.GetEol: Boolean;
begin
Result := fTokenId = tkNull;
end;
function Ti8008ASMSyn.GetToken: String;
var
Len: LongInt;
begin
Len := Run - fTokenPos;
SetString(Result, (FLine + fTokenPos), Len);
end;
function Ti8008ASMSyn.GetTokenAttribute: TSynHighlighterAttributes;
begin
case fTokenID of
tkComment: Result := fCommentAttri;
tkIdentifier: Result := fIdentifierAttri;
tkKey: Result := fKeyAttri;
tkNumber: Result := fNumberAttri;
tkSpace: Result := fSpaceAttri;
tkString: Result := fStringAttri;
tkSymbol: Result := fSymbolAttri;
tkUnknown: Result := fIdentifierAttri;
else Result := nil;
end;
end;
function Ti8008ASMSyn.GetTokenKind: integer;
begin
Result := Ord(fTokenId);
end;
function Ti8008ASMSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function Ti8008ASMSyn.GetTokenPos: Integer;
begin
Result := fTokenPos;
end;
function Ti8008ASMSyn.GetIdentChars: TSynIdentChars;
begin
Result := TSynValidStringChars; //DDH 10/17/01
end;
{$IFNDEF SYN_CPPB_1} class {$ENDIF} //mh 2000-07-14
function Ti8008ASMSyn.GetLanguageName: string;
begin
Result := 'i8008 Assembly';
end;
function Ti8008ASMSyn.IsFilterStored: Boolean;
begin
Result := fDefaultFilter <> SYNS_FilterX86Assembly;
end;
function Ti8008ASMSyn.GetSampleSource: string;
begin
Result := '';
end;
initialization
MakeIdentTable;
RegisterPlaceableHighlighter(Ti8008ASMSyn);
end.
|
unit Nathan.MapFile.Core.Tests;
interface
uses
DUnitX.TestFramework,
Nathan.Resources.ResourceManager,
Nathan.MapFile.Core;
type
[TestFixture]
TTestNathanMapFile = class(TObject)
const
DemoMap = '.\ExceptionStackTraceDemo.map';
private
FCut: INathanMapFile;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
[Test]
procedure Test_HasCreated;
[Test]
procedure Test_HasAllProperties;
[Test]
procedure Test_Scan_Ex;
[TestCase('Scan_57_01', '$0020413C,0,$203DFC')]
[TestCase('Scan_57_02', '$0020413D,1,$203DFC')]
[TestCase('Scan_57_03', '$00204144,8,$203DFC')]
procedure Test_Scan_Line57(CAValue, OffsetValue, StartAddrValue: Integer);
[Test]
procedure Test_Scan_Line57_TwoTimes;
[Test]
procedure Test_Scan_Line57_OverConstructor;
[TestCase('VAFromAddress01', '$14E20B0,$10E10B0')]
procedure Test_VAFromAddress(AddrValue, VAValue: Integer);
end;
implementation
uses
System.SysUtils,
System.IOUtils;
procedure TTestNathanMapFile.Setup;
begin
TResourceManager.SaveResource('ExDemoMap', DemoMap);
end;
procedure TTestNathanMapFile.TearDown;
begin
FCut := nil;
if TFile.Exists(DemoMap) then
TFile.Delete(DemoMap);
end;
procedure TTestNathanMapFile.Test_HasCreated;
begin
FCut := TNathanMapFile.Create();
Assert.IsNotNull(FCut);
end;
procedure TTestNathanMapFile.Test_HasAllProperties;
begin
FCut := TNathanMapFile.Create();
FCut.MapFilename := 'MapFilename';
FCut.CrashAddress := $2020;
Assert.AreEqual('MapFilename', FCut.MapFilename);
Assert.AreEqual($2020, FCut.CrashAddress);
end;
procedure TTestNathanMapFile.Test_Scan_Ex;
begin
FCut := TNathanMapFile.Create();
FCut.CrashAddress := $2020;
Assert.WillRaiseWithMessage(
procedure
begin
FCut.Scan;
end,
EArgumentException,
'MapFilename "" or CrashAddress "8224" invalid!');
end;
procedure TTestNathanMapFile.Test_Scan_Line57(CAValue, OffsetValue, StartAddrValue: Integer);
begin
FCut := TNathanMapFile.Create();
FCut.MapFilename := DemoMap;
FCut.CrashAddress := CAValue;
Assert.WillNotRaiseAny(
procedure
begin
FCut.Scan;
end);
Assert.AreEqual(OffsetValue, FCut.MapReturn.Offset);
Assert.AreEqual(57, FCut.MapReturn.LineNumberFromAddr);
Assert.AreEqual(StartAddrValue, FCut.MapReturn.ModuleStartFromAddr);
Assert.AreEqual('Main', FCut.MapReturn.ModuleNameFromAddr);
Assert.AreEqual('Main.TForm1.FormCreate', FCut.MapReturn.ProcNameFromAddr);
Assert.AreEqual('Main.pas', FCut.MapReturn.SourceNameFromAddr);
Assert.AreEqual(42, FCut.MapReturn.LineNumberErrors);
end;
procedure TTestNathanMapFile.Test_Scan_Line57_TwoTimes;
begin
FCut := TNathanMapFile.Create();
FCut.MapFilename := DemoMap;
FCut.CrashAddress := $0020413C;
Assert.WillNotRaiseAny(
procedure
begin
FCut.Scan;
end);
Assert.AreEqual(0, FCut.MapReturn.Offset);
Assert.AreEqual(57, FCut.MapReturn.LineNumberFromAddr);
Assert.AreEqual($203DFC, FCut.MapReturn.ModuleStartFromAddr);
Assert.AreEqual('Main', FCut.MapReturn.ModuleNameFromAddr);
Assert.AreEqual('Main.TForm1.FormCreate', FCut.MapReturn.ProcNameFromAddr);
Assert.AreEqual('Main.pas', FCut.MapReturn.SourceNameFromAddr);
Assert.AreEqual(42, FCut.MapReturn.LineNumberErrors);
FCut.MapFilename := DemoMap;
FCut.CrashAddress := $0020413D;
Assert.WillNotRaiseAny(
procedure
begin
FCut.Scan;
end);
Assert.AreEqual(1, FCut.MapReturn.Offset);
Assert.AreEqual(57, FCut.MapReturn.LineNumberFromAddr);
Assert.AreEqual($203DFC, FCut.MapReturn.ModuleStartFromAddr);
Assert.AreEqual('Main', FCut.MapReturn.ModuleNameFromAddr);
Assert.AreEqual('Main.TForm1.FormCreate', FCut.MapReturn.ProcNameFromAddr);
Assert.AreEqual('Main.pas', FCut.MapReturn.SourceNameFromAddr);
Assert.AreEqual(42, FCut.MapReturn.LineNumberErrors);
end;
procedure TTestNathanMapFile.Test_Scan_Line57_OverConstructor;
begin
FCut := TNathanMapFile.Create(DemoMap, $0020413C);
Assert.WillNotRaiseAny(
procedure
begin
FCut.Scan;
end);
Assert.AreEqual(0, FCut.MapReturn.Offset);
Assert.AreEqual(57, FCut.MapReturn.LineNumberFromAddr);
Assert.AreEqual($203DFC, FCut.MapReturn.ModuleStartFromAddr);
Assert.AreEqual('Main', FCut.MapReturn.ModuleNameFromAddr);
Assert.AreEqual('Main.TForm1.FormCreate', FCut.MapReturn.ProcNameFromAddr);
Assert.AreEqual('Main.pas', FCut.MapReturn.SourceNameFromAddr);
Assert.AreEqual(42, FCut.MapReturn.LineNumberErrors);
end;
procedure TTestNathanMapFile.Test_VAFromAddress(AddrValue, VAValue: Integer);
begin
Assert.AreEqual(VAValue, TNathanMapFile.VAFromAddress(AddrValue));
end;
initialization
TDUnitX.RegisterTestFixture(TTestNathanMapFile);
end.
|
unit ExButtons;
{$mode objfpc}{$H+}
interface
uses
Graphics, Classes, SysUtils, LMessages, Types, Controls, StdCtrls, Forms;
type
TButtonExState = (bxsNormal, bxsHot, bxsDown, bxsFocused, bxsDisabled);
TButtonExBorderWidth = 1..10;
TButtonEx = class;
TButtonExBorder = class(TPersistent)
private
FButton: TButtonEx;
FColorNormal: TColor;
FColorHot: TColor;
FColorDown: TColor;
FColorDisabled: TColor;
FColorFocused: TColor;
FWidthNormal: TButtonExBorderWidth;
FWidthHot: TButtonExBorderWidth;
FWidthDown: TButtonExBorderWidth;
FWidthDisabled: TButtonExBorderWidth;
FWidthFocused: TButtonExBorderWidth;
procedure SetWidthNormal(const Value: TButtonExBorderWidth);
procedure SetColorNormal(const Value: TColor);
public
constructor Create(AButton: TButtonEx);
published
property ColorNormal: TColor read FColorNormal write SetColorNormal;
property ColorHot: TColor read FColorHot write FColorHot;
property ColorDown: TColor read FColorDown write FColorDown;
property ColorDisabled: TColor read FColorDisabled write FColorDisabled;
property ColorFocused: TColor read FColorFocused write FColorFocused;
property WidthNormal: TButtonExBorderWidth read FWidthNormal write SetWidthNormal;
property WidthHot: TButtonExBorderWidth read FWidthHot write FWidthHot;
property WidthDown: TButtonExBorderWidth read FWidthDown write FWidthDown;
property WidthDisabled: TButtonExBorderWidth read FWidthDisabled write FWidthDisabled;
property WidthFocused: TButtonExBorderWidth read FWidthFocused write FWidthFocused;
end;
TButtonExColors = class(TPersistent)
private
FButton: TButtonEx;
FColorNormalFrom: TColor;
FColorNormalTo: TColor;
FColorHotFrom: TColor;
FColorHotTo: TColor;
FColorDownFrom: TColor;
FColorDownTo: TColor;
FColorDisabledFrom: TColor;
FColorDisabledTo: TColor;
FColorFocusedFrom: TColor;
FColorFocusedTo: TColor;
procedure SetColorNormalFrom(const Value: TColor);
procedure SetColorNormalTo(const Value: TColor);
public
constructor Create(AButton: TButtonEx);
published
property ColorNormalFrom: TColor read FColorNormalFrom write SetColorNormalFrom;
property ColorNormalTo: TColor read FColorNormalTo write SetColorNormalTo;
property ColorHotFrom: TColor read FColorHotFrom write FColorHotFrom;
property ColorHotTo: TColor read FColorHotTo write FColorHotTo;
property ColorDownFrom: TColor read FColorDownFrom write FColorDownFrom;
property ColorDownTo: TColor read FColorDownTo write FColorDownTo;
property ColorDisabledFrom: TColor read FColorDisabledFrom write FColorDisabledFrom;
property ColorDisabledTo: TColor read FColorDisabledTo write FColorDisabledTo;
property ColorFocusedFrom: TColor read FColorFocusedFrom write FColorFocusedFrom;
property ColorFocusedTo: TColor read FColorFocusedTo write FColorFocusedTo;
end;
TButtonEx = class(TCustomButton)
private
FAlignment: TAlignment;
FBorder: TButtonExBorder;
FCanvas: TCanvas;
FColors: TButtonExColors;
FDefaultDrawing: Boolean;
FFontDisabled: TFont;
FFontDown: TFont;
FFontFocused: TFont;
FFontHot: TFont;
FGradient: Boolean;
FMargin: integer;
FShowFocusRect: Boolean;
FState: TButtonExState;
FWordwrap: Boolean;
procedure SetAlignment(const Value: TAlignment);
procedure SetDefaultDrawing(const Value: Boolean);
procedure SetGradient(const Value: Boolean);
procedure SetShowFocusRect(const Value: Boolean);
procedure SetMargin(const Value: integer);
procedure SetWordWrap(const Value: Boolean);
protected
procedure CalculatePreferredSize(var PreferredWidth, PreferredHeight: Integer;
WithThemeSpace: Boolean); override;
class function GetControlClassDefaultSize: TSize; override;
function GetDrawTextFlags: Cardinal;
procedure MouseEnter; override;
procedure MouseLeave; override;
procedure PaintButton;
procedure PaintCustomButton;
procedure PaintThemedButton;
procedure WMKillFocus(var Message: TLMKillFocus); message LM_KILLFOCUS;
procedure WMPaint(var Msg: TLMPaint); message LM_PAINT;
procedure WMSetFocus(var Message: TLMSetFocus); message LM_SETFOCUS;
procedure WndProc(var Message: TLMessage); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property Anchors;
property AutoSize;
property BorderSpacing;
property Cancel;
property Caption;
//property Color; removed for new property Colors
property Constraints;
property Cursor;
property Default;
//property DoubleBuffered; // PaintButton is not called when this is set.
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property Height;
property HelpContext;
property HelpKeyword;
property HelpType;
property Hint;
property Left;
property ModalResult;
property ParentBiDiMode;
//property ParentDoubleBuffered;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop default True;
property Tag;
property Top;
property Visible;
property Width;
property OnChangeBounds;
property OnClick;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDrag;
property OnUTF8KeyPress;
property Alignment: TAlignment read FAlignment write SetAlignment default taCenter;
property Border: TButtonExBorder read FBorder write FBorder;
property Colors: TButtonExColors read FColors write FColors;
property DefaultDrawing: Boolean read FDefaultDrawing write SetDefaultDrawing default true;
property FontDisabled: TFont read FFontDisabled write FFontDisabled;
property FontDown: TFont read FFontDown write FFontDown;
property FontFocused: TFont read FFontFocused write FFontFocused;
property FontHot: TFont read FFontHot write FFontHot;
property Gradient: Boolean read FGradient write SetGradient default true;
property Margin: integer read FMargin write SetMargin;
property ShowFocusRect: Boolean read FShowFocusRect write SetShowFocusRect default true;
property Wordwrap: Boolean read FWordWrap write SetWordWrap default false;
end;
implementation
uses
LCLType, LCLIntf, Themes;
{ TButtonExBorder }
constructor TButtonExBorder.Create(AButton: TButtonEx);
begin
inherited Create;
FButton := AButton;
end;
procedure TButtonExBorder.SetColorNormal(const Value: TColor);
begin
if FColorNormal = Value then exit;
FColorNormal := Value;
FButton.Invalidate;
end;
procedure TButtonExBorder.SetWidthNormal(const Value: TButtonExBorderWidth);
begin
if FWidthNormal = Value then exit;
FWidthNormal := Value;
FButton.Invalidate;
end;
{ TButtonExColors }
constructor TButtonExColors.Create(AButton: TButtonEx);
begin
inherited Create;
FButton := AButton;
end;
procedure TButtonExColors.SetColorNormalFrom(const Value: TColor);
begin
if FColorNormalFrom = Value then
exit;
FColorNormalFrom := Value;
FButton.Invalidate;
end;
procedure TButtonExColors.SetColorNormalTo(const Value: TColor);
begin
if FColorNormalTo = Value then
exit;
FColorNormalTo := Value;
FButton.Invalidate;
end;
{ TButtonEx }
constructor TButtonEx.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FDefaultDrawing := true;
FGradient := true;
FShowFocusRect := true;
// Background colors
FColors := TButtonExColors.Create(Self);
FColors.ColorNormalFrom := $00FCFCFC;
FColors.ColorNormalTo := $00CFCFCF;
FColors.ColorHotFrom := $00FCFCFC;
FColors.ColorHotTo := $00F5D9A7;
FColors.ColorDownFrom := $00FCFCFC;
FColors.ColorDownTo := $00DBB368;
FColors.ColorDisabledFrom := $00F4F4F4;
FColors.ColorDisabledTo := $00F4F4F4;
FColors.ColorFocusedFrom := $00FCFCFC;
FColors.ColorFocusedTo := $00CFCFCF;
// Fonts
FFontDisabled := TFont.Create;
FFontDisabled.Assign(Font);
FFontDisabled.Color := clGrayText;
FFontDisabled.OnChange := @FontChanged;
FFontDown := TFont.Create;
FFontDown.Assign(Font);
FFontDown.OnChange := @FontChanged;
FFontFocused := TFont.Create;
FFontFocused.Assign(Font);
FFontFocused.OnChange := @FontChanged;
FFontHot := TFont.Create;
FFontHot.Assign(Font);
FFontHot.OnChange := @FontChanged;
// Border
FBorder := TButtonExBorder.Create(Self);
FBorder.ColorNormal := $00707070;
FBorder.ColorHot := $00B17F3C;
FBorder.ColorDown := $008B622C;
FBorder.ColorDisabled := $00B5B2AD;
FBorder.ColorFocused := $00B17F3C;
FBorder.WidthNormal := 1;
FBorder.WidthHot := 1;
FBorder.WidthDown := 1;
FBorder.WidthDisabled := 1;
FBorder.WidthFocused := 1;
// Other
FMargin := 5;
FAlignment := taCenter;
FState := bxsNormal;
end;
destructor TButtonEx.Destroy;
begin
FFontHot.Free;
FFontDown.Free;
FFontDisabled.Free;
FFontFocused.Free;
FColors.Free;
FBorder.Free;
FCanvas.Free;
inherited;
end;
procedure TButtonEx.CalculatePreferredSize(var PreferredWidth,
PreferredHeight: Integer; WithThemeSpace: Boolean);
var
flags: Cardinal;
txtSize: TSize;
R: TRect;
details: TThemedElementDetails;
begin
FCanvas.Font.Assign(Font);
R := ClientRect;
InflateRect(R, -FMargin, 0);
R.Bottom := MaxInt; // Max height possible
flags := GetDrawTextFlags + DT_CALCRECT;
// rectangle available for text
details := ThemeServices.GetElementDetails(tbPushButtonNormal);
if FWordWrap then
begin
with ThemeServices.GetTextExtent(FCanvas.Handle, details, Caption, flags, @R) do begin
txtSize.CX := Right;
txtSize.CY := Bottom;
end;
end else
with ThemeServices.GetTextExtent(FCanvas.Handle, details, Caption, flags, nil) do begin
txtSize.CX := Right;
txtSize.CY := Bottom;
end;
PreferredHeight := txtSize.CY + 2 * FMargin;
PreferredWidth := txtSize.CX + 2 * FMargin;
if not FWordWrap then
PreferredHeight := 0;
end;
class function TButtonEx.GetControlClassDefaultSize: TSize;
begin
Result.CX := 75;
Result.CY := 25;
end;
function TButtonEx.GetDrawTextFlags: Cardinal;
begin
Result := DT_VCENTER or DT_NOPREFIX;
case FAlignment of
taLeftJustify:
if IsRightToLeft then Result := Result or DT_RIGHT else Result := Result or DT_LEFT;
taRightJustify:
if IsRightToLeft then Result := Result or DT_LEFT else Result := Result or DT_RIGHT;
taCenter:
Result := Result or DT_CENTER;
end;
if IsRightToLeft then
result := Result or DT_RTLREADING;
if FWordWrap then
Result := Result or DT_WORDBREAK and not DT_SINGLELINE
else
Result := Result or DT_SINGLELINE and not DT_WORDBREAK;;
end;
procedure TButtonEx.MouseEnter;
begin
if FState <> bxsDisabled then
begin
FState := bxsHot;
Invalidate;
end;
inherited;
end;
procedure TButtonEx.MouseLeave;
begin
if (FState <> bxsDisabled) then
begin
if Focused then
FState := bxsFocused
else
FState := bxsNormal;
Invalidate;
end;
inherited;
end;
procedure TButtonEx.PaintButton;
begin
if FDefaultDrawing then
PaintThemedButton
else
PaintCustomButton;
end;
procedure TButtonEx.PaintCustomButton;
var
lCanvas: TCanvas;
lBitmap: TBitmap;
lRect, R: TRect;
lBorderColor: TColor;
lBorderWidth: integer;
lColorFrom: TColor;
lColorTo: TColor;
lTextFont: TFont;
lAlignment: TAlignment;
flags: Cardinal;
i: integer;
txtSize: TSize;
txtPt: TPoint;
begin
if (csDestroying in ComponentState) or not HandleAllocated then
exit;
// Bitmap
lBitmap := TBitmap.Create;
lBitmap.Width := Width;
lBitmap.Height := Height;
lCanvas := lBitmap.Canvas;
// State
lBorderColor := Border.ColorNormal;
lColorFrom := Colors.ColorNormalFrom;
lColorTo := Colors.ColorNormalTo;
lTextFont := Font;
lBorderWidth := Border.WidthNormal;
if not (csDesigning in ComponentState) then
begin
case FState of
bxsFocused:
begin
lBorderColor := FBorder.ColorFocused;
lColorFrom := FColors.ColorFocusedFrom;
lColorTo := FColors.ColorFocusedTo;
lTextFont := FFontFocused;
lBorderWidth := FBorder.WidthFocused;
end;
bxsHot:
begin
lBorderColor := FBorder.ColorHot;
lColorFrom := FColors.ColorHotFrom;
lColorTo := FColors.ColorHotTo;
lTextFont := FFontHot;
lBorderWidth := FBorder.WidthHot;
end;
bxsDown:
begin
lBorderColor := FBorder.ColorDown;
lColorFrom := FColors.ColorDownFrom;
lColorTo := FColors.ColorDownTo;
lTextFont := FFontDown;
lBorderWidth := FBorder.WidthDown;
end;
bxsDisabled:
begin
lBorderColor := FBorder.ColorDisabled;
lColorFrom := FColors.ColorDisabledFrom;
lColorTo := FColors.ColorDisabledTo;
lTextFont := FFontDisabled;
lBorderWidth := FBorder.WidthDisabled;
end;
end;
end;
// Background
lRect := Rect(0, 0, Width, Height);
if FGradient then
lCanvas.GradientFill(lRect, lColorFrom, lColorTo, gdVertical)
else
begin
lCanvas.Brush.Style := bsSolid;
lCanvas.Brush.Color := lColorFrom;
lCanvas.FillRect(lRect);
end;
// Border
lCanvas.Pen.Width := 1;
lCanvas.Pen.Color := lBorderColor;
for i := 1 to lBorderWidth do
begin
lCanvas.MoveTo(i - 1, i - 1);
lCanvas.LineTo(Width - i, i - 1);
lCanvas.LineTo(Width - i, Height - i);
lCanvas.LineTo(i - 1, Height - i);
lCanvas.LineTo(i - 1, i - 1);
end;
// Caption
lCanvas.Pen.Width := 1;
lCanvas.Brush.Style := bsClear;
lCanvas.Font.Assign(lTextFont);
flags := GetDrawTextFlags;
R := lRect;
DrawText(FCanvas.Handle, PChar(Caption), Length(Caption), R, flags + DT_CALCRECT);
txtSize.CX := R.Right - R.Left;
txtSize.CY := R.Bottom - R.Top;
lAlignment := FAlignment;
if IsRightToLeft then begin
if lAlignment = taLeftJustify then
lAlignment := taRightJustify
else if lAlignment = taRightJustify then
lAlignment := taLeftJustify;
end;
case lAlignment of
taLeftJustify:
txtPt.X := FMargin;
taRightJustify:
txtPt.X := Width - txtSize.CX - FMargin;
taCenter:
txtPt.X := (Width - txtSize.CX) div 2;
end;
txtPt.Y := (Height - txtSize.CY + 1) div 2;
R := Rect(txtPt.X, txtPt.Y, txtPt.X + txtSize.CX, txtPt.Y + txtSize.CY);
DrawText(lCanvas.Handle, PChar(Caption), -1, R, flags);
// Draw focus rectangle
if FShowFocusRect and Focused then
begin
InflateRect(lRect, -2, -2);
DrawFocusRect(lCanvas.Handle, lRect);
end;
// Draw the button
FCanvas.Draw(0, 0, lBitmap);
lBitmap.Free;
end;
procedure TButtonEx.PaintThemedButton;
var
btn: TThemedButton;
details: TThemedElementDetails;
lRect: TRect;
flags: Cardinal;
txtSize: TSize;
txtPt: TPoint;
begin
if (csDestroying in ComponentState) or not HandleAllocated then
exit;
lRect := Rect(0, 0, Width, Height);
if FState = bxsDisabled then
btn := tbPushButtonDisabled
else if FState = bxsDown then
btn := tbPushButtonPressed
else if FState = bxsHot then
btn := tbPushButtonHot
else
if Focused or Default then
btn := tbPushButtonDefaulted
else
btn := tbPushButtonNormal;
// Background
details := ThemeServices.GetElementDetails(btn);
InflateRect(lRect, 1, 1);
ThemeServices.DrawElement(FCanvas.Handle, details, lRect);
InflateRect(lRect, -1, -1);
// Text
FCanvas.Font.Assign(Font);
flags := GetDrawTextFlags;
with ThemeServices.GetTextExtent(FCanvas.Handle, details, Caption, flags, @lRect) do begin
txtSize.CX := Right;
txtSize.CY := Bottom;
end;
case FAlignment of
taLeftJustify:
if IsRightToLeft then
txtPt.X := Width - txtSize.CX - FMargin
else
txtPt.X := FMargin;
taRightJustify:
if IsRightToLeft then
txtPt.X := FMargin
else
txtPt.X := Width - txtSize.CX - FMargin;
taCenter:
txtPt.X := (Width - txtSize.CX) div 2;
end;
txtPt.Y := (Height + 1 - txtSize.CY) div 2;
lRect := Rect(txtPt.X, txtPt.Y, txtPt.X + txtSize.CX, txtPt.Y + txtSize.CY);
ThemeServices.DrawText(FCanvas, details, Caption, lRect, flags, 0);
end;
procedure TButtonEx.SetAlignment(const Value: TAlignment);
begin
if FAlignment = Value then
exit;
FAlignment := Value;
Invalidate;
end;
procedure TButtonEx.SetDefaultDrawing(const Value: Boolean);
begin
if FDefaultDrawing = Value then
exit;
FDefaultDrawing := Value;
Invalidate;
end;
procedure TButtonEx.SetGradient(const Value: Boolean);
begin
if FGradient = Value then
exit;
FGradient := Value;
Invalidate;
end;
procedure TButtonEx.SetShowFocusRect(const Value: Boolean);
begin
if FShowFocusRect = Value then
exit;
FShowFocusRect := Value;
if Focused then Invalidate;
end;
procedure TButtonEx.SetMargin(const Value: integer);
begin
if FMargin = Value then
exit;
FMargin := Value;
Invalidate;
end;
procedure TButtonEx.SetWordWrap(const Value: Boolean);
begin
if FWordWrap = Value then
exit;
FWordWrap := Value;
Invalidate;
end;
procedure TButtonEx.WMKillFocus(var Message: TLMKillFocus);
begin
inherited WMKillFocus(Message);
if (FState = bxsFocused) then
begin
FState := bxsNormal;
Invalidate;
end;
end;
procedure TButtonEx.WMSetFocus(var Message: TLMSetFocus);
begin
inherited WMSetFocus(Message);
if (FState = bxsNormal) then
begin
FState := bxsFocused;
Invalidate;
end;
end;
procedure TButtonEx.WMPaint(var Msg: TLMPaint);
begin
inherited;
PaintButton;
end;
procedure TButtonEx.WndProc(var Message: TLMessage);
begin
if not (csDesigning in ComponentState) then
begin
case Message.Msg of
LM_KEYDOWN:
begin
if (Message.WParam = VK_RETURN) or (Message.WParam = VK_SPACE) then
if FState <> bxsDisabled then
FState := bxsDown;
Invalidate;
end;
LM_KEYUP:
begin
if (Message.WParam = VK_RETURN) or (Message.WParam = VK_SPACE) then
if FState <> bxsDisabled then
FState := bxsFocused;
Invalidate;
end;
CM_DIALOGKEY:
begin
if (Message.WParam = VK_RETURN) and Default and (not Focused) and (FState <> bxsDisabled) then
Click;
if (Message.WParam = VK_ESCAPE) and Cancel and (FState <> bxsDisabled) then
Click;
end;
CM_ENABLEDCHANGED:
begin
if not Enabled then
FState := bxsDisabled
else
FState := bxsNormal;
Invalidate;
end;
LM_LBUTTONDOWN:
begin
FState := bxsDown;
Invalidate;
end;
LM_LBUTTONUP:
begin
if (FState <> bxsNormal) and (FState <> bxsFocused) and (FState <> bxsDisabled) then
begin
FState := bxsHot;
Invalidate;
end;
end;
end;
end;
inherited;
end;
end.
|
unit WizMain;
interface
uses
SysUtils, ToolsApi;
type
EActionServices = class(Exception);
TActionServices = class(TNotifierObject, IOTAWizard, IOTAMenuWizard)
private
FIndex: Integer;
procedure SetIndex(const Value: Integer);
public
function GetIDString: string;
function GetName: string;
function GetState: TWizardState;
procedure Execute;
function GetMenuText: string;
property Index: Integer read FIndex write SetIndex;
end;
implementation
uses
FrmMain;
var
ActionServices: TActionServices;
resourcestring
sActionError = 'Error creating ActionServices wizard';
{ TActionServices }
procedure TActionServices.Execute;
begin
if Form2 = nil then
Form2 := TForm2.Create(nil);
Form2.Show;
end;
function TActionServices.GetIDString: string;
begin
Result := 'Borland.ActionServices.Demo.1'; { do not localize }
end;
function TActionServices.GetMenuText: string;
resourcestring
sMenuText = 'Test Action Services';
begin
Result := sMenuText;
end;
function TActionServices.GetName: string;
begin
Result := 'Borland.ActionServices.Demo'; { do not localize }
end;
function TActionServices.GetState: TWizardState;
begin
Result := [wsEnabled];
end;
procedure InitActionServices;
begin
if (BorlandIDEServices <> nil) then
begin
ActionServices := TActionServices.Create;
ActionServices.Index := (BorlandIDEServices as IOTAWizardServices).AddWizard(ActionServices as IOTAWizard);
if ActionServices.Index < 0 then
raise EActionServices.Create(sActionError);
end;
end;
procedure DoneActionServices;
begin
if (BorlandIDEServices <> nil) then
begin
if Form2 <> nil then
Form2.Free;
(BorlandIDEServices as IOTAWizardServices).RemoveWizard(ActionServices.Index);
end;
end;
procedure TActionServices.SetIndex(const Value: Integer);
begin
FIndex := Value;
end;
initialization
InitActionServices;
finalization
DoneActionServices;
end.
|
{$G+}
Unit String_s;
{
Strings library v1.1
by Maple Leaf, 1996
-------------------------------------------------------------------------
no comments ...
}
interface
Function IStr (n : LongInt) : String; { int->string }
Function RStr (n : Real) : String; { real->string }
Function IVal (s : String) : LongInt; { string->int }
Function RVal (s : String) : Real; { string->real }
{ Fast conversions }
Function Dec2Hex (n:longint) : String; { int->hex(string) }
Function Hex2Dec (s:string) : LongInt; { hex(string)->int }
Function Dec2Bin (n:longint) : String; { int->bin(string) }
Function Bin2Dec (s:string) : LongInt; { bin(string)->int }
{ basis conversions }
function UCase (txt : string) : string;
{ Returns the same text processing letters between 'a' and 'z' to 'A'..'Z' }
function DCase (txt : string) : string;
{ Complementary function of UCASE.Transform letters between 'A'-'Z' to 'a'-'z' }
function LTrim(s : String) : string;
function RTrim(s : String) : string;
function AllTrim(s : String) : string;
{ Functions which provide initial/final/intermediar Space-characters deletion }
function DCaseButFirst (txt : string) : string;
{ Like DCASE, except the first letter which is gonna be a big one }
function RightPos (str1,str2 : string) : byte;
{ Returns position of string STR1 in the string STR2, searching from the
right to the left position of the string }
function PosOfStr (str1,str2 : string; initpos:byte) : byte;
{ Returns the position of STR1 into STR2, starting search with INITPOS position }
function Space (n : byte) : string;
{ Returns a string of #32 , with length = n }
function Strng (n:byte; c:byte): string;
{ Returns a string which contains n characters with ASCII code C }
implementation
const HexDigit : string = '0123456789ABCDEF';
BinDigit : string = '01';
Function Dec2Hex (n:longint) : String; { int->hex(string) }
var s:string; nr:byte;
begin
s:=''; nr:=0;
repeat
s:=HexDigit[1+(n and $F)] + s;
n:=n shr 4; inc(nr);
until (n=0) or (n=$FFFFFFFF) or (nr>=8);
Dec2Hex:=s;
end;
Function Hex2Dec (s:string) : LongInt; { hex(string)->int }
var n:longint; nr:byte;
begin
if s='' then begin
Hex2Dec:=0;
exit
end;
while (s[1]='0') and (s[0]>#1) do delete(s,1,1);
s:=UCase(s);
n:=0; nr:=0;
repeat
inc(nr);
n:=(n shl 4) + longint((pos(s[nr],HexDigit) - 1));
until (nr>=8) or (nr>=length(s));
Hex2Dec:=n;
end;
Function Dec2Bin (n:longint) : String; { int->bin(string) }
var s:string; nr:byte;
begin
s:=''; nr:=0;
repeat
s:=BinDigit[1+(n and 1)] + s;
n:=n shr 1; inc(nr);
until (n=0) or (n=$FFFFFFFF) or (nr>=32);
Dec2Bin:=s;
end;
Function Bin2Dec (s:string) : LongInt; { bin(string)->int }
var n:longint; nr:byte;
begin
if s='' then begin
Bin2Dec:=0;
exit
end;
while (s[1]='0') and (s[0]>#1) do delete(s,1,1);
n:=0; nr:=0;
repeat
inc(nr);
n:=(n shl 1) + (pos(s[nr],BinDigit) - 1);
until (nr>=32) or (nr>=length(s));
Bin2Dec:=n;
end;
Function IStr(n:LongInt) : String;
var qs:string[20];
begin
str(n,qs); istr:=qs;
end;
Function IVal(s:String) : LongInt;
var n:longint; c:integer;
begin
val(s,n,c); if c<>0 then n:=0;
ival:=n;
end;
Function RStr(n:real) : String;
var qs:string[20];
begin
str(n:10:4,qs); rstr:=qs;
end;
Function RVal(s:String) : real;
var n:longint; c:integer;
begin
val(s,n,c); if c<>0 then n:=0;
rval:=n;
end;
function LTrim(s : String) : string;
begin
while (s[1]=' ') and (length(s)>0) do delete(s,1,1);
LTrim:=s;
end;
function RTrim(s : String) : string;
begin
while (s[Length(s)]=' ') and (length(s)>0) do delete(s,Length(s),1);
RTrim:=s;
end;
function AllTrim(s : String) : string;
var k:byte;
begin
k:=1;
while k<=length(s) do begin
if s[k]=#32 then delete(s,k,1) else inc(k);
end;
AllTrim:=s;
end;
function ucase;
var n:byte;
begin
if txt<>'' then for n:=1 to length(txt) do txt[n]:=upcase(txt[n]);
ucase:=txt;
end;
function dcase;
var n:byte;
begin
if txt<>'' then
for n:=1 to length(txt) do
if txt[n] in ['A'..'Z'] then txt[n]:=chr(ord(txt[n])+32);
dcase:=txt;
end;
function dcasebutfirst;
var n:byte;
begin
if txt<>'' then
for n:=1 to length(txt) do
if txt[n] in ['A'..'Z'] then txt[n]:=chr(ord(txt[n])+32);
n:=1;
while not(txt[n] in ['a'..'z']) and (n<=length(txt)) do inc(n);
txt[n]:=upcase(txt[n]);
dcasebutfirst:=txt;
end;
function rightpos;
var n,p:byte;
label _1;
begin
p:=0;
for n:=length(str2) downto 1 do
if pos(str1,copy(str2,n,length(str2)-n+1))<>0 then begin
p:=n-1+pos(str1,copy(str2,n,length(str2)-n+1));
goto _1;
end;
_1:
rightpos:=p;
end;
function PosOfStr;
var p:byte;
begin
p:=initpos-1+pos(str1,copy(str2,initpos,length(str2)-initpos+1));
if p=initpos-1 then p:=0;
PosOfStr:=p;
end;
function space;
var s:string;
begin
s:='';
while length(s)<n do s:=s+' ';
space:=s;
end;
function strng;
var s:string;
begin
s:='';
while length(s)<n do s:=s+chr(c);
strng:=s;
end;
begin
end.
|
unit CheckNetwork;
interface
uses wininet, windows;
function IsInternet : boolean;
function IsNetwork : boolean;
function InternetConnected: Boolean;
implementation
function IsInternet : boolean;
var
origin : cardinal;
begin
result := InternetGetConnectedState(@origin,0);
//connections origins by origin value
//NO INTERNET CONNECTION = 0;
//INTERNET_CONNECTION_MODEM = 1;
//INTERNET_CONNECTION_LAN = 2;
//INTERNET_CONNECTION_PROXY = 4;
//INTERNET_CONNECTION_MODEM_BUSY = 8;
end;
function IsNetwork : boolean;
var origin : cardinal;
begin
// result := InternetCheckConnection(@origin);
//connections origins by origin value
//NO INTERNET CONNECTION = 0;
//INTERNET_CONNECTION_MODEM = 1;
//INTERNET_CONNECTION_LAN = 2;
//INTERNET_CONNECTION_PROXY = 4;
//INTERNET_CONNECTION_MODEM_BUSY = 8;
end;
////网络是否连通
function InternetConnected: Boolean;
const
// local system uses a modem to connect to the Internet.
INTERNET_CONNECTION_MODEM = 1;
// local system uses a local area network to connect to the Internet.
INTERNET_CONNECTION_LAN = 2;
// local system uses a proxy server to connect to the Internet.
INTERNET_CONNECTION_PROXY = 4;
// local system's modem is busy with a non-Internet connection.
INTERNET_CONNECTION_MODEM_BUSY = 8;
var
dwConnectionTypes : DWORD;
begin
dwConnectionTypes := INTERNET_CONNECTION_MODEM+ INTERNET_CONNECTION_LAN
+ INTERNET_CONNECTION_PROXY;
Result := InternetGetConnectedState(@dwConnectionTypes, 0) ;
end;
end.
|
{
Ultibo Font Builder Tool.
Copyright (C) 2016 - SoftOz Pty Ltd.
Arch
====
<All>
Boards
======
<All>
Licence
=======
LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt)
Credits
=======
Information for this unit was obtained from:
References
==========
PC Screen Fonts (PSF) - https://en.wikipedia.org/wiki/PC_Screen_Font
A number of PSF format fonts in various stlyes and sizes are available from:
http://v3.sk/~lkundrak/fonts/kbd/
Note that this site also lists a number of other fonts in raw format (no header)
which contain the font character data in the same format as the PSF files but
cannot currently be converted by this tool.
http://v3.sk/~lkundrak/fonts/
Font Builder
============
The fonts supported by Ultibo are a bitmap format that contains a block of data
where each character is represented by a number of consecutive bytes.
Fonts can either be statically compiled as a pascal unit and loaded during startup
or can be dynamically loaded by passing a header and data block to the FontLoad()
function.
For an 8x16 (8 pixels wide and 16 pixels high) font the data contains 8 bits (1 byte)
for each of the 16 rows that make up a character and each character would be
16 bytes long.
For a 12x22 font the data contains 12 bits padded to 16 bits (2 bytes) for each of
the 22 rows that make up a character. Therefore each character would be 44 bytes
in length.
The font unit can support any size font from 8x6 to 32x64 including every combination
in between.
For fonts where the bits per row is greater than one byte both little endian and big
endian format is supported.
This tool currently supports converting PC Screen Fonts (PSF) into a pascal unit
suitable for including in an Ultibo project. Additional formats will be supported
in future.
}
unit DlgExport;
{$MODE Delphi}
interface
uses
LCLIntf, LCLType, LMessages, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TfrmExport = class(TForm)
lblFileName: TLabel;
saveMain: TSaveDialog;
txtFileName: TEdit;
cmdFileName: TButton;
chkIncludeUnicode: TCheckBox;
cmdCancel: TButton;
cmdExport: TButton;
lblName: TLabel;
txtName: TEdit;
lblDescription: TLabel;
txtDescription: TEdit;
lblUnitName: TLabel;
txtUnitName: TEdit;
procedure cmdFileNameClick(Sender: TObject);
procedure txtFileNameChange(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function CheckUnitName(const UnitName:String):Boolean;
function NormalizeUnitName(const UnitName:String):String;
function ShowExport(var Name,Description,UnitName,FileName:String;var IncludeUnicode:Boolean):Boolean;
end;
var
frmExport: TfrmExport;
implementation
{$R *.lfm}
{==============================================================================}
function TfrmExport.CheckUnitName(const UnitName:String):Boolean;
var
Count:Integer;
begin
{}
Result:=False;
if Length(UnitName) <> 0 then
begin
for Count:=1 to Length(UnitName) do
begin
if not(UnitName[Count] in ['a'..'z','A'..'Z','0'..'9','_','.']) then Exit;
end;
Result:=True;
end;
end;
{==============================================================================}
function TfrmExport.NormalizeUnitName(const UnitName:String):String;
var
Count:Integer;
begin
{}
Result:=UnitName;
if Length(Result) <> 0 then
begin
for Count:=1 to Length(Result) do
begin
if not(Result[Count] in ['a'..'z','A'..'Z','0'..'9','_','.']) then
begin
Result[Count]:='_';
end;
end;
end;
end;
{==============================================================================}
function TfrmExport.ShowExport(var Name,Description,UnitName,FileName:String;var IncludeUnicode:Boolean):Boolean;
begin
{}
Result:=False;
txtName.Text:=Name;
txtDescription.Text:=Description;
txtUnitName.Text:=UnitName;
txtFileName.Text:=FileName;
chkIncludeUnicode.Checked:=IncludeUnicode;
if ShowModal = mrOk then
begin
Name:=txtName.Text;
Description:=txtDescription.Text;
UnitName:=txtUnitName.Text;
FileName:=txtFileName.Text;
IncludeUnicode:=chkIncludeUnicode.Checked;
Result:=True;
end;
end;
{==============================================================================}
procedure TfrmExport.FormShow(Sender: TObject);
begin
{}
{Adjust Labels}
lblName.Top:=txtName.Top + ((txtName.Height - lblName.Height) div 2);
lblDescription.Top:=txtDescription.Top + ((txtDescription.Height - lblDescription.Height) div 2);
lblUnitName.Top:=txtUnitName.Top + ((txtUnitName.Height - lblUnitName.Height) div 2);
lblFileName.Top:=txtFileName.Top + ((txtFileName.Height - lblFileName.Height) div 2);
{Adjust Buttons}
if txtFileName.Height > cmdFileName.Height then
begin
cmdFileName.Height:=txtFileName.Height;
cmdFileName.Width:=txtFileName.Height;
cmdFileName.Top:=txtFileName.Top + ((txtFileName.Height - cmdFileName.Height) div 2);
end
else
begin
cmdFileName.Height:=txtFileName.Height + 2;
cmdFileName.Width:=txtFileName.Height + 2;
cmdFileName.Top:=txtFileName.Top - 1;
end;
if cmdFileName.Height > cmdExport.Height then
begin
cmdExport.Height:=cmdFileName.Height;
cmdCancel.Height:=cmdFileName.Height;
end;
{Check PixelsPerInch}
if PixelsPerInch > 96 then
begin
{Adjust Button}
{cmdFileName.Top:=txtFileName.Top;
cmdFileName.Height:=txtFileName.Height;
cmdFileName.Width:=cmdFileName.Height;}
end;
end;
{==============================================================================}
procedure TfrmExport.txtFileNameChange(Sender: TObject);
begin
{}
txtUnitName.Text:=ExtractFileName(ChangeFileExt(txtFileName.Text,''));
end;
{==============================================================================}
procedure TfrmExport.cmdFileNameClick(Sender: TObject);
begin
{}
saveMain.Title:='Export font';
{$IFDEF WINDOWS}
saveMain.Filter:='Pascal source files|*.pas||All files|*.*';
{$ENDIF}
{$IFDEF LINUX}
saveMain.Filter:='Pascal source files|*.pas||All files|*';
{$ENDIF}
saveMain.Filename:=txtFileName.Text;
if Length(saveMain.InitialDir) = 0 then
begin
saveMain.InitialDir:=ExtractFilePath(Application.ExeName);
end;
if saveMain.Execute then
begin
txtFileName.Text:=saveMain.FileName;
end;
end;
{==============================================================================}
{==============================================================================}
end.
|
unit FCRC32;
{32 Bit CRC, fast 4KB table version, polynomial (used in zip and others)}
interface
(*************************************************************************
DESCRIPTION : 32 Bit CRC
REQUIREMENTS : TP6/7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : [1] zlib 1.2.x CRC32 routines (http://www.gzip.org/zlib/)
[2] http://www.intel.com/technology/comms/perfnet/download/CRC_generators.pdf
REMARKS : - A note for FPC users: The current implementation is for
little-endian processors only! Users interested in
big-endian endian code should send an e-mail.
- intel papers ([2] and two others) from mid. 2005 do NOT
mention the zlib 'slicing by 4' routines from Oct/Nov 2003.
For a discussion see e.g. http://www.c10n.info/archives/383/
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 27.06.07 W.Ehrhardt Initial pure single Pascal version
0.11 27.06.07 we BIT16 version with local array[0..3] of byte
0.12 28.06.07 we BASM16 version
0.13 28.06.07 we Leading/trailing single byte processing
0.14 28.06.07 we BASM32 version
0.15 29.06.07 we BASM16: align helpers
0.16 30.06.07 we PByte/PLong local for TP5x
0.17 06.07.07 we {$ifdef ENDIAN_BIG}, remarks and references
0.18 07.07.07 we Bugfix BIT16 leading single byte processing
0.19 04.10.07 we FPC: {$asmmode intel}
0.20 06.09.08 we Fix for FPC222: dest for jecxz out of range
0.21 12.11.08 we uses BTypes, Ptr2Inc and/or Str255
0.22 19.07.09 we D12 fix: assign with typecast string(fname)
0.23 08.03.12 we {$ifndef BIT16} instead of {$ifdef WIN32}
0.24 26.12.12 we D17 and PurePascal
0.25 16.08.15 we Removed $ifdef DLL / stdcall
0.26 29.11.17 we FCRC32File - fname: string
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2007-2017 Wolfgang Ehrhardt
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.
----------------------------------------------------------------------------*)
{$i STD.INC}
{$ifdef BIT64}
{$ifndef PurePascal}
{$define PurePascal}
{$endif}
{$endif}
uses
BTypes;
procedure FCRC32Init(var CRC: longint);
{-initialize context}
procedure FCRC32Update(var CRC: longint; Msg: pointer; Len: word);
{-update CRC with Msg data}
procedure FCRC32Final(var CRC: longint);
{-CRC32 finalize calculation}
function FCRC32SelfTest: boolean;
{-Self test for FCRC32}
procedure FCRC32Full(var CRC: longint; Msg: pointer; Len: word);
{-CRC32 of Msg with init/update/final}
procedure FCRC32File({$ifdef CONST} const {$endif} fname: string;
var CRC: longint; var buf; bsize: word; var Err: word);
{-CRC32 of file, buf: buffer with at least bsize bytes}
{$ifndef BIT16}
procedure FCRC32UpdateXL(var CRC: longint; Msg: pointer; Len: longint);
{-update CRC with Msg data}
procedure FCRC32FullXL(var CRC: longint; Msg: pointer; Len: longint);
{-CRC32 of Msg with init/update/final}
{$endif}
implementation
const
Mask32 = longint($FFFFFFFF);
{$ifdef StrictLong}
{$warnings off}
{$R-} {avoid D9 errors!}
{$endif}
{$ifdef BASM16}
{$i ALIGN.INC}
{$endif}
const
{$ifdef BASM16}
{$ifdef A4_FCRC32}
AlignDummy_FCRC32: word = 0;
{$endif}
{$endif}
CTab0: array[0..255] of longint = (
$00000000,$77073096,$ee0e612c,$990951ba,$076dc419,$706af48f,$e963a535,$9e6495a3,
$0edb8832,$79dcb8a4,$e0d5e91e,$97d2d988,$09b64c2b,$7eb17cbd,$e7b82d07,$90bf1d91,
$1db71064,$6ab020f2,$f3b97148,$84be41de,$1adad47d,$6ddde4eb,$f4d4b551,$83d385c7,
$136c9856,$646ba8c0,$fd62f97a,$8a65c9ec,$14015c4f,$63066cd9,$fa0f3d63,$8d080df5,
$3b6e20c8,$4c69105e,$d56041e4,$a2677172,$3c03e4d1,$4b04d447,$d20d85fd,$a50ab56b,
$35b5a8fa,$42b2986c,$dbbbc9d6,$acbcf940,$32d86ce3,$45df5c75,$dcd60dcf,$abd13d59,
$26d930ac,$51de003a,$c8d75180,$bfd06116,$21b4f4b5,$56b3c423,$cfba9599,$b8bda50f,
$2802b89e,$5f058808,$c60cd9b2,$b10be924,$2f6f7c87,$58684c11,$c1611dab,$b6662d3d,
$76dc4190,$01db7106,$98d220bc,$efd5102a,$71b18589,$06b6b51f,$9fbfe4a5,$e8b8d433,
$7807c9a2,$0f00f934,$9609a88e,$e10e9818,$7f6a0dbb,$086d3d2d,$91646c97,$e6635c01,
$6b6b51f4,$1c6c6162,$856530d8,$f262004e,$6c0695ed,$1b01a57b,$8208f4c1,$f50fc457,
$65b0d9c6,$12b7e950,$8bbeb8ea,$fcb9887c,$62dd1ddf,$15da2d49,$8cd37cf3,$fbd44c65,
$4db26158,$3ab551ce,$a3bc0074,$d4bb30e2,$4adfa541,$3dd895d7,$a4d1c46d,$d3d6f4fb,
$4369e96a,$346ed9fc,$ad678846,$da60b8d0,$44042d73,$33031de5,$aa0a4c5f,$dd0d7cc9,
$5005713c,$270241aa,$be0b1010,$c90c2086,$5768b525,$206f85b3,$b966d409,$ce61e49f,
$5edef90e,$29d9c998,$b0d09822,$c7d7a8b4,$59b33d17,$2eb40d81,$b7bd5c3b,$c0ba6cad,
$edb88320,$9abfb3b6,$03b6e20c,$74b1d29a,$ead54739,$9dd277af,$04db2615,$73dc1683,
$e3630b12,$94643b84,$0d6d6a3e,$7a6a5aa8,$e40ecf0b,$9309ff9d,$0a00ae27,$7d079eb1,
$f00f9344,$8708a3d2,$1e01f268,$6906c2fe,$f762575d,$806567cb,$196c3671,$6e6b06e7,
$fed41b76,$89d32be0,$10da7a5a,$67dd4acc,$f9b9df6f,$8ebeeff9,$17b7be43,$60b08ed5,
$d6d6a3e8,$a1d1937e,$38d8c2c4,$4fdff252,$d1bb67f1,$a6bc5767,$3fb506dd,$48b2364b,
$d80d2bda,$af0a1b4c,$36034af6,$41047a60,$df60efc3,$a867df55,$316e8eef,$4669be79,
$cb61b38c,$bc66831a,$256fd2a0,$5268e236,$cc0c7795,$bb0b4703,$220216b9,$5505262f,
$c5ba3bbe,$b2bd0b28,$2bb45a92,$5cb36a04,$c2d7ffa7,$b5d0cf31,$2cd99e8b,$5bdeae1d,
$9b64c2b0,$ec63f226,$756aa39c,$026d930a,$9c0906a9,$eb0e363f,$72076785,$05005713,
$95bf4a82,$e2b87a14,$7bb12bae,$0cb61b38,$92d28e9b,$e5d5be0d,$7cdcefb7,$0bdbdf21,
$86d3d2d4,$f1d4e242,$68ddb3f8,$1fda836e,$81be16cd,$f6b9265b,$6fb077e1,$18b74777,
$88085ae6,$ff0f6a70,$66063bca,$11010b5c,$8f659eff,$f862ae69,$616bffd3,$166ccf45,
$a00ae278,$d70dd2ee,$4e048354,$3903b3c2,$a7672661,$d06016f7,$4969474d,$3e6e77db,
$aed16a4a,$d9d65adc,$40df0b66,$37d83bf0,$a9bcae53,$debb9ec5,$47b2cf7f,$30b5ffe9,
$bdbdf21c,$cabac28a,$53b39330,$24b4a3a6,$bad03605,$cdd70693,$54de5729,$23d967bf,
$b3667a2e,$c4614ab8,$5d681b02,$2a6f2b94,$b40bbe37,$c30c8ea1,$5a05df1b,$2d02ef8d);
CTab1: array[0..255] of longint = (
$00000000,$191b3141,$32366282,$2b2d53c3,$646cc504,$7d77f445,$565aa786,$4f4196c7,
$c8d98a08,$d1c2bb49,$faefe88a,$e3f4d9cb,$acb54f0c,$b5ae7e4d,$9e832d8e,$87981ccf,
$4ac21251,$53d92310,$78f470d3,$61ef4192,$2eaed755,$37b5e614,$1c98b5d7,$05838496,
$821b9859,$9b00a918,$b02dfadb,$a936cb9a,$e6775d5d,$ff6c6c1c,$d4413fdf,$cd5a0e9e,
$958424a2,$8c9f15e3,$a7b24620,$bea97761,$f1e8e1a6,$e8f3d0e7,$c3de8324,$dac5b265,
$5d5daeaa,$44469feb,$6f6bcc28,$7670fd69,$39316bae,$202a5aef,$0b07092c,$121c386d,
$df4636f3,$c65d07b2,$ed705471,$f46b6530,$bb2af3f7,$a231c2b6,$891c9175,$9007a034,
$179fbcfb,$0e848dba,$25a9de79,$3cb2ef38,$73f379ff,$6ae848be,$41c51b7d,$58de2a3c,
$f0794f05,$e9627e44,$c24f2d87,$db541cc6,$94158a01,$8d0ebb40,$a623e883,$bf38d9c2,
$38a0c50d,$21bbf44c,$0a96a78f,$138d96ce,$5ccc0009,$45d73148,$6efa628b,$77e153ca,
$babb5d54,$a3a06c15,$888d3fd6,$91960e97,$ded79850,$c7cca911,$ece1fad2,$f5facb93,
$7262d75c,$6b79e61d,$4054b5de,$594f849f,$160e1258,$0f152319,$243870da,$3d23419b,
$65fd6ba7,$7ce65ae6,$57cb0925,$4ed03864,$0191aea3,$188a9fe2,$33a7cc21,$2abcfd60,
$ad24e1af,$b43fd0ee,$9f12832d,$8609b26c,$c94824ab,$d05315ea,$fb7e4629,$e2657768,
$2f3f79f6,$362448b7,$1d091b74,$04122a35,$4b53bcf2,$52488db3,$7965de70,$607eef31,
$e7e6f3fe,$fefdc2bf,$d5d0917c,$cccba03d,$838a36fa,$9a9107bb,$b1bc5478,$a8a76539,
$3b83984b,$2298a90a,$09b5fac9,$10aecb88,$5fef5d4f,$46f46c0e,$6dd93fcd,$74c20e8c,
$f35a1243,$ea412302,$c16c70c1,$d8774180,$9736d747,$8e2de606,$a500b5c5,$bc1b8484,
$71418a1a,$685abb5b,$4377e898,$5a6cd9d9,$152d4f1e,$0c367e5f,$271b2d9c,$3e001cdd,
$b9980012,$a0833153,$8bae6290,$92b553d1,$ddf4c516,$c4eff457,$efc2a794,$f6d996d5,
$ae07bce9,$b71c8da8,$9c31de6b,$852aef2a,$ca6b79ed,$d37048ac,$f85d1b6f,$e1462a2e,
$66de36e1,$7fc507a0,$54e85463,$4df36522,$02b2f3e5,$1ba9c2a4,$30849167,$299fa026,
$e4c5aeb8,$fdde9ff9,$d6f3cc3a,$cfe8fd7b,$80a96bbc,$99b25afd,$b29f093e,$ab84387f,
$2c1c24b0,$350715f1,$1e2a4632,$07317773,$4870e1b4,$516bd0f5,$7a468336,$635db277,
$cbfad74e,$d2e1e60f,$f9ccb5cc,$e0d7848d,$af96124a,$b68d230b,$9da070c8,$84bb4189,
$03235d46,$1a386c07,$31153fc4,$280e0e85,$674f9842,$7e54a903,$5579fac0,$4c62cb81,
$8138c51f,$9823f45e,$b30ea79d,$aa1596dc,$e554001b,$fc4f315a,$d7626299,$ce7953d8,
$49e14f17,$50fa7e56,$7bd72d95,$62cc1cd4,$2d8d8a13,$3496bb52,$1fbbe891,$06a0d9d0,
$5e7ef3ec,$4765c2ad,$6c48916e,$7553a02f,$3a1236e8,$230907a9,$0824546a,$113f652b,
$96a779e4,$8fbc48a5,$a4911b66,$bd8a2a27,$f2cbbce0,$ebd08da1,$c0fdde62,$d9e6ef23,
$14bce1bd,$0da7d0fc,$268a833f,$3f91b27e,$70d024b9,$69cb15f8,$42e6463b,$5bfd777a,
$dc656bb5,$c57e5af4,$ee530937,$f7483876,$b809aeb1,$a1129ff0,$8a3fcc33,$9324fd72);
CTab2: array[0..255] of longint = (
$00000000,$01c26a37,$0384d46e,$0246be59,$0709a8dc,$06cbc2eb,$048d7cb2,$054f1685,
$0e1351b8,$0fd13b8f,$0d9785d6,$0c55efe1,$091af964,$08d89353,$0a9e2d0a,$0b5c473d,
$1c26a370,$1de4c947,$1fa2771e,$1e601d29,$1b2f0bac,$1aed619b,$18abdfc2,$1969b5f5,
$1235f2c8,$13f798ff,$11b126a6,$10734c91,$153c5a14,$14fe3023,$16b88e7a,$177ae44d,
$384d46e0,$398f2cd7,$3bc9928e,$3a0bf8b9,$3f44ee3c,$3e86840b,$3cc03a52,$3d025065,
$365e1758,$379c7d6f,$35dac336,$3418a901,$3157bf84,$3095d5b3,$32d36bea,$331101dd,
$246be590,$25a98fa7,$27ef31fe,$262d5bc9,$23624d4c,$22a0277b,$20e69922,$2124f315,
$2a78b428,$2bbade1f,$29fc6046,$283e0a71,$2d711cf4,$2cb376c3,$2ef5c89a,$2f37a2ad,
$709a8dc0,$7158e7f7,$731e59ae,$72dc3399,$7793251c,$76514f2b,$7417f172,$75d59b45,
$7e89dc78,$7f4bb64f,$7d0d0816,$7ccf6221,$798074a4,$78421e93,$7a04a0ca,$7bc6cafd,
$6cbc2eb0,$6d7e4487,$6f38fade,$6efa90e9,$6bb5866c,$6a77ec5b,$68315202,$69f33835,
$62af7f08,$636d153f,$612bab66,$60e9c151,$65a6d7d4,$6464bde3,$662203ba,$67e0698d,
$48d7cb20,$4915a117,$4b531f4e,$4a917579,$4fde63fc,$4e1c09cb,$4c5ab792,$4d98dda5,
$46c49a98,$4706f0af,$45404ef6,$448224c1,$41cd3244,$400f5873,$4249e62a,$438b8c1d,
$54f16850,$55330267,$5775bc3e,$56b7d609,$53f8c08c,$523aaabb,$507c14e2,$51be7ed5,
$5ae239e8,$5b2053df,$5966ed86,$58a487b1,$5deb9134,$5c29fb03,$5e6f455a,$5fad2f6d,
$e1351b80,$e0f771b7,$e2b1cfee,$e373a5d9,$e63cb35c,$e7fed96b,$e5b86732,$e47a0d05,
$ef264a38,$eee4200f,$eca29e56,$ed60f461,$e82fe2e4,$e9ed88d3,$ebab368a,$ea695cbd,
$fd13b8f0,$fcd1d2c7,$fe976c9e,$ff5506a9,$fa1a102c,$fbd87a1b,$f99ec442,$f85cae75,
$f300e948,$f2c2837f,$f0843d26,$f1465711,$f4094194,$f5cb2ba3,$f78d95fa,$f64fffcd,
$d9785d60,$d8ba3757,$dafc890e,$db3ee339,$de71f5bc,$dfb39f8b,$ddf521d2,$dc374be5,
$d76b0cd8,$d6a966ef,$d4efd8b6,$d52db281,$d062a404,$d1a0ce33,$d3e6706a,$d2241a5d,
$c55efe10,$c49c9427,$c6da2a7e,$c7184049,$c25756cc,$c3953cfb,$c1d382a2,$c011e895,
$cb4dafa8,$ca8fc59f,$c8c97bc6,$c90b11f1,$cc440774,$cd866d43,$cfc0d31a,$ce02b92d,
$91af9640,$906dfc77,$922b422e,$93e92819,$96a63e9c,$976454ab,$9522eaf2,$94e080c5,
$9fbcc7f8,$9e7eadcf,$9c381396,$9dfa79a1,$98b56f24,$99770513,$9b31bb4a,$9af3d17d,
$8d893530,$8c4b5f07,$8e0de15e,$8fcf8b69,$8a809dec,$8b42f7db,$89044982,$88c623b5,
$839a6488,$82580ebf,$801eb0e6,$81dcdad1,$8493cc54,$8551a663,$8717183a,$86d5720d,
$a9e2d0a0,$a820ba97,$aa6604ce,$aba46ef9,$aeeb787c,$af29124b,$ad6fac12,$acadc625,
$a7f18118,$a633eb2f,$a4755576,$a5b73f41,$a0f829c4,$a13a43f3,$a37cfdaa,$a2be979d,
$b5c473d0,$b40619e7,$b640a7be,$b782cd89,$b2cddb0c,$b30fb13b,$b1490f62,$b08b6555,
$bbd72268,$ba15485f,$b853f606,$b9919c31,$bcde8ab4,$bd1ce083,$bf5a5eda,$be9834ed);
CTab3: array[0..255] of longint = (
$00000000,$b8bc6765,$aa09c88b,$12b5afee,$8f629757,$37def032,$256b5fdc,$9dd738b9,
$c5b428ef,$7d084f8a,$6fbde064,$d7018701,$4ad6bfb8,$f26ad8dd,$e0df7733,$58631056,
$5019579f,$e8a530fa,$fa109f14,$42acf871,$df7bc0c8,$67c7a7ad,$75720843,$cdce6f26,
$95ad7f70,$2d111815,$3fa4b7fb,$8718d09e,$1acfe827,$a2738f42,$b0c620ac,$087a47c9,
$a032af3e,$188ec85b,$0a3b67b5,$b28700d0,$2f503869,$97ec5f0c,$8559f0e2,$3de59787,
$658687d1,$dd3ae0b4,$cf8f4f5a,$7733283f,$eae41086,$525877e3,$40edd80d,$f851bf68,
$f02bf8a1,$48979fc4,$5a22302a,$e29e574f,$7f496ff6,$c7f50893,$d540a77d,$6dfcc018,
$359fd04e,$8d23b72b,$9f9618c5,$272a7fa0,$bafd4719,$0241207c,$10f48f92,$a848e8f7,
$9b14583d,$23a83f58,$311d90b6,$89a1f7d3,$1476cf6a,$accaa80f,$be7f07e1,$06c36084,
$5ea070d2,$e61c17b7,$f4a9b859,$4c15df3c,$d1c2e785,$697e80e0,$7bcb2f0e,$c377486b,
$cb0d0fa2,$73b168c7,$6104c729,$d9b8a04c,$446f98f5,$fcd3ff90,$ee66507e,$56da371b,
$0eb9274d,$b6054028,$a4b0efc6,$1c0c88a3,$81dbb01a,$3967d77f,$2bd27891,$936e1ff4,
$3b26f703,$839a9066,$912f3f88,$299358ed,$b4446054,$0cf80731,$1e4da8df,$a6f1cfba,
$fe92dfec,$462eb889,$549b1767,$ec277002,$71f048bb,$c94c2fde,$dbf98030,$6345e755,
$6b3fa09c,$d383c7f9,$c1366817,$798a0f72,$e45d37cb,$5ce150ae,$4e54ff40,$f6e89825,
$ae8b8873,$1637ef16,$048240f8,$bc3e279d,$21e91f24,$99557841,$8be0d7af,$335cb0ca,
$ed59b63b,$55e5d15e,$47507eb0,$ffec19d5,$623b216c,$da874609,$c832e9e7,$708e8e82,
$28ed9ed4,$9051f9b1,$82e4565f,$3a58313a,$a78f0983,$1f336ee6,$0d86c108,$b53aa66d,
$bd40e1a4,$05fc86c1,$1749292f,$aff54e4a,$322276f3,$8a9e1196,$982bbe78,$2097d91d,
$78f4c94b,$c048ae2e,$d2fd01c0,$6a4166a5,$f7965e1c,$4f2a3979,$5d9f9697,$e523f1f2,
$4d6b1905,$f5d77e60,$e762d18e,$5fdeb6eb,$c2098e52,$7ab5e937,$680046d9,$d0bc21bc,
$88df31ea,$3063568f,$22d6f961,$9a6a9e04,$07bda6bd,$bf01c1d8,$adb46e36,$15080953,
$1d724e9a,$a5ce29ff,$b77b8611,$0fc7e174,$9210d9cd,$2aacbea8,$38191146,$80a57623,
$d8c66675,$607a0110,$72cfaefe,$ca73c99b,$57a4f122,$ef189647,$fdad39a9,$45115ecc,
$764dee06,$cef18963,$dc44268d,$64f841e8,$f92f7951,$41931e34,$5326b1da,$eb9ad6bf,
$b3f9c6e9,$0b45a18c,$19f00e62,$a14c6907,$3c9b51be,$842736db,$96929935,$2e2efe50,
$2654b999,$9ee8defc,$8c5d7112,$34e11677,$a9362ece,$118a49ab,$033fe645,$bb838120,
$e3e09176,$5b5cf613,$49e959fd,$f1553e98,$6c820621,$d43e6144,$c68bceaa,$7e37a9cf,
$d67f4138,$6ec3265d,$7c7689b3,$c4caeed6,$591dd66f,$e1a1b10a,$f3141ee4,$4ba87981,
$13cb69d7,$ab770eb2,$b9c2a15c,$017ec639,$9ca9fe80,$241599e5,$36a0360b,$8e1c516e,
$866616a7,$3eda71c2,$2c6fde2c,$94d3b949,$090481f0,$b1b8e695,$a30d497b,$1bb12e1e,
$43d23e48,$fb6e592d,$e9dbf6c3,$516791a6,$ccb0a91f,$740cce7a,$66b96194,$de0506f1);
{$ifdef StrictLong}
{$warnings on}
{$ifdef RangeChecks_on}
{$R+}
{$endif}
{$endif}
{$ifdef ENDIAN_BIG}
const
CTab0 = 'Little-endian only, see Remark';
{$endif}
{$ifndef BIT16}
(**** 32+ Bit Delphi2+/FPC/VP *****)
{$ifdef PurePascal}
{---------------------------------------------------------------------------}
procedure FCRC32UpdateXL(var CRC: longint; Msg: pointer; Len: longint);
{-update CRC with Msg data}
var
i,t: longint;
ta: packed array[0..3] of byte absolute t;
begin
{Process bytewise until Msg is on dword boundary}
while (Len>0) and (__P2I(Msg) and 3 <> 0) do begin
CRC := CTab0[byte(CRC) xor pByte(Msg)^] xor (CRC shr 8);
inc(Ptr2Inc(Msg));
dec(Len);
end;
{Process remaining complete dwords}
while Len>3 do begin
t := CRC xor pLongint(Msg)^;
inc(Ptr2Inc(Msg),4);
dec(Len,4);
CRC := CTab3[ta[0]] xor CTab2[ta[1]] xor CTab1[ta[2]] xor CTab0[ta[3]];
end;
{Process remaining bytes}
for i:=1 to Len do begin
CRC := CTab0[byte(CRC) xor pByte(Msg)^] xor (CRC shr 8);
inc(Ptr2Inc(Msg));
end;
end;
{$else}
{---------------------------------------------------------------------------}
procedure FCRC32UpdateXL(var CRC: longint; Msg: pointer; Len: longint);
{-update CRC with Msg data}
begin
asm
push ebx
push edi
mov ecx,[Len]
mov eax,[CRC]
mov eax,[eax]
mov edi,[Msg]
or ecx,ecx {Fix for FPC222: dest for jecxz out of range}
jnz @@1
jmp @@9
{Process bytewise until edi Msg pointer is on dword boundary}
@@1: test edi,3
jz @@2
movzx ebx,byte ptr [edi]
inc edi
xor bl,al
shr eax,8
xor eax,dword ptr CTab0[ebx*4]
dec ecx
jnz @@1
@@2: cmp ecx,3
jbe @@4
{Process remaining complete dwords}
{Save old ecx and let new ecx count dwords}
push ecx
shr ecx,2
@@3: mov edx,[edi]
xor edx,eax
add edi,4
movzx ebx,dl
mov eax,dword ptr CTab3[ebx*4]
shr edx,8
movzx ebx,dl
xor eax,dword ptr CTab2[ebx*4]
shr edx,8
movzx ebx,dl
xor eax,dword ptr CTab1[ebx*4]
shr edx,8
movzx ebx,dl
xor eax,dword ptr CTab0[ebx*4]
dec ecx
jnz @@3
{Get number of remaing bytes}
pop ecx
and ecx,3
{Process remaining bytes}
@@4: jecxz @@6
@@5: movzx ebx,byte ptr [edi]
inc edi
xor bl,al
shr eax,8
xor eax,dword ptr CTab0[ebx*4]
dec ecx
jnz @@5
{Store result CRC and restore registers}
@@6: mov edx,[CRC]
mov [edx],eax
@@9: pop edi
pop ebx
end;
end;
{$endif}
{---------------------------------------------------------------------------}
procedure FCRC32Update(var CRC: longint; Msg: pointer; Len: word);
{-update CRC with Msg data}
begin
FCRC32UpdateXL(CRC, Msg, Len);
end;
{$else}
(**** TP5-7/Delphi1 for 386+ *****)
{$ifndef BASM16}
{---------------------------------------------------------------------------}
procedure FCRC32Update(var CRC: longint; Msg: pointer; Len: word);
{-update CRC with Msg data}
var
i: word;
t: longint;
ta: packed array[0..3] of byte absolute t;
begin
{Process bytewise until Msg is on dword boundary}
while (Len>0) and (longint(Msg) and 3 <> 0) do begin
CRC := CTab0[byte(CRC) xor pByte(Msg)^] xor (CRC shr 8);
inc(Ptr2Inc(Msg));
dec(Len);
end;
{Process remaining complete dwords}
while Len>3 do begin
t := CRC xor pLongint(Msg)^;
inc(Ptr2Inc(Msg),4);
dec(Len,4);
CRC := CTab3[ta[0]] xor CTab2[ta[1]] xor CTab1[ta[2]] xor CTab0[ta[3]];
end;
{Process remaining bytes}
for i:=1 to Len do begin
CRC := CTab0[byte(CRC) xor pByte(Msg)^] xor (CRC shr 8);
inc(Ptr2Inc(Msg));
end;
end;
{$else}
{---------------------------------------------------------------------------}
procedure FCRC32Update(var CRC: longint; Msg: pointer; Len: word); assembler;
{-update CRC with Msg data}
asm
{ax: crc; bx,si: addr; cx: Len; di: Msg; dx: temp}
mov cx,[len]
les si,[CRC]
db $66; mov ax,es:[si]
db $66; sub bx,bx {clear ebx}
les di,[Msg]
or cx,cx
jnz @@1
jmp @@9
{Process bytewise until Msg is on dword boundary}
@@1: test di,3
jz @@2
db $66; mov dx,ax
xor dx,es:[di]
inc di
mov bl,dl
db $66; shr ax,8
db $66,$67,$8D,$34,$5B;
db $66; xor ax,word ptr CTab0[bx+si]
dec cx
jnz @@1
{Process remaining complete dwords}
@@2: cmp cx,3
jbe @@3
push cx
shr cx,2
@@l:
db $66; mov dx,es:[di]
db $66; xor dx,ax
add di,4
mov bl,dl
db $66,$67,$8D,$34,$5B;
db $66; mov ax,word ptr CTab3[bx+si]
mov bl,dh
db $66; shr dx,16
db $66,$67,$8D,$34,$5B;
db $66; xor ax,word ptr CTab2[bx+si]
mov bl,dl
db $66,$67,$8D,$34,$5B;
db $66; xor ax,word ptr CTab1[bx+si]
mov bl,dh
db $66,$67,$8D,$34,$5B;
db $66; xor ax,word ptr CTab0[bx+si]
dec cx
jnz @@l
pop cx
and cx,3
{Process remaining bytes}
@@3: jcxz @@5
@@4:
db $66; mov dx,ax
xor dx,es:[di]
inc di
mov bl,dl
db $66; shr ax,8
db $66,$67,$8D,$34,$5B;
db $66; xor ax,word ptr CTab0[bx+si]
dec cx
jnz @@4
@@5: les si,CRC
db $66; mov es:[si],ax
@@9:
end;
{$endif BASM16}
{$endif BIT16}
{$ifndef BIT16}
{---------------------------------------------------------------------------}
procedure FCRC32FullXL(var CRC: longint; Msg: pointer; Len: longint);
{-CRC32 of Msg with init/update/final}
begin
FCRC32Init(CRC);
FCRC32UpdateXL(CRC, Msg, Len);
FCRC32Final(CRC);
end;
{$endif}
{---------------------------------------------------------------------------}
procedure FCRC32Init(var CRC: longint);
{-CRC initialization}
begin
CRC := Mask32;
end;
{---------------------------------------------------------------------------}
procedure FCRC32Final(var CRC: longint);
{-CRC32: finalize calculation}
begin
CRC := CRC xor Mask32;
end;
{---------------------------------------------------------------------------}
procedure FCRC32Full(var CRC: longint; Msg: pointer; Len: word);
{-CRC32 of Msg with init/update/final}
begin
FCRC32Init(CRC);
FCRC32Update(CRC, Msg, Len);
FCRC32Final(CRC);
end;
{---------------------------------------------------------------------------}
function FCRC32SelfTest: boolean;
{-self test for FCRC32}
const
s: string[17] = '0123456789abcdefg';
Check = longint($BE6CBE90);
var
i: integer;
CRC, CRCF: longint;
begin
FCRC32Full(CRCF, @s[1], length(s));
FCRC32Init(CRC);
for i:=1 to length(s) do FCRC32Update(CRC, @s[i], 1);
FCRC32Final(CRC);
FCRC32SelfTest := (CRC=Check) and (CRCF=Check);
end;
{$i-} {Force I-}
{---------------------------------------------------------------------------}
procedure FCRC32File({$ifdef CONST} const {$endif} fname: string;
var CRC: longint; var buf; bsize: word; var Err: word);
{-CRC32 of file, buf: buffer with at least bsize bytes}
var
{$ifdef VirtualPascal}
fms: word;
{$else}
fms: byte;
{$endif}
{$ifndef BIT16}
L: longint;
{$else}
L: word;
{$endif}
f: file;
begin
fms := FileMode;
{$ifdef VirtualPascal}
FileMode := $40; {open_access_ReadOnly or open_share_DenyNone;}
{$else}
FileMode := 0;
{$endif}
system.assign(f,{$ifdef D12Plus} string {$endif} (fname));
system.reset(f,1);
Err := IOResult;
FileMode := fms;
if Err<>0 then exit;
FCRC32Init(CRC);
L := bsize;
while (Err=0) and (L=bsize) do begin
system.blockread(f,buf,bsize,L);
Err := IOResult;
{$ifndef BIT16}
FCRC32UpdateXL(CRC, @buf, L);
{$else}
FCRC32Update(CRC, @buf, L);
{$endif}
end;
system.close(f);
if IOResult=0 then;
FCRC32Final(CRC);
end;
{$ifdef DumpAlign}
begin
writeln('Align FCRC32: ',ofs(CTab0) and 3:2, ofs(CTab1) and 3:2, ofs(CTab2) and 3:2, ofs(CTab3) and 3:2);
{$endif}
end.
|
unit TestDelphiNetConst;
{
AFS May 2005
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
Basic test of class constants in Delphi.NET
}
interface
type
TTemperatureConverter = class(TObject)
public
const AbsoluteZero = -273;
end;
type
TMyClass = class
const
x = 12;
y = TMyClass.x + 23;
procedure Hello;
private
const
s = 'A string constant';
end;
TTestConstFirst = class(TObject)
const SOME_CONST = 1;
private
testInt: Int32;
end;
TTestConstFirst2 = class(TObject)
const
SOME_CONST = 1;
OTHER_CONST = 2;
private
testInt: Int32;
end;
implementation
{ TMyClass }
procedure TMyClass.Hello;
begin
end;
end.
|
unit MapObject;
{$MODE Delphi}
INTERFACE
USES LCLIntf, LCLType, LMessages, Graphics, Classes, Map, LinkedList;
TYPE TMapObjectType = (OBJECT_FOOD, OBJECT_POWERUP, OBJECT_PACMAN, OBJECT_GHOST);
TYPE TMapObject = CLASS
PUBLIC
CONSTRUCTOR create(_x, _y, _w, _h : INTEGER); OVERLOAD;
FUNCTION getLeft() : INTEGER;
FUNCTION getTop() : INTEGER;
FUNCTION getRight() : INTEGER;
FUNCTION getBottom() : INTEGER;
FUNCTION getWidth() : INTEGER;
FUNCTION getHeight() : INTEGER;
FUNCTION getCenterX() : INTEGER;
FUNCTION getCenterY() : INTEGER;
FUNCTION collides(other : TMapObject) : BOOLEAN;
FUNCTION getType() : TMapObjectType; VIRTUAL; ABSTRACT;
PROCEDURE onCollide(other : TMapObject; objects : TLinkedList); VIRTUAL; ABSTRACT;
PROCEDURE move(map : TMap; objects : TLinkedList); VIRTUAL; ABSTRACT;
PROCEDURE draw(canvas : TCanvas); VIRTUAL; ABSTRACT;
FUNCTION blocksMovement(tile : TTile) : BOOLEAN; OVERLOAD; VIRTUAL;
FUNCTION blocksMovement(other : TMapObject) : BOOLEAN; OVERLOAD; VIRTUAL;
PROTECTED
x,y,w,h : INTEGER;
END;
TYPE TMobileObject = CLASS(TMapObject)
PUBLIC
CONSTRUCTOR create(_x, _y, _w, _h, _speed, _direction : INTEGER);
PROCEDURE setDirection(dir : INTEGER);
FUNCTION getDirectionX(dir : INTEGER) : INTEGER;
FUNCTION getDirectionY(dir : INTEGER) : INTEGER;
FUNCTION getDirection() : INTEGER;
FUNCTION canMove(newx, newy : INTEGER; map : TMap) : BOOLEAN;
PROCEDURE move(map : TMap; objects : TLinkedList); OVERRIDE;
PROTECTED
speed : INTEGER;
direction : INTEGER;
END;
PROCEDURE loadSpriteSheet(bmp : TBitmap; x1,y1,x2,y2, xt, yt : INTEGER; VAR arr : ARRAY OF TBitmap);
IMPLEMENTATION
CONSTRUCTOR TMapObject.create(_x, _y, _w, _h : INTEGER);
BEGIN
w := _w;
h := _h;
x := _x - w DIV 2;
y := _y - h DIV 2;
END;
FUNCTION TMapObject.getLeft() : INTEGER;
BEGIN
getLeft := x;
END;
FUNCTION TMapObject.getTop() : INTEGER;
BEGIN
getTop := y;
END;
FUNCTION TMapObject.getRight() : INTEGER;
BEGIN
getRight := x + w;
END;
FUNCTION TMapObject.getBottom() : INTEGER;
BEGIN
getBottom := y + h;
END;
FUNCTION TMapObject.getWidth() : INTEGER;
BEGIN
getWidth := w;
END;
FUNCTION TMapObject.getHeight() : INTEGER;
BEGIN
getHeight := h;
END;
FUNCTION TMapObject.getCenterX() : INTEGER;
BEGIN
getCenterX := x + w DIV 2;
END;
FUNCTION TMapObject.getCenterY() : INTEGER;
BEGIN
getCenterY := y + h DIV 2;
END;
FUNCTION TMapObject.blocksMovement(tile : TTile) : BOOLEAN;
BEGIN
blocksMovement := (tile <> 0);
END;
FUNCTION TMapObject.blocksMovement(other : TMapObject) : BOOLEAN;
BEGIN
blocksMovement := FALSE;
END;
FUNCTION TMapObject.collides(other : TMapObject) : BOOLEAN;
BEGIN
collides := NOT (
(getLeft() > other.getRight()) OR
(getRight() < other.getLeft()) OR
(getTop() > other.getBottom()) OR
(getBottom() < other.getTop())
);
END;
CONSTRUCTOR TMobileObject.create(_x, _y, _w, _h, _speed, _direction : INTEGER);
BEGIN
INHERiTED create(_x, _y, _w, _h);
speed := _speed;
direction := _direction;
END;
PROCEDURE TMobileObject.setDirection(dir : INTEGER);
BEGIN
direction := dir;
END;
FUNCTION TMobileObject.getDirectionX(dir : INTEGER) : INTEGER;
BEGIN
IF dir = 2 THEN
getDirectionX := 1
ELSE IF dir = 4
THEN getDirectionX := -1
ELSE
getDirectionX := 0;
END;
FUNCTION TMobileObject.getDirectionY(dir : INTEGER) : INTEGER;
BEGIN
IF dir = 1 THEN
getDirectionY := -1
ELSE IF dir = 3 THEN
getDirectionY := 1
ELSE
getDirectionY := 0;
END;
FUNCTION TMobileObject.getDirection() : INTEGER;
BEGIN
getDirection := direction;
END;
FUNCTION TMobileObject.canMove(newx, newy : INTEGER; map : TMap) : BOOLEAN;
VAR tx, ty : INTEGER;
BEGIN
canMove := TRUE;
FOR tx := 0 TO (getWidth()-1) DIV TILE_SIZE DO
FOR ty := 0 TO (getHeight()-1) DIV TILE_SIZE DO
IF blocksMovement(map.getPixel(newx + tx*TILE_SIZE, newy + ty*TILE_SIZE)) THEN
canMove := FALSE;
FOR tx := 0 TO (getWidth()-1) DIV TILE_SIZE DO
IF blocksMovement(map.getPixel(newx + tx*TILE_SIZE, newy+h-1)) THEN
canMove := FALSE;
FOR ty := 0 TO (getHeight()-1) DIV TILE_SIZE DO
IF blocksMovement(map.getPixel(newx+w-1, newy+ty*TILE_SIZE)) THEN
canMove := FALSE;
IF blocksMovement(map.getPixel(newx + w - 1, newy + h - 1)) THEN
canMove := FALSE;
END;
PROCEDURE TMobileObject.move(map : TMap; objects : TLinkedList);
VAR newx, newy : INTEGER;
VAR ptr, next : TLinkedNode;
BEGIN
newx := x + getDirectionX(direction);
newy := y + getDirectionY(direction);
IF canMove(newx, newy, map) THEN
BEGIN
IF newx >= map.getWidth()*TILE_SIZE THEN newx := -w+1;
IF newx <= -w THEN newx := map.getWidth()*TILE_SIZE-1;
IF newy >= map.getHeight()*TILE_SIZE THEN newy := -h+1;
IF newy <= -h THEN newy := map.getHeight()*TILE_SIZE-1;
x := newx;
y := newy;
END;
ptr := objects.getFirst();
WHILE ptr <> NIL DO
BEGIN
next := ptr.getNext();
IF ptr.getObject() <> self THEN
BEGIN
IF collides(TMapObject(ptr.getObject())) THEN
BEGIN
onCollide(TMapObject(ptr.getObject()), objects);
TMapObject(ptr.getObject()).onCollide(self, objects);
END;
END;
ptr := next;
END;
END;
PROCEDURE loadSpriteSheet(bmp : TBitmap; x1,y1,x2,y2, xt, yt : INTEGER; VAR arr : ARRAY OF TBitmap);
VAR x, y, sprw, sprh : INTEGER;
VAR src, dest : TRect;
BEGIN
sprw := (x2-x1) DIV xt;
sprh := (y2-y1) DIV yt;
dest.left := 0;
dest.top := 0;
dest.right := sprw;
dest.bottom := sprh;
FOR y := 0 TO yt-1 DO
BEGIN
src.top := y1+y*sprh;
src.bottom := src.top + sprh;
FOR x := 0 TO xt-1 DO
BEGIN
src.left := x1+x*sprw;
src.right := src.left + sprw;
arr[y*xt+x] := TBitmap.create();
arr[y*xt+x].width := sprw;
arr[y*xt+x].height := sprh;
arr[y*xt+x].canvas.copyRect(dest, bmp.canvas, src);
arr[y*xt+x].TransparentColor := clFuchsia;
END
END;
END;
END.
|
unit IdHeaderCoderUTF;
interface
{$i IdCompilerDefines.inc}
uses
IdGlobal, IdHeaderCoderBase;
type
TIdHeaderCoderUTF = class(TIdHeaderCoder)
public
class function Decode(const ACharSet: string; const AData: TIdBytes): String; override;
class function Encode(const ACharSet, AData: String): TIdBytes; override;
class function CanHandle(const ACharSet: String): Boolean; override;
end;
// RLebeau 4/17/10: this forces C++Builder to link to this unit so
// RegisterHeaderCoder can be called correctly at program startup...
(*$HPPEMIT '#pragma link "IdHeaderCoderUTF"'*)
implementation
uses
SysUtils;
class function TIdHeaderCoderUTF.Decode(const ACharSet: string; const AData: TIdBytes): String;
var
LEncoding: TIdTextEncoding;
LBytes: TIdBytes;
begin
Result := '';
LBytes := nil;
if TextIsSame(ACharSet, 'UTF-7') then begin {do not localize}
LEncoding := TIdTextEncoding.UTF7;
end
else if TextIsSame(ACharSet, 'UTF-8') then begin {do not localize}
LEncoding := TIdTextEncoding.UTF8;
end else
begin
Exit;
end;
LBytes := TIdTextEncoding.Convert(
LEncoding,
TIdTextEncoding.Unicode,
AData);
Result := TIdTextEncoding.Unicode.GetString(LBytes, 0, Length(LBytes));
end;
class function TIdHeaderCoderUTF.Encode(const ACharSet, AData: String): TIdBytes;
var
LEncoding: TIdTextEncoding;
begin
Result := nil;
if TextIsSame(ACharSet, 'UTF-7') then begin {do not localize}
LEncoding := TIdTextEncoding.UTF7;
end
else if TextIsSame(ACharSet, 'UTF-8') then begin {do not localize}
LEncoding := TIdTextEncoding.UTF8;
end else
begin
Exit;
end;
Result := TIdTextEncoding.Convert(
TIdTextEncoding.Unicode,
LEncoding,
TIdTextEncoding.Unicode.GetBytes(AData));
end;
class function TIdHeaderCoderUTF.CanHandle(const ACharSet: String): Boolean;
begin
Result := PosInStrArray(ACharSet, ['UTF-7', 'UTF-8'], False) > -1; {do not localize}
end;
initialization
RegisterHeaderCoder(TIdHeaderCoderUTF);
finalization
UnregisterHeaderCoder(TIdHeaderCoderUTF);
end.
|
unit xTCPClient;
interface
uses System.Types,System.Classes, xFunction, system.SysUtils, xTCPClientBase,
xConsts, System.IniFiles, xClientType, xVCL_FMX;
type
TStuReadyEvent = procedure( nTotalCount : Integer) of object;
type
TStuProgressEvent = procedure( nReadyCount, nTotalCount : Integer) of object;
type
TTCPClient = class(TTCPClientBase)
private
FOnStuReady: TStuReadyEvent;
FOnStuLogin: TNotifyEvent;
FOnStopExam: TNotifyEvent;
FOnStartExam: TNotifyEvent;
FOnStuProgress: TStuProgressEvent;
FLoginSeccess : Boolean; // 登录是否成功
FCanRevData : Boolean; // 是否可以接收数据
FRevData : TBytes; // 接收的数据包
procedure ReadINI;
procedure WriteINI;
/// <summary>
/// 发送命令
/// </summary>
procedure SendOrder(aData : TBytes);
/// <summary>
/// 解析数据
/// </summary>
procedure AnalysisData;
protected
/// <summary>
/// 接收数据包
/// </summary>
procedure RevPacksData(aPacks: TArray<Byte>); override;
public
constructor Create; override;
destructor Destroy; override;
/// <summary>
/// 考生登录
/// </summary>
function StuLogin(nStuID : Integer) : Boolean;
/// <summary>
/// 发送考生状态
/// </summary>
procedure SendStuState(AState : TClientState);
/// <summary>
/// 学员机准备考试
/// </summary>
procedure StuReadyExam;
public
/// <summary>
/// 学员登录事件
/// </summary>
property OnStuLogin : TNotifyEvent read FOnStuLogin write FOnStuLogin;
/// <summary>
/// 学员准备事件
/// </summary>
property OnStuReady : TStuReadyEvent read FOnStuReady write FOnStuReady;
/// <summary>
/// 学员准备进度事件
/// </summary>
property OnStuProgress : TStuProgressEvent read FOnStuProgress write FOnStuProgress;
/// <summary>
/// 开始考试事件
/// </summary>
property OnStartExam : TNotifyEvent read FOnStartExam write FOnStartExam;
/// <summary>
/// 停止考试事件
/// </summary>
property OnStopExam : TNotifyEvent read FOnStopExam write FOnStopExam;
end;
implementation
{ TTCPServer }
procedure TTCPClient.AnalysisData;
var
aBuf : TBytes;
begin
aBuf := AnalysisRevData(FRevData);
if Assigned(aBuf) then
begin
// 解析数据
if Length(aBuf) = 4 then
begin
case aBuf[1] of
1 :
begin
if Assigned(FOnStuLogin) then
FOnStuLogin(Self);
end;
4 :
begin
if Assigned(FOnStartExam) then
FOnStartExam(Self);
end;
5 :
begin
if Assigned(FOnStopExam) then
FOnStopExam(Self);
end;
end;
end
else if Length(aBuf) = 5 then
begin
if aBuf[1] = 2 then
begin
if Assigned(FOnStuReady) then
FOnStuReady(aBuf[2]);
end
else if aBuf[1] = 6 then
begin
FLoginSeccess := aBuf[2] = 1;
end;
end
else if Length(aBuf) = 6 then
begin
if aBuf[1] = 3 then
begin
if Assigned(FOnStuProgress) then
FOnStuProgress(aBuf[2], aBuf[3]);
end;
end;
end;
end;
constructor TTCPClient.Create;
begin
inherited;
ReadINI;
end;
destructor TTCPClient.Destroy;
begin
WriteINI;
inherited;
end;
procedure TTCPClient.ReadINI;
begin
with TIniFile.Create(sPubIniFileName) do
begin
ServerIP := ReadString('Option', 'SeverIP', '');
ServerPort := ReadInteger('Option', 'ServerPort', 15000);
Free;
end;
end;
procedure TTCPClient.RevPacksData(aPacks: TArray<Byte>);
procedure AddData(nData : Byte);
var
nLen : Integer;
begin
nLen := Length(FRevData);
SetLength(FRevData, nLen + 1);
FRevData[nLen] := nData;
end;
var
i : Integer;
nByte : Byte;
begin
inherited;
for i := 0 to Length(aPacks) - 1 do
begin
nByte := aPacks[i];
if nByte = $7E then
begin
if Length(FRevData) = 0 then
begin
FCanRevData := True;
AddData(nByte);
end
else
begin
if FRevData[Length(FRevData)-1] = $7E then
begin
SetLength(FRevData, 0);
FCanRevData := True;
AddData(nByte);
end
else
begin
AddData(nByte);
// 转译字符处理
AnalysisData;
SetLength(FRevData, 0);
FCanRevData := False;
end;
end;
end
else
begin
if FCanRevData then
begin
AddData(nByte);
end;
end;
end;
end;
procedure TTCPClient.SendOrder(aData: TBytes);
var
aBuf : TBytes;
begin
if Active then
begin
aBuf := BuildData(aData);
SendPacksDataBase(aBuf, '', '');
end;
end;
procedure TTCPClient.SendStuState(AState: TClientState);
var
aBuf : Tbytes;
begin
SetLength(aBuf, 2);
aBuf[0] := 7;
aBuf[1] := Integer(AState);
SendOrder(aBuf);
end;
function TTCPClient.StuLogin(nStuID: Integer): Boolean;
function WaitResult( nMSeconds : Cardinal ) : Boolean;
var
nTick : Cardinal;
begin
nTick := TThread.GetTickCount;
repeat
MyProcessMessages;
Sleep(1);
Result := FLoginSeccess;
until (TThread.GetTickCount - nTick > nMSeconds) or Result;
end;
var
aBuf : Tbytes;
begin
SetLength(aBuf, 4);
aBuf[0] := 6;
aBuf[1] := nStuID shr 16 and $FF;
aBuf[2] := nStuID shr 8 and $FF;
aBuf[3] := nStuID and $FF;
FLoginSeccess := False;
SendOrder(aBuf);
Result := True;
// Result := WaitResult(2000);
end;
procedure TTCPClient.StuReadyExam;
var
aBuf : Tbytes;
begin
SetLength(aBuf, 1);
aBuf[0] := 8;
SendOrder(aBuf);
end;
procedure TTCPClient.WriteINI;
begin
with TIniFile.Create(sPubIniFileName) do
begin
writestring('Option', 'SeverIP', ServerIP);
WriteInteger('Option', 'ServerPort', ServerPort);
Free;
end;
end;
end.
|
{*********************************************}
{ TeeChart Delphi Component Library }
{ Digital Series and Legend Last Values Demo }
{ Copyright (c) 1995-2001 by David Berneda }
{ All rights reserved }
{*********************************************}
{$P-} { <-- VERY IMPORTANT WHEN USING OnGet.. EVENTS }
unit lastvalu;
interface
{ This forms show 4 line series in "Stairs" mode.
( LineSeries1.Stairs := True ; )
Legend Style is "lsLastValues" meaning the Legend will draw the
Last value for each Series.
}
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Chart, Series, ExtCtrls, StdCtrls, Teengine, Buttons,
TeeProcs;
type
TDigitalForm = class(TForm)
Chart1: TChart;
LineSeries1: TLineSeries;
LineSeries2: TLineSeries;
LineSeries3: TLineSeries;
LineSeries4: TLineSeries;
Panel1: TPanel;
CheckBox1: TCheckBox;
Timer1: TTimer;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
BitBtn3: TBitBtn;
CheckBox4: TCheckBox;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure CheckBox2Click(Sender: TObject);
procedure CheckBox3Click(Sender: TObject);
procedure Chart1GetLegendText(Sender: TCustomAxisPanel;
LegendStyle: TLegendStyle; Index: Longint; var LegendText: String);
procedure CheckBox4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
procedure TDigitalForm.FormCreate(Sender: TObject);
var t,tt:Longint;
begin
Chart1.ApplyZOrder:=CheckBox4.Checked; { ZOrder or not ZOrder... }
Chart1.Legend.Inverted:=True;
{ Fill Series with random values }
for t:=0 to Chart1.SeriesCount-1 do
With Chart1.Series[t] do
begin
Clear;
for tt:=1 to 100 do Add( 2*t+Random(2), '', clTeeColor);
end;
end;
procedure TDigitalForm.CheckBox1Click(Sender: TObject);
begin
Timer1.Enabled:=CheckBox1.Checked; { start / stop animation }
end;
procedure TDigitalForm.Timer1Timer(Sender: TObject);
var t:Longint;
begin
Timer1.Enabled:=False; { <-- stop the timer }
{ Now, add a new point to each Series }
for t:=0 to Chart1.SeriesCount-1 do
With Chart1.Series[t] do Add( 2*t+Random(2),'',clTeeColor);
{ Scroll the Horizontal Axis }
With Chart1.BottomAxis do { <-- with the Horizontal Axis... }
Begin
Automatic := False; { <-- we dont want automatic scaling }
Maximum := LineSeries1.XValues.Last;
Minimum := Maximum - 100; { we want to see the last 100 points only }
End;
{ re-start timer }
Timer1.Enabled:=True;
end;
procedure TDigitalForm.CheckBox2Click(Sender: TObject);
begin
Chart1.View3D:=CheckBox2.Checked;
end;
procedure TDigitalForm.CheckBox3Click(Sender: TObject);
begin
if CheckBox3.Checked then
Chart1.Legend.LegendStyle:=lsLastValues
else
Chart1.Legend.LegendStyle:=lsAuto;
end;
procedure TDigitalForm.Chart1GetLegendText(Sender: TCustomAxisPanel;
LegendStyle: TLegendStyle; Index: Longint; var LegendText: String);
begin
{ we want to show the Series Title as well as the Last Values }
if LegendStyle=lsLastValues then
LegendText:=LegendText+' --> '+Chart1.Series[Index].Title;
end;
procedure TDigitalForm.CheckBox4Click(Sender: TObject);
begin
Chart1.ApplyZOrder:=CheckBox4.Checked;
Chart1.Repaint;
end;
end.
|
//Основной модуль
//BuckUp системы
//Среда разработки: Delphi 6.0
//Дата: 2007-05-10
//Дополнительные библиотеки:
// VCLZip, ElTree, RxLib, ToolBar97, LMD
unit fMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, kpSFXCfg, VCLZip, VCLUnZip, StdCtrls, ElTree, ImgList, Menus,
TB97Ctls, TB97, TB97Tlbr, ActnList, ComCtrls, Placemnt, TB97Tlwn,
ExtCtrls, RXClock;
type
TfrmMain = class(TForm)
Zip: TVCLZip;
ImageList: TImageList;
Dock1: TDock97;
Dock2: TDock97;
MainToolbar: TToolbar97;
btnOptions: TToolbarButton97;
MainMenu: TMainMenu;
mnmFile: TMenuItem;
mnmBackUp: TMenuItem;
mnmUnBackUp: TMenuItem;
mnmOptions: TMenuItem;
N2: TMenuItem;
mnmExit: TMenuItem;
N1: TMenuItem;
mnmInformation: TMenuItem;
mnmAbout: TMenuItem;
btnBackUp: TToolbarButton97;
btnUnBackUp: TToolbarButton97;
ActionList: TActionList;
AcBackUp: TAction;
AcUnBackUp: TAction;
AcOptions: TAction;
AcExit: TAction;
ToolbarSep971: TToolbarSep97;
acAbout: TAction;
fProgress: TToolWindow97;
FileProgressBar: TProgressBar;
TotalProgressBar: TProgressBar;
Storage: TFormStorage;
btnCancel: TButton;
lblWait: TLabel;
UnZip: TVCLUnZip;
lblRemainding: TLabel;
procedure AcBackUpExecute(Sender: TObject);
procedure AcUnBackUpExecute(Sender: TObject);
procedure AcOptionsExecute(Sender: TObject);
procedure AcExitExecute(Sender: TObject);
procedure acAboutExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ZipFilePercentDone(Sender: TObject; Percent: Integer);
procedure ZipTotalPercentDone(Sender: TObject; Percent: Integer);
procedure btnCancelClick(Sender: TObject);
procedure UnZipFilePercentDone(Sender: TObject; Percent: Integer);
procedure UnZipTotalPercentDone(Sender: TObject; Percent: Integer);
private
fStartZipping,
fStartUnZipping: TDateTime;
fFlag: boolean;
public
end;
var
frmMain: TfrmMain;
implementation
uses
kpZipObj,
fOptions,
fAbout;
{$R *.dfm}
procedure TfrmMain.AcBackUpExecute(Sender: TObject);
var
files, format_files,
name, path: string;
i: integer;
begin
Storage.StoredValues.RestoreValues;
name := Storage.StoredValues.Values['Name'].Value;
if (name = '') then
begin
Application.MessageBox('Не указано имя архива.', 'Предупреждение', MB_OK);
exit;
end;
path := Storage.StoredValues.Values['ZipPath'].Value;
if (path = '') then
begin
Application.MessageBox('Не указано расположение архива.', 'Предупреждение', MB_OK);
exit;
end;
Zip.ZipName := path + name + '.zip';
//TODO: При использовании FilesList.Items.Text
//отображается только первая запись в списке
files := Storage.StoredValues.Values['FilesList'].Value;
if (files = '') then
begin
Application.MessageBox('Не выбрано ниодного файла для архивирования.', 'Предупреждение', MB_OK);
exit;
end;
//формирование FilesList
format_files := '';
for i := 1 to length(files) do
begin
if (files[i] <> '|') then
format_files := format_files + files[i]
else
begin
Zip.FilesList.Add(format_files);
format_files := '';
end;
end;
//формирование ExcludeList
files := Storage.StoredValues.Values['ExcludeList'].Value;
format_files := '';
for i := 1 to length(files) do
begin
if (files[i] <> '|') then
format_files := format_files + files[i]
else
begin
Zip.ExcludeList.Add(format_files);
format_files := '';
end;
end;
fFlag := true;
//архивирование
With Zip do
begin
Recurse := True;
StorePaths := True;
PackLevel := 10;
fProgress.Top := Top + (Height - fProgress.Height) div 2;
fProgress.Left := Left + (Width - fProgress.Width) div 2;
fProgress.Caption := 'Создание архива';
frmMain.Enabled := false;
Screen.Cursor := crHourGlass;
fProgress.Visible := true;
fStartZipping := now;
Zip;
fProgress.Visible := false;
Screen.Cursor := crDefault;
frmMain.Enabled := true;
end;
Application.MessageBox('Архивирование завершено.', 'Сообщение', MB_OK);
end;
procedure TfrmMain.AcUnBackUpExecute(Sender: TObject);
begin
Storage.StoredValues.RestoreValues;
UnZip.ZipName := Storage.StoredValues.Values['UnZipPath'].Value;
if (UnZip.ZipName = '') then
begin
Application.MessageBox('Не указано расположение архива.', 'Предупреждение', MB_OK);
exit;
end;
UnZip.DestDir := Storage.StoredValues.Values['UnZipDestDir'].Value;
if (UnZip.DestDir = '') then
begin
Application.MessageBox('Не указана директория извлечения архива.', 'Предупреждение', MB_OK);
exit;
end;
fFlag := true;
//разархивирование
with UnZip do
begin
DoAll := true;
RecreateDirs := False;
RetainAttributes := True;
fProgress.Top := Top + (Height - fProgress.Height) div 2;
fProgress.Left := Left + (Width - fProgress.Width) div 2;
fProgress.Caption := 'Извлечение файлов из архива';
frmMain.Enabled := false;
Screen.Cursor := crHourGlass;
fProgress.Visible := true;
fStartUnZipping := now;
Unzip;
fProgress.Visible := false;
Screen.Cursor := crDefault;
frmMain.Enabled := true;
end;
end;
procedure TfrmMain.AcOptionsExecute(Sender: TObject);
var
frm: TfrmOptions;
begin
frm := TfrmOptions.Create(self);
frm.ShowModal;
end;
procedure TfrmMain.AcExitExecute(Sender: TObject);
begin
Close;
end;
procedure TfrmMain.acAboutExecute(Sender: TObject);
var
frm: TfrmAbout;
begin
frm := TfrmAbout.Create(self);
frm.ShowModal;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
fProgress.Visible := false;
end;
procedure TfrmMain.ZipFilePercentDone(Sender: TObject; Percent: Integer);
begin
FileProgressBar.Position := Percent;
end;
procedure TfrmMain.ZipTotalPercentDone(Sender: TObject; Percent: Integer);
begin
Application.ProcessMessages;
if (fFlag = false) then
begin
if (Application.MessageBox('Архивирование не завершено.'#10#13'Завершить работу программы?', 'Подтверждение', MB_OKCANCEL) = IDOK) then
halt(0)
else
fFlag := true;
end;
if (Percent > 0) then
lblRemainding.Caption := 'Длительность: ' + TimeToStr(now - fStartZipping) + #10#13 + 'Завершение: ' + TimeToStr(now - fStartZipping -(100 * (now - fStartZipping) / percent));
TotalProgressBar.Position := Percent;
end;
procedure TfrmMain.btnCancelClick(Sender: TObject);
begin
fFlag := false;
end;
procedure TfrmMain.UnZipFilePercentDone(Sender: TObject; Percent: Integer);
begin
FileProgressBar.Position := Percent;
end;
procedure TfrmMain.UnZipTotalPercentDone(Sender: TObject;
Percent: Integer);
begin
Application.ProcessMessages;
if (fFlag = false) then
begin
if (Application.MessageBox('Разархивирование не завершено.'#10#13'Завершить работу программы?', 'Подтверждение', MB_OKCANCEL) = IDOK) then
halt(0)
else
fFlag := true;
end;
if (Percent > 0) then
lblRemainding.Caption := 'Длительность: ' + TimeToStr(now - fStartUnZipping) + #10#13 + 'Завершение: ' + TimeToStr(now - fStartUnZipping -(100 * (now - fStartUnZipping) / percent));
TotalProgressBar.Position := Percent;
end;
end.
|
unit CompetitorList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB,
System.ImageList, Vcl.ImgList, Vcl.StdCtrls, Vcl.Mask, RzEdit,
RzButton, RzTabs, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel, Vcl.ExtCtrls,
RzPanel, RzDBEdit, RzCmboBx;
type
TfrmCompetitorList = class(TfrmBaseGridDetail)
edCompName: TRzDBEdit;
cmbBranch: TRzComboBox;
Label2: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure cmbBranchChange(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
procedure FilterList;
public
{ Public declarations }
protected
function EntryIsValid: boolean; override;
function NewIsAllowed: boolean; override;
function EditIsAllowed: boolean; override;
procedure SearchList; override;
procedure BindToObject; override;
end;
var
frmCompetitorList: TfrmCompetitorList;
implementation
{$R *.dfm}
uses
AuxData, IFinanceDialogs, FormsUtil;
procedure TfrmCompetitorList.BindToObject;
begin
inherited;
end;
procedure TfrmCompetitorList.cmbBranchChange(Sender: TObject);
begin
inherited;
FilterList;
end;
function TfrmCompetitorList.EditIsAllowed: boolean;
begin
Result := true;
end;
function TfrmCompetitorList.EntryIsValid: boolean;
var
error: string;
begin
if Trim(edCompName.Text) = '' then error := 'Please enter name.';
if error <> '' then ShowErrorBox(error);
Result := error = '';
end;
procedure TfrmCompetitorList.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
dmAux.Free;
inherited;
end;
procedure TfrmCompetitorList.FormCreate(Sender: TObject);
begin
dmAux := TdmAux.Create(self);
PopulateBranchComboBox(cmbBranch);
inherited;
end;
procedure TfrmCompetitorList.FormShow(Sender: TObject);
begin
inherited;
FilterList;
end;
function TfrmCompetitorList.NewIsAllowed: boolean;
begin
Result := true;
end;
procedure TfrmCompetitorList.SearchList;
begin
grList.DataSource.DataSet.Locate('comp_name',edSearchKey.Text,
[loPartialKey,loCaseInsensitive]);
end;
procedure TfrmCompetitorList.FilterList;
var
filterStr: string;
begin
if cmbBranch.ItemIndex > -1 then
filterStr := 'loc_code = ''' + cmbBranch.Value + ''''
else
filterStr := '';
grList.DataSource.DataSet.Filter := filterStr;
end;
end.
|
unit PrimesWriting;
interface
uses
SysUtils,
Classes,
SyncObjs,
PrimesSieve;
type
TPrimesWriterController = class
private
FSieve: TPrimesSieve;
FThreads: TList;
FFileStream: TFileStream;
FCS: TCriticalSection;
procedure TerminateThreads;
procedure RemoveThread(AThread: TThread);
function GetWorking: Boolean;
public
constructor Create(const AMaxValue: TNumberValue;
const AThreadCount: Integer;
const AGeneralFileName: string);
destructor Destroy; override;
property Working: Boolean read GetWorking;
end;
implementation
type
TPrimesWriterThread = class(TThread)
private
FController: TPrimesWriterController;
FFileStream: TFileStream;
protected
procedure Execute; override;
public
constructor Create(const AController: TPrimesWriterController;
const APersonalFileName: string);
destructor Destroy; override;
end;
{ TPrimesWriterController }
constructor TPrimesWriterController.Create(const AMaxValue: TNumberValue;
const AThreadCount: Integer; const AGeneralFileName: string);
var
I: Integer;
begin
try
FFileStream := TFileStream.Create(AGeneralFileName, fmCreate);
FSieve := TPrimesSieve.Create(AMaxValue);
FThreads := TList.Create;
FCS := TCriticalSection.Create;
except
FFileStream.Free;
FThreads.Free;
FSieve.Free;
FCS.Free;
raise;
end;
try
for I := 1 to AThreadCount do
FThreads.Add(TPrimesWriterThread.Create(Self, Format('thread%d.txt', [I])));
except //when excepted, we will terminate threads created before
TerminateThreads;
raise;
end;
end;
destructor TPrimesWriterController.Destroy;
begin
TerminateThreads;
FFileStream.Free;
FCS.Free;
FSieve.Free;
FThreads.Free;
inherited;
end;
procedure TPrimesWriterController.RemoveThread(AThread: TThread);
var
LIndex: Integer;
begin
FCS.Acquire;
try
LIndex := FThreads.IndexOf(AThread);
if LIndex >= 0 then
FThreads.Delete(LIndex);
finally
FCS.Release;
end;
end;
procedure TPrimesWriterController.TerminateThreads;
var
I: Integer;
begin
for I := 0 to FThreads.Count - 1 do
TThread(FThreads[I]).Terminate; //completing destruct sequences: TThread.Terminate -> TThread.Free(FreeOnTerminate = True) -> TPrimesWriterPool.ReleaseThread - remove from list
while Working do
Sleep(100); //wait, while threads terminating
end;
function TPrimesWriterController.GetWorking: Boolean;
begin
Result := FThreads.Count > 0;
end;
{ TPrimesWriterThread }
constructor TPrimesWriterThread.Create(const AController: TPrimesWriterController;
const APersonalFileName: string);
begin
FFileStream := TFileStream.Create(APersonalFileName, fmCreate);
FController := AController;
inherited Create;
FreeOnTerminate := True;
end;
destructor TPrimesWriterThread.Destroy;
begin
FController.RemoveThread(Self); //notify pool about destruction
FFileStream.Free;
inherited;
end;
procedure TPrimesWriterThread.Execute;
var
LValue: TNumberValue;
LStr: AnsiString;
LRes: Boolean;
begin
while (not Terminated) do
begin
FController.FCS.Acquire;
try
LRes := FController.FSieve.GetNext(LValue);
if LRes then //GENERAL Log
begin
LStr := AnsiString(UIntToStr(UInt64(LValue)) + ' ');
FController.FFileStream.Write(LStr[1], Length(LStr));
end;
finally
FController.FCS.Release;
end;
if LRes then
FFileStream.Write(LStr[1], Length(LStr)) //Personal log
else
Terminate; //finalize work correctly
end;
end;
end.
|
unit Unit1Test;
interface
uses
SysUtils, Classes, TestFramework, Unit1;
type
ExceptionClass = class of Exception;
TTestMethod = procedure of object;
{ by chrismo -- test cases that trap for specific exception classes have
a lot of duplication. This test case attempts to refactor the common code
into a CheckException method. But it's awkward to use. }
// refactoring out calls to trap specific exception classes
TTestMyObject = class(TTestCase)
private
FMyObject: TMyObject;
FTestResult: boolean;
FTestString: string;
protected
procedure CallStrToIntIsZero;
procedure CheckException(AMethod: TTestMethod;
AExceptionClass: ExceptionClass);
public
procedure Setup; override;
procedure TearDown; override;
published
procedure testMyObject;
procedure TestEMyObject;
procedure TestStrToIntIsZero;
end;
{ majohnson replies with a TTestCase that overrides RunTest ... essentially
putting the functionality of chrismo's CheckException method into
RunTest. Simpler, cleaner, easy to use. }
TTestMyObjectOverrideRunTest = class(TTestCase)
private
FExpectedException: ExceptionClass;
FMyObject: TMyObject;
public
procedure SetExpectedException(Value :ExceptionClass);
procedure RunTest(testResult :TTestResult); override;
procedure Setup; override;
procedure TearDown; override;
published
procedure TestStrToIntIsZero;
end;
function Suite: ITestSuite;
implementation
function Suite: ITestSuite;
begin
Result := TestSuite('Test MyObject',
[TTestMyObject.Suite,
TTestMyObjectOverrideRunTest.Suite]);
end;
{ TTestMyObject }
procedure TTestMyObject.CallStrToIntIsZero;
begin
FTestResult := FMyObject.StrToIntIsZero(FTestString);
end;
procedure TTestMyObject.CheckException(AMethod: TTestMethod;
AExceptionClass: ExceptionClass);
begin
try
AMethod;
fail('Expected exception not raised');
except
on E: Exception do
begin
if E.ClassType <> AExceptionClass then
raise;
end
end;
end;
procedure TTestMyObject.Setup;
begin
FMyObject := TMyObject.Create;
end;
procedure TTestMyObject.TearDown;
begin
FMyObject.Free;
end;
procedure TTestMyObject.TestEMyObject;
begin
CheckException(FMyObject.RandomException, EMyObject);
end;
procedure TTestMyObject.testMyObject;
begin
try
FMyObject.DoSomething;
except
assert(false);
end;
end;
procedure TTestMyObject.TestStrToIntIsZero;
begin
FTestString := 'blah';
CheckException(CallStrToIntIsZero, EConvertError);
end;
{ TTestMyObjectOverrideRunTest }
procedure TTestMyObjectOverrideRunTest.RunTest(testResult :TTestResult);
begin
try
inherited runTest(testResult);
if FExpectedException <> nil then
fail('Excepted Exception did not occur');
except
on E: Exception do
begin
if FExpectedException = nil then
raise
else
if E.ClassType <> FExpectedException then
raise;
end;
end;
{ clear the exception until the next test registers an Exception }
FExpectedException := nil;
end;
procedure TTestMyObjectOverrideRunTest.SetExpectedException(
Value: ExceptionClass);
begin
FExpectedException := Value
end;
procedure TTestMyObjectOverrideRunTest.Setup;
begin
FMyObject := TMyObject.Create;
end;
procedure TTestMyObjectOverrideRunTest.TearDown;
begin
FMyObject.Free;
end;
procedure TTestMyObjectOverrideRunTest.TestStrToIntIsZero;
begin
SetExpectedException(EConvertError);
FMyObject.StrToIntIsZero('blah');
end;
end.
|
unit PascalCoin.RPC.Test.Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FrameStand,
PascalCoin.RPC.Test.Account, PascalCoin.RPC.Test.AccountList,
PascalCoin.RPC.Test.Node, PascalCoin.Test.Wallet,
PascalCoin.RPC.Test.Operations, PascalCoin.RPC.Test.RawOp,
PascalCoin.RPC.Test.Payload, PascalCoin.RPC.Interfaces;
type
TForm1 = class(TForm)
NodeSelect: TComboBox;
Layout1: TLayout;
NodeLabel: TLabel;
FrameStand1: TFrameStand;
NodeLayout: TLayout;
ToolBar1: TToolBar;
ContentLayout: TLayout;
AccountButton: TButton;
NodeURLLabel: TLabel;
AccountListButton: TButton;
NodeStatusButton: TButton;
WalletButton: TButton;
OpsButton: TButton;
RawOpButton: TButton;
PayloadButton: TButton;
procedure AccountButtonClick(Sender: TObject);
procedure AccountListButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure NodeSelectChange(Sender: TObject);
procedure NodeStatusButtonClick(Sender: TObject);
procedure OpsButtonClick(Sender: TObject);
procedure PayloadButtonClick(Sender: TObject);
procedure RawOpButtonClick(Sender: TObject);
procedure WalletButtonClick(Sender: TObject);
private
{ Private declarations }
FAccountFrame: TFrameInfo<TAccountFrame>;
FAccountListFrame: TFrameInfo<TAccountsList>;
FNodeStatusFrame: TFrameInfo<TNodeStatusFrame>;
FWalletFrame: TFrameInfo<TWalletFrame>;
FOpsFrame: TFrameInfo<TOperationsFrame>;
FRawOpFrame: TFrameInfo<TRawOpFrame>;
FPayloadFrame: TFrameInfo<TPayloadTest>;
FAPI: IPascalCoinAPI;
procedure HideLastFrame;
function GetAPI: IPascalCoinAPI;
public
{ Public declarations }
property API: IPascalCoinAPI read GetAPI;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses Spring.Container, PascalCoin.RPC.Test.DM;
procedure TForm1.AccountButtonClick(Sender: TObject);
begin
HideLastFrame;
if not Assigned(FAccountFrame) then
FAccountFrame := FrameStand1.New<TAccountFrame>(ContentLayout);
FAccountFrame.Show();
end;
procedure TForm1.AccountListButtonClick(Sender: TObject);
begin
HideLastFrame;
if Not Assigned(FAccountListFrame) then
FAccountListFrame := FrameStand1.New<TAccountsList>(ContentLayout);
FAccountListFrame.Show();
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
NodeSelect.Items.Clear;
NodeSelect.Items.Add('Local TestNet | http://127.0.0.1:4103');
if NodeSelect.Items.Count > 0 then
NodeSelect.ItemIndex := 0;
end;
function TForm1.GetAPI: IPascalCoinAPI;
begin
if FAPI = nil then
FAPI := GlobalContainer.Resolve<IPascalCoinAPI>;
Result := FAPI;
end;
procedure TForm1.HideLastFrame;
begin
if FrameStand1.LastShownFrame <> nil then
begin
FrameStand1.FrameInfo(FrameStand1.LastShownFrame).Hide();
end;
end;
procedure TForm1.NodeSelectChange(Sender: TObject);
var lItem: TArray<string>;
begin
lItem := NodeSelect.Items[NodeSelect.ItemIndex].Split(['|']);
DM.URI := lItem[1].Trim;
API.URI(DM.URI);
NodeURLLabel.Text := API.nodestatus.version;
end;
procedure TForm1.NodeStatusButtonClick(Sender: TObject);
begin
HideLastFrame;
if not Assigned(FNodeStatusFrame) then
FNodeStatusFrame := FrameStand1.New<TNodeStatusFrame>(ContentLayout);
FNodeStatusFrame.Show();
end;
procedure TForm1.OpsButtonClick(Sender: TObject);
begin
HideLastFrame;
if not Assigned(FOpsFrame) then
FOpsFrame := FrameStand1.New<TOperationsFrame>(ContentLayout);
FOpsFrame.Show();
end;
procedure TForm1.PayloadButtonClick(Sender: TObject);
begin
HideLastFrame;
if Not Assigned(FPayloadFrame) then
FPayLoadFrame := FrameStand1.New<TPayloadTest>(ContentLayout);
FPayloadFrame.Show();
end;
procedure TForm1.RawOpButtonClick(Sender: TObject);
begin
HideLastFrame;
if not Assigned(FRawOpFrame) then
FRawOpFrame := FrameStand1.New<TRawOpFrame>(ContentLayout);
FRawOpFrame.Show();
end;
procedure TForm1.WalletButtonClick(Sender: TObject);
begin
HideLastFrame;
if not Assigned(FWalletFrame) then
FWalletFrame := FrameStand1.New<TWalletFrame>(ContentLayout);
FWalletFrame.Show;
end;
end.
|
unit Finance.Currencies;
interface
uses
Finance.interfaces,
System.JSON;
type
TFinanceCurrencies = class(TInterfacedObject, iFinanceCurrencies)
private
FParent : iFinance;
FSource : string;
FUSD : iFinanceCurrency;
FEUR : iFinanceCurrency;
FGBP : iFinanceCurrency;
FARS : iFinanceCurrency;
FCAD : iFinanceCurrency;
FAUD : iFinanceCurrency;
FJPY : iFinanceCurrency;
FCNY : iFinanceCurrency;
FBTC : iFinanceCurrency;
public
constructor Create(Parent : iFinance);
destructor Destroy; override;
function Source : string; overload;
function Source(value : string) : iFinanceCurrencies; overload;
function GetUSD : iFinanceCurrency;
function GetEUR : iFinanceCurrency;
function GetGBP : iFinanceCurrency;
function GetARS : iFinanceCurrency;
function GetCAD : iFinanceCurrency;
function GetAUD : iFinanceCurrency;
function GetJPY : iFinanceCurrency;
function GetCNY : iFinanceCurrency;
function GetBTC : iFinanceCurrency;
function SetJSON( value : TJSONObject) : iFinanceCurrencies;
function GetJSONArray : TJSONArray;
function &End : iFinance;
end;
implementation
uses
Injection,
Finance.Currency,
System.Generics.Collections;
{ TFinanceCurrencies }
constructor TFinanceCurrencies.Create(Parent: iFinance);
begin
TInjection.Weak(@FParent, Parent);
FUSD := TFinanceCurrency.Create(Self);
FEUR := TFinanceCurrency.Create(Self);
FGBP := TFinanceCurrency.Create(Self);
FARS := TFinanceCurrency.Create(Self);
FCAD := TFinanceCurrency.Create(Self);
FAUD := TFinanceCurrency.Create(Self);
FJPY := TFinanceCurrency.Create(Self);
FCNY := TFinanceCurrency.Create(Self);
FBTC := TFinanceCurrency.Create(Self);
end;
destructor TFinanceCurrencies.Destroy;
begin
inherited;
end;
function TFinanceCurrencies.&End: iFinance;
begin
Result := FParent;
end;
function TFinanceCurrencies.GetARS: iFinanceCurrency;
begin
Result := FARS;
end;
function TFinanceCurrencies.GetAUD: iFinanceCurrency;
begin
Result := FAUD;
end;
function TFinanceCurrencies.GetBTC: iFinanceCurrency;
begin
Result := FBTC;
end;
function TFinanceCurrencies.GetCAD: iFinanceCurrency;
begin
Result := FCAD;
end;
function TFinanceCurrencies.GetCNY: iFinanceCurrency;
begin
Result := FCNY;
end;
function TFinanceCurrencies.GetEUR: iFinanceCurrency;
begin
Result := FEUR;
end;
function TFinanceCurrencies.GetGBP: iFinanceCurrency;
begin
Result := FGBP;
end;
function TFinanceCurrencies.GetJPY: iFinanceCurrency;
begin
Result := FJPY;
end;
function TFinanceCurrencies.GetJSONArray: TJSONArray;
var
JSONArray : TJSONArray;
begin
JSONArray := TJSONArray.Create;
JSONArray.AddElement(FUSD.getJSON);
JSONArray.AddElement(FEUR.getJSON);
JSONArray.AddElement(FGBP.getJSON);
JSONArray.AddElement(FARS.getJSON);
JSONArray.AddElement(FCAD.getJSON);
JSONArray.AddElement(FAUD.getJSON);
JSONArray.AddElement(FJPY.getJSON);
JSONArray.AddElement(FCNY.getJSON);
JSONArray.AddElement(FBTC.getJSON);
Result := JSONArray;
end;
function TFinanceCurrencies.GetUSD: iFinanceCurrency;
begin
Result := FUSD;
end;
function TFinanceCurrencies.SetJSON(value: TJSONObject): iFinanceCurrencies;
begin
Result := Self;
FSource := value.pairs[0].JsonValue.Value;
FUSD.SetJSON(value.pairs[1]);
FEUR.SetJSON(value.pairs[2]);
FGBP.SetJSON(value.pairs[3]);
FARS.SetJSON(value.pairs[4]);
FCAD.SetJSON(value.pairs[5]);
FAUD.SetJSON(value.pairs[6]);
FJPY.SetJSON(value.pairs[7]);
FCNY.SetJSON(value.pairs[8]);
FBTC.SetJSON(value.pairs[9]);
end;
function TFinanceCurrencies.Source(value: string): iFinanceCurrencies;
begin
Result := Self;
FSource := value;
end;
function TFinanceCurrencies.Source: string;
begin
Result := FSource;
end;
end.
|
{ Copyright (C) 1998-2018, written by Shkolnik Mike
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
This components allows to create a
TButton, TCheckBox and TRadioButton with multi-line captions.
To use drop a component on form and set a WordWrap property.
}
unit SMultiBtn;
interface
{$I SMVersion.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons;
type
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TSMButton = class(TButton)
private
FWordWrap: Boolean;
FLayout: TTextLayout;
FAlignment: TAlignment;
procedure SetWordWrap(Value: Boolean);
procedure SetLayout(Value: TTextLayout);
procedure SetAlignment(Value: TAlignment);
protected
procedure CreateParams(var Params: TCreateParams); override;
public
constructor Create(AOwner: TComponent); override;
published
property Alignment: TAlignment read FAlignment write SetAlignment default taCenter;
property Layout: TTextLayout read FLayout write SetLayout default tlCenter;
property WordWrap: Boolean read FWordWrap write SetWordWrap default True;
end;
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TSMCheckBox = class(TCheckBox)
private
FTransparent: Boolean;
FWordWrap: Boolean;
FLayout: TTextLayout;
FAlignment: TAlignment;
procedure SetLayout(Value: TTextLayout);
procedure SetAlignment(Value: TAlignment);
procedure SetTransparent(Value: Boolean);
procedure SetWordWrap(Value: Boolean);
procedure DrawCheckBox(R: TRect; AState: TCheckBoxState; al: TAlignment);
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
public
constructor Create(AOwner: TComponent); override;
procedure WndProc(var Message: TMessage); override;
procedure Invalidate; override;
published
property Transparent: Boolean read FTransparent write SetTransparent default False;
property WordWrap: Boolean read FWordWrap write SetWordWrap default True;
property Alignment: TAlignment read FAlignment write SetAlignment default taCenter;
property Layout: TTextLayout read FLayout write SetLayout default tlCenter;
end;
{$IFDEF SM_ADD_ComponentPlatformsAttribute}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TSMRadioButton = class(TRadioButton)
private
FWordWrap: Boolean;
FLayout: TTextLayout;
FAlignment: TAlignment;
procedure SetWordWrap(Value: Boolean);
procedure SetLayout(Value: TTextLayout);
procedure SetAlignment(Value: TAlignment);
protected
procedure CreateParams(var Params: TCreateParams); override;
public
constructor Create(AOwner: TComponent); override;
published
property Alignment: TAlignment read FAlignment write SetAlignment default taCenter;
property Layout: TTextLayout read FLayout write SetLayout default tlCenter;
property WordWrap: Boolean read FWordWrap write SetWordWrap default True;
end;
procedure Register;
implementation
{$R SMultiBtn.Res}
var
FCheckWidth, FCheckHeight: Integer;
procedure GetCheckBoxSize;
begin
with TBitmap.Create do
try
Handle := LoadBitmap(0, PChar(32759));
FCheckWidth := Width div 4;
FCheckHeight := Height div 3;
finally
Free;
end;
end;
{ TSMButton }
constructor TSMButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAlignment := taCenter;
FLayout := tlCenter;
FWordWrap := True;
end;
procedure TSMButton.SetWordWrap(Value: Boolean);
begin
if (FWordWrap <> Value) then
begin
FWordWrap := Value;
ReCreateWnd;
end;
end;
procedure TSMButton.SetLayout(Value: TTextLayout);
begin
if (FLayout <> Value) then
begin
FLayout := Value;
ReCreateWnd;
end;
end;
procedure TSMButton.SetAlignment(Value: TAlignment);
begin
if (FAlignment <> Value) then
begin
FAlignment := Value;
ReCreateWnd;
end;
end;
procedure TSMButton.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
case Alignment of
taLeftJustify: Params.Style := Params.Style or BS_LEFT;
taRightJustify: Params.Style := Params.Style or BS_RIGHT;
taCenter: Params.Style := Params.Style or BS_CENTER;
end;
case Layout of
tlTop: Params.Style := Params.Style or BS_TOP;
tlCenter: Params.Style := Params.Style or BS_VCENTER;
tlBottom: Params.Style := Params.Style or BS_BOTTOM;
end;
if FWordWrap then
Params.Style := Params.Style or BS_MULTILINE
else
Params.Style := Params.Style and not BS_MULTILINE;
end;
{ TSMCheckBox }
constructor TSMCheckBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAlignment := taCenter;
FLayout := tlCenter;
FTransparent := False;
FWordWrap := True;
end;
procedure TSMCheckBox.SetLayout(Value: TTextLayout);
begin
if (FLayout <> Value) then
begin
FLayout := Value;
ReCreateWnd;
end;
end;
procedure TSMCheckBox.SetAlignment(Value: TAlignment);
begin
if (FAlignment <> Value) then
begin
FAlignment := Value;
ReCreateWnd;
end;
end;
procedure TSMCheckBox.SetTransparent(Value: Boolean);
begin
if (FTransparent <> Value) then
begin
FTransparent := Value;
if FTransparent then
ControlStyle := ControlStyle - [csOpaque]
else
ControlStyle := ControlStyle + [csOpaque];
ReCreateWnd;
end;
end;
procedure TSMCheckBox.SetWordWrap(Value: Boolean);
begin
if (FWordWrap <> Value) then
begin
FWordWrap := Value;
ReCreateWnd;
end;
end;
procedure TSMCheckBox.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
case Alignment of
taLeftJustify: Params.Style := Params.Style or BS_LEFT;
taRightJustify: Params.Style := Params.Style or BS_RIGHT;
taCenter: Params.Style := Params.Style or BS_CENTER;
end;
case Layout of
tlTop: Params.Style := Params.Style or BS_TOP;
tlCenter: Params.Style := Params.Style or BS_VCENTER;
tlBottom: Params.Style := Params.Style or BS_BOTTOM;
end;
if FWordWrap then
Params.Style := Params.Style or BS_MULTILINE or BS_TOP
else
Params.Style := Params.Style and not BS_MULTILINE or not BS_TOP;
if Transparent then
Params.ExStyle := Params.ExStyle or WS_EX_TRANSPARENT {or not WS_CLIPCHILDREN or not WS_CLIPSIBLINGS};
end;
procedure TSMCheckBox.CreateWnd;
begin
inherited CreateWnd;
if Transparent and
Assigned(Parent) and
Parent.HandleAllocated then
begin
SetWindowLong(Parent.Handle, GWL_STYLE,
GetWindowLong(Parent.Handle, GWL_STYLE) and not WS_CLIPCHILDREN);
end;
end;
procedure TSMCheckBox.WndProc(var Message: TMessage);
//var
// Rect: TRect;
begin
with Message do
case Msg of
WM_ERASEBKGND,
WM_Move: begin
if Transparent then
begin
// Invalidate;
Message.Result := 1;
exit;
end
end;
CN_CTLCOLORMSGBOX..CN_CTLCOLORSTATIC:
begin
// SetTextColor(WParam, RGB(0, 0, 255));
SetBkMode(WParam, Windows.TRANSPARENT);
{
GetClipBox(WParam, Rect);
OffsetRect(Rect, Left, Top);
RedrawWindow(Parent.Handle, @Rect, 0, RDW_ERASE or RDW_INVALIDATE or RDW_NOCHILDREN or RDW_UPDATENOW);
}
Result := Parent.Brush.Handle;
Exit;
end;
end;
inherited WndProc(Message);
end;
procedure TSMCheckBox.DrawCheckBox(R: TRect; AState: TCheckBoxState; al: TAlignment);
var
DrawState: Integer;
DrawRect: TRect;
begin
case AState of
cbChecked: DrawState := DFCS_BUTTONCHECK or DFCS_CHECKED;
cbUnchecked: DrawState := DFCS_BUTTONCHECK;
else // cbGrayed
DrawState := DFCS_BUTTON3STATE or DFCS_CHECKED;
end;
case al of
taRightJustify: begin
DrawRect.Left := R.Right - FCheckWidth;
DrawRect.Right := R.Right;
end;
taCenter: begin
DrawRect.Left := R.Left + (R.Right - R.Left - FCheckWidth) div 2;
DrawRect.Right := DrawRect.Left + FCheckWidth;
end;
else // taLeftJustify
DrawRect.Left := R.Left;
DrawRect.Right := DrawRect.Left + FCheckWidth;
end;
DrawRect.Top := R.Top + (R.Bottom - R.Top - FCheckWidth) div 2;
DrawRect.Bottom := DrawRect.Top + FCheckHeight;
DrawFrameControl({Canvas.}Handle, DrawRect, DFC_BUTTON, DrawState);
end;
procedure TSMCheckBox.WMPaint(var Message: TWMPaint);
var
Rect: TRect;
begin
inherited;
exit;
if Transparent and
Assigned(Parent) and
Parent.HandleAllocated then
begin
PaintHandler(Message);
GetClipBox({Canvas.}Handle, Rect);
// OffsetRect(Rect, Left, Top);
// RedrawWindow(Parent.Handle, @Rect, 0, RDW_ERASE or RDW_INVALIDATE or RDW_NOCHILDREN or RDW_UPDATENOW)
DrawCheckBox(Rect, State, Alignment);
end
else
PaintHandler(Message);
end;
procedure TSMCheckBox.Invalidate;
var
Rect: TRect;
// i: Integer;
DC: HDC;
begin
inherited;
exit;
if Transparent and
Assigned(Parent) and
Parent.HandleAllocated then
begin
DC := GetDC(Handle);
SetBkMode(DC, Windows.TRANSPARENT);
GetClipBox(DC {Canvas.Handle}, Rect);
OffsetRect(Rect, Left, Top);
RedrawWindow(Parent.Handle, @Rect, 0, RDW_ERASE or RDW_INVALIDATE or RDW_NOCHILDREN or RDW_UPDATENOW);
ReleaseDC(Handle, DC);
{ Rect := BoundsRect;
InvalidateRect(Parent.Handle, @Rect, True);
for i := 0 to ControlCount - 1 do
Controls[i].Invalidate;
} end
else
inherited Invalidate;
end;
{ TSMRadioButton }
constructor TSMRadioButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAlignment := taCenter;
FLayout := tlCenter;
FWordWrap := True;
end;
procedure TSMRadioButton.SetLayout(Value: TTextLayout);
begin
if (FLayout <> Value) then
begin
FLayout := Value;
ReCreateWnd;
end;
end;
procedure TSMRadioButton.SetAlignment(Value: TAlignment);
begin
if (FAlignment <> Value) then
begin
FAlignment := Value;
ReCreateWnd;
end;
end;
procedure TSMRadioButton.SetWordWrap(Value: Boolean);
begin
if (FWordWrap <> Value) then
begin
FWordWrap := Value;
ReCreateWnd;
end;
end;
procedure TSMRadioButton.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
case Alignment of
taLeftJustify: Params.Style := Params.Style or BS_LEFT;
taRightJustify: Params.Style := Params.Style or BS_RIGHT;
taCenter: Params.Style := Params.Style or BS_CENTER;
end;
case Layout of
tlTop: Params.Style := Params.Style or BS_TOP;
tlCenter: Params.Style := Params.Style or BS_VCENTER;
tlBottom: Params.Style := Params.Style or BS_BOTTOM;
end;
if FWordWrap then
Params.Style := Params.Style or BS_MULTILINE or BS_TOP
else
Params.Style := Params.Style and not BS_MULTILINE or not BS_TOP;
end;
procedure Register;
begin
RegisterComponents('SMComponents', [TSMButton, TSMCheckBox, TSMRadioButton]);
end;
initialization
GetCheckBoxSize;
end.
|
unit MasterMind.API;
interface
const
CODE_SIZE = 4;
MAX_GUESSES = 12;
type
TMasterMindCodeColor = (mmcGreen, mmcYellow, mmcOrange, mmcRed, mmcWhite, mmcBrown);
TMasterMindCode = array[0..CODE_SIZE - 1] of TMasterMindCodeColor;
TMasterMindHint = (mmhNoMatch, mmhWrongPlace, mmhCorrect);
TGuessEvaluationResult = array[0..CODE_SIZE - 1] of TMasterMindHint;
TEvaluatedGuess = record
GuessedCode: TMasterMindCode;
GuessResult: TGuessEvaluationResult;
end;
TPreviousGuesses = array of TEvaluatedGuess;
IGuessEvaluator = interface
['{168D4F90-D778-4BCF-A401-D32241932779}']
function EvaluateGuess(const CodeToBeGuessed, Guess: TMasterMindCode): TGuessEvaluationResult;
end;
ICodeSelector = interface
['{909D1C37-3715-4C0E-8BA4-703F0068426A}']
function SelectNewCode: TMasterMindCode;
end;
IGamePresenter = interface
['{E5412473-10EB-4B5F-B0A7-88C66FEE6A1A}']
procedure NewGame;
function GetCodeToBeGuessed: TMasterMindCode;
procedure TakeGuess(const Guess: TMasterMindCode);
property CodeToBeGuessed: TMasterMindCode read GetCodeToBeGuessed;
end;
IGameView = interface
['{C188DF5F-1B9D-423C-8619-FA00C617B601}']
procedure Start;
procedure StartRequestGuess(const PreviousGuesses: TPreviousGuesses);
procedure ShowGuesses(const PreviousGuesses: TPreviousGuesses);
procedure ShowPlayerWinsMessage(const PreviousGuesses: TPreviousGuesses);
procedure ShowPlayerLosesMessage(const PreviousGuesses: TPreviousGuesses);
end;
implementation
end. |
1 program DobbelRonde;
2 { Etienne van Delden, 0618959, 26-09-2006 }
3 { Dit programma hoort bij de opgave 'Dobbel Simulatie' en bepaalt simuleert
4 een aantal dobbelrondes. Er word willekeurig gegooid door een vast aantal
5 spelers, waarvan 1 met een dodecaeder gooit. Deze simulatie gebeurt zo vaak
6 als word aangegeven in de input. }
7
8 const
9 AantalSpelers = 5; // Het aantal spelers
10
11 type
12 AlleSpelers = 0 .. AantalSpelers; // Dit type loopt van 0, geen winnaar
13 // tot de laatste speler
14
15 var
16 worp: Integer; // het gegooide getal
17 max: Integer; // het tot nu toe behaalde maximum
18 winnaar: AlleSpelers; // de winnaar(s)
19 i: Integer; // teller variabele/ hulp variabele
20 AantalRondes: Integer; // het aantal rondes
21 speler: Integer; // de huidige speler is..
22 WinRondes: array [ AlleSpelers ] of Integer;
23 // array voor het bijhouden van de score
24 // van iedere speler + geen winnaar
25
26 begin
27 ///// 1. Inititialisatie /////
28 Randomize; // initialisatie random generator
29 max := 0; // er is nog geen maximum
30 winnaar := 0; // speler 0 is standaard winnaar
31 speler := 1; // speler 1 is als eerst aan de buurt
32
33 for i := 0 to AantalSpelers do begin // initialisatie win frequentie per
34 WinRondes[ i ] := 0 // speler
35 end;
36
37 i := 0; // teller initialisatie
38
39 ///// 2. Het programma /////
40 /// 2.1 Lees het aantal Rondes ///
41 readln( AantalRondes ); // Hoeveel rondes worden gespeeld?
42
43 /// 2.2 Executeer aantal rondes ///
44 // Hoofdlus: herhaalt het spelen van
45 // 1 ronde tot AantalRondes
46 while i <> AantalRondes do
47 begin
48 // Speler 1 tot AantalSpelers gooien
49 // ieder, hierbij word de winnaar van
50 // deze ronde bijgehouden
51 for speler := 1 to AantalSpelers do begin
52 /// 2.2.1 Word de dodecaeder gegooid of 2 dice 6? ///
53 if speler = 1 then
54 begin
55 worp := random( 12 ) // Speler 1 gooit met een dodecaeder
56 end
57 else
58 begin
59 worp := random( 6 ) + random( 6 ) // Alle anderen met 2x dice 6
60 end;
61
62 /// 2.2.2 Bepaal het maximum van de gegooide worp ///
63 if max < worp then // er is een nieuw maximum gegooid
64 begin
65 max := worp;
66 winnaar := speler
67 end
68 else if max = worp then // het maximum is niet meer uniek
69 begin
70 winnaar := 0 // speler 0 word nu winnaar
71 end;
72 end; // Alle spelers hebben gegooid
73
74 /// 2.2.3 Winnaar array aanpassen en resetten waarden ///
75 // speler [ winnaar ] heeft 1 keer
76 // meer gewonnen
77 WinRondes[ winnaar ] := WinRondes[ winnaar ] + 1;
78 max := 0; // nieuwe ronde, nieuw maximum
79 worp := 0; // nieuwe ronde, nieuwe kansen
80
81
82 i := i + 1; // teller ophogen, op naar de
83 // volgende rond
84 end;
85 /// 2.3 Output wegschrijven ///
86
87 for i := 1 to AantalSpelers do begin
88 write( WinRondes[ i ], ' ' ) // schrijf hoe vaak speler i won
89 end;
90
91 write( WinRondes[ 0 ]); // schrijf hoe vaak er geen winnar was
92
93 end. |
unit Printer;
interface
uses
System.SysUtils, InterfaceTela;
type
TPrinter = class(TInterfacedObject, ITela)
private
Itens: PrintList;
public
procedure Print;
procedure AddNaTela(Item: ITela);
end;
implementation
{ TPrinter }
procedure TPrinter.AddNaTela(Item: ITela);
begin
Itens := Itens + [Item];
end;
procedure TPrinter.Print;
var
Aux: ITela;
begin
for Aux in Itens do
Aux.Print;
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.Bind.Consts;
interface
resourcestring
SBindingComponentsCategory = 'LiveBindings';
SBindingComponentsMiscCategory = 'LiveBindings Misc';
SBindingComponentsDeprecatedCategory = 'LiveBindings Deprecated'; // Temporary
SInvalidBindCompRegistration = 'Invalid LiveBindings registration';
SInvalidBindCompUnregistration = 'Invalid LiveBindings unregistration';
SInvalidBindCompEnumeration = 'Invalid LiveBindings enumeration';
SInvalidBindCompCreation = 'Invalid LiveBindings creation';
SInvalidBindCompFactory = 'Invalid LiveBindings factory';
SInvalidBindCompFactoryEnumeration = 'Invalid LiveBindings factory enumeration';
SInvalidBindCompDesigner = 'Invalid LiveBindings designer';
SInvalidBindCompComponents = 'Invalid data bound components';
sDisplayTextAttr = 'Display Text';
sMinValueAttr = 'Min Value';
sMaxValueAttr = 'Max Value';
sArgCount = 'Unexpected argument count';
sNameAttr = 'Name';
sValueAttr = 'Value';
sControlAttr = 'Control Expression';
sSourceAttr = 'Source Expression';
sSourceComponentAttr = 'Source Component';
sIDAttr = 'ID';
sStateAttr = 'State';
sNoDataSet = 'Error in %0:s. No dataset.';
sNotImplemented = 'Not implemented';
sNoListEditor = 'Error in %0:s. No list control editor available for %1:s';
sNoNamedListEditor = 'Error in %0:s. No list control editor "%2:s" available for %1:s';
sNoEnumerator = 'Error in %0:s. No enumerator available for %1:s';
sNoInsertItem = 'Error in %0:s. Inserted item not available for %1:s';
sNoControl = 'Error in %0:s. No control component';
SDataSourceUnidirectional = 'Error in %0:s: Operation not allowed on a unidirectional data source';
sNoControlObserverSupport = 'Error in %0:s. No observer support for %1:s';
sErrorNoLookupSupport = 'Error in %0:s when attempting to fill a lookup list with a control (%1:s) which does not support lookups';
sNoLookupSupport = 'A lookup list can''t be created with a control (%0:s) which does not support lookups';
sObjectValueExpected = 'TObject value expected';
sLinkFieldNotFound = 'Unable to determine field name in %s';
sLinkUnexpectedGridCurrentType = 'Unexpected grid current type in %s';
// Categories
SDataBindingsCategory_BindingExpressions = 'Binding Expressions';
SDataBindingsCategory_Links = 'Links';
SDataBindingsCategory_Lists = 'Lists';
SQuickBindingsCategory = 'Quick Bindings';
SDataBindingsCategory_DBLinks = 'DB Links (deprecated)';
// Method
sCheckedState = 'CheckedState';
sCheckedStateDesc = 'Bidirectional method to either get the checked state of a control,'#13#10 +
'or set the checked state in a control'#13#10 +
'Example usage when binding to a TCheckBox:'#13#10 +
' CheckedState(Self)';
sSelectedText = 'SelectedText';
sSelectedTextDesc = 'Bidirectional method to either get the text selected in a control,'#13#10 +
'or set the text selected in a control'#13#10 +
'Example usage when binding to a TListBox:'#13#10 +
' SelectedText(Self)';
sSelectedItem = 'SelectedItem';
sSelectedItemDesc = 'Bidirectional method to either get the selected item in a control,'#13#10 +
'or set the selected item in a control'#13#10 +
'Example usage when binding to a TListBox:'#13#10 +
' SelectedItem(Self).Text';
sSelectedLookupValue = 'SelectedLookupValue';
sSelectedLookupValueDesc = 'Bidirectional method to either get the selected lookup value in a control'#13#10 +
'Example usage when binding to a TListBox:'#13#10 +
' SelectedLookupValue(Self).AsString';
sSelectedValue = 'SelectedValue';
sSelectedValueDesc = 'Bidirectional method to either get the selected value in a control,'#13#10 +
'or set the selected lookup value in a control'#13#10 +
'Example usage when binding to a TListBox:'#13#10 +
' SelectedLookupValue(Self).AsString';
sSelectedDateTime = 'SelectedDateTime';
sSelectedDateTimeDesc = 'Bidirectional method to either get the selected DateTime in a control,'#13#10 +
'or set the selected DateTime value in a control'#13#10 +
'Example usage when binding to a TCustomDateTimeEdit:'#13#10 +
' SelectedDateTime(Self)';
sLookup = 'Lookup';
sLookupDesc = 'Lookup a value in a bind scope. Returns the lookup value.'#13#10 +
'Example usage:'#13#10 +
' Lookup(BindScope, "keyfieldname", lookupkeyvalue, "valuefieldname")';
//LinkObservers
sBindLinkIncompatible = 'Error configuring %s: Object must implement IBindLink';
sBindPositionIncompatible = 'Error configuring %s: Object must implement IBindPosition';
SDuplicateName = 'Duplicate name ''%s'' in %s';
SNotEditing = 'Not editing';
SFieldNotFound = 'Field ''%s'' not found';
sNoBindsourceAdapter = 'No adapter';
sSameSourceAndControlComponent = 'Error in %s: Source component and control component cannot be the same';
// Data generator fields collection
sTypeAttr = 'Field Type';
sGeneratorAttr = 'Generator';
sMemberNotFound = 'Error in %2:s: Member %0:s not found in %1:s';
sComponentEvalError = 'EvalError in %0:s: %1:s';
// Navigator hints
SFirstRecord = 'First record';
SPriorRecord = 'Prior record';
SNextRecord = 'Next record';
SLastRecord = 'Last record';
SInsertRecord = 'Insert record';
SDeleteRecord = 'Delete record';
SEditRecord = 'Edit record';
SPostEdit = 'Post edit';
SCancelEdit = 'Cancel edit';
SConfirmCaption = 'Confirm';
SRefreshRecord = 'Refresh data';
SApplyUpdates = 'Apply updates';
SCancelUpdates = 'Cancel updates';
SDeleteRecordQuestion = 'Delete record?';
sScopeLookupNotImplemented = '%s does not implement IScopeLookup';
sNoBidiLookup = 'Lookup controls do not support bidirectional editing';
sDataSourceReadOnly = 'Cannot modify a read-only data source';
sDataSourceClosed = 'Cannot perform this operation on a closed dataset';
sInvalidInstance = 'New instance of type %0:s does not match expected type %1:s';
sNilList = 'List is nil';
sUnknownEditor = 'Unknown editor: %s';
sControlMember = 'Control Member';
sSourceMember = 'Source Member';
sCustomFormat = 'Custom Format';
implementation
end.
|
{*******************************************************}
{ }
{ Borland Delphi Sample }
{ }
{ Copyright (c) 2001 Inprise Corporation }
{ }
{*******************************************************}
(*
TImageProducer provides button images on behalf of a TAdapterActionButton. Assign
to the TAdapterActionButton.ImageProducer property.
Properties:
CacheDir - Directory where .jpg files will be created. May be a relative path.
VirtualDir - Virtual directory mapped to the actual directory specified with the
CacheDir property. May be a relative path. Uses at runtime only.
FileLifeTime -
Indicates when to recreate a .jpg file. A .jpg file will be recreated when
then the difference between the current time and the file creation time exceeds
the lifetime value. Used at runtime only. If the minute and day values are zero,
image files will not be recreated.
Color, Font, Height, etc. - These properties are used to define the appearance
of the buttons. The button captions are defined by the TAdapterActionButton.
Designtime behavior - While in design mode, .jpg files a are recreated when the
properties such as color, font, and so forth are changed. Each time a file is
recreated it is given a unique name so that the HTML preview will update
(the preview won't update unless the generated HTML has changed). When the
TImageProducer is destroyed, it deletes all .jpg files that it has created.
Runtime behavior - When the app is running, .jpg files are not recreated until they
expires. File expiration is calculated using the FileLifeTime property. Changes
made to the imageproducer component at designtime will not show at runtime until the
.jpg is recreated. To force recreation, delete the .jpg files from the CacheDir.
The filenames created at runtime are different from the filenames used at designtime.
.jpg files created at runtime are not deleted when the web app terminates.
Changing the component - If you add any properties that affect the appearance, be sure
to update TImageButtonAttributes.IsEqual. Otherwise, the preview will not update
as the properties are changed.
*)
unit ImgBtnProducer;
interface
uses Classes, Messages, HTTPApp, HTTPProd,
WebComp, Contnrs, SysUtils, SiteComp, AdaptReq, Graphics, SyncObjs;
type
TImageEvent = (evNone, evOver, evOut, evDown);
// Implement WebSnap interfaces.
// IWebVariableName, IGetScriptObject enable activescripting
TBaseImageProducer = class(TComponent, IActionImageProducer, IImageProducer, IGetScriptObject, IWebVariableName)
protected
function WebImageHREF(AComponent: TComponent; const ACaption: WideString; AEvent: TImageEvent): string; virtual;
procedure RenderAdapterImage(ARequest: IImageRequest;
AResponse: IImageResponse); virtual;
{ IWebVariableName }
function GetVariableName: string;
{ IGetScriptObject }
function GetScriptObject: IDispatch;
function ImplGetScriptObject: IDispatch; virtual;
{ IActionImageProducer }
function GetAdapterImage(Sender: TComponent; const ACaption: WideString): IInterface;
function GetDisplayStyle(Sender: TComponent): string;
function GetAdapterEventImage(Sender: TComponent; const AEvent, ACaption: WideString): IInterface;
end;
// Object to manage image attributes. We'll use this to keep a copy of the original attributes
// so that we can update image files when attributes change.
TImageButtonAttributes = class(TObject)
private
FHeight: Integer;
FWidth: Integer;
FColor: TColor;
FFont: TFont;
FBottomRightColor: TColor;
FFocusColor: TColor;
FTopLeftColor: TColor;
procedure SetFont(const Value: TFont);
public
constructor Create;
destructor Destroy; override;
procedure CopyFrom(const AAttributes: TImageButtonAttributes);
function IsEqual(const AAttributes: TImageButtonAttributes): Boolean;
property Width: Integer read FWidth write FWidth;
property Height: Integer read FHeight write FHeight;
property Color: TColor read FColor write FColor;
property Font: TFont read FFont write SetFont;
property TopLeftColor: TColor read FTopLeftColor write FTopLeftColor;
property BottomRightColor: TColor read FBottomRightColor write FBottomRightColor;
property FocusColor: TColor read FFocusColor write FFocusColor;
end;
// Image producer with button attributes
TBaseImageButtonProducer = class(TBaseImageProducer)
private
FAttributes: TImageButtonAttributes;
function GetColor: TColor;
function GetHeight: Integer;
function GetWidth: Integer;
function GetTopLeftColor: TColor;
function GetBottomRightColor: TColor;
function GetFocusColor: TColor;
procedure SetTopLeftColor(const Value: TColor);
procedure SetBottomRightColor(const Value: TColor);
procedure SetFocusColor(const Value: TColor);
procedure SetColor(const Value: TColor);
procedure SetHeight(const Value: Integer);
procedure SetWidth(const Value: Integer);
function GetFont: TFont;
procedure SetFont(const Value: TFont);
protected
function PropertiesAsStrings(const ACaption: WideString; ADisabled: Boolean; AEvent: TImageEvent): TStrings;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Width: Integer read GetWidth write SetWidth default 75;
property Height: Integer read GetHeight write SetHeight default 25;
property Color: TColor read GetColor write SetColor default $00CCCCCC;
property Font: TFont read GetFont write SetFont;
property TopLeftColor: TColor read GetTopLeftColor write SetTopLeftColor default clWhite;
property BottomRightColor: TColor read GetBottomRightColor write SetBottomRightColor default clGray;
property FocusColor: TColor read GetFocusColor write SetFocusColor default clYellow;
end;
TFileLifeTime = class(TPersistent)
private
FDays: Cardinal;
FMinutes: Cardinal;
public
procedure Assign(Source: TPersistent); override;
function TimeHasExpired(ADateTime: TDateTime): Boolean;
published
constructor Create;
property Days: Cardinal read FDays write FDays default 0;
property Minutes: Cardinal read FMinutes write FMinutes default 1;
end;
// Manage button image files. Create new files when properties are changes.
TCustomImageButtonProducer = class(TBaseImageButtonProducer)
private
FLastAttributes: TImageButtonAttributes;
FCacheDir: string;
FVirtualDir: string;
FFileLifeTime: TFileLifeTime;
function FileHasExpired(const AFileName: string): Boolean;
procedure SetFileLifeTime(const Value: TFileLifeTime);
protected
procedure CreateImageFile(const AFileName: string;
AComponent: TComponent; const ACaption: WideString; AEvent: TImageEvent);
function WebImageHREF(AComponent: TComponent; const ACaption: WideString; AEvent: TImageEvent): string; override;
function MakeFileName(AComponent: TComponent; AEvent: TImageEvent): string;
public
property CacheDir: string read FCacheDir write FCacheDir;
property VirtualDir: string read FVirtualDir write FVirtualDir;
property FileLifeTime: TFileLifeTime read FFileLifeTime write SetFileLifeTime;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TImageButtonProducer = class(TCustomImageButtonProducer)
published
property Width;
property Height;
property CacheDir;
property VirtualDir;
property Color;
property Font;
property FileLifeTime;
property TopLeftColor;
property BottomRightColor;
property FocusColor;
end;
// An instance of this object gets created each time server-side script is used to references an image. This
// object holds the characteristics that make each image distinct (e.g.; caption, event, component).
TImageObject = class(TInterfacedObject, IWebImageHREF,
IGetAdapterItemRequestParams, IInterfaceComponentReference)
private
FProducer: TBaseImageProducer;
FComponent: TComponent;
FCaption: WideString;
FEvent: TImageEvent;
protected
{ IInterfaceComponentReference }
function GetComponent: TComponent;
{ IWebImageHREF }
function WebImageHREF(var AHREF: string): Boolean;
{ IGetAdapterRequestParams }
procedure GetAdapterItemRequestParams(
var AIdentifier: string; AParams: IAdapterItemRequestParams);
public
constructor Create(AProducer: TBaseImageProducer; AComponent: TComponent; const ACaption: WideString;
const AEvent: string = '');
end;
TComponentImageFileList = class;
// Keep a list of image files that are in use by an image producer component. At runtime, when
// there are multiple web module instances, all image producers with the same name share
// a file set.
TImageFileList = class(TObject)
private
FFileNames: TStrings;
FCaptions: TStrings;
FComponentImageFileList: TComponentImageFileList;
FFileID: Integer;
FClearCache: Boolean;
function GetFileID: string;
public
constructor Create(AComponentImageFileList: TComponentImageFileList; AClearCache: Boolean);
destructor Destroy; override;
procedure ClearCache;
function CaptionChanged(const AFileName, ACaption: string): Boolean;
procedure AddFile(const AFileName: string; const ACaption: string);
procedure Lock;
procedure Unlock;
property FileID: string read GetFileID;
end;
// Keep lists of image files that are used by all image producer components.
TComponentImageFileList = class(TObject)
private
FFileLists: TObjectList;
FComponentNames: TStrings;
FFileID: Integer;
FLock: TCriticalSection;
function GetImageFileList(AComponent: TComponent): TImageFileList;
function GetComponentName(AComponent: TComponent): string;
function NextFileID: Integer;
public
constructor Create;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
property ImageFileList[AComponent: TComponent]: TImageFileList read GetImageFileList; default;
end;
const
ImageEventNames: array[TImageEvent] of string = ('', 'onmouseover', 'onmouseout', 'onmousedown');
implementation
uses WebConst, Windows,
Variants, AutoAdap, DrawBtn, WebCntxt, MidProd, DateUtils;
var
FComponentImageFileList: TComponentImageFileList;
{ TImageObject }
constructor TImageObject.Create(AProducer: TBaseImageProducer;
AComponent: TComponent; const ACaption: WideString; const AEvent: string);
var
I: TImageEvent;
begin
inherited Create;
FComponent := AComponent;
FProducer := AProducer;
FCaption := ACaption;
FEvent := evNone;
for I := Low(TImageEvent) to High(TImageEvent) do
if CompareText(AEvent, ImageEventNames[I]) = 0 then
begin
FEvent := I;
break;
end;
end;
procedure TImageObject.GetAdapterItemRequestParams(
var AIdentifier: string; AParams: IAdapterItemRequestParams);
begin
// Not implemented because we always return static hrefs rather
// than an href that is dispatched throught TAdapterDispatcher
end;
function TImageObject.GetComponent: TComponent;
begin
Result := FComponent;
end;
function TImageObject.WebImageHREF(var AHREF: string): Boolean;
begin
AHREF := FProducer.WebImageHREF(FComponent, FCaption, FEvent);
Result := AHREF <> '';
end;
{ TBaseImageProducer }
function TBaseImageProducer.GetVariableName: string;
begin
Result := Self.Name;
end;
function TBaseImageProducer.WebImageHREF(AComponent: TComponent; const ACaption: WideString;
AEvent: TImageEvent): string;
begin
Result := '';
// Descendent implements
end;
procedure TBaseImageProducer.RenderAdapterImage(ARequest: IImageRequest;
AResponse: IImageResponse);
begin
// Descendent implements
Assert(False);
end;
function TBaseImageProducer.GetScriptObject: IDispatch;
begin
Result := ImplGetScriptObject;
end;
function TBaseImageProducer.ImplGetScriptObject: IDispatch;
begin
Result := TImageProducerWrapper.Create(Self);
end;
function TBaseImageProducer.GetAdapterImage(Sender: TComponent; const ACaption: WideString): IInterface;
begin
Result := TImageObject.Create(Self, Sender, ACaption);
end;
function ComponentDisabled(AComponent: TComponent): Boolean;
var
WebEnabled: IWebEnabled;
begin
if Supports(AComponent, IWebEnabled, WebEnabled) then
Result := not WebEnabled.WebEnabled
else
Result := False;
end;
{ TBaseImageButtonProducer }
constructor TBaseImageButtonProducer.Create(AOwner: TComponent);
begin
inherited;
FAttributes := TImageButtonAttributes.Create;
Width := 75;
Height := 25;
Color := $00CCCCCC;
TopLeftColor := clWhite;
BottomRightColor := clGray;
FocusColor := clYellow;
end;
destructor TBaseImageButtonProducer.Destroy;
begin
FAttributes.Free;
inherited;
end;
function TBaseImageButtonProducer.GetColor: TColor;
begin
Result := FAttributes.Color;
end;
function TBaseImageButtonProducer.GetTopLeftColor: TColor;
begin
Result := FAttributes.TopLeftColor;
end;
function TBaseImageButtonProducer.GetBottomRightColor: TColor;
begin
Result := FAttributes.BottomRightColor;
end;
function TBaseImageButtonProducer.GetFocusColor: TColor;
begin
Result := FAttributes.FocusColor;
end;
function TBaseImageButtonProducer.GetFont: TFont;
begin
Result := FAttributes.Font;
end;
function TBaseImageButtonProducer.GetHeight: Integer;
begin
Result := FAttributes.Height;
end;
function TBaseImageButtonProducer.GetWidth: Integer;
begin
Result := FAttributes.Width;
end;
(* jmt!!!
function TBaseImageButtonProducer.PropertiesAsStrings(const ACaption: WideString; ADisabled: Boolean;
AEvent: TImageEvent): TStrings;
procedure AddStringValue(const AName, AValue: string);
begin
if AValue <> '' then
Result.Add(Format('%s=%s', [AName, AValue]));
end;
procedure AddIntValue(const AName: string; AValue: Integer);
begin
if AValue > 0 then
AddStringValue(AName, IntToStr(AValue));
end;
begin
Result := TStringList.Create;
try
if ADisabled then
AddStringValue(sFontColor, ColorToString(clGrayText));
AddStringValue(sTxt, ACaption);
AddIntValue(sWidth, Width);
AddIntValue(sHeight, Height);
AddStringValue(sColor, ColorToString(Color));
AddStringValue(sFontColor, ColorToString(Font.Color));
AddStringValue(sFontName, Font.Name);
AddIntValue(sFontSize, Font.Size);
if not ADisabled then
case AEvent of
evNone, evOut: ;
evOver, evDown: AddStringValue(sUp, '0');
end;
except
Result.Free;
raise;
end;
end;
*)
function TBaseImageButtonProducer.PropertiesAsStrings(const ACaption: WideString; ADisabled: Boolean;
AEvent: TImageEvent): TStrings;
procedure AddStringValue(const AName, AValue: string);
begin
if AValue <> '' then
Result.Add(Format('%s=%s', [AName, AValue]));
end;
procedure AddIntValue(const AName: string; AValue: Integer);
begin
if AValue > 0 then
AddStringValue(AName, IntToStr(AValue));
end;
begin
Result := TStringList.Create;
try
if ADisabled then
AddStringValue(sFontColor, ColorToString(clGrayText));
AddStringValue(sTxt, ACaption);
AddIntValue(sWidth, Width);
AddIntValue(sHeight, Height);
AddStringValue(sColor, ColorToString(Color));
AddStringValue(sTLColor, ColorToString(TopLeftColor));
AddStringValue(sBRColor, ColorToString(BottomRightColor));
AddStringValue(sFocusColor, ColorToString(FocusColor));
AddStringValue(sFontColor, ColorToString(Font.Color));
AddStringValue(sFontName, Font.Name);
AddIntValue(sFontSize, Font.Size);
AddStringValue(sFontBold, IntToStr(Integer(fsBold in Font.Style)));
AddStringValue(sFontItalic, IntToStr(Integer(fsItalic in Font.Style)));
AddStringValue(sFontUnderline, IntToStr(Integer(fsUnderline in Font.Style)));
AddStringValue(sFontStrikeOut, IntToStr(Integer(fsStrikeout in Font.Style)));
case AEvent of
evNone, evOut, evOver: AddStringValue(sUp, '1');
evDown: AddStringValue(sUp, '0');
end;
if AEvent = evOver then
AddStringValue(sFocused, '1')
else
AddStringValue(sFocused, '0');
if ADisabled then
AddStringValue(sEnabled, '0')
else
AddStringValue(sEnabled, '1')
except
Result.Free;
raise;
end;
end;
function TBaseImageProducer.GetAdapterEventImage(Sender: TComponent;
const AEvent, ACaption: WideString): IInterface;
begin
Result := TImageObject.Create(Self, Sender, ACaption, AEvent);
end;
function TBaseImageProducer.GetDisplayStyle(Sender: TComponent): string;
begin
Result := AdapterActionHTMLElementTypeNames[htmlaEventImages];
end;
{ TCustomImageButtonProducer }
constructor TCustomImageButtonProducer.Create(AOwner: TComponent);
begin
inherited;
CacheDir := '';
VirtualDir := '/images';
FLastAttributes := TImageButtonAttributes.Create;
FFileLifeTime := TFileLifeTime.Create;
end;
destructor TCustomImageButtonProducer.Destroy;
begin
FLastAttributes.Free;
FFileLifeTime.Free;
inherited;
end;
function TCustomImageButtonProducer.MakeFileName(
AComponent: TComponent; AEvent: TImageEvent): string;
var
FileID: string;
WebVariableName: IWebVariableName;
IteratorIndex: IIteratorIndex;
begin
if csDesigning in ComponentState then
FileID := '-' + FComponentImageFileList[Self].FileID;
Result := CacheDir;
if Result <> '' then
if not IsPathDelimiter(Result, Length(Result)) then
Result := Result + PathDelim;
if Supports(IUnknown(AComponent), IWebVariableName, WebVariableName) then
Result := Result + WebVariableName.VariableName;
if Supports(IUnknown(AComponent), IIteratorIndex, IteratorIndex)
and IteratorIndex.InIterator then
Result := Result + '-' + IntToStr(IteratorIndex.IteratorIndex);
if ComponentDisabled(AComponent) then
Result := Result + '-Disabled'
else if ImageEventNames[AEvent] <> '' then
Result := Result + '-' + ImageEventNames[AEvent];
Result := Result + FileID + '.jpg';
// Fully qualify file name
if DesignerFileManager <> nil then
Result := DesignerFileManager.QualifyFileName(Result)
else
Result := QualifyFileName(Result);
end;
procedure TCustomImageButtonProducer.CreateImageFile(const AFileName: string; AComponent: TComponent;
const ACaption: WideString; AEvent: TImageEvent);
var
MimeType: string;
S: TStream;
P: TStrings;
F: TFileStream;
begin
P := PropertiesAsStrings(ACaption, ComponentDisabled(AComponent), AEvent);
try
S := DrawButton(P, MimeType);
try
F := TFileStream.Create(AFileName, fmCreate);
try
if F <> nil then
F.CopyFrom(S, 0);
finally
F.Free;
end;
FComponentImageFileList[Self].AddFile(AFileName, ACaption);
finally
S.Free;
end;
finally
P.Free;
end;
end;
function TCustomImageButtonProducer.FileHasExpired(const AFileName: string): Boolean;
begin
Result := False;
if not (csDesigning in ComponentState) then
if FileExists(AFileName) then
Result := FileLifeTime.TimeHasExpired(FileDateToDateTime(FileAge(AFileName)));
end;
function TCustomImageButtonProducer.WebImageHREF(
AComponent: TComponent; const ACaption: WideString; AEvent: TImageEvent): string;
function MakeURI(const AFileName: string): string;
var
I: Integer;
begin
Result := AFileName;
for I := 1 to Length(Result) do
if IsPathDelimiter(AFileName, I) then
Result[I] := '/';
end;
var
FileName: string;
Exists: Boolean;
begin
if csDesigning in ComponentState then
if not FAttributes.IsEqual(FLastAttributes) then
begin
FComponentImageFileList[Self].ClearCache;
FLastAttributes.CopyFrom(FAttributes);
end;
FileName := MakeFileName(AComponent, AEvent);
Exists := FileExists(FileName) and not FileHasExpired(FileName);
if Exists then
begin
if FComponentImageFileList[Self].CaptionChanged(FileName, ACaption) then
begin
if csDesigning in ComponentState then
begin
FComponentImageFileList[Self].ClearCache;
FileName := MakeFileName(AComponent, AEvent);
end;
Exists := False;
end;
end;
if not Exists then
CreateImageFile(FileName, AComponent, ACaption, AEvent);
if csDesigning in ComponentState then
Result := MakeURI(FileName)
else
if WebContext <> nil then
Result := PathInfoToRelativePath(WebContext.Request.InternalPathInfo) +
VirtualDir + '/' + ExtractFileName(FileName);
end;
procedure TCustomImageButtonProducer.SetFileLifeTime(
const Value: TFileLifeTime);
begin
FFileLifeTime.Assign(Value);
end;
{ TImageButtonAttributes }
procedure TImageButtonAttributes.CopyFrom(
const AAttributes: TImageButtonAttributes);
begin
FHeight := AAttributes.FHeight;
FWidth := AAttributes.FWidth;
FColor := AAttributes.FColor;
Font := AAttributes.FFont;
FTopLeftColor := AAttributes.FTopLeftColor;
FBottomRightColor := AAttributes.FBottomRightColor;
FFocusColor := AAttributes.FFocusColor;
FFont.Style := AAttributes.FFont.Style;
end;
constructor TImageButtonAttributes.Create;
begin
inherited;
FFont := TFont.Create;
end;
destructor TImageButtonAttributes.Destroy;
begin
FFont.Free;
end;
function TImageButtonAttributes.IsEqual(
const AAttributes: TImageButtonAttributes): Boolean;
begin
Result :=
(FHeight = AAttributes.FHeight) and
(FWidth = AAttributes.FWidth) and
(FColor = AAttributes.FColor) and
(FFont.Color = AAttributes.FFont.Color) and
(FFont.Size = AAttributes.FFont.Size) and
(FTopLeftColor = AAttributes.FTopLeftColor) and
(FBottomRightColor = AAttributes.FBottomRightColor) and
(FFocusColor = AAttributes.FFocusColor) and
(FFont.Style = AAttributes.FFont.Style) and
(FFont.Name = AAttributes.FFont.Name);
end;
procedure TBaseImageButtonProducer.SetTopLeftColor(const Value: TColor);
begin
FAttributes.TopLeftColor := Value;
end;
procedure TBaseImageButtonProducer.SetBottomRightColor(const Value: TColor);
begin
FAttributes.BottomRightColor := Value;
end;
procedure TBaseImageButtonProducer.SetFocusColor(const Value: TColor);
begin
FAttributes.FocusColor := Value;
end;
procedure TBaseImageButtonProducer.SetColor(const Value: TColor);
begin
FAttributes.Color := Value;
end;
procedure TBaseImageButtonProducer.SetFont(const Value: TFont);
begin
FAttributes.Font := Value;
end;
procedure TBaseImageButtonProducer.SetHeight(const Value: Integer);
begin
FAttributes.Height := Value;
end;
procedure TBaseImageButtonProducer.SetWidth(const Value: Integer);
begin
FAttributes.Width := Value;
end;
procedure TImageButtonAttributes.SetFont(const Value: TFont);
begin
FFont.Assign(Value);
end;
{ TImageFileList }
procedure TImageFileList.AddFile(const AFileName, ACaption: string);
var
I: Integer;
begin
Lock;
try
I := FFileNames.IndexOf(AFileName);
if I >= 0 then
begin
FFileNames[I] := AFileName;
FCaptions[I] := ACaption;
end
else
begin
FFileNames.Add(AFileName);
FCaptions.Add(ACaption);
end;
finally
Unlock;
end;
end;
procedure TImageFileList.ClearCache;
var
I: Integer;
begin
Lock;
try
for I := 0 to FFileNames.Count - 1 do
SysUtils.DeleteFile(FFileNames[I]);
FFileNames.Clear;
FCaptions.Clear;
FFileID := FComponentImageFileList.NextFileID;
finally
Unlock;
end;
end;
constructor TImageFileList.Create(AComponentImageFileList: TComponentImageFileList;
AClearCache: Boolean);
begin
FClearCache := AClearCache;
FComponentImageFileList := AComponentImageFileList;
FFileNames := TStringList.Create;
FCaptions := TStringList.Create;
end;
destructor TImageFileList.Destroy;
begin
if FClearCache then
ClearCache;
FCaptions.Free;
FFileNames.Free;
inherited;
end;
procedure TImageFileList.Lock;
begin
FComponentImageFileList.Lock;
end;
procedure TImageFileList.Unlock;
begin
FComponentImageFileList.Unlock;
end;
function TImageFileList.GetFileID: string;
var
I: Integer;
begin
Lock;
try
I := FFileID;
finally
Unlock;
end;
Result := IntToStr(I);
end;
function TImageFileList.CaptionChanged(const AFileName,
ACaption: string): Boolean;
var
I: Integer;
begin
Lock;
try
I := FFileNames.IndexOf(AFileName);
Result := (I >= 0) and (CompareText(FCaptions[I], ACaption) <> 0);
finally
Unlock;
end;
end;
{ TComponentImageFileList }
constructor TComponentImageFileList.Create;
begin
FFileLists := TObjectList.Create(True {Owned});
FComponentNames := TStringList.Create;
FLock := TCriticalSection.Create;
FFileID := GetTickCount;
end;
destructor TComponentImageFileList.Destroy;
begin
FFileLists.Free;
FComponentNames.Free;
FLock.Free;
inherited;
end;
function TComponentImageFileList.GetComponentName(AComponent: TComponent): string;
begin
Result := AComponent.Name;
end;
function TComponentImageFileList.GetImageFileList(
AComponent: TComponent): TImageFileList;
var
I: Integer;
S: string;
begin
S := GetComponentName(AComponent);
Lock;
try
I := FComponentNames.IndexOf(S);
if I >= 0 then
Result := TImageFileList(FFileLists[I])
else
begin
Result := TImageFileList.Create(Self, csDesigning in AComponent.ComponentState);
FFileLists.Add(Result);
FComponentNames.Add(S);
end;
finally
Unlock;
end;
end;
procedure TComponentImageFileList.Lock;
begin
FLock.Enter;
end;
function TComponentImageFileList.NextFileID: Integer;
begin
Inc(FFileID);
Result := FFileID;
end;
procedure TComponentImageFileList.Unlock;
begin
FLock.Leave;
end;
{ TFileLifeTime }
procedure TFileLifeTime.Assign(Source: TPersistent);
begin
if Source is TFileLifeTime then
begin
Days := TFileLifeTime(Source).Days;
Minutes := TFileLifeTime(Source).Minutes;
end;
inherited Assign(Source);
end;
constructor TFileLifeTime.Create;
begin
inherited;
FMinutes := 1;
end;
function TFileLifeTime.TimeHasExpired(ADateTime: TDateTime): Boolean;
begin
Result := False;
if (Minutes <> 0) or (Days <> 0) then
begin
ADateTime := IncMinute(ADateTime, Minutes);
ADateTime := IncDay(ADateTime, Days);
Result := ADateTime < Now;
end;
end;
initialization
FComponentImageFileList := TComponentImageFileList.Create;
finalization
FreeAndNil(FComponentImageFileList);
end.
|
unit UDaoFuncionario;
interface
uses uDao, DB, SysUtils, Messages, UFuncionario, UEndereco, UDaoCidade,
UDaoCargo, UUsuario;
type DaoFuncionario = class(Dao)
private
protected
umFuncionario : Funcionario;
umEndereco : Endereco;
umaDaoCidade : DaoCidade;
umCargo : DaoCargo;
umUsuario : Usuario;
public
Constructor CrieObjeto;
Destructor Destrua_se;
function Salvar(obj:TObject): string; override;
function GetDS : TDataSource; override;
function Carrega(obj:TObject): TObject; override;
function Buscar(obj : TObject) : Boolean; override;
function Excluir(obj : TObject) : string ; override;
function VefiricaCPF(obj : TObject) : Boolean;
procedure AtualizaGrid;
procedure Ordena(campo: string);
end;
implementation
uses UDaoUsuario, UAplicacao;
var umaDaoUsuario : DaoUsuario;
{ DaoFuncionario }
function DaoFuncionario.Buscar(obj: TObject): Boolean;
var
prim: Boolean;
sql, e, onde: string;
umFuncionario: Funcionario;
begin
e := ' and ';
onde := ' where';
prim := true;
umFuncionario := Funcionario(obj);
sql := 'select * from funcionario';
if umFuncionario.getId <> 0 then
begin
if prim then //SE FOR O PRIMEIRO, SETA COMO FLAG COMO FALSO PQ É O PRIMEIRO
begin
prim := false;
sql := sql+onde;
end
else //SE NAO, COLOCA CLAUSULA AND PARA JUNTAR CONDIÇOES
sql := sql+e;
sql := sql+' idfuncionario = '+inttostr(umFuncionario.getId); //COLOCA CONDIÇAO NO SQL
end;
if umFuncionario.getNome_RazaoSoCial <> '' then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end
else
sql := sql+e;
sql := sql+' nome like '+quotedstr('%'+umFuncionario.getNome_RazaoSoCial+'%');
end;
if umFuncionario.getCPF_CNPJ <> '' then
begin
if prim then
begin
prim := false;
sql := sql+onde;
end
else
sql := sql+e;
sql := sql+' cpf = '''+umFuncionario.getCPF_CNPJ+'''';
end;
with umDM do
begin
QFuncionario.Close;
QFuncionario.sql.Text := sql+' order by idfuncionario';
QFuncionario.Open;
if QFuncionario.RecordCount > 0 then
result := True
else
result := false;
end;
end;
procedure DaoFuncionario.AtualizaGrid;
begin
with umDM do
begin
QFuncionario.Close;
QFuncionario.sql.Text := 'select * from funcionario order by idfuncionario';
QFuncionario.Open;
end;
end;
function DaoFuncionario.VefiricaCPF(obj: TObject): Boolean;
var sql : string;
umFuncionario : Funcionario;
begin
umFuncionario := Funcionario(obj);
sql := 'select * from funcionario where cpf = '''+umFuncionario.getCPF_CNPJ+''' and datademissao IS NULL';
with umDM do
begin
QFuncionario.Close;
QFuncionario.sql.Text := sql+' order by idfuncionario';
QFuncionario.Open;
if QFuncionario.RecordCount > 0 then
result := True
else
result := false;
end;
end;
function DaoFuncionario.Carrega(obj: TObject): TObject;
var
umFuncionario : Funcionario;
umEndereco : Endereco;
begin
umFuncionario := Funcionario(obj);
umEndereco := Endereco.CrieObjeto;
with umDM do
begin
if not QFuncionario.Active then
QFuncionario.Open;
if umFuncionario.getId <> 0 then
begin
QFuncionario.Close;
QFuncionario.SQL.Text := 'select * from funcionario where idfuncionario = '+IntToStr(umFuncionario.getId);
QFuncionario.Open;
end;
umFuncionario.setId(QFuncionarioidfuncionario.AsInteger);
umFuncionario.setNome_RazaoSoCial(QFuncionarionome.AsString);
//Endereço
umEndereco.setLogradouro(QFuncionariologradouro.AsString);
umEndereco.setNumero(QFuncionarionumero.AsString);
umEndereco.setCEP(QFuncionariocep.AsString);
umEndereco.setBairro(QFuncionariobairro.AsString);
umEndereco.setComplemento(QFuncionariocomplemento.AsString);
umFuncionario.setumEndereco(umEndereco);
umFuncionario.setEmail(QFuncionarioemail.AsString);
umFuncionario.setTelefone(QFuncionariotelefone.AsString);
umFuncionario.setCelular(QFuncionariocelular.AsString);
umFuncionario.setCPF_CNPJ(QFuncionariocpf.AsString);
umFuncionario.setRG_IE(QFuncionariorg.AsString);
umFuncionario.setCTPS(QFuncionarioctps.AsString);
umFuncionario.setCNH(QFuncionariocnh.AsString);
umFuncionario.setDataAdmissao(QFuncionariodataadmissao.AsDateTime);
umFuncionario.setDataDemissao(QFuncionariodatademissao.AsDateTime);
umFuncionario.setDataVencimento(QFuncionariodatavencimento.AsDateTime);
umFuncionario.setDataNasc_Fund(QFuncionariodatanascimento.AsDateTime);
umFuncionario.setDataCadastro(QFuncionariodatacadastro.AsDateTime);
umFuncionario.setDataUltAlteracao(QFuncionariodataalteracao.AsDateTime);
umFuncionario.setObservacao(QFuncionarioobservacao.AsString);
//Busca a Cidade referente ao Funcionario
umFuncionario.getumEndereco.getumaCidade.setId(QFuncionarioidcidade.AsInteger);
umaDaoCidade.Carrega(umFuncionario.getumEndereco.getumaCidade);
//Busca o Cargo referente ao Funcionario
umFuncionario.getUmCargo.setId(QFuncionarioidcargo.AsInteger);
umCargo.Carrega(umFuncionario.getUmCargo);
end;
result := umFuncionario;
Self.AtualizaGrid;
end;
constructor DaoFuncionario.CrieObjeto;
begin
inherited;
umaDaoCidade := DaoCidade.CrieObjeto;
umCargo := DaoCargo.CrieObjeto;
end;
destructor DaoFuncionario.Destrua_se;
begin
inherited;
end;
function DaoFuncionario.Excluir(obj: TObject): string;
var
umFuncionario: Funcionario;
begin
umFuncionario := Funcionario(obj);
with umDM do
begin
try
beginTrans;
QFuncionario.SQL := UpdateFuncionario.DeleteSQL;
QFuncionario.Params.ParamByName('OLD_idfuncionario').Value := umFuncionario.getId;
QFuncionario.ExecSQL;
Commit;
result := 'Funcionario excluído com sucesso!';
except
on e:Exception do
begin
rollback;
if pos('violates foreign key',e.Message)>0 then
result := 'Ocorreu um erro! O Funcionario não pode ser excluído pois ja está sendo usado pelo sistema.'
else
result := 'Ocorreu um erro! Funcionario não foi excluído. Erro: '+e.Message;
end;
end;
end;
Self.AtualizaGrid;
end;
function DaoFuncionario.GetDS: TDataSource;
begin
umDM.QFuncionario.FieldByName('nome').DisplayWidth := 60;
umDM.QFuncionario.FieldByName('logradouro').DisplayWidth := 60;
Self.AtualizaGrid;
result := umDM.DSFuncionario;
end;
procedure DaoFuncionario.Ordena(campo: string);
begin
umDM.QFuncionario.IndexFieldNames := campo;
end;
function DaoFuncionario.Salvar(obj: TObject): string;
var
umFuncionario : Funcionario;
begin
umFuncionario := Funcionario(obj);
with umDM do
begin
try
beginTrans;
QFuncionario.Close;
if (idLogado = umFuncionario.getId) then
nomeLogado := umFuncionario.getNome_RazaoSoCial;
if umFuncionario.getId = 0 then
begin
if (Self.Buscar(umFuncionario)) then
begin
Result := 'Já existe um funcionário com esse CPF cadastrado!';
Self.AtualizaGrid;
Exit;
end;
QFuncionario.SQL := UpdateFuncionario.InsertSQL
end
else
begin
if (not Self.Buscar(umFuncionario)) and (not umFuncionario.verificaNome) then
begin
if (not Self.VefiricaCPF(umFuncionario)) then
begin
QFuncionario.SQL := UpdateFuncionario.ModifySQL;
QFuncionario.Params.ParamByName('OLD_idfuncionario').Value := umFuncionario.getId;
end
else
begin
Result := 'Já existe um funcionário com esse CPF cadastrado!';
Self.AtualizaGrid;
Exit;
end;
end
else
begin
QFuncionario.SQL := UpdateFuncionario.ModifySQL;
QFuncionario.Params.ParamByName('OLD_idfuncionario').Value := umFuncionario.getId;
end;
end;
QFuncionario.Params.ParamByName('nome').Value := umFuncionario.getNome_RazaoSoCial;
QFuncionario.Params.ParamByName('logradouro').Value := umFuncionario.getumEndereco.getLogradouro;
QFuncionario.Params.ParamByName('numero').Value := umFuncionario.getumEndereco.getNumero;
QFuncionario.Params.ParamByName('cep').Value := umFuncionario.getumEndereco.getCEP;
QFuncionario.Params.ParamByName('bairro').Value := umFuncionario.getumEndereco.getBairro;
QFuncionario.Params.ParamByName('complemento').Value := umFuncionario.getumEndereco.getComplemento;
QFuncionario.Params.ParamByName('idcidade').Value := umFuncionario.getumEndereco.getumaCidade.getId;
QFuncionario.Params.ParamByName('email').Value := umFuncionario.getEmail;
QFuncionario.Params.ParamByName('telefone').Value := umFuncionario.getTelefone;
QFuncionario.Params.ParamByName('celular').Value := umFuncionario.getCelular;
QFuncionario.Params.ParamByName('cpf').Value := umFuncionario.getCPF_CNPJ;
QFuncionario.Params.ParamByName('rg').Value := umFuncionario.getRG_IE;
QFuncionario.Params.ParamByName('ctps').Value := umFuncionario.getCTPS;
QFuncionario.Params.ParamByName('cnh').Value := umFuncionario.getCNH;
if umFuncionario.getDataVencimento <> StrToDateTime('30/12/1899') then
QFuncionario.Params.ParamByName('datavencimento').Value := umFuncionario.getDataVencimento;
if umFuncionario.getDataAdmissao <> StrToDateTime('30/12/1899') then
QFuncionario.Params.ParamByName('dataadmissao').Value := umFuncionario.getDataAdmissao;
if umFuncionario.getDataDemissao <> StrToDateTime('30/12/1899') then
begin
QFuncionario.Params.ParamByName('datademissao').Value := umFuncionario.getDataDemissao;
if umFuncionario.getId <> 0 then
begin
umaDaoUsuario := DaoUsuario.CrieObjeto;
umUsuario := Usuario.CrieObjeto;
umaDaoUsuario.BuscarFuncionario(umFuncionario.getId);
umaDaoUsuario.CarregaUsuario(umUsuario);
umUsuario.getUmFuncionario.setId(umFuncionario.getId);
umUsuario.setStatus('BLOQUEADO');
umaDaoUsuario.Salvar(umUsuario);
end;
end;
QFuncionario.Params.ParamByName('idcargo').Value := umFuncionario.getUmCargo.getId;
QFuncionario.Params.ParamByName('datanascimento').Value := umFuncionario.getDataNasc_Fund;
QFuncionario.Params.ParamByName('datacadastro').Value := umFuncionario.getDataCadastro;
QFuncionario.Params.ParamByName('dataalteracao').Value := umFuncionario.getDataUltAlteracao;
QFuncionario.Params.ParamByName('observacao').Value := umFuncionario.getObservacao;
QFuncionario.ExecSQL;
Commit;
result := 'Funcionário salvo com sucesso!';
except
on e: Exception do
begin
rollback;
Result := 'Ocorreu um erro! Funcionário não foi salvo. Erro: '+e.Message;
end;
end;
end;
Self.AtualizaGrid;
end;
end.
|
unit GR32_TestGuiPngDisplay;
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1 or LGPL 2.1 with linking exception
*
* 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.
*
* Alternatively, the contents of this file may be used under the terms of the
* Free Pascal modified version of the GNU Lesser General Public License
* Version 2.1 (the "FPC modified LGPL License"), in which case the provisions
* of this license are applicable instead of those above.
* Please see the file LICENSE.txt for additional information concerning this
* license.
*
* The Original Code is Graphics32
*
* The Initial Developer of the Original Code is
* Christian-W. Budde
*
* Portions created by the Initial Developer are Copyright (C) 2000-2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
interface
uses
{$IFDEF FPC} LCLIntf, {$ELSE} Windows, Messages, {$ENDIF}
SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
GR32, GR32_Image;
type
TFmDisplay = class(TForm)
BtNo: TButton;
BtYes: TButton;
Image32: TImage32;
LbQuestion: TLabel;
LbRenderer: TLabel;
RbInternal: TRadioButton;
RbPngImage: TRadioButton;
procedure FormShow(Sender: TObject);
procedure RbInternalClick(Sender: TObject);
procedure RbPngImageClick(Sender: TObject);
private
FReference : TBitmap32;
FInternal : TBitmap32;
procedure ClearImage32;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Reference: TBitmap32 read FReference write FReference;
property Internal: TBitmap32 read FInternal write FInternal;
end;
var
FmDisplay: TFmDisplay;
implementation
{$IFDEF FPC}
{$R *.lfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
constructor TFmDisplay.Create(AOwner: TComponent);
begin
inherited;
FInternal := TBitmap32.Create;
FInternal.DrawMode := dmBlend;
FReference := TBitmap32.Create;
FReference.DrawMode := dmBlend;
end;
destructor TFmDisplay.Destroy;
begin
FreeAndNil(FInternal);
FreeAndNil(FReference);
inherited;
end;
procedure TFmDisplay.FormShow(Sender: TObject);
begin
RbInternal.Checked := True;
RbInternalClick(Sender);
end;
procedure TFmDisplay.ClearImage32;
const
Colors: array [Boolean] of TColor32 = ($FFFFFFFF, $FFB0B0B0);
var
R: TRect;
I, J: Integer;
OddY: Integer;
TilesHorz, TilesVert: Integer;
TileX, TileY: Integer;
TileHeight, TileWidth: Integer;
begin
Image32.Bitmap.Clear($FFFFFFFF);
TileHeight := 8;
TileWidth := 8;
R := Image32.ClientRect;
TilesHorz := (R.Right - R.Left) div TileWidth;
TilesVert := (R.Bottom - R.Top) div TileHeight;
TileY := 0;
for J := 0 to TilesVert do
begin
TileX := 0;
OddY := J and $1;
for I := 0 to TilesHorz do
begin
Image32.Bitmap.FillRectS(TileX, TileY, TileX + TileWidth, TileY + TileHeight, Colors[I and $1 = OddY]);
Inc(TileX, TileWidth);
end;
Inc(TileY, TileHeight);
end
end;
procedure TFmDisplay.RbInternalClick(Sender: TObject);
begin
with Image32 do
begin
ClearImage32;
Bitmap.Draw(0, 0, FInternal);
end;
end;
procedure TFmDisplay.RbPngImageClick(Sender: TObject);
begin
with Image32 do
begin
ClearImage32;
Bitmap.Draw(0, 0, FReference);
end;
end;
end.
|
unit Sequence;
interface
type
TSequence = class(TObject)
private
protected
FValue: Integer;
public
constructor Create(StartValue: Integer = 0);
function NextValue: Integer; virtual;
property Value: Integer read FValue write FValue;
end;
implementation
constructor TSequence.Create(StartValue: Integer = 0);
begin
inherited Create;
FValue := StartValue;
end;
function TSequence.NextValue: Integer;
begin
Inc(FValue);
Result := FValue;
end;
end.
|
unit Initializer.Locale;
interface
uses
Forms, SysUtils, StdCtrls, ExtCtrls, Windows, Classes, Graphics, Controls,
Global.LanguageString;
procedure ApplyLocaleToMainformAndArrangeButton;
implementation
uses Form.Main;
type
THackControl = class(TControl);
THackMainForm = class(TfMain);
TLocaleApplier = class
public
constructor Create(MainformToApply: TfMain);
procedure ApplyLocale;
private
Mainform: THackMainForm;
procedure ApplyLocaleToTrim;
procedure ApplyLocaleToAnalytics;
procedure ApplyLocaleToErase;
procedure ApplyLocaleToFirmware;
procedure ApplyLocaleToSemiautoTrim;
procedure ApplyLocaleToDownloader;
procedure ApplyLocaleToHelp;
procedure ApplyLocaleToOptimizer;
procedure ApplyLocaleToSSDSelector;
procedure ArrangeButton(ImageToFit: TImage; LabelToArrange: TLabel);
procedure ArrangeButtonsInMain;
end;
procedure ApplyLocaleToMainformAndArrangeButton;
var
LocaleApplier: TLocaleApplier;
begin
LocaleApplier := TLocaleApplier.Create(fMain);
LocaleApplier.ApplyLocale;
LocaleApplier.ArrangeButtonsInMain;
FreeAndNil(LocaleApplier);
end;
constructor TLocaleApplier.Create(MainformToApply: TfMain);
begin
Mainform := THackMainForm(MainformToApply);
end;
procedure TLocaleApplier.ApplyLocale;
begin
ApplyLocaleToFirmware;
ApplyLocaleToErase;
ApplyLocaleToOptimizer;
ApplyLocaleToAnalytics;
ApplyLocaleToTrim;
ApplyLocaleToSemiautoTrim;
ApplyLocaleToDownloader;
ApplyLocaleToHelp;
ApplyLocaleToSSDSelector;
ArrangeButtonsInMain;
end;
procedure TLocaleApplier.ApplyLocaleToFirmware;
begin
Mainform.lFirmUp.Caption := BtFirmware[CurrLang];
Mainform.lUpdate.Caption := CapFirm[CurrLang];
Mainform.lUSB.Caption := CapSelUSB[CurrLang];
Mainform.lNewFirm.Caption := CapNewFirm[CurrLang];
Mainform.cAgree.Caption := CapWarnErase[CurrLang];
Mainform.bFirmStart.Caption := BtDoUpdate[CurrLang];
end;
procedure TLocaleApplier.ApplyLocaleToErase;
begin
Mainform.lErase.Caption := BtErase[CurrLang];
Mainform.lEraseUSB.Caption := CapErase[CurrLang];
Mainform.lUSBErase.Caption := CapSelUSB[CurrLang];
Mainform.cEraseAgree.Caption := CapWarnErase[CurrLang];
Mainform.bEraseUSBStart.Caption := BtDoErase[CurrLang];
end;
procedure TLocaleApplier.ApplyLocaleToOptimizer;
begin
Mainform.lOptimize.Caption := BtOpt[CurrLang];
Mainform.lNameOpt.Caption := CapNameOpt[CurrLang];
Mainform.bStart.Caption := BtDoOpt[CurrLang];
Mainform.bRtn.Caption := BtRollback[CurrLang];
end;
procedure TLocaleApplier.ApplyLocaleToAnalytics;
begin
Mainform.lAnalytics.Caption := BtAnaly[CurrLang];
Mainform.lAnaly.Caption := CapAnaly[CurrLang];
end;
procedure TLocaleApplier.ApplyLocaleToTrim;
begin
Mainform.lTrim.Caption := BtTrim[CurrLang];
Mainform.lTrimName.Caption := CapTrimName[CurrLang];
Mainform.bTrimStart.Caption := CapStartManTrim[CurrLang];
Mainform.bSchedule.Caption := BtSemiAutoTrim[CurrLang];
end;
procedure TLocaleApplier.ApplyLocaleToSemiautoTrim;
begin
Mainform.lSchName.Caption := CapSemiAutoTrim[CurrLang];
Mainform.lSchExp.Caption := CapSemiAutoTrimExp[CurrLang];
Mainform.cTrimRunning.Caption := ChkSemiAutoTrim[CurrLang];
Mainform.bReturn.Caption := BtRtn[CurrLang];
end;
procedure TLocaleApplier.ApplyLocaleToSSDSelector;
begin
Mainform.SSDSelLbl.Caption := CapSSDSelOpn[CurrLang];
end;
procedure TLocaleApplier.ApplyLocaleToDownloader;
begin
Mainform.bCancel.Caption := BtDnldCncl[CurrLang];
end;
procedure TLocaleApplier.ApplyLocaleToHelp;
begin
Mainform.lHelp.Caption := BtHelp[CurrLang];
end;
procedure TLocaleApplier.ArrangeButton
(ImageToFit: TImage; LabelToArrange: TLabel);
begin
LabelToArrange.left :=
ImageToFit.Left + (ImageToFit.Width div 2) - (LabelToArrange.Width div 2);
end;
procedure TLocaleApplier.ArrangeButtonsInMain;
begin
ArrangeButton(Mainform.iFirmUp, Mainform.lFirmUp);
ArrangeButton(Mainform.iErase, Mainform.lErase);
ArrangeButton(Mainform.iOptimize, Mainform.lOptimize);
ArrangeButton(Mainform.iAnalytics, Mainform.lAnalytics);
ArrangeButton(Mainform.iHelp, Mainform.lHelp);
ArrangeButton(Mainform.iTrim, Mainform.lTrim);
end;
end.
|
unit WiseStatusLine;
interface
uses Classes, Dialogs, StdCtrls, ExtCtrls, DateUtils, Graphics, SysUtils;
type TWiseStatusLine = class(TLabel)
private
timer: TTimer;
expiration: TDateTime;
public
constructor Create(owner: TComponent); override;
procedure Show(msg: string; millis: integer = -1; color: TColor = clWindowText);
procedure Clear();
procedure OnTimer(Sender: TObject);
end;
implementation
procedure TWiseStatusLine.OnTimer(Sender: TObject);
begin
if CompareTime(Now, Self.expiration) = 1 then
Self.Clear;
end;
constructor TWiseStatusLine.Create(owner: TComponent);
begin
inherited Create(owner);
Self.timer := TTimer.Create(nil);
Self.timer.Interval := 100;
Self.timer.OnTimer := OnTimer;
end;
procedure TWiseStatusLine.Show(msg: string; millis: integer = -1; color: TColor = clWindowText);
begin
Self.Font.Color := color;
Self.Caption := msg;
if millis = -1 then
Self.expiration := IncYear(Now, 1)
else
Self.expiration := IncMilliSecond(Time(), millis);
end;
procedure TWiseStatusLine.Clear();
begin
Self.Caption := '';
end;
end.
|
unit SecurityData;
interface
uses
System.SysUtils, System.Classes, 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, Data.Win.ADODB;
type
TdmSecurity = class(TDataModule)
dscUser: TDataSource;
dscRole: TDataSource;
dstUsers: TADODataSet;
dstRoles: TADODataSet;
dstRoleRights: TADODataSet;
dstRights: TADODataSet;
dstUserRoles: TADODataSet;
dstUsersid_num: TStringField;
dstUsersemployee_lastname: TStringField;
dstUsersemployee_firstname: TStringField;
dstUsersemployee_middlename: TStringField;
dstUsersemployee_name: TStringField;
dstUsersusername: TStringField;
dstUserspassword: TStringField;
dstUsersid_num_1: TStringField;
dstUserscredit_limit: TBCDField;
procedure fdtUserBeforePost(DataSet: TDataSet);
procedure dstUserspasswordGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dmSecurity: TdmSecurity;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
uses
AppData, SecurityUtil;
procedure TdmSecurity.dstUserspasswordGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
Text := '*****';
end;
procedure TdmSecurity.fdtUserBeforePost(DataSet: TDataSet);
begin
// DataSet.FieldByName('PASSKEY').AsString := Encrypt(DataSet.FieldByName('PASSKEY').AsString);
end;
end.
|
unit ufQYesNo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Controls.Presentation, FMX.ListBox, FMX.TabControl, uBusiObj;
const
cTabName = 'TabQYesNo';
cHeaderTitle = 'Sample Survey Question';
cTag = uBusiObj.tnYesNo;
type
TfraQYesNo = class(TFrame)
ToolBar1: TToolBar;
btnCancel: TSpeedButton;
btnDone: TSpeedButton;
lblHeaderTItle: TLabel;
Label1: TLabel;
Layout1: TLayout;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
Label2: TLabel;
Label3: TLabel;
ListBoxGroupFooter1: TListBoxGroupFooter;
Button1: TButton;
procedure btnCancelClick(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FOnNextBtnClick: ^TProc; //<TObject>; -in the future, this should contain the ID of the next question.
FOnCloseTab: ^TProc;
procedure AnimateTrans(AAnimateRule: TAnimateRule);
public
{ Public declarations }
procedure PopuUI;
end;
TTabOfFrame = class(TTabItem)
strict private
FOnNextBtnClick: TProc; //<TObject>;
FOnCloseTab: TProc; //<TObject>;
{
FTabItemState: TTabItemState;
//FOnBackBtnClick: TProc<TObject>;
//FOnDoneBtnClick: TProc<TObject>; // TProc<TObject, TUpdateMade, integer>;
FOnAfterSave: TProc<TUpdateMade, integer>;
FOnAfterDeleted: TProc<TUpdateMade, integer>;
FCarID: integer;
FOnUOMPickList: TProc<TEdit>;
FOnATPickList: TProc<TEdit>;
}
private
// FRecID: integer;
public
FCallerTab: TTabItem;
FFrameMain: TfraQYesNo;
property OnNextBtnClick: TProc read FOnNextBtnClick write FOnNextBtnClick;
property OnCloseTab: TProc read FOnCloseTab write FOnCloseTab;
procedure CloseTab(AIsRelease: Boolean);
constructor Create(AOwner: TComponent); // supply various params here. AReccordID: integer); // ; AUserRequest: TUserRequest
destructor Destroy; override;
procedure ShowTab(ACallerTab: TTabItem); //; AUserRequest: TUserIntentInit; ATID, ACarID: integer);
end;
implementation
{$R *.fmx}
//uses uBusiObj;
{ TfraQYesNo }
procedure TfraQYesNo.AnimateTrans(AAnimateRule: TAnimateRule);
begin
try
if AAnimateRule = uBusiObj.TAnimateRule.arInit then
begin
Layout1.Align := TAlignLayout.None;
Layout1.Position.X := Layout1.Width;
end
else if AAnimateRule = uBusiObj.TAnimateRule.arIn then
begin
//Layout1.Position.X := Layout1.Width;
Layout1.AnimateFloat('Position.X', 0, 0.3, TAnimationType.InOut, TInterpolationType.Linear);
end
else if AAnimateRule = uBusiObj.TAnimateRule.arOut then
begin
// Layout1.Position.X := Layout1.Width;
Layout1.AnimateFloat('Position.X', Layout1.Width, 0.2, TAnimationType.InOut, TInterpolationType.Linear);
end;
finally
if AAnimateRule = uBusiObj.TAnimateRule.arIn then
Layout1.Align := TAlignLayout.Client;
end;
end;
procedure TfraQYesNo.btnCancelClick(Sender: TObject);
begin
TTabOfFrame(Owner).CloseTab(false);
end;
procedure TfraQYesNo.Button1Click(Sender: TObject);
begin
showmessage('Survey data submitted');
// TTabOfFrame(Owner).CloseTab(false);
end;
procedure TfraQYesNo.PopuUI;
begin
// empty
end;
procedure TfraQYesNo.SpeedButton1Click(Sender: TObject);
begin
end;
{ TTabOfFrame }
procedure TTabOfFrame.CloseTab(AIsRelease: Boolean);
begin
TTabControl(Self.Owner).ActiveTab := FCallerTab;
if Assigned(FOnCloseTab) then
FOnCloseTab();
end;
constructor TTabOfFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Name := cTabName;
Tag := Integer(cTag);
// create main frame
FFrameMain := TfraQYesNo.Create(Self);
FFrameMain.Parent := Self;
// FFrameMain.Layout1.Align := TAlignLayout.None;
FFrameMain.Tag := Integer(cTag); //uBusiObj.tnUOMUpd);
// define events
FFrameMain.FOnNextBtnClick := @OnNextBtnClick;
FFrameMain.FOnCloseTab := @OnCloseTab;
{
//FFrameMain.FOnBackBtnClick := @OnBackBtnClick;
//FFrameMain.FOnDoneBtnClick := @OnDoneBtnClick;
FFrameMain.FOnAfterDelete := @OnAfterDelete;
FFrameMain.FOnUOMPickList := @OnUOMPickList;
FFrameMain.FOnATPickList := @OnATPickList;
// create header frame
FFrameHdr := TfraCarHdr.Create(Self);
FFrameHdr.Parent := FFrameMain.Layout1;
//FFrameHdr.FOnHdrEditClick := @OnHdrEditClick;
FFrameHdr.loEdit.Visible := false;
FFrameHdr.lblCarName.Align := TAlignLayout.Contents;
FFrameHdr.lblCarName.Margins.Left := 100;
FFrameHdr.lblCarName.Margins.Top := 0;
}
end;
destructor TTabOfFrame.Destroy;
begin
FFrameMain.Free;
inherited;
end;
procedure TTabOfFrame.ShowTab(ACallerTab: TTabItem);
begin
FCallerTab := ACallerTab;
{
FRecID := ATID;
FCarID := ACarID;
FTabItemState.UserIntentInit := AUserRequest;
FTabItemState.UserIntentCurr := UserIntentInitToCurr(AUserRequest);
}
FFrameMain.AnimateTrans(TAnimateRule.arInit);
TTabControl(Self.Owner).ActiveTab := Self;
// if FTabItemState.UserIntentCurr = uicAdding then
// FFrameMain.edtDescript.SetFocus;
FFrameMain.AnimateTrans(TAnimateRule.arIn);
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 16384,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
September '1999
Problem 41 O(N3) Dfs Method
}
program
DirectingEdges;
const
MaxN = 100;
var
N, E : Integer;
G : array [0 .. MaxN, 1 .. MaxN] of Integer;
M : array[1 .. MaxN] of Boolean;
D : array[1 .. MaxN] of Integer;
I, J, K, L : Integer;
Fl : Boolean;
F : Text;
function Dfs (V : Integer) : Boolean;
var
I : Integer;
begin
M[V] := True;
for I := 1 to N do
if (G[V, I] + G[I, V] = 1) and not M[I] then
if Odd(D[I]) or Dfs(I) then
begin
Dec(D[V], G[V, I]); Dec(D[I], G[I, V]);
G[V, I] := 1 - G[V, I]; G[I, V] := 1 - G[I, V];
Inc(D[V], G[V, I]); Inc(D[I], G[I, V]);
Dfs := True;
Exit;
end;
Dfs := False;
end;
procedure Solve;
begin
repeat
Fl := True;
for I := 1 to N do
if Odd(D[I]) then
Break;
if I < N then
begin
Fl := False;
FillChar(M, SizeOf(M), 0);
Dfs(I);
end;
until Fl;
end;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N, E);
for I := 1 to E do
begin
Readln(F, J, K);
G[J, K] := 1;
Inc(D[J]);
end;
Close(F);
end;
procedure WriteOutput;
begin
Assign(F, 'output.txt');
ReWrite(F);
Writeln(F, N, ' ', E);
for I := 1 to N do
for J := 1 to N do
if G[I, J] > 0 then
Writeln(F, I, ' ', J);
Close(F);
end;
begin
ReadInput;
Solve;
WriteOutput;
end.
|
unit uObjectDrawing;
interface
uses
System.Math,
System.SysUtils,
System.Types,
Vcl.Graphics,
Vcl.Forms,
uMyTypes;
type
TDrawingObject = class(TObject)
private
_zoom: Double;
_backPlane: TBitmap;
_canvasFrontEnd: TCanvas;
_canvasFrontEnd_Height: Integer; // potrebujeme koli prevrateniu Y osi pri kresleni
_drawOffset: TPoint;
_zoomOffset: TPoint;
function PX(valueMM: Double; axis: String = ''): integer;
function MM(valuePX: integer; axis: String = ''): Double;
published
constructor Create(frontCanvas: TCanvas);
property CanvasHeight: Integer read _canvasFrontEnd_Height write _canvasFrontEnd_Height;
procedure Init(farba: TColor);
procedure Line(zaciatok, koniec: TMyPoint; farba: TColor = clWhite; hrubka: Double = 0);
procedure Text(X, Y: Integer; text: string; farba: TColor = clWhite; velkost: Byte = 10);
procedure FlipToFront;
procedure ZoomAll(maxPlocha: TMyRect; canvasSizeX, canvasSizeY, canvasOffsetX, canvasOffsetY: integer; okraj: Double = 3);
public
procedure SetZoom(factor: Double; bod: TPoint); overload;
procedure SetZoom(factor: Double; X, Y: integer); overload;
end;
implementation
{ TDrawingObject }
uses uDebug;
constructor TDrawingObject.Create(frontCanvas: TCanvas);
begin
inherited Create;
_canvasFrontEnd := frontCanvas;
_backPlane := TBitmap.Create;
_backPlane.Width := Screen.Width;
_backPlane.Height := Screen.Height;
end;
procedure TDrawingObject.SetZoom(factor: Double; bod: TPoint);
begin
SetZoom(factor, bod.X, bod.Y);
end;
procedure TDrawingObject.FlipToFront;
var
rect: TRect;
begin
rect := _canvasFrontEnd.ClipRect;
_canvasFrontEnd.CopyRect(rect, _backPlane.Canvas, rect);
end;
procedure TDrawingObject.Init(farba: TColor);
begin
// inicializacia vykresu (napr. vykreslenie pozadia farbou)
with _backPlane.Canvas do begin
Brush.Color := farba;
Brush.Style := bsSolid;
Rectangle(_canvasFrontEnd.ClipRect);
end;
end;
procedure TDrawingObject.Line(zaciatok, koniec: TMyPoint; farba: TColor = clWhite; hrubka: Double = 0);
begin
with _backPlane.Canvas do begin
Pen.Style := psSolid;
Pen.Color := farba;
if (hrubka = 0) then
Pen.Width := 1
else
Pen.Width := PX(hrubka);
fDebug.LogMessage('FROM:'+MyPointToStr(zaciatok)+' TO:'+MyPointToStr(koniec));
MoveTo(
PX(zaciatok.X, 'x'),
PX(zaciatok.Y, 'y')
);
LineTo(
PX(koniec.X, 'x'),
PX(koniec.Y, 'y')
);
end;
fDebug.LogMessage('FROM:'+inttostr(PX(zaciatok.X, 'x'))+','+inttostr(PX(zaciatok.Y, 'y'))+' TO:'+inttostr(PX(koniec.X, 'x') + 1)+','+inttostr(PX(koniec.Y, 'y') + 1));
end;
function TDrawingObject.MM(valuePX: integer; axis: String): Double;
begin
if axis = '' then begin
result := valuePX / _zoom;
end else begin
if axis = 'x' then
result := (valuePX - _drawOffset.X - _zoomOffset.X) / _zoom
else if axis = 'y' then
result := (valuePX - _drawOffset.Y - _zoomOffset.Y) / _zoom;
end;
end;
function TDrawingObject.PX(valueMM: Double; axis: String = ''): integer;
begin
if axis = '' then begin
result := Round(valueMM * _zoom);
end else begin
if axis = 'x' then
result := Round( valueMM * _zoom ) + _drawOffset.X + _zoomOffset.X
else if axis = 'y' then
result := _canvasFrontEnd_Height - (Round( valueMM * _zoom) + _drawOffset.Y + _zoomOffset.Y);
end;
end;
procedure TDrawingObject.ZoomAll(maxPlocha: TMyRect; canvasSizeX, canvasSizeY, canvasOffsetX, canvasOffsetY: integer; okraj: Double);
var
zoomX, zoomY: Double;
begin
// vypocitame aky ma byt zoom faktor, aby sa cela plocha zmestila na obrazovku
zoomX := canvasSizeX / ((maxPlocha.BtmR.X - maxPlocha.TopL.X) + okraj);
zoomY := canvasSizeY / ((maxPlocha.BtmR.Y - maxPlocha.TopL.Y) + okraj);
_zoom := Min(zoomX, zoomY);
_drawOffset.X := -PX(maxPlocha.TopL.X) + canvasOffsetX;
_drawOffset.Y := -PX(maxPlocha.TopL.Y) + canvasOffsetY;
fDebug.LogMessage('CANVAS SIZE y:'+inttostr(canvasSizeY));
fDebug.LogMessage('CANVAS OFFSET y:'+inttostr(canvasOffsetY));
fDebug.LogMessage('ZOOM:'+floattostr(_zoom));
fDebug.LogMessage('DRAW OFFSET y:'+inttostr(_drawOffset.Y));
end;
procedure TDrawingObject.SetZoom(factor: Double; X, Y: integer);
var
zoomx,zoomy: Double;
edgeDistPX_x_old: integer;
edgeDistPX_x_new: integer;
edgeDistMM_x_old: Double;
edgeDistPX_y_old: integer;
edgeDistPX_y_new: integer;
edgeDistMM_y_old: Double;
begin
// okrajove podmienky
if ((factor > 1) AND (_zoom < 50)) OR
((factor < 1) AND (_zoom > 1)) then
_zoom := _zoom * factor; // zoomuje len ak platia tieto 2 podmienky
// ak bola funkcia zavolana s parametrom Factor = 0, resetne uzivatelsky zoom
if (factor = 0) then
_zoom := 1;
// ak bola funkcia zavolana s parametrami X = Y = -1, resetne uzivatelsky offset
if (X = -1) AND (Y = -1) then begin
_zoomOffset.X := 0;
_zoomOffset.Y := 0;
end;
// ulozime si vzdialenost k hrane este pri starom zoome
edgeDistPX_x_old := X - _drawOffset.X - _zoomOffset.X;
edgeDistPX_y_old := Y - _drawOffset.Y - _zoomOffset.Y;
edgeDistMM_x_old := MM( edgeDistPX_x_old );
edgeDistMM_y_old := MM( edgeDistPX_y_old );
// nastavenie zoomu (ak nie je zadany parameter zoomVal, nazoomuje cely panel)
// zoomx := (fMain.ClientWidth - 10) / objSirka;
// zoomy := (fMain.ClientHeight - fMain.ToolBar1.Height - 10 - 20 {status bar}) / objVyska;
// objZoom := Min(zoomx, zoomy) * objZoomFactor;
if (X > 0) AND (Y > 0) then begin // ochrana pred znicenim hodnoty v objZoomOffsetX(Y) ked sa procedura zavola bez pozicie kurzora
// este nastavime posunutie celeho vykreslovania - aby mys aj po prezoomovani
// ostavala nad tym istym miestom panela
edgeDistPX_x_new := PX( edgeDistMM_x_old );
edgeDistPX_y_new := PX( edgeDistMM_y_old );
_zoomOffset.X := _zoomOffset.X + ((edgeDistPX_x_old) - (edgeDistPX_x_new));
_zoomOffset.Y := _zoomOffset.Y + ((edgeDistPX_y_old) - (edgeDistPX_y_new));
end;
end;
procedure TDrawingObject.Text(X, Y: Integer; text: string; farba: TColor; velkost: Byte);
begin
with _backPlane.Canvas do begin
Font.Size := velkost;
Font.Color := farba;
TextOut(X, Y, text);
end;
end;
end.
|
// 6-Faça um algoritmo que lê uma temperatura em Fahrenheit e calcule a
// temperatura correspondente em Celsius. Ao final o programa deve exibir
// as duas temperaturas.
// – Usar a fórmula:
// C = (5 * (F-32) / 9)
Program Temperatura;
var
fah, cel : real;
Begin
writeln('Informe a temperatura em Fahrenheit: ');
readln(fah);
cel := 5*((fah-32)/9);
writeln('Temperatura em:');
writeln('Fahrenheit: ', fah:6:2);
writeln('Celsius: ', cel:6:2);
End.
|
unit Generator;
interface
uses
Properties;
type TGenerator = class
private
FName: string;
FProperties: TProperties;
function getName: string;
procedure setName(const aName: string);
function getProperties: TProperties;
procedure setProperties(const aProperties:TProperties);
published
property name: string read getName write setName;
property properties: TProperties read getProperties write setProperties;
public
constructor Create; overload;
constructor Create(const aName: string; const aProperties: TProperties); overload;
destructor Destroy; override;
end;
implementation
{ TGenerator }
constructor TGenerator.Create;
begin
inherited Create;
name := '';
properties := nil;
end;
constructor TGenerator.Create(const aName: string;
const aProperties: TProperties);
begin
inherited Create;
name := aName;
properties := aProperties;
end;
destructor TGenerator.Destroy;
var
i: Integer;
begin
if assigned(FProperties) then
begin
for i := FProperties.Count - 1 downto 0 do
FProperties.Items[i].Free;
FProperties.Free;
end;
inherited Destroy;
end;
function TGenerator.getName: string;
begin
result := FName;
end;
function TGenerator.getProperties: TProperties;
begin
result := FProperties;
end;
procedure TGenerator.setName(const aName: string);
begin
FName := aName;
end;
procedure TGenerator.setProperties(const aProperties: TProperties);
begin
FProperties := aProperties;
end;
end.
|
unit LLVM.Imports.Target;
interface
//based on Target.h
uses
LLVM.Imports,
LLVM.Imports.Types;
{$MINENUMSIZE 4}
type
TLLVMByteOrdering = (LLVMBigEndian, LLVMLittleEndian);
TLLVMTargetDataRef = type TLLVMRef;
TLLVMTargetLibraryInfoRef = type TLLVMRef;
//LLVM supports macros to generate the functions to import
//we'll simply do it at runtime by providing parameterized functions
//which allows to initialize other new targets in the future even if they're not listed here
const
//Targets
CLLVMTARGET_AArch64 = 'AArch64';
CLLVMTARGET_AMDGPU = 'AMDGPU';
CLLVMTARGET_ARM = 'ARM';
CLLVMTARGET_BPF = 'BPF';
CLLVMTARGET_Hexagon = 'Hexagon';
CLLVMTARGET_Lanai = 'Lanai';
CLLVMTARGET_Mips = 'Mips';
CLLVMTARGET_MSP430 = 'MSP430';
CLLVMTARGET_NVPTX = 'NVPTX';
CLLVMTARGET_PowerPC = 'PowerPC';
CLLVMTARGET_Sparc = 'Sparc';
CLLVMTARGET_SystemZ = 'SystemZ';
CLLVMTARGET_X86 = 'X86';
CLLVMTARGET_XCore = 'XCore';
//AsmPrinters
CLLVMASMPRINTER_AArch64 = 'AArch64';
CLLVMASMPRINTER_AMDGPU = 'AMDGPU';
CLLVMASMPRINTER_ARM = 'ARM';
CLLVMASMPRINTER_BPF = 'BPF';
CLLVMASMPRINTER_Hexagon = 'Hexagon';
CLLVMASMPRINTER_Lanai = 'Lanai';
CLLVMASMPRINTER_Mips = 'Mips';
CLLVMASMPRINTER_MSP430 = 'MSP430';
CLLVMASMPRINTER_NVPTX = 'NVPTX';
CLLVMASMPRINTER_PowerPC = 'PowerPC';
CLLVMASMPRINTER_Sparc = 'Sparc';
CLLVMASMPRINTER_SystemZ = 'SystemZ';
CLLVMASMPRINTER_X86 = 'X86';
CLLVMASMPRINTER_XCore = 'XCore';
//AsmParser
CLLVMASMPARSER_AArch64 = 'AArch64';
CLLVMASMPARSER_AMDGPU = 'AMDGPU';
CLLVMASMPARSER_ARM = 'ARM';
CLLVMASMPARSER_Hexagon = 'Hexagon';
CLLVMASMPARSER_Lanai = 'Lanai';
CLLVMASMPARSER_Mips = 'Mips';
CLLVMASMPARSER_PowerPC = 'PowerPC';
CLLVMASMPARSER_Sparc = 'Sparc';
CLLVMASMPARSER_SystemZ = 'SystemZ';
CLLVMASMPARSER_X86 = 'X86';
//Disassembler
CLLVMDISASSEMBLER_AArch64 = 'AArch64';
CLLVMDISASSEMBLER_AMDGPU = 'AMDGPU';
CLLVMDISASSEMBLER_ARM = 'ARM';
CLLVMDISASSEMBLER_BPF = 'BPF';
CLLVMDISASSEMBLER_Hexagon = 'Hexagon';
CLLVMDISASSEMBLER_Lanai = 'Lanai';
CLLVMDISASSEMBLER_Mips = 'Mips';
CLLVMDISASSEMBLER_PowerPC = 'PowerPC';
CLLVMDISASSEMBLER_Sparc = 'Sparc';
CLLVMDISASSEMBLER_SystemZ = 'SystemZ';
CLLVMDISASSEMBLER_X86 = 'x86';
CLLVMDISASSEMBLER_XCore = 'XCore';
//routines to dynamic call a specific function by name
function LLVMInitializeTargetInfo(const TargetName: string): Boolean;
function LLVMInitializeTarget(const TargetName: string): Boolean;
function LLVMInitializeTargetMC(const TargetName: string): Boolean;
function LLVMInitializeAsmPrinter(const AsmPrinterName: string): Boolean;
function LLVMInitializeAsmParser(const AsmParserName: string): Boolean;
function LLVMInitializeDisassembler(const DisassemblerName: string): Boolean;
function LLVMGetModuleDataLayout(M: TLLVMModuleRef): TLLVMTargetDataRef; cdecl; external CLLVMLibrary;
procedure LLVMSetModuleDataLayout(M: TLLVMModuleRef; DL: TLLVMTargetDataRef); cdecl; external CLLVMLibrary;
function LLVMCreateTargetData(const StringRep: PLLVMChar): TLLVMTargetDataRef; cdecl; external CLLVMLibrary;
procedure LLVMDisposeTargetData(TD: TLLVMTargetDataRef); cdecl; external CLLVMLibrary;
procedure LLVMAddTargetLibraryInfo(TLI: TLLVMTargetLibraryInfoRef; PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
function LLVMCopyStringRepOfTargetData(TD: TLLVMTargetDataRef): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMByteOrder(TD: TLLVMTargetDataRef): TLLVMByteOrdering; cdecl; external CLLVMLibrary;
function LLVMPointerSize(TD: TLLVMTargetDataRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMPointerSizeForAS(TD: TLLVMTargetDataRef; AdressSpace: Cardinal): Cardinal; cdecl; external CLLVMLibrary;
function LLVMIntPtrType(TD: TLLVMTargetDataRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMIntPtrTypeForAS(TD: TLLVMTargetDataRef; AddressSpace: Cardinal): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMIntPtrTypeInContext(C: TLLVMContextRef; TD: TLLVMTargetDataRef): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMIntPtrTypeForASInContext(C: TLLVMContextRef; TD: TLLVMTargetDataRef; AddressSpace: Cardinal): TLLVMTypeRef; cdecl; external CLLVMLibrary;
function LLVMSizeOfTypeInBits(TD: TLLVMTargetDataRef; Ty: TLLVMTypeRef): UInt64; cdecl; external CLLVMLibrary;
function LLVMStoreSizeOfType(TD: TLLVMTargetDataRef; Ty: TLLVMTypeRef): UInt64; cdecl; external CLLVMLibrary;
function LLVMABISizeOfType(TD: TLLVMTargetDataRef; Ty: TLLVMTypeRef): UInt64; cdecl; external CLLVMLibrary;
function LLVMABIAlignmentOfType(TD: TLLVMTargetDataRef; Ty: TLLVMTypeRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMCallFrameAlignmentOfType(TD: TLLVMTargetDataRef; Ty: TLLVMTypeRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMPreferredAlignmentOfType(TD: TLLVMTargetDataRef; Ty: TLLVMTypeRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMPreferredAlignmentOfGlobal(TD: TLLVMTargetDataRef; GlobalVar: TLLVMValueRef): Cardinal; cdecl; external CLLVMLibrary;
function LLVMElementAtOffset(TD: TLLVMTargetDataRef; StructTy: TLLVMTypeRef; Offset: UInt64): Cardinal; cdecl; external CLLVMLibrary;
function LLVMOffsetOfElement(TD: TLLVMTargetDataRef; StructTy: TLLVMTypeRef; Element: Cardinal): UInt64; cdecl; external CLLVMLibrary;
implementation
uses
Windows,
SysUtils;
const
CTargetInfoProc = 'LLVMInitialize%sTargetInfo';
CTargetProc = 'LLVMInitialize%sTarget';
CTargetMCProc = 'LLVMInitialize%sTargetMC';
CAsmPrinterProc = 'LLVMInitialize%sAsmPrinter';
CAsmParserProc = 'LLVMInitialize%sAsmParser';
CDisassemblerProc = 'LLVMInitialize%sDisassembler';
type
TInitProc = procedure; cdecl;
function TryDynCallProc(const AName: string): Boolean;
var
LLib: THandle;
LDynProc: TInitProc;
begin
if AName = '' then
Exit(False);
LLib := GetModuleHandle(CLLVMLibrary);
if LLib <> 0 then
begin
@LDynProc := GetProcAddress(LLib, PWideChar(AName));
if Assigned(LDynProc) then
begin
LDynProc();
Exit(True);
end;
end;
Result := False;
end;
function LLVMInitializeTargetInfo(const TargetName: string): Boolean;
begin
Result := TryDynCallProc(Format(CTargetInfoProc, [TargetName]));
end;
function LLVMInitializeTarget(const TargetName: string): Boolean;
begin
Result := TryDynCallProc(Format(CTargetProc, [TargetName]));
end;
function LLVMInitializeTargetMC(const TargetName: string): Boolean;
begin
Result := TryDynCallProc(Format(CTargetMCProc, [TargetName]));
end;
function LLVMInitializeAsmPrinter(const AsmPrinterName: string): Boolean;
begin
Result := TryDynCallProc(Format(CAsmPrinterProc, [AsmPrinterName]));
end;
function LLVMInitializeAsmParser(const AsmParserName: string): Boolean;
begin
Result := TryDynCallProc(Format(CAsmParserProc, [AsmParserName]));
end;
function LLVMInitializeDisassembler(const DisassemblerName: string): Boolean;
begin
Result := TryDynCallProc(Format(CDisassemblerProc, [DisassemblerName]));
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC MySQL metadata }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.MySQLMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator;
type
TFDPhysMySQLNameModes = set of (nmCaseSens, nmDefLowerCase, nmDBApply);
TFDPhysMySQLMetadata = class (TFDPhysConnectionMetadata)
private
FNameModes: TFDPhysMySQLNameModes;
FNameDoubleQuote: Boolean;
protected
function GetKind: TFDRDBMSKind; override;
function GetTxSavepoints: 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 GetDefValuesSupported: TFDPhysDefaultValues; override;
function GetArrayExecMode: TFDPhysArrayExecMode; override;
function GetLimitOptions: TFDPhysLimitOptions; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function GetAsyncAbortSupported: Boolean; override;
function GetServerCursorSupported: Boolean; override;
function GetBackslashEscSupported: Boolean; 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 InternalEscapeEscape(AEscape: Char; const AStr: String): String; override;
function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
public
constructor Create(const AConnection: TFDPhysConnection;
ANameDoubleQuote: Boolean; AServerVersion, AClientVersion: TFDVersion;
ANameModes: TFDPhysMySQLNameModes; AIsUnicode: Boolean);
end;
TFDPhysMySQLCommandGenerator = class(TFDPhysCommandGenerator)
private
FCurrentCatalog: String;
protected
function GetIdentity(ASessionScope: Boolean): String; override;
function GetSingleRowTable: String; override;
function GetPessimisticLock: String; override;
function GetSavepoint(const AName: String): String; override;
function GetRollbackToSavepoint(const AName: 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 GetColumnType(AColumn: TFDDatSColumn): String; override;
function GetMerge(AAction: TFDPhysMergeAction): String; override;
public
constructor Create(const ACommand: IFDPhysCommand); overload;
constructor Create(const AConnection: IFDPhysConnection); overload;
end;
implementation
uses
System.SysUtils, Data.DB,
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Param, FireDAC.Stan.Option;
const
// copied here from FireDAC.Phys.MySQLCli to remove dependency
NAME_LEN = 64;
{-------------------------------------------------------------------------------}
{ TFDPhysMySQLMetadata }
{-------------------------------------------------------------------------------}
constructor TFDPhysMySQLMetadata.Create(const AConnection: TFDPhysConnection;
ANameDoubleQuote: Boolean; AServerVersion, AClientVersion: TFDVersion;
ANameModes: TFDPhysMySQLNameModes; AIsUnicode: Boolean);
var
sKwd: String;
begin
inherited Create(AConnection, AServerVersion, AClientVersion, AIsUnicode);
FNameModes := ANameModes;
FNameDoubleQuote := ANameDoubleQuote;
sKwd :=
'ADD,ALL,ALTER,' +
'ANALYZE,AND,AS,' +
'ASC,ASENSITIVE,BEFORE,' +
'BETWEEN,BIGINT,BINARY,' +
'BLOB,BOTH,BY,' +
'CALL,CASCADE,CASE,' +
'CHANGE,CHAR,CHARACTER,' +
'CHECK,COLLATE,COLUMN,' +
'CONDITION,CONNECTION,CONSTRAINT,' +
'CONTINUE,CONVERT,CREATE,' +
'CROSS,CURRENT_DATE,CURRENT_TIME,' +
'CURRENT_TIMESTAMP,CURRENT_USER,CURSOR,' +
'DATABASE,DATABASES,DAY_HOUR,' +
'DAY_MICROSECOND,DAY_MINUTE,DAY_SECOND,' +
'DEC,DECIMAL,DECLARE,' +
'DEFAULT,DELAYED,DELETE,' +
'DESC,DESCRIBE,DETERMINISTIC,' +
'DISTINCT,DISTINCTROW,DIV,' +
'DOUBLE,DROP,DUAL,' +
'EACH,ELSE,ELSEIF,' +
'ENCLOSED,ESCAPED,EXISTS,' +
'EXIT,EXPLAIN,FALSE,' +
'FETCH,FLOAT,FLOAT4,' +
'FLOAT8,FOR,FORCE,' +
'FOREIGN,FROM,FULLTEXT,' +
'GRANT,GROUP,HAVING,' +
'HIGH_PRIORITY,HOUR_MICROSECOND,HOUR_MINUTE,' +
'HOUR_SECOND,IF,IGNORE,' +
'IN,INDEX,INFILE,' +
'INNER,INOUT,INSENSITIVE,' +
'INSERT,INT,INT1,' +
'INT2,INT3,INT4,' +
'INT8 INTEGER,INTERVAL,' +
'INTO,IS,ITERATE,' +
'JOIN,KEY,KEYS,' +
'KILL,LEADING,LEAVE,' +
'LEFT,LIKE,LIMIT,' +
'LINES,LOAD,LOCALTIME,' +
'LOCALTIMESTAMP,LOCK,LONG,' +
'LONGBLOB,LONGTEXT,LOOP,' +
'LOW_PRIORITY,MATCH,MEDIUMBLOB,' +
'MEDIUMINT,MEDIUMTEXT,MIDDLEINT,' +
'MINUTE_MICROSECOND,MINUTE_SECOND,MOD,' +
'MODIFIES,NATURAL,NOT,' +
'NO_WRITE_TO_BINLOG,NULL,NUMERIC,' +
'ON,OPTIMIZE,OPTION,' +
'OPTIONALLY,OR,ORDER,' +
'OUT,OUTER,OUTFILE,' +
'PRECISION,PRIMARY,PROCEDURE,' +
'PURGE,RAID0,READ,' +
'READS,REAL,REFERENCES,' +
'REGEXP,RELEASE,RENAME,' +
'REPEAT,REPLACE,REQUIRE,' +
'RESTRICT,RETURN,REVOKE,' +
'RIGHT,RLIKE,SCHEMA,' +
'SCHEMAS,SECOND_MICROSECOND,SELECT,' +
'SENSITIVE,SEPARATOR,SET,' +
'SHOW,SMALLINT,SONAME,' +
'SPATIAL,SPECIFIC,SQL,' +
'SQLEXCEPTION,SQLSTATE,SQLWARNING,' +
'SQL_BIG_RESULT,SQL_CALC_FOUND_ROWS,SQL_SMALL_RESULT,' +
'SSL,STARTING,STRAIGHT_JOIN,' +
'TABLE,TERMINATED,THEN,' +
'TINYBLOB,TINYINT,TINYTEXT,' +
'TO,TRAILING,TRIGGER,' +
'TRUE,UNDO,UNION,' +
'UNIQUE,UNLOCK,UNSIGNED,' +
'UPDATE,USAGE,USE,' +
'UPGRADE,' +
'USING,UTC_DATE,UTC_TIME,' +
'UTC_TIMESTAMP,VALUES,VARBINARY,' +
'VARCHAR,VARCHARACTER,VARYING,' +
'WHEN,WHERE,WHILE,' +
'WITH,WRITE,' +
'XOR,YEAR_MONTH,ZEROFILL';
if (AServerVersion = 0) or (AServerVersion >= mvMySQL050100) then
sKwd := sKwd +
',ACCESSIBLE,LINEAR,MASTER_SSL_VERIFY_SERVER_CERT,' +
'RANGE,READ_ONLY,READ_WRITE';
if (AServerVersion = 0) or (AServerVersion >= mvMySQL050500) then
sKwd := sKwd +
',GENERAL,IGNORE_SERVER_IDS,MASTER_HEARTBEAT_PERIOD,' +
'MAXVALUE,RESIGNAL,SIGNAL,' +
'SLOW';
if (AServerVersion = 0) or (AServerVersion >= mvMySQL050600) then
sKwd := sKwd +
',CURRENT,CURSOR_NAME,DATA,' +
'DATAFILE,DATE,DATETIME,' +
'DAY,DEFAULT_AUTH,DEFINER,' +
'DELAY_KEY_WRITE,DES_KEY_FILE,DIAGNOSTICS,' +
'DIRECTORY,DISABLE,DISCARD,' +
'DISK,DUMPFILE,DUPLICATE,' +
'DYNAMIC,ENABLE,ENDS,' +
'ENGINE,ENGINES,ENUM,' +
'ERROR,ERRORS,ESCAPE,' +
'EVENT,EVENTS,EVERY,' +
'EXCHANGE,EXPANSION,EXTENDED,' +
'EXTENT_SIZE,FAST,FAULTS,' +
'FILE,FIRST,FIXED,' +
'FOUND,FULL,FUNCTION,' +
'GEOMETRY,GEOMETRYCOLLECTION,GET,' +
'GET_FORMAT,GLOBAL,GRANTS,' +
'HASH,HOSTS,HOUR,' +
'IDENTIFIED,IMPORT,INDEXES,' +
'INITIAL_SIZE,INSERT_METHOD,INVOKER,' +
'IO,IO_THREAD,IPC,' +
'ISOLATION,ISSUER,KEY_BLOCK_SIZE,' +
'LAST,LEAVES,LESS,' +
'LEVEL,LINESTRING,LIST,' +
'LOCAL,LOCKS,LOGFILE,' +
'LOGS,MASTER,MASTER_BIND,' +
'MASTER_CONNECT_RETRY,MASTER_DELAY,MASTER_HOST,' +
'MASTER_LOG_FILE,MASTER_LOG_POS,MASTER_PASSWORD,' +
'MASTER_PORT,MASTER_RETRY_COUNT,MASTER_SERVER_ID,' +
'MASTER_SSL,MASTER_SSL_CA,MASTER_SSL_CAPATH,' +
'MASTER_SSL_CERT,MASTER_SSL_CIPHER,MASTER_SSL_CRL,' +
'MASTER_SSL_CRLPATH,MASTER_SSL_KEY,MASTER_USER,' +
'MAX_CONNECTIONS_PER_HOUR,MAX_QUERIES_PER_HOUR,MAX_ROWS,' +
'MAX_SIZE,MAX_UPDATES_PER_HOUR,MAX_USER_CONNECTIONS,' +
'MEDIUM,MEMORY,MERGE,' +
'MESSAGE_TEXT,MICROSECOND,MIGRATE,' +
'MINUTE,MIN_ROWS,MODE,' +
'MODIFY,MONTH,MULTILINESTRING,' +
'MULTIPOINT,MULTIPOLYGON,MUTEX,' +
'MYSQL_ERRNO,NAME,NAMES,' +
'NATIONAL,NCHAR,NDB,' +
'NDBCLUSTER,NEW,NEXT,' +
'NODEGROUP,NONE,NO_WAIT,' +
'NUMBER,NVARCHAR,OFFSET,' +
'OLD_PASSWORD,ONE,ONE_SHOT,' +
'PACK_KEYS,PAGE,PARTIAL,' +
'PARTITION,PARTITIONING,PARTITIONS,' +
'PASSWORD,PHASE,PLUGIN,' +
'PLUGINS,PLUGIN_DIR,POINT,' +
'POLYGON,PRESERVE,PREV,' +
'PRIVILEGES,PROCESSLIST,PROFILE,' +
'PROFILES,PROXY,QUARTER,' +
'QUERY,QUICK,READ_ONLY,' +
'REBUILD,RECOVER,REDOFILE,' +
'REDO_BUFFER_SIZE,REDUNDANT,RELAY,' +
'RELAYLOG,RELAY_LOG_FILE,RELAY_LOG_POS,' +
'RELAY_THREAD,RELOAD,REORGANIZE,' +
'REPEATABLE,REPLICATION,RESUME,' +
'RETURNED_SQLSTATE,RETURNS,REVERSE,' +
'ROLLUP,ROUTINE,ROW,' +
'ROWS,ROW_COUNT,ROW_FORMAT,' +
'RTREE,SCHEDULE,SCHEMA_NAME,' +
'SECOND,SERIAL,SERIALIZABLE,' +
'SESSION,SHARE,SHUTDOWN,' +
'SIMPLE,SNAPSHOT,SOUNDS,' +
'SOURCE,SQL_BUFFER_RESULT,SQL_CACHE,' +
'SQL_NO_CACHE,SQL_THREAD,SQL_TSI_DAY,' +
'SQL_TSI_HOUR,SQL_TSI_MINUTE,SQL_TSI_MONTH,' +
'SQL_TSI_QUARTER,SQL_TSI_SECOND,SQL_TSI_WEEK,' +
'SQL_TSI_YEAR,STARTS,STATUS,' +
'STORAGE,STRING,SUBCLASS_ORIGIN,' +
'SUBJECT,SUBPARTITION,SUBPARTITIONS,' +
'SUPER,SUSPEND,SWAPS,' +
'SWITCHES,TABLES,TABLESPACE,' +
'TABLE_CHECKSUM,TABLE_NAME,TEMPORARY,' +
'TEMPTABLE,TEXT,THAN,' +
'TIME,TIMESTAMP,TIMESTAMPADD,' +
'TIMESTAMPDIFF,TRANSACTION,TRIGGERS,' +
'TYPE,TYPES,UNCOMMITTED,' +
'UNDEFINED,UNDOFILE,UNDO_BUFFER_SIZE,' +
'UNKNOWN,UNTIL,USER,' +
'USER_RESOURCES,USE_FRM,VALUE,' +
'VARIABLES,VIEW,WAIT,' +
'WARNINGS,WEEK,WEIGHT_STRING,' +
'WORK,X509,XML,' +
'YEAR';
if (AServerVersion = 0) or (AServerVersion >= mvMariaDB100300) then
sKwd := sKwd +
',INTERSECT,EXCEPT';
FKeywords.CommaText := sKwd;
ConfigQuoteChars;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.MySQL;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts;
begin
Result := GetNameCaseSensParts;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetNameCaseSensParts: TFDPhysNameParts;
begin
if nmCaseSens in FNameModes then begin
Result := [npBaseObject, npObject];
if nmDBApply in FNameModes then
Include(Result, npCatalog);
end
else
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
if nmDefLowerCase in FNameModes then begin
Result := [npBaseObject, npObject];
if nmDBApply in FNameModes then
Include(Result, npCatalog);
end
else
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetParamNameMaxLength: Integer;
begin
Result := NAME_LEN;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetNameParts: TFDPhysNameParts;
begin
Result := [npCatalog, npBaseObject, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel;
ASide: TFDPhysNameQuoteSide): Char;
begin
Result := #0;
case AQuote of
ncDefault:
Result := '`';
ncSecond:
if FNameDoubleQuote then
Result := '"';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetTxSavepoints: Boolean;
begin
Result := (GetServerVersion >= mvMySQL040100);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetIdentityInsertSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
if GetServerVersion >= mvMySQL040000 then
Result := dvDef
else
Result := dvNone;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetArrayExecMode: TFDPhysArrayExecMode;
begin
Result := aeOnErrorUndoAll;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetLimitOptions: TFDPhysLimitOptions;
begin
Result := [loSkip, loRows];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
Result := [soWithoutFrom, soInlineView];
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetAsyncAbortSupported: Boolean;
begin
Result := GetServerVersion >= mvMySQL050000;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetServerCursorSupported: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.GetBackslashEscSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.InternalEscapeBoolean(const AStr: String): String;
begin
Result := FDUnquote(AStr, '''');
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.InternalEscapeDate(const AStr: String): String;
begin
if GetServerVersion >= mvMySQL040000 then
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS DATE)'
else
Result := AnsiQuotedStr(AStr, '''');
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
if GetServerVersion >= mvMySQL040000 then
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS DATETIME)'
else
Result := AnsiQuotedStr(AStr, '''');
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.InternalEscapeTime(const AStr: String): String;
begin
if GetServerVersion >= mvMySQL040000 then
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS TIME)'
else
Result := AnsiQuotedStr(AStr, '''');
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.InternalEscapeFloat(const AStr: String): String;
begin
Result := AStr;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String;
var
sName: String;
A1, A2, A3: String;
i: Integer;
function AddArgs: string;
begin
Result := '(' + AddEscapeSequenceArgs(Aseq) + ')';
end;
begin
sName := ASeq.FName;
if Length(ASeq.FArgs) >= 1 then begin
A1 := ASeq.FArgs[0];
if Length(ASeq.FArgs) >= 2 then begin
A2 := ASeq.FArgs[1];
if Length(ASeq.FArgs) >= 3 then
A3 := ASeq.FArgs[2];
end;
end;
case ASeq.FFunc of
// the same
// char
efASCII,
efCHAR_LENGTH,
efCONCAT,
efCHAR,
efINSERT,
efLCASE,
efLEFT,
efLTRIM,
efLOCATE,
efOCTET_LENGTH,
efREPEAT,
efREPLACE,
efRIGHT,
efRTRIM,
efSPACE,
efSUBSTRING,
efUCASE,
// numeric
efACOS,
efASIN,
efATAN,
efATAN2,
efABS,
efCEILING,
efCOS,
efCOT,
efDEGREES,
efEXP,
efFLOOR,
efLOG,
efLOG10,
efMOD,
efPOWER,
efPI,
efRADIANS,
efSIGN,
efSIN,
efSQRT,
efTAN,
// date and time
efCURDATE,
efCURTIME,
efNOW,
efDAYNAME,
efDAYOFMONTH,
efDAYOFWEEK,
efDAYOFYEAR,
efHOUR,
efMINUTE,
efMONTH,
efMONTHNAME,
efQUARTER,
efSECOND,
efYEAR,
// system
efIFNULL:
Result := sName + AddArgs;
// convert
efCONVERT:
if GetServerVersion >= mvMySQL040000 then
Result := sName + AddArgs
else
Result := A1;
// character
efLENGTH: Result := 'LENGTH(RTRIM(' + A1 + '))';
efPOSITION: Result := 'POSITION(' + A1 + ' IN ' + A2 + ')';
efBIT_LENGTH:
if GetServerVersion >= mvMySQL040000 then
Result := sName + AddArgs
else
Result := '(LENGTH(' + A1 + ') * 8)';
// numeric
efRANDOM: Result := 'RAND' + AddArgs;
efROUND,
efTRUNCATE:
if A2 = '' then
Result := sName + '(' + A1 + ', 0)'
else
Result := sName + AddArgs;
// date and time
efTIMESTAMPADD:
if GetServerVersion >= mvMySQL050000 then begin
ASeq.FArgs[0] := UpperCase(FDUnquote(Trim(A1), ''''));
if (GetServerVersion >= mvMySQL050060) and (ASeq.FArgs[0] = 'FRAC_SECOND') then
ASeq.FArgs[0] := 'MICROSECOND';
Result := sName + AddArgs;
end
else begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
if A1 = 'WEEK' then begin
A1 := 'DAY';
A2 := A2 + ' * 7';
end;
Result := 'DATE_ADD(' + A3 + ', INTERVAL ' + A2 + ' ' + A1 + ')';
end;
efTIMESTAMPDIFF:
if GetServerVersion >= mvMySQL050000 then begin
ASeq.FArgs[0] := UpperCase(FDUnquote(Trim(A1), ''''));
if (GetServerVersion >= mvMySQL050060) and (ASeq.FArgs[0] = 'FRAC_SECOND') then
ASeq.FArgs[0] := 'MICROSECOND';
Result := sName + AddArgs;
end
else
UnsupportedEscape(ASeq);
efEXTRACT:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
Result := sName + '(' + A1 + ' FROM ' + A2 + ')';
end;
efWEEK:
if GetServerVersion >= mvMySQL040000 then
Result := '(WEEK(' + A1 + ') + 1)'
else
Result := sName + AddArgs;
// system
efCATALOG: Result := 'DATABASE()';
efSCHEMA: Result := '''''';
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;
else
UnsupportedEscape(ASeq);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.InternalEscapeEscape(AEscape: Char; const AStr: String): String;
begin
Result := AStr + ' ESCAPE ''';
if AEscape = '\' then
Result := Result + '\\'''
else
Result := Result + AEscape + '''';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLMetadata.InternalGetSQLCommandKind(
const ATokens: TStrings): TFDPhysCommandKind;
var
sToken: String;
begin
sToken := ATokens[0];
if sToken = 'SHOW' then
Result := skSelect
else if sToken = 'EXPLAIN' then
Result := skSelect
else if sToken = 'CALL' then
Result := skExecute
else if sToken = 'REPLACE' then
Result := skMerge
else if sToken = 'START' then
if ATokens.Count = 1 then
Result := skNotResolved
else if ATokens[1] = 'TRANSACTION' then
Result := skStartTransaction
else
Result := inherited InternalGetSQLCommandKind(ATokens)
else if sToken = 'BEGIN' then
Result := skStartTransaction
else if sToken = 'USE' then
Result := skSetSchema
else
Result := inherited InternalGetSQLCommandKind(ATokens);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMySQLCommandGenerator }
{-------------------------------------------------------------------------------}
constructor TFDPhysMySQLCommandGenerator.Create(const ACommand: IFDPhysCommand);
begin
inherited Create(ACommand);
FCurrentCatalog := ACommand.Connection.CurrentCatalog;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysMySQLCommandGenerator.Create(const AConnection: IFDPhysConnection);
begin
inherited Create(AConnection);
FCurrentCatalog := AConnection.CurrentCatalog;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommandGenerator.GetIdentity(ASessionScope: Boolean): String;
begin
Result := 'LAST_INSERT_ID()';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommandGenerator.GetSingleRowTable: String;
begin
Result := 'DUAL';
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommandGenerator.GetPessimisticLock: String;
var
lNeedFrom: Boolean;
begin
// FOptions.UpdateOptions.LockWait is not used - MySQL always waits
lNeedFrom := False;
Result := 'SELECT ' + GetSelectList(True, False, lNeedFrom) + BRK +
'FROM ' + GetFrom + BRK + 'WHERE ' + GetWhere(False, True, False) + BRK;
if FOptions.UpdateOptions.LockPoint = lpImmediate then
Result := Result + 'FOR UPDATE'
else
Result := Result + 'LOCK IN SHARE MODE';
FCommandKind := skSelectForLock;
ASSERT(lNeedFrom);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommandGenerator.GetSavepoint(const AName: String): String;
begin
Result := 'SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommandGenerator.GetRollbackToSavepoint(const AName: String): String;
begin
Result := 'ROLLBACK TO SAVEPOINT ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommandGenerator.GetCall(const AName: String): String;
begin
Result := 'CALL ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommandGenerator.GetStoredProcCall(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
var
i: Integer;
oParam: TFDParam;
rName: TFDPhysParsedName;
sSET, sCALL, sSELECT, sFUNC, sName, sVar, sPar, sCast: String;
lFunction, lPrepStmt: Boolean;
begin
sSET := '';
sCALL := '';
sSELECT := '';
sFUNC := '';
lFunction := False;
rName.FCatalog := ACatalog;
rName.FSchema := ASchema;
rName.FBaseObject := APackage;
lPrepStmt := AProc[1] = '*';
if lPrepStmt then
rName.FObject := Copy(AProc, 2, MaxInt)
else
rName.FObject := AProc;
sName := FConnMeta.EncodeObjName(rName, FCommand, [eoQuote, eoNormalize]);
rName.FCatalog := '';
rName.FSchema := '';
rName.FBaseObject := '';
for i := 0 to FParams.Count - 1 do begin
case FParams.BindMode of
pbByName: oParam := FParams[i];
pbByNumber: oParam := FParams.ParamByPosition(i + 1);
else oParam := nil;
end;
if lPrepStmt then
sVar := '?'
else begin
sVar := '@P' + IntToStr(i + 1);
if oParam.ParamType in [ptUnknown, ptInput, ptInputOutput] then begin
if sSET <> '' then
sSET := sSET + ', ';
sSET := sSET + sVar + ' = ?';
end;
if oParam.ParamType in [ptInputOutput, ptOutput] then begin
if sSELECT <> '' then
sSELECT := sSELECT + ', ';
rName.FObject := oParam.SQLName;
sPar := FConnMeta.EncodeObjName(rName, FCommand, [eoQuote, eoNormalize]);
case oParam.DataType of
ftSmallint, ftInteger, ftAutoInc, ftLargeint, ftShortint:
sCast := 'SIGNED';
ftWord, ftLongWord, ftByte:
sCast := 'UNSIGNED';
// ftFloat, ftExtended, ftSingle
ftCurrency, ftBCD, ftFMTBcd:
// On 5.1 CAST(123.456, DECIMAL) -> 123
// On 5.0 -> 123.456
if (FConnMeta.ServerVersion >= mvMySQL050100) and
(oParam.Precision = 0) and (oParam.NumericScale = 0) then
sCast := ''
else begin
sCast := 'DECIMAL';
if (oParam.Precision <> 0) or (oParam.NumericScale <> 0) then begin
sCast := sCast + '(';
if oParam.Precision <> 0 then
sCast := sCast + IntToStr(oParam.Precision)
else
sCast := sCast + IntToStr(65);
if oParam.NumericScale <> 0 then
sCast := sCast + ',' + IntToStr(oParam.NumericScale);
sCast := sCast + ')';
end;
end;
ftDate:
sCast := 'DATE';
ftTime:
sCast := 'TIME';
ftDateTime, ftTimeStamp:
sCast := 'DATETIME';
else
sCast := '';
end;
if sCast <> '' then
sSELECT := sSELECT + 'CAST(' + sVar + ' AS ' + sCast + ') AS ' + sPar
else
sSELECT := sSELECT + sVar + ' AS ' + sPar;
if sFUNC = '' then
sFUNC := sName + '(' + sVar
else
sFUNC := sFUNC + ', ' + sVar;
end;
end;
if lPrepStmt and (oParam.ParamType <> ptResult) or
not lPrepStmt and (oParam.ParamType in [ptUnknown, ptInput]) then
if sFUNC = '' then
sFUNC := sName + '(' + sVar
else
sFUNC := sFUNC + ', ' + sVar;
if oParam.ParamType = ptResult then
lFunction := True;
end;
if sFUNC = '' then
sFUNC := sName + '()'
else
sFUNC := sFUNC + ')';
if lFunction then begin
if sSELECT <> '' then
sSELECT := sFUNC + ' AS RESULT, ' + sSELECT
else
sSELECT := sFUNC + ' AS RESULT';
end
else
sCALL := sFUNC;
Result := '';
if sSET <> '' then begin
if Result <> '' then
Result := Result + '; ';
Result := Result + 'SET ' + sSET;
end;
if sCALL <> '' then begin
if Result <> '' then
Result := Result + '; ';
Result := Result + 'CALL ' + sCALL;
end;
if sSELECT <> '' then begin
if Result <> '' then
Result := Result + '; ';
Result := Result + 'SELECT ' + sSELECT;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommandGenerator.GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String;
var
sName, sCatalog: String;
lWasWhere: Boolean;
function EncodeName: String;
var
rName: TFDPhysParsedName;
begin
rName.FCatalog := ACatalog;
rName.FSchema := ASchema;
if AKind in [mkIndexFields, mkPrimaryKeyFields, mkForeignKeyFields] then
if ABaseObject <> '' then
rName.FBaseObject := ABaseObject
else
rName.FBaseObject := AObject
else
rName.FObject := AObject;
Result := FConnMeta.EncodeObjName(rName, FCommand, [eoQuote, eoNormalize]);
end;
function EncodeFKName: String;
var
rName: TFDPhysParsedName;
begin
rName.FCatalog := '';
rName.FSchema := '';
rName.FBaseObject := '';
rName.FObject := AObject;
Result := FConnMeta.EncodeObjName(rName, FCommand, [eoNormalize]);
end;
procedure AddWhere(const ACond: String);
begin
if lWasWhere then
Result := Result + ' AND ' + ACond
else begin
Result := Result + ' WHERE ' + ACond;
lWasWhere := True;
end;
end;
begin
lWasWhere := False;
Result := '';
case AKind of
mkCatalogs:
begin
Result := 'SHOW DATABASES';
if AWildcard <> '' then
Result := Result + ' LIKE ''' + AWildcard + '''';
end;
mkSchemas:
;
mkTables:
begin
Result := 'SHOW ';
if FConnMeta.ServerVersion >= mvMySQL050002 then
Result := Result + 'FULL ';
Result := Result + 'TABLES';
if (ACatalog <> '') and (CompareText(ACatalog, FCurrentCatalog) <> 0) then
Result := Result + ' IN ' + ACatalog;
if AWildcard <> '' then
Result := Result + ' LIKE ''' + AWildcard + '''';
end;
mkTableFields:
begin
Result := 'SHOW COLUMNS';
if AWildcard <> '' then
Result := Result + ' LIKE ''' + AWildcard + '''';
Result := Result + ' FROM ' + EncodeName();
end;
mkIndexes,
mkIndexFields,
mkPrimaryKey,
mkPrimaryKeyFields:
begin
Result := 'SHOW INDEX';
if AWildcard <> '' then
Result := Result + ' LIKE ''' + AWildcard + '''';
Result := Result + ' FROM ' + EncodeName();
end;
mkForeignKeys,
mkForeignKeyFields:
if (FConnMeta.ServerVersion < mvMySQL032300) or
((FConnMeta.ServerVersion >= mvMySQL050000) and (FConnMeta.ServerVersion < mvMySQL050100)) then
Result := ''
else begin
if ACatalog = '' then
sCatalog := FCurrentCatalog
else
sCatalog := ACatalog;
if FConnMeta.ServerVersion >= mvMySQL050100 then
Result := inherited GetSelectMetaInfo(AKind, sCatalog, '', ABaseObject,
AObject, AWildcard, AObjectScopes, ATableKinds, AOverload)
else
Result := 'SHOW TABLE STATUS FROM ' + sCatalog + ' LIKE ''' +
EncodeFKName() + '''';
end;
mkPackages:
;
mkProcs:
if FConnMeta.ServerVersion < mvMySQL050000 then
Result := ''
else begin
Result := 'SELECT CAST(NULL AS UNSIGNED) AS RECNO, ROUTINE_SCHEMA AS CATALOG_NAME, ' +
'CAST(NULL AS CHAR(64)) AS SCHEMA_NAME, CAST(NULL AS CHAR(64)) AS PACK_NAME, ' +
'ROUTINE_NAME AS PROC_NAME, CAST(NULL AS UNSIGNED) AS OVERLOAD, ' +
'CASE ROUTINE_TYPE ' +
'WHEN ''FUNCTION'' THEN ' + IntToStr(Integer(pkFunction)) +
' WHEN ''PROCEDURE'' THEN ' + IntToStr(Integer(pkProcedure)) + ' END AS PROC_TYPE, ' +
'CASE LOWER(ROUTINE_SCHEMA) ' +
'WHEN ''mysql'' THEN ' + IntToStr(Integer(osSystem)) +
' WHEN ''information_schema'' THEN ' + IntToStr(Integer(osSystem)) +
' WHEN ''' + LowerCase(FCurrentCatalog) + ''' THEN ' + IntToStr(Integer(osMy)) +
' ELSE ' + IntToStr(Integer(osOther)) + ' END AS PROC_SCOPE, ' +
'CAST(NULL AS UNSIGNED) AS IN_PARAMS, CAST(NULL AS UNSIGNED) AS OUT_PARAMS ' +
'FROM INFORMATION_SCHEMA.ROUTINES';
if ACatalog <> '' then
AddWhere('LOWER(ROUTINE_SCHEMA) = LOWER(''' + ACatalog + ''')');
if AWildcard <> '' then
AddWhere('ROUTINE_NAME LIKE ''' + AWildcard + '''');
Result := Result + ' ORDER BY 3, 5';
end;
mkProcArgs:
begin
sName := EncodeName();
Result := 'SHOW CREATE PROCEDURE ' + sName + ';' +
'SHOW CREATE FUNCTION ' + sName;
end;
mkGenerators,
mkResultSetFields,
mkTableTypeFields:
;
else
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommandGenerator.GetLimitSelect(const ASQL: String;
ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String;
begin
if ASkip > 0 then
Result := ASQL + BRK + 'LIMIT ' + IntToStr(ASkip) + ', ' + IntToStr(ARows)
else if ARows >= 0 then
Result := ASQL + BRK + 'LIMIT ' + IntToStr(ARows)
else begin
Result := ASQL;
AOptions := [];
end;
end;
{-------------------------------------------------------------------------------}
// http://dev.mysql.com/doc/refman/5.6/en/string-type-overview.html
function TFDPhysMySQLCommandGenerator.GetColumnType(AColumn: TFDDatSColumn): String;
begin
case AColumn.DataType of
dtBoolean:
Result := 'BOOLEAN';
dtSByte:
Result := 'TINYINT';
dtInt16:
Result := 'SMALLINT';
dtInt32:
Result := 'INT';
dtInt64:
Result := 'BIGINT';
dtByte:
Result := 'TINYINT UNSIGNED';
dtUInt16:
Result := 'SMALLINT UNSIGNED';
dtUInt32:
Result := 'INT UNSIGNED';
dtUInt64:
Result := 'BIGINT UNSIGNED';
dtSingle:
Result := 'FLOAT';
dtDouble,
dtExtended:
Result := 'DOUBLE';
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:
Result := 'DATETIME';
dtTime:
Result := 'TIME';
dtDate:
Result := 'DATE';
dtDateTimeStamp:
Result := 'TIMESTAMP';
dtAnsiString:
begin
if (caFixedLen in AColumn.ActualAttributes) and (AColumn.Size <= 255) then
Result := 'CHAR'
else
Result := 'VARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtWideString:
begin
if (caFixedLen in AColumn.ActualAttributes) and (AColumn.Size <= 255) then
Result := 'NATIONAL CHAR'
else
Result := 'NATIONAL VARCHAR';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtByteString:
begin
if (caFixedLen in AColumn.ActualAttributes) and (AColumn.Size <= 255) then
Result := 'BINARY'
else
Result := 'VARBINARY';
Result := Result + GetColumnDim(AColumn.Size, -1, -1, -1, -1, -1);
end;
dtBlob,
dtHBlob,
dtHBFile:
Result := 'LONGBLOB';
dtMemo,
dtWideMemo,
dtXML,
dtHMemo,
dtWideHMemo:
Result := 'LONGTEXT';
dtGUID:
Result := 'CHAR(38)';
dtUnknown,
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef,
dtParentRowRef,
dtObject:
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMySQLCommandGenerator.GetMerge(AAction: TFDPhysMergeAction): String;
begin
Result := '';
case AAction of
maInsertUpdate: Result := GenerateInsert() + BRK + 'ON DUPLICATE KEY UPDATE ' + GetUpdate();
maInsertIgnore: Result := 'INSERT IGNORE INTO ' + GetFrom + BRK + GetInsert('');
end;
end;
{-------------------------------------------------------------------------------}
initialization
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.MySQL, S_FD_MySQL_RDBMS);
end.
|
unit MediaProcessing.Convertor.HHAU.PCM.Impl;
interface
uses Windows,SysUtils,Classes,MediaProcessing.Convertor.HHAU.PCM,MediaProcessing.Definitions,MediaProcessing.Global,HHCommon, HHDecoder;
type
TMediaProcessor_ConvertorHhAu_Pcm_Impl =class (TMediaProcessor_Convertor_HhAu_Pcm,IMediaProcessorImpl)
private
FAudioDecoder: THHAudioDecoder;
protected
procedure Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); override;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses uBaseClasses;
{ TMediaProcessor_ConvertorHhAu_Pcm_Impl }
constructor TMediaProcessor_ConvertorHhAu_Pcm_Impl.Create;
begin
inherited;
FAudioDecoder:=THHAudioDecoder.Create;
end;
destructor TMediaProcessor_ConvertorHhAu_Pcm_Impl.Destroy;
begin
FreeAndNil(FAudioDecoder);
inherited;
end;
procedure TMediaProcessor_ConvertorHhAu_Pcm_Impl.Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal);
var
aStreamData: PHV_FRAME;
aMetaInfo: PHHAV_INFO;
b: boolean;
begin
CheckIfChannel0(aInFormat);
TArgumentValidation.NotNil(aInData);
Assert(aInfoSize=sizeof(HHAV_INFO));
aStreamData:=aInData;
Assert(aStreamData.zeroFlag=0);
Assert(aStreamData.oneFlag=1);
aOutData:=nil;
aOutDataSize:=0;
aOutInfo:=nil;
aOutInfoSize:=0;
Assert(aStreamData.streamFlag = FRAME_FLAG_A);
aMetaInfo:=PHHAV_INFO(aInfo);
FAudioDecoder.Lock;
try
b:=false;
try
FAudioDecoder.DecodeToPCM(aStreamData,aMetaInfo^);
b:=true;
except
end;
if b then
begin
aOutData:=FAudioDecoder.CurrentBuffer;
aOutDataSize:=FAudioDecoder.CurrentBufferSize;
aOutInfo:=nil;
aOutInfoSize:=0;
aOutFormat.Clear;
aOutFormat.biMediaType:=mtAudio;
aOutFormat.biStreamType:=stPCM;
aOutFormat.biFrameFlags:=[ffKeyFrame];
aOutFormat.AudioChannels:=aMetaInfo.nAudioChannels;
aOutFormat.AudioBitsPerSample:=aMetaInfo.nAudioBits;
aOutFormat.AudioSamplesPerSec:=aMetaInfo.nAudioSamples;
Include(aOutFormat.biFrameFlags,ffKeyFrame);
end;
finally
FAudioDecoder.Unlock;
end;
end;
initialization
MediaProceccorFactory.RegisterMediaProcessorImplementation(TMediaProcessor_ConvertorHhAu_Pcm_Impl);
end.
|
unit MaintenanceDrawer;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseDocked, RzLabel, Vcl.StdCtrls,
Vcl.ExtCtrls, RzPanel, RzCmboBx, RzTabs, AppConstants, SaveIntf, NewIntf;
type
TfrmMaintenanceDrawer = class(TfrmBaseDocked,ISave,INew)
pnlMenu: TRzPanel;
DockPanel: TRzPanel;
cmbType: TRzComboBox;
lblDate: TLabel;
pcType: TRzPageControl;
tsEntities: TRzTabSheet;
tsLoanRelated: TRzTabSheet;
urlBanks: TRzURLLabel;
urlEmployer: TRzURLLabel;
urlGroups: TRzURLLabel;
urlDesignation: TRzURLLabel;
urlCompetitors: TRzURLLabel;
urlInformationSources: TRzURLLabel;
urlLoanTypes: TRzURLLabel;
urlAccountTypes: TRzURLLabel;
urlLoanClassification: TRzURLLabel;
urlPurpose: TRzURLLabel;
urlCancellationReasons: TRzURLLabel;
urlRejectionReasons: TRzURLLabel;
urlChargeTypes: TRzURLLabel;
urlClosureReasons: TRzURLLabel;
tsAccounting: TRzTabSheet;
urlAccountClass: TRzURLLabel;
urlLineItems: TRzURLLabel;
urlAccountTitles: TRzURLLabel;
urlSubsidiaryTypes: TRzURLLabel;
urlSubsidiaries: TRzURLLabel;
procedure cmbTypeClick(Sender: TObject);
procedure urlLoanTypesClick(Sender: TObject);
procedure urlAccountTypesClick(Sender: TObject);
procedure urlLoanClassificationClick(Sender: TObject);
procedure urlPurposeClick(Sender: TObject);
procedure urlCancellationReasonsClick(Sender: TObject);
procedure urlRejectionReasonsClick(Sender: TObject);
procedure urlChargeTypesClick(Sender: TObject);
procedure urlClosureReasonsClick(Sender: TObject);
procedure urlGroupsClick(Sender: TObject);
procedure urlEmployerClick(Sender: TObject);
procedure urlBanksClick(Sender: TObject);
procedure urlDesignationClick(Sender: TObject);
procedure urlCompetitorsClick(Sender: TObject);
procedure urlInformationSourcesClick(Sender: TObject);
procedure urlAccountClassClick(Sender: TObject);
procedure urlLineItemsClick(Sender: TObject);
procedure urlAccountTitlesClick(Sender: TObject);
procedure urlSubsidiaryTypesClick(Sender: TObject);
procedure urlSubsidiariesClick(Sender: TObject);
private
{ Private declarations }
DOCKED_FORM: TForms;
procedure DockForm(const fm: TForms; const title: string = '');
public
{ Public declarations }
function Save: boolean;
procedure Cancel;
procedure New;
end;
implementation
{$R *.dfm}
uses
GroupList, EmployerList, BanksList, DesignationList, LoanClassificationList,
CompetitorList, FormsUtil, IFinanceGlobal, PurposeList, IFinanceDialogs, LoanTypeList,
AccountTypeList, LoanCancellationReasonList, LoanRejectionReasonList,
LoanClassChargeTypeList, InfoSourceList, LoanClosureReasonList, AccountClassList,
LineItemList, AccountTitlesList, SubsidiaryTypeList, SubsidiaryList;
procedure TfrmMaintenanceDrawer.Cancel;
var
intf: ISave;
begin
try
if DockPanel.ControlCount > 0 then
if Supports(DockPanel.Controls[0] as TForm,ISave,intf) then
intf.Cancel;
except
on e:Exception do ShowErrorBox(e.Message);
end;
end;
procedure TfrmMaintenanceDrawer.cmbTypeClick(Sender: TObject);
begin
inherited;
pcType.ActivePageIndex := cmbType.ItemIndex;
end;
procedure TfrmMaintenanceDrawer.DockForm(const fm: TForms; const title: string);
var
frm: TForm;
control: integer;
begin
//if (pnlDockMain.ControlCount = 0) or (DOCKED_FORM <> fm) then
begin
control := 0;
while control < DockPanel.ControlCount do
begin
if DockPanel.Controls[control] is TForm then
begin
(DockPanel.Controls[control] as TForm).Close;
(DockPanel.Controls[control] as TForm).Free;
end;
Inc(control);
end;
// instantiate form
case fm of
fmGroupList : frm := TfrmGroupList.Create(Application);
fmEmployerList: frm := TfrmEmployerList.Create(Application);
fmBanksList: frm := TfrmBanksList.Create(Application);
fmDesignationList: frm := TfrmDesignationList.Create(Application);
fmLoanClassList: frm := TfrmLoanClassificationList.Create(Application);
fmCompetitorList: frm := TfrmCompetitorList.Create(Application);
fmPurposeList: frm := TfrmPurposeList.Create(Application);
fmLoanTypeList: frm := TfrmLoanTypeList.Create(Application);
fmAcctTypeList: frm := TfrmAccountTypeList.Create(Application);
fmLoanCancelReasonList: frm := TfrmLoanCancelReasonList.Create(Application);
fmLoanRejectReasonList: frm := TfrmLoanRejectionReasonList.Create(Application);
fmChargeTypeList: frm := TfrmLoanClassChargeTypeList.Create(Application);
fmInfoSourceList: frm := TfrmInfoSourceList.Create(Application);
fmLoanCloseReasonList: frm := TfrmLoanCloseReasonList.Create(Application);
fmMaintenanceDrawer: frm := TfrmMaintenanceDrawer.Create(Application);
fmAccountClassList: frm := TfrmAccountClassList.Create(Application);
fmLineItemList: frm := TfrmLineItemList.Create(Application);
fmAccountTitlesList: frm := TfrmAccountTitlesList.Create(Application);
fmSubsidiaryTypeList: frm := TfrmSubsidiaryTypeList.Create(Application);
fmSubsidiaryList: frm := TfrmSubsidiaryList.Create(Application);
else
frm := nil;
end;
if Assigned(frm) then
begin
DOCKED_FORM := fm;
lblTitle.Caption := title;
frm.ManualDock(DockPanel);
frm.Show;
end;
end;
end;
procedure TfrmMaintenanceDrawer.New;
var
intf: INew;
begin
try
if DockPanel.ControlCount > 0 then
if Supports(DockPanel.Controls[0] as TForm,INew,intf) then
intf.New;
except
on e:Exception do ShowErrorBox(e.Message);
end;
end;
procedure TfrmMaintenanceDrawer.urlAccountTitlesClick(Sender: TObject);
begin
inherited;
DockForm(fmAccountTitlesList,(Sender as TRzURLLabel).Caption);
end;
function TfrmMaintenanceDrawer.Save: boolean;
var
intf: ISave;
begin
try
if DockPanel.ControlCount > 0 then
if Supports(DockPanel.Controls[0] as TForm,ISave,intf) then
Result := intf.Save;
except
on e:Exception do ShowErrorBox(e.Message);
end;
end;
procedure TfrmMaintenanceDrawer.urlAccountClassClick(Sender: TObject);
begin
inherited;
DockForm(fmAccountClassList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlLineItemsClick(Sender: TObject);
begin
inherited;
DockForm(fmLineItemList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlAccountTypesClick(Sender: TObject);
begin
inherited;
DockForm(fmAcctTypeList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlBanksClick(Sender: TObject);
begin
inherited;
DockForm(fmBanksList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlCancellationReasonsClick(Sender: TObject);
begin
inherited;
DockForm(fmLoanCancelReasonList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlChargeTypesClick(Sender: TObject);
begin
inherited;
DockForm(fmChargeTypeList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlClosureReasonsClick(Sender: TObject);
begin
inherited;
DockForm(fmLoanCloseReasonList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlCompetitorsClick(Sender: TObject);
begin
inherited;
DockForm(fmCompetitorList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlDesignationClick(Sender: TObject);
begin
inherited;
DockForm(fmDesignationList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlEmployerClick(Sender: TObject);
begin
inherited;
DockForm(fmEmployerList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlGroupsClick(Sender: TObject);
begin
inherited;
DockForm(fmGroupList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlInformationSourcesClick(Sender: TObject);
begin
inherited;
DockForm(fmInfoSourceList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlLoanClassificationClick(Sender: TObject);
begin
inherited;
DockForm(fmLoanClassList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlLoanTypesClick(Sender: TObject);
begin
inherited;
DockForm(fmLoanTypeList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlPurposeClick(Sender: TObject);
begin
inherited;
DockForm(fmPurposeList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlRejectionReasonsClick(Sender: TObject);
begin
inherited;
DockForm(fmLoanRejectReasonList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlSubsidiariesClick(Sender: TObject);
begin
inherited;
DockForm(fmSubsidiaryList,(Sender as TRzURLLabel).Caption);
end;
procedure TfrmMaintenanceDrawer.urlSubsidiaryTypesClick(Sender: TObject);
begin
inherited;
DockForm(fmSubsidiaryTypeList,(Sender as TRzURLLabel).Caption);
end;
end.
|
{===============================================================================
Copyright(c) 2014, 北京北研兴电力仪表有限责任公司
All rights reserved.
学员信息单元
+ TStudentControl 学员数信息控制类
===============================================================================}
unit xStudentControl;
interface
uses
System.Classes, System.SysUtils, xStudentInfo, xStudentAction;
type
/// <summary>
/// 学员数信息控制类
/// </summary>
TStudentControl = class
private
FStuList : TStringList;
FStuAction : TStudentAction;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 学员列表
/// </summary>
property StuList : TStringList read FStuList write FStuList;
/// <summary>
/// 添加学员
/// </summary>
procedure AddStu(AStuInfo : TStudentInfo);
/// <summary>
/// 修改学员
/// </summary>
procedure EditStu(AStuInfo : TStudentInfo);
/// <summary>
/// 删除学员
/// </summary>
function DelStu(AStuInfo : TStudentInfo) : Boolean; overload;
function DelStu(nStuNum : Integer) : Boolean; overload;
/// <summary>
/// 查询考生(模糊查找)
/// </summary>
/// <param name="sKey">输入查询的关键字,登录名/姓名/身份证号</param>
procedure SearchStus(sKey: string; slStus: TStringList);
/// <summary>
/// 根据编号查询学员信息
/// </summary>
function SearchStu(sStuNum : Integer) : TStudentInfo;
/// <summary>
/// 清空学员表
/// </summary>
procedure ClearStus;
/// <summary>
/// 是否存在登录的考生 (登录时用,只检查登录名,用户名,或者卡号)
/// </summary>
function StuExist(AStuInfo : TStudentInfo) : Boolean;
/// <summary>
/// 考生是否存在
/// </summary>
/// <param name="nNum">学员编号</param>
procedure IsExisStu(nStuNum : Integer; slstu: TStringList); overload;
/// <param name="sStuName">学员姓名</param>
procedure IsExisStu(sStuName : string; slstu: TStringList); overload;
/// <param name="sStuLoginName">学员登录名</param>
/// <param name="sStuPwd">学员登录名密码</param>
procedure IsExisStu(sStuLoginName, sStuPwd : string; slstu: TStringList); overload;
end;
var
StudentControl : TStudentControl;
implementation
uses
xFunction;
{ TStudentControl }
procedure TStudentControl.AddStu(AStuInfo: TStudentInfo);
begin
if Assigned(AStuInfo) then
begin
if Assigned(FStuAction) then
begin
AStuInfo.stuNumber := FStuAction.GetStuMaxNumber;
FStuAction.SaveStuData(AStuInfo);
FStuList.AddObject(IntToStr(AStuInfo.stuNumber), AStuInfo);
end;
end;
end;
constructor TStudentControl.Create;
begin
FStuList := TStringList.Create;
FStuAction := TStudentAction.Create;
FStuAction.SelStusAll(FStuList);
end;
function TStudentControl.DelStu(AStuInfo: TStudentInfo) : Boolean;
begin
result := False;
if Assigned(AStuInfo) then
result := DelStu(AStuInfo.stuNumber);
end;
function TStudentControl.DelStu(nStuNum: Integer) : Boolean;
var
nIndex : Integer;
begin
Result := False;
// 释放学员对象
nIndex := FStuList.IndexOf(IntToStr(nStuNum));
if nIndex <> -1 then
begin
// 删除数据库中记录
FStuAction.DelStu(nStuNum);
{$IFDEF MSWINDOWS}
FStuList.Objects[nIndex].Free;
{$ENDIF}
// 删除list
FStuList.Delete(nIndex);
Result := True;
end;
end;
procedure TStudentControl.ClearStus;
begin
if Assigned(FStuAction) then
begin
FStuAction.ClearStus;
ClearStringList(FStuList);
end;
end;
destructor TStudentControl.Destroy;
begin
ClearStringList(FStuList);
FStuList.Free;
FStuAction.Free;
inherited;
end;
procedure TStudentControl.EditStu(AStuInfo: TStudentInfo);
begin
if Assigned(AStuInfo) then
begin
if Assigned(FStuAction) then
begin
FStuAction.SaveStuData(AStuInfo);
end;
end;
end;
procedure TStudentControl.IsExisStu(nStuNum : Integer; slstu: TStringList);
var
i: Integer;
begin
for i := 0 to FStuList.Count - 1 do
begin
if TStudentInfo(FStuList.Objects[i]).stuNumber = nStuNum then
begin
slstu.AddObject('',FStuList.Objects[i]);
Break;
end;
end;
end;
procedure TStudentControl.IsExisStu(sStuName : string; slstu: TStringList);
var
i: Integer;
begin
if Assigned(slstu) then
begin
for i := 0 to FStuList.Count - 1 do
begin
if TStudentInfo(FStuList.Objects[i]).stuName = sStuName then
begin
slstu.AddObject('',FStuList.Objects[i]);
end;
end;
end;
end;
procedure TStudentControl.IsExisStu(sStuLoginName, sStuPwd: string;
slstu: TStringList);
var
i: Integer;
begin
for i := 0 to FStuList.Count - 1 do
begin
if (TStudentInfo(FStuList.Objects[i]).stuLogin = sStuLoginName) and
(TStudentInfo(FStuList.Objects[i]).stuPwd = sStuPwd) then
begin
slstu.AddObject('',FStuList.Objects[i]);
end
end;
end;
function TStudentControl.SearchStu(sStuNum: Integer): TStudentInfo;
var
nIndex : integer;
begin
Result := nil;
nIndex := FStuList.IndexOf(IntToStr(sStuNum));
if nIndex <> -1 then
begin
Result := TStudentInfo(FStuList.Objects[nIndex]);
end;
end;
procedure TStudentControl.SearchStus(sKey: string; slStus: TStringList);
var
i: Integer;
begin
if Assigned(slStus) then
begin
ClearStringList(slStus);
for i := 0 to FStuList.Count - 1 do
with TStudentInfo(FStuList.Objects[i]) do
begin
//利用函数 Pos 在TStringlist中模糊查找
if (Pos(sKey,stuLogin)>0) or (Pos(sKey,stuName) >0) or (Pos(sKey,stuIdCard) >0) then
slStus.AddObject(IntToStr(stuNumber), FStuList.Objects[i]);
end;
end;
end;
function TStudentControl.StuExist(AStuInfo: TStudentInfo) : Boolean;
var
i : integer;
begin
Result := False;
if Assigned(AStuInfo) then
begin
for i := 0 to FStuList.Count - 1 do
begin
with TStudentInfo(FStuList.Objects[i]) do
begin
if (stuLogin = AStuInfo.stuLogin ) or (stuName = AStuInfo.stuName) or
(stuIdCard = AStuInfo.stuIDcard) then
begin
Result := True;
AStuInfo.Assign(TStudentInfo(FStuList.Objects[i]));
Break;
end;
end;
end;
end;
end;
end.
|
{***************************************************************
*
* Project : UDPServer
* Unit Name: ServerMainForm
* Purpose : Demonstrates UDPServer component
* Date : 21/01/2001 - 16:08:50
* History :
*
****************************************************************}
unit ServerMainForm;
interface
uses
{$IFDEF Linux}
QControls, QForms, QStdCtrls,
{$ELSE}
controls, forms, stdctrls,
{$ENDIF}
Classes, IdSocketHandle, IdUDPServer;
type
TfrmMain = class(TForm)
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
private
UDPServer: TIdUDPServer;
procedure UDPServerUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
uses IdGlobal, SysUtils;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
UDPServer := TIdUDPServer.Create(self);
with UDPServer do
begin
Bindings.add.Port := IdPORT_ECHO;
Bindings.add.Port := IdPORT_CHARGEN;
OnUDPRead := UDPServerUDPRead;
Active := True;
end;
end;
procedure TfrmMain.UDPServerUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
const
rowlength = 75;
var
s: string;
i, row: integer;
c: Char;
begin
SetLength(s, AData.Size);
AData.Read(s[1], AData.Size);
with ABinding do
Memo1.Lines.Add(Format('%s:%d> %s', [PeerIP, PeerPort, s]));
case ABinding.Port of
IdPORT_ECHO : ;
IdPORT_CHARGEN :
begin
i := 1; c := '0'; row := 0;
SetLength(s, UDPServer.BufferSize);
while i <= Length(s) do
begin
if c > #95 then c := '0';
if i mod (rowlength + 1) = 0 then
begin
s[i] := #13;
c := chr(ord('0') + row mod (95 - ord('0')));
inc(row);
end
else
s[i] := c;
inc(i); inc(c);
end;
end;
end;
with ABinding do
SendTo(PeerIP, PeerPort, s[1], Length(s));
end;
end.
|
unit Settings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Menus, ExtCtrls, ComCtrls, pngimage;
type
TSettingsForm = class(TForm)
Save: TButton;
Button1: TButton;
Button2: TButton;
S1: TShape;
S2: TShape;
S3: TShape;
Label1: TLabel;
UBar: TTrackBar;
UnitN: TLabel;
MapT: TComboBox;
Label3: TLabel;
Detail: TLabel;
Image1: TImage;
Image2: TImage;
StaticText1: TStaticText;
Blood: TCheckBox;
Button3: TButton;
procedure SaveClick(Sender: TObject);
//function EnumDM(w, h, bpp, rr: Cardinal): Boolean;
//procedure ResolutionChange(Sender: TObject);
//function EnumRR(w, h, bpp, rr: Cardinal): Boolean;
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure UBarChange(Sender: TObject);
procedure BloodClick(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
SettingsForm: TSettingsForm;
implementation
uses Menu;
{$R *.dfm}
//type
// DisplayModeEnum = function(w, h, bpp, refresh: Cardinal): Boolean of object;
var
F: TextFile;
//devMode: TDeviceMode;
eStr: String;
SrRC: TSearchRec;
ResX, ResY: Integer;
procedure TSettingsForm.SaveClick(Sender: TObject);
begin
AssignFile(F, 'Config.cfg');
Rewrite(F);
//Writeln(F, Resolution.Text);
//Writeln(F, Copy(RefreshRate.Text, 0, Length(RefreshRate.Text)-2));
if S3.Brush.Color = clGreen then
Writeln(F, 'High') else
if S2.Brush.Color = clGreen then
Writeln(F, 'Medium') else
if S1.Brush.Color = clGreen then
Writeln(F, 'Low') else
Writeln(F, 'Very Low');
Writeln(F, UBar.Position);
if MapT.Text <> '' then
Writeln(F, MapT.Text) else
Writeln(F, 'Default');
if Blood.Checked then
Writeln(F, 1)
else
Writeln(F, 0);
CloseFile(F);
MenuForm.Show;
SettingsForm.Destroy;
end;
procedure TSettingsForm.Button3Click(Sender: TObject);
begin
MenuForm.Show;
SettingsForm.Destroy;
end;
(*
function TSettingsForm.EnumRR(w, h, bpp, rr: Cardinal): Boolean;
var
str: String;
begin
Result := True;
if (w <> ResX) or (h <> ResY) or (rr < 60) then Exit;
str := Format('%dHz', [rr]);
if RefreshRate.Items.IndexOf(str) = -1 then
RefreshRate.Items.Add(str);
end;
function TSettingsForm.EnumDM(w, h, bpp, rr: Cardinal): Boolean;
var
str: String;
begin
Result := True;
if (( w <> 800 ) or ( h <> 600 ))
and (( w <> 1024 ) or ( h <> 768 ))
and (( w <> 1152 ) or ( h <> 864 ))
and (( w <> 1280 ) or ( h <> 960 )) then
Exit;
str := Format('%dx%d', [w, h]);
if Resolution.Items.IndexOf(str) = -1 then
Resolution.Items.Add(str);
end;
procedure EnumerateDisplays(cb: DisplayModeEnum);
var
I: Integer;
modeExists: LongBool;
begin
I := 0;
modeExists := EnumDisplaySettings(nil, I, devMode);
while modeExists do
begin
with devMode do
begin
if not cb(dmPelsWidth, dmPelsHeight, dmBitsPerPel, dmDisplayFrequency) then
Exit;
end;
Inc(I);
modeExists := EnumDisplaySettings(nil, I, devMode);
end;
end;
procedure TSettingsForm.ResolutionChange(Sender: TObject);
var
I: Integer;
begin
I := 1;
while Resolution.Text[I] <> 'x' do Inc(I);
ResX := StrToInt(Copy(Resolution.Text, 0, I-1));
ResY := StrToInt(Copy(Resolution.Text, I+1, Length(Resolution.Text)));
RefreshRate.Clear;
EnumerateDisplays(EnumRR);
RefreshRate.ItemIndex := RefreshRate.Items.Count-1;
end;
*)
procedure TSettingsForm.FormCreate(Sender: TObject);
var
TStr: String;
I: Integer;
begin
Width := 800;
Height := 600;
Left := GetSystemMetrics(SM_CXSCREEN) div 2 - Width div 2;
Top := GetSystemMetrics(SM_CYSCREEN) div 2 - Height div 2;
//Image1.Picture.Bitmap.LoadFromFile('Pic2.dat');
//Image2.Picture.Bitmap.LoadFromFile('Pic.dat');
DoubleBuffered := True;
//EnumerateDisplayS(EnumDM);
//Resolution.ItemIndex := 0;
ResX := 800;
ResY := 600;
//RefreshRate.Clear;
//EnumerateDisplayS(EnumRR);
//RefreshRate.ItemIndex := RefreshRate.Items.Count-1;
UnitN.Caption := UnitN.Caption+' 15';
eStr := '15';
UBar.Position := 15;
if FindFirst('Data\Terrain\Themes\inf.pci', faAnyFile, SrRc) = 0 then
begin
AssignFile(F, 'Data\Terrain\Themes\inf.pci');
Reset(F);
repeat
Readln(F, TStr);
MapT.Items.Add(TStr);
until eof(F);
CloseFile(F);
MapT.ItemIndex := 0;
end;
if FindFirst('config.cfg', faAnyFile, SrRc) = 0 then
begin
AssignFile(F, 'config.cfg');
Reset(F);
(*Readln(F, TStr);
Resolution.ItemIndex := Resolution.Items.IndexOf(TStr);
I := 1;
while Resolution.Text[I] <> 'x' do Inc(I);
ResX := StrToInt(Copy(Resolution.Text, 0, I-1));
ResY := StrToInt(Copy(Resolution.Text, I+1, Length(Resolution.Text)));
Readln(F, TStr);
RefreshRate.Clear;
EnumerateDisplayS(EnumRR);
Refreshrate.ItemIndex := Refreshrate.Items.IndexOf(TStr+'Hz');
*)
Readln(F, TStr);
if TStr = 'High' then
begin
S1.Brush.Color := clGreen;
S2.Brush.Color := clGreen;
S3.Brush.Color := clGreen;
end else
if TStr = 'Medium' then
begin
S1.Brush.Color := clGreen;
S2.Brush.Color := clGreen;
S3.Brush.Color := clMaroon;
end else
if TStr = 'Low' then
begin
S1.Brush.Color := clGreen;
S2.Brush.Color := clMaroon;
S3.Brush.Color := clMaroon;
end else
if TStr = 'Very Low' then
begin
S1.Brush.Color := clMaroon;
S2.Brush.Color := clMaroon;
S3.Brush.Color := clMaroon;
end;
Detail.Caption := TStr;
Readln(F, I);
UBar.Position := I;
Readln(F, TStr);
MapT.ItemIndex := MapT.Items.IndexOf(TStr);
Readln(F, I);
if I = 0 then
Blood.Checked := False
else
Blood.Checked := True;
CloseFile(F);
end;
//I := 1;
//while Resolution.Text[I] <> 'x' do Inc(I);
// UnitN.Width := 20;
// UnitN.Height := 20;
end;
procedure TSettingsForm.Button2Click(Sender: TObject);
begin
if S1.Brush.Color = clMaroon then S1.Brush.Color := clGreen else
if S2.Brush.Color = clMaroon then S2.Brush.Color := clGreen else
if S3.Brush.Color = clMaroon then S3.Brush.Color := clGreen;
Blood.Enabled := True;
if S3.Brush.Color = clGreen then Detail.Caption := 'High' else
if S2.Brush.Color = clGreen then Detail.Caption := 'Medium' else
if S1.Brush.Color = clGreen then Detail.Caption := 'Low' else
begin
Blood.Checked := False;
Blood.Enabled := False;
Detail.Caption := 'Very Low';
end;
end;
procedure TSettingsForm.Button1Click(Sender: TObject);
begin
if S3.Brush.Color = clGreen then S3.Brush.Color := clMaroon else
if S2.Brush.Color = clGreen then S2.Brush.Color := clMaroon else
if S1.Brush.Color = clGreen then S1.Brush.Color := clMaroon;
Blood.Enabled := True;
if S3.Brush.Color = clGreen then Detail.Caption := 'High' else
if S2.Brush.Color = clGreen then Detail.Caption := 'Medium' else
if S1.Brush.Color = clGreen then Detail.Caption := 'Low' else
begin
Detail.Caption := 'Very Low';
Blood.Checked := False;
Blood.Enabled := False;
end;
end;
procedure TSettingsForm.UBarChange(Sender: TObject);
begin
UnitN.Caption := Copy(UnitN.Caption, 0, Length(UnitN.Caption)-3)+' '+IntToStr(UBar.Position);
UnitN.Caption := Copy(UnitN.Caption, 0, Length(UnitN.Caption)-3)+' '+IntToStr(UBar.Position);
end;
procedure TSettingsForm.BloodClick(Sender: TObject);
begin
if Detail.Caption = 'Very Low' then
Blood.Checked := False;
end;
end.
|
unit PersistentDialogU;
//Base class for a dialog form which can be created and freed
//on the fly, but can still be persistent when created with
//the constructor 'make'. It then streams out its dfm file to
//a temp directory and reads it back in when recreated.
//User must take care of erasing the temp-folder when
//application finishes.
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls;
type
TPersistentDialog = class(TForm)
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
private
fTempDir: string;
fOnFirstCreate: TNotifyEvent;
{ Private declarations }
public
constructor Make(const TempDir: string);
destructor Destroy; override;
function GetPopupPosition(p: TPoint; w, h, sw, sh: integer): TPoint;
property OnFirstCreate: TNotifyEvent read fOnFirstCreate write fOnFirstCreate;
{ Public declarations }
end;
var
PersistentDialog: TPersistentDialog;
implementation
{$R *.DFM}
uses FileCtrl;
{ TPersistentDialog }
destructor TPersistentDialog.Destroy;
begin
if fTempDir <> '' then
if DirectoryExists(fTempDir) then
begin
Visible := false;
WriteComponentResFile(fTempDir + '\' + ClassName + '.dfm', Self);
end;
inherited;
end;
constructor TPersistentDialog.Make(const TempDir: string);
var p: TPoint;
begin
if (TempDir <> '') and FileExists(TempDir + '\' + ClassName + '.dfm') then
begin
CreateNew(nil);
ReadComponentResFile(TempDir + '\' + ClassName + '.dfm', Self);
if Assigned(OnCreate) then
OnCreate(Self);
end
else
begin
Create(nil);
if Assigned(fOnFirstCreate) then fOnFirstCreate(Self);
end;
if Length(TempDir) > 0 then
fTempDir := TempDir
else
fTempDir := '';
GetCursorPos(p);
p := GetPopupPosition(p, Width, Height, screen.Width, screen.Height);
SetBounds(p.x, p.y, Width, Height);
end;
function TPersistentDialog.GetPopupPosition(p: TPoint; w, h, sw, sh: integer): TPoint;
begin
if p.x > w + 10 then
Result.x := p.x - w - 10
else
Result.x := p.x + 10;
if p.y - (h div 2) > 0 then
Result.y := p.y - (h div 2)
else
Result.y := p.y;
end;
end.
|
unit rPCE;
{$OPTIMIZATION OFF} // REMOVE AFTER UNIT IS DEBUGGED
interface
uses SysUtils, Classes, ORNet, ORFn, uPCE, UBACore, ORClasses, windows;
const
LX_ICD = 12;
LX_CPT = 13;
LX_SCT = 14;
LX_Threshold = 15;
PCE_IMM = 20;
PCE_SK = 21;
PCE_PED = 22;
PCE_HF = 23;
PCE_XAM = 24;
PCE_TRT = 25;
SCC_YES = 1;
SCC_NO = 0;
SCC_NA = -1;
var
uEncLocation: integer;
// uEncDateTime: TFMDateTime;
type
TSCConditions = record
SCAllow: Boolean; // prompt for service connected
SCDflt: Boolean; // default if prompting service connected
AOAllow: Boolean; // prompt for agent orange exposure
AODflt: Boolean; // default if prompting agent orange exposure
IRAllow: Boolean; // prompt for ionizing radiation exposure
IRDflt: Boolean; // default if prompting ionizing radiation
ECAllow: Boolean; // prompt for environmental conditions
ECDflt: Boolean; // default if prompting environmental cond.
MSTAllow: Boolean; // prompt for military sexual trauma
MSTDflt: Boolean; // default if prompting military sexual trauma
HNCAllow: Boolean; // prompt for Head or Neck Cancer
HNCDflt: Boolean; // default if prompting Head or Neck Cancer
CVAllow: Boolean; // prompt for Combat Veteran Related
CVDflt: Boolean; // default if prompting Comabt Veteran
SHDAllow: Boolean; // prompt for Shipboard Hazard and Defense
SHDDflt: Boolean; // default if prompting Shipboard Hazard and Defense
CLAllow: Boolean; // prompt for camp lejeune
CLDflt: Boolean; // default if propmpting camp lejeune
end;
type
TPCECodeDescriptions = record
codeList : TORStringList;
end;
TPCEListCodesProc = procedure(Dest: TStrings; SectionIndex: Integer);
TAskPCE = (apPrimaryNeeded, apPrimaryOutpatient, apPrimaryAlways,
apNeeded, apOutpatient, apAlways, apNever, apDisable);
function GetVisitCat(InitialCat: char; Location: integer; Inpatient: boolean): char;
function GetDiagnosisText(Narrative: String; Code: String): String;
function GetFreqOfText(SearchStr: String): integer;
{assign and read values from fPCEData}
//function SetRPCEncouterInfo(PCEData: TPCEData): boolean;
function SetRPCEncLocation(Loc: Integer): boolean;
//function SetRPCEncDateTime(DT: TFMDateTime): boolean;
function PCERPCEncLocation: integer;
//function PCERPCEncDateTime: TFMDateTime;
function GetLocSecondaryVisitCode(Loc: integer): char;
{check for active person class on provider}
function CheckActivePerson(provider:string;DateTime:TFMDateTime): boolean;
function ForcePCEEntry(Loc: integer): boolean;
{"Other" form PCE calls}
procedure LoadcboOther(Dest: TStrings; Location, fOtherApp: Integer);
{ Lexicon Lookup Calls }
function LexiconToCode(IEN, LexApp: Integer; ADate: TFMDateTime = 0): string;
procedure ListLexicon(Dest: TStrings; const x: string; LexApp: Integer; ADate: TFMDateTime = 0; AExtend: Boolean = False; AI10Active: Boolean = False);
//procedure GetI10Alternatives(Dest: TStrings; SCTCode: string);
function IsActiveICDCode(ACode: string; ADate: TFMDateTime = 0): boolean;
function IsActiveCPTCode(ACode: string; ADate: TFMDateTime = 0): boolean;
function IsActiveSCTCode(ACode: string; ADate: TFMDateTime = 0): boolean;
function IsActiveCode(ACode: string; LexApp: integer; ADate: TFMDateTime = 0): boolean;
function GetICDVersion(ADate: TFMDateTime = 0): String;
{ Encounter Form Elements }
procedure DeletePCE(const AVisitStr: string);
function EligbleConditions: TSCConditions;
procedure ListVisitTypeSections(Dest: TStrings);
procedure ListVisitTypeCodes(Dest: TStrings; SectionIndex: Integer);
procedure ListVisitTypeByLoc(Dest: TStrings; Location: Integer; ADateTime: TFMDateTime = 0);
function AutoSelectVisit(Location: integer): boolean;
function UpdateVisitTypeModifierList(Dest: TStrings; Index: integer): string;
procedure ListDiagnosisSections(Dest: TStrings);
procedure ListDiagnosisCodes(Dest: TStrings; SectionIndex: Integer);
procedure UpdateDiagnosisObj(CodeNarr: String; ItemIndex: Integer);
procedure ListExamsSections(Dest: TStrings);
procedure ListExamsCodes(Dest: TStrings; SectionIndex: Integer);
procedure ListHealthSections(Dest: TStrings);
procedure ListHealthCodes(Dest: TStrings; SectionIndex: Integer);
procedure ListImmunizSections(Dest: TStrings);
procedure ListImmunizCodes(Dest: TStrings; SectionIndex: Integer);
procedure ListPatientSections(Dest: TStrings);
procedure ListPatientCodes(Dest: TStrings; SectionIndex: Integer);
procedure ListProcedureSections(Dest: TStrings);
procedure ListProcedureCodes(Dest: TStrings; SectionIndex: Integer);
function ModifierList(CPTCode: string): string;
procedure ListCPTModifiers(Dest: TStrings; CPTCodes, NeededModifiers: string);
function ModifierName(ModIEN: string): string;
function ModifierCode(ModIEN: string): string;
function UpdateModifierList(Dest: TStrings; Index: integer): string;
procedure ListSkinSections(Dest: TStrings);
procedure ListSkinCodes(Dest: TStrings; SectionIndex: Integer);
procedure ListSCDisabilities(Dest: TStrings);
procedure LoadPCEDataForNote(Dest: TStrings; ANoteIEN: Integer; VStr: string);
function GetVisitIEN(NoteIEN: Integer): string;
procedure SavePCEData(PCEList: TStringList; ANoteIEN, ALocation: integer);
function DataHasCPTCodes(AList: TStrings): boolean;
function GetAskPCE(Loc: integer): TAskPCE;
function HasVisit(const ANoteIEN, ALocation: integer; const AVisitDate: TFMDateTime): Integer;
procedure LoadImmSeriesItems(Dest: TStrings);
procedure LoadImmReactionItems(Dest: TStrings);
procedure LoadSkResultsItems(Dest: TStrings);
procedure LoadPEDLevelItems(Dest: TStrings);
procedure LoadHFLevelItems(Dest: TStrings);
procedure LoadXAMResultsItems(Dest: TStrings);
procedure LoadHistLocations(Dest: TStrings);
procedure AddProbsToDiagnoses;
procedure RefreshPLDiagnoses;
//GAF
function GAFOK: boolean;
function MHClinic(const Location: integer): boolean;
procedure RecentGAFScores(const Limit: integer);
function SaveGAFScore(const Score: integer; GAFDate: TFMDateTime; Staff: Int64): boolean;
function GAFURL: string;
function MHTestsOK: boolean;
function MHTestAuthorized(Test: string): boolean;
function AnytimeEncounters: boolean;
function AutoCheckout(Loc: integer): boolean;
{ Encounter }
//function RequireExposures(ANote: Integer): Boolean; {RAB}
function RequireExposures(ANote, ATitle: Integer): Boolean;
function PromptForWorkload(ANote, ATitle: Integer; VisitCat: Char; StandAlone: boolean): Boolean;
function DefaultProvider(ALocation: integer; AUser: Int64; ADate: TFMDateTime;
ANoteIEN: integer): string;
function IsUserAProvider(AUser: Int64; ADate: TFMDateTime): boolean;
function IsUserAUSRProvider(AUser: Int64; ADate: TFMDateTime): boolean;
function IsCancelOrNoShow(ANote: integer): boolean;
function IsNonCountClinic(ALocation: integer): boolean;
// HNC Flag
//function HNCOK: boolean;
implementation
uses uGlobalVar, TRPCB, rCore, uCore, uConst, fEncounterFrame, UBAGlobals, UBAConst, rMisc, fDiagnoses;
var
uLastLocation: Integer;
uLastDFN: String;
uLastEncDt: TFMDateTime;
uVTypeLastLoc: Integer;
uVTypeLastDate: double = 0;
uDiagnoses: TStringList;
uExams: TStringList;
uHealthFactors: TStringList;
uImmunizations: TStringList;
uPatientEds: TStringList;
uProcedures: TStringList;
uSkinTests: TStringList;
uVisitTypes: TStringList;
uVTypeForLoc: TStringList;
uProblems: TStringList;
uModifiers: TORStringList = nil;
uGAFOK: boolean;
uGAFOKCalled: boolean = FALSE;
uLastForceLoc: integer = -1;
uLastForce: boolean;
uHasCPT: TStringList = nil;
uGAFURL: string;
uGAFURLChecked: boolean = FALSE;
uMHOK: boolean;
uMHOKChecked: boolean = FALSE;
uVCInitialCat: char = #0;
uVCLocation: integer = -2;
uVCInpatient: boolean = FALSE;
uVCResult: char;
uAPUser: Int64 = -1;
uAPLoc: integer = -2;
uAPAsk: TAskPCE;
uAnytimeEnc: integer = -1;
UAutoSelLoc: integer = -1;
UAutoSelVal: boolean;
uLastChkOut: boolean;
uLastChkOutLoc: integer = -2;
uLastIsClinicLoc: integer = 0;
uLastIsClinic: boolean = FALSE;
uPCECodeDescriptions: TPCECodeDescriptions;
// uHNCOK: integer = -1;
function GetVisitCat(InitialCat: char; Location: integer; Inpatient: boolean): char;
var
tmp: string;
begin
if(InitialCat <> uVCInitialCat) or (Location <> uVCLocation) or
(Inpatient <> uVCInpatient) then
begin
uVCInitialCat := InitialCat;
uVCLocation := Location;
uVCInpatient := Inpatient;
tmp := sCallV('ORWPCE GETSVC', [InitialCat, Location, BOOLCHAR[Inpatient]]);
if(tmp <> '') then
uVCResult := tmp[1]
else
uVCResult := InitialCat;
end;
Result := uVCResult
end;
function GetDiagnosisText(Narrative: String; Code: String): String;
var
idx: integer;
str: string;
begin
// Result := sCallV('ORWPCE GET DX TEXT', [Narrative, Code]);
if uPCECodeDescriptions.codeList <> nil then
begin
idx := uPCECodeDescriptions.codeList.IndexOfPieces([Code, Narrative], 1);
if idx = -1 then
begin
Result := sCallV('ORWPCE GET DX TEXT', [Narrative, Code]);
str := Code + U + Narrative + U + Result;
uPCECodeDescriptions.codeList.add(str);
end
else
begin
str := uPCECodeDescriptions.codeList[idx];
if (Code = Piece(str, U, 1)) and (Narrative = Piece(str, U, 2)) then Result := Piece(str, U, 3)
else
begin
Result := sCallV('ORWPCE GET DX TEXT', [Narrative, Code]);
str := Code + U + Narrative + U + Result;
uPCECodeDescriptions.codeList.add(str);
end;
end;
end
else
begin
uPCECodeDescriptions.codeList := TORStringList.Create;
Result := sCallV('ORWPCE GET DX TEXT', [Narrative, Code]);
str := Code + U + Narrative + U + Result;
uPCECodeDescriptions.codeList.add(str);
end;
end;
function GetFreqOfText(SearchStr: String): integer;
begin
Result := StrToInt(sCallV('ORWLEX GETFREQ', [SearchStr]));
end;
{ Lexicon Lookup Calls }
function LexiconToCode(IEN, LexApp: Integer; ADate: TFMDateTime = 0): string;
var
CodeSys: string;
begin
case LexApp of
LX_ICD: CodeSys := 'ICD';
LX_CPT: CodeSys := 'CHP';
LX_SCT: CodeSys := 'GMPX';
end;
Result := Piece(sCallV('ORWPCE LEXCODE', [IEN, CodeSys, ADate]), U, 1);
end;
procedure ListLexicon(Dest: TStrings; const x: string; LexApp: Integer; ADate: TFMDateTime = 0; AExtend: Boolean = False; AI10Active: Boolean = False);
var
CodeSys: string;
ExtInt: integer;
begin
case LexApp of
LX_ICD: CodeSys := 'ICD';
LX_CPT: CodeSys := 'CHP';
LX_SCT: CodeSys := 'GMPX';
end;
if AExtend then
ExtInt := 1
else
ExtInt := 0;
if (LexApp = LX_ICD) and AExtend and AI10Active then
CallV('ORWLEX GETI10DX', [x, ADate])
else
CallV('ORWPCE4 LEX', [x, CodeSys, ADate, ExtInt, True]);
FastAssign(RPCBrokerV.Results, Dest);
end;
//TODO: Code for I10 mapped alternatives - remove if not reinstated as requirement
{procedure GetI10Alternatives(Dest: TStrings; SCTCode: string);
begin
CallV('ORWLEX GETALTS', [SCTCode, 'SCT']);
FastAssign(RPCBrokerV.Results, Dest);
end;}
function IsActiveICDCode(ACode: string; ADate: TFMDateTime = 0): boolean;
begin
Result := IsActiveCode(ACode, LX_ICD, ADate);
end;
function IsActiveCPTCode(ACode: string; ADate: TFMDateTime = 0): boolean;
begin
Result := IsActiveCode(ACode, LX_CPT, ADate);
end;
function IsActiveSCTCode(ACode: string; ADate: TFMDateTime = 0): boolean;
begin
Result := IsActiveCode(ACode, LX_SCT, ADate);
end;
function IsActiveCode(ACode: string; LexApp: integer; ADate: TFMDateTime = 0): boolean;
var
CodeSys: string;
begin
case LexApp of
LX_ICD: CodeSys := 'ICD';
LX_CPT: CodeSys := 'CHP';
LX_SCT: CodeSys := 'GMPX';
end;
Result := (sCallV('ORWPCE ACTIVE CODE',[ACode, CodeSys, ADate]) = '1');
end;
function GetICDVersion(ADate: TFMDateTime = 0): String;
begin
Result := sCallV('ORWPCE ICDVER', [ADate]);
end;
{ Encounter Form Elements ------------------------------------------------------------------ }
procedure DeletePCE(const AVisitStr: string);
begin
sCallV('ORWPCE DELETE', [AVisitStr, Patient.DFN]);
end;
procedure LoadEncounterForm;
{ load the major coding lists that are used by the encounter form for a given location }
var
i: integer;
uTempList: TStringList;
EncDt: TFMDateTime;
begin
uLastLocation := uEncLocation;
EncDt := Trunc(uEncPCEData.VisitDateTime);
if uEncPCEData.VisitCategory = 'E' then EncDt := Trunc(FMNow);
uLastEncDt := EncDt;
EncLoadDateTime := Now;
//add problems to the top of diagnoses.
uTempList := TstringList.Create;
if UBAGlobals.BILLING_AWARE then //BAPHII 1.3.10
begin
UBACore.BADxList := TStringList.Create;
end;
try
uDiagnoses.clear;
if BILLING_AWARE then
begin
UBACore.BADxList.Clear; //BAPHII 1.3.10
end;
CallVistA('ORWPCE DIAG', [uEncLocation, EncDT, Patient.DFN], uTempList);
//tCallV(uTempList, 'ORWPCE DIAG', [uEncLocation, EncDt]); //BAPHII 1.3.10
uDiagnoses.add(utemplist.strings[0]); //BAPHII 1.3.10
AddProbsToDiagnoses; //BAPHII 1.3.10
// BA 25 AddProviderPatientDaysDx(uDxLst, IntToStr(Encounter.Provider), Patient.DFN);
for i := 1 to (uTempList.Count-1) do //BAPHII 1.3.10
uDiagnoses.add(uTemplist.strings[i]); //BAPHII 1.3.10
finally
uTempList.free;
end;
tCallV(uVisitTypes, 'ORWPCE VISIT', [uEncLocation, EncDt]);
tCallV(uProcedures, 'ORWPCE PROC', [uEncLocation, EncDt]);
tCallV(uImmunizations, 'ORWPCE IMM', [uEncLocation]);
tCallV(uSkinTests, 'ORWPCE SK', [uEncLocation]);
tCallV(uPatientEds, 'ORWPCE PED', [uEncLocation]);
tCallV(uHealthFactors, 'ORWPCE HF', [uEncLocation]);
tCallV(uExams, 'ORWPCE XAM', [uEncLocation]);
if uVisitTypes.Count > 0 then uVisitTypes.Delete(0); // discard counts
if uDiagnoses.Count > 0 then uDiagnoses.Delete(0);
if uProcedures.Count > 0 then uProcedures.Delete(0);
if uImmunizations.Count > 0 then uImmunizations.Delete(0);
if uSkinTests.Count > 0 then uSkinTests.Delete(0);
if uPatientEds.Count > 0 then uPatientEds.Delete(0);
if uHealthFactors.Count > 0 then uHealthFactors.Delete(0);
if uExams.Count > 0 then uExams.Delete(0);
if (uVisitTypes.Count > 0) and (CharAt(uVisitTypes[0], 1) <> U) then uVisitTypes.Insert(0, U);
if (uDiagnoses.Count > 0) and (CharAt(uDiagnoses[0], 1) <> U) then uDiagnoses.Insert(0, U);
if (uProcedures.Count > 0) and (CharAt(uProcedures[0], 1) <> U) then uProcedures.Insert(0, U);
if (uImmunizations.Count > 0) and (CharAt(uImmunizations[0], 1) <> U) then uImmunizations.Insert(0, U);
if (uSkinTests.Count > 0) and (CharAt(uSkinTests[0], 1) <> U) then uSkinTests.Insert(0, U);
if (uPatientEds.Count > 0) and (CharAt(uPatientEds[0], 1) <> U) then uPatientEds.Insert(0, U);
if (uHealthFactors.Count > 0) and (CharAt(uHealthFactors[0], 1) <> U) then uHealthFactors.Insert(0, U);
if (uExams.Count > 0) and (CharAt(uExams[0], 1) <> U) then uExams.Insert(0, U);
end;
{Visit Types-------------------------------------------------------------------}
procedure ListVisitTypeSections(Dest: TStrings);
{ return section names in format: ListIndex^SectionName (sections begin with '^') }
var
i: Integer;
x: string;
begin
if (uLastLocation <> uEncLocation) then LoadEncounterForm;
for i := 0 to uVisitTypes.Count - 1 do if CharAt(uVisitTypes[i], 1) = U then
begin
x := Piece(uVisitTypes[i], U, 2);
if Length(x) = 0 then x := '<No Section Name>';
Dest.Add(IntToStr(i) + U + Piece(uVisitTypes[i], U, 2) + U + x);
end;
end;
procedure ListVisitTypeCodes(Dest: TStrings; SectionIndex: Integer);
{ return visit types in format: visit type <TAB> amount of time <TAB> CPT code <TAB> CPT code }
var
i: Integer;
s: string;
function InsertTab(x: string): string;
{ turn the white space between the name and the number of minutes into a single tab }
begin
if CharAt(x, 20) = ' '
then Result := Trim(Copy(x, 1, 20)) + U + Trim(Copy(x, 21, Length(x)))
else Result := Trim(x) + U;
end;
begin {ListVisitTypeCodes}
Dest.Clear;
i := SectionIndex + 1; // first line after the section name
while (i < uVisitTypes.Count) and (CharAt(uVisitTypes[i], 1) <> U) do
begin
s := Pieces(uVisitTypes[i], U, 1, 2) + U + InsertTab(Piece(uVisitTypes[i], U, 2)) + U + Piece(uVisitTypes[i], U, 1) +
U + IntToStr(i);
Dest.Add(s);
Inc(i);
end;
end;
procedure ListVisitTypeByLoc(Dest: TStrings; Location: Integer; ADateTime: TFMDateTime = 0);
var
i: Integer;
x, SectionName: string;
EncDt: TFMDateTime;
begin
EncDt := Trunc(ADateTime);
if (uVTypeLastLoc <> Location) or (uVTypeLastDate <> EncDt) then
begin
uVTypeForLoc.Clear;
if Location = 0 then Exit;
SectionName := '';
CallV('ORWPCE VISIT', [Location, EncDt]);
with RPCBrokerV do for i := 0 to Results.Count - 1 do
begin
x := Results[i];
if CharAt(x, 1) = U
then SectionName := Piece(x, U, 2)
else uVTypeForLoc.Add(Piece(x, U, 1) + U + SectionName + U + Piece(x, U, 2));
end;
uVTypeLastLoc := Location;
uVTypeLastDate := EncDt;
end;
FastAssign(uVTypeForLoc, Dest);
end;
function AutoSelectVisit(Location: integer): boolean;
begin
if UAutoSelLoc <> Location then
begin
UAutoSelVal := (sCallV('ORWPCE AUTO VISIT TYPE SELECT', [Location]) = '1');
UAutoSelLoc := Location;
end;
Result := UAutoSelVal;
end;
{Diagnosis---------------------------------------------------------------------}
procedure ListDiagnosisSections(Dest: TStrings);
{ return section names in format: ListIndex^SectionName (sections begin with '^') }
var
i: Integer;
x: string;
begin
if (uLastLocation <> uEncLocation) or (uLastDFN <> patient.DFN) or (uLastEncDt <> Trunc(uEncPCEData.VisitDateTime))
or PLUpdated or IsDateMoreRecent(PLUpdateDateTime, EncLoadDateTime) then RefreshPLDiagnoses;
if PLUpdated then PLUpdated := False;
for i := 0 to uDiagnoses.Count - 1 do if CharAt(uDiagnoses[i], 1) = U then
begin
x := Piece(uDiagnoses[i], U, 2);
if Length(x) = 0 then x := '<No Section Name>';
Dest.Add(IntToStr(i) + U + Piece(uDiagnoses[i], U, 2) + U + x);
end;
end;
procedure ListDiagnosisCodes(Dest: TStrings; SectionIndex: Integer);
{ return diagnoses within section in format:
diagnosis <TAB> ICDInteger <TAB> .ICDDecimal <TAB> ICD Code }
var
i: Integer;
t, c, f, p, ICDCSYS: string;
begin
Dest.Clear;
i := SectionIndex + 1; // first line after the section name
while (i < uDiagnoses.Count) and (CharAt(uDiagnoses[i], 1) <> U) do
begin
c := Piece(uDiagnoses[i], U, 1);
t := Piece(uDiagnoses[i], U, 2);
f := Piece(uDiagnoses[i], U, 3);
p := Piece(uDiagnoses[i], U, 4);
ICDCSYS := Piece(uDiagnoses[i], U, 5);
//identify inactive codes.
if (Pos('#', f) > 0) or (Pos('$', f) > 0) then
t := '# ' + t;
Dest.Add(c + U + t + U + c + U + f + U + p + U + ICDCSYS);
Inc(i);
end;
end;
procedure AddProbsToDiagnoses;
var
i: integer; //loop index
EncDT: TFMDateTime;
ICDVersion: String;
begin
//get problem list
EncDT := Trunc(uEncPCEData.VisitDateTime);
uLastDFN := patient.DFN;
ICDVersion := piece(Encounter.GetICDVersion, U, 1);
tCallV(uProblems, 'ORWPCE ACTPROB', [Patient.DFN, EncDT]);
if uProblems.count > 0 then
begin
//add category to udiagnoses
uDiagnoses.add(U + DX_PROBLEM_LIST_TXT);
for i := 1 to (uProblems.count-1) do //start with 1 because strings[0] is the count of elements.
begin
//filter out 799.9 and inactive codes when ICD-9 is active
if (ICDVersion = 'ICD') and ((piece(uProblems.Strings[i],U,3) = '799.9') or (piece(uProblems.Strings[i],U,13) = '#')) then continue;
// otherwise add all active problems (including 799.9, R69, and inactive codes) to udiagnosis
uDiagnoses.add(piece(uProblems.Strings[i], U, 3) + U + piece(uProblems.Strings[i], U, 2) + U +
piece(uProblems.Strings[i], U, 13) + U + piece(uProblems.Strings[i], U, 1) + U +
piece(uProblems.Strings[i], U, 14));
end;
//1.3.10
if BILLING_AWARE then
begin
// add New Section and dx codes to Encounter Diagnosis Section and Code List.
// Diagnoses -> Provider/Patient/24 hrs
uDiagnoses.add(UBAConst.ENCOUNTER_TODAYS_DX); //BAPHII 1.3.10
//BADxList := AddProviderPatientDaysDx(UBACore.uDxLst, IntToStr(Encounter.Provider), Patient.DFN); //BAPHII 1.3.10
rpcGetProviderPatientDaysDx(IntToStr(Encounter.Provider), Patient.DFN); //BAPHII 1.3.10
for i := 0 to (UBACore.uDxLst.Count-1) do //BAPHII 1.3.10
uDiagnoses.add(UBACore.uDxLst[i]); //BAPHII 1.3.10
// Code added after presentation.....
// Add Personal Diagnoses Section and Codes to Encounter Diagnosis Section and Code List.
UBACore.uDxLst.Clear;
uDiagnoses.Add(UBAConst.ENCOUNTER_PERSONAL_DX);
UBACore.uDxLst := rpcGetPersonalDxList(User.DUZ);
for i := 0 to (UBACore.uDxLst.Count -1) do
begin
uDiagnoses.Add(UBACore.uDxLst.Strings[i]);
end;
end;
end;
end;
procedure RefreshPLDiagnoses;
var
i: integer;
uDiagList: TStringList;
EncDt: TFMDateTime;
begin
EncDt := Trunc(uEncPCEData.VisitDateTime);
if uEncPCEData.VisitCategory = 'E' then EncDt := Trunc(FMNow);
//add problems to the top of diagnoses.
uDiagList := TStringList.Create;
try
uDiagnoses.clear;
CallVistA('ORWPCE DIAG', [uEncLocation, EncDT, Patient.DFN], uDiagList);
uDiagnoses.add(uDiaglist.Strings[0]);
AddProbsToDiagnoses;
for i := 1 to (uDiagList.Count-1) do
uDiagnoses.add(uDiaglist.Strings[i]);
finally
uDiagList.free;
end;
end;
procedure UpdateDiagnosisObj(CodeNarr: String; ItemIndex: Integer);
//CodeNarr format = ICD-9/10 code ^ Narrative ^ ICD-9/10 code ^ # and/or $ ^ Problem IEN ^ ICD coding system (10D or ICD)
var
i: Integer;
begin
i := ItemIndex + 1;
uDiagnoses[i] := Pieces(CodeNarr, U, 1, 2) + U + U + Piece(CodeNarr, U, 5) + U + Piece(CodeNarr, U, 6);
end;
{Immunizations-----------------------------------------------------------------}
procedure LoadImmReactionItems(Dest: TStrings);
begin
tCallV(Dest,'ORWPCE GET SET OF CODES',['9000010.11','.06','1']);
end;
procedure LoadImmSeriesItems(Dest: TStrings);
{loads items into combo box on Immunixation screen}
begin
tCallV(Dest,'ORWPCE GET SET OF CODES',['9000010.11','.04','1']);
end;
procedure ListImmunizSections(Dest: TStrings);
{ return section names in format: ListIndex^SectionName (sections begin with '^') }
var
i: Integer;
x: string;
begin
if (uLastLocation <> uEncLocation) then LoadEncounterForm;
for i := 0 to uImmunizations.Count - 1 do if CharAt(uImmunizations[i], 1) = U then
begin
x := Piece(uImmunizations[i], U, 2);
if Length(x) = 0 then x := '<No Section Name>';
Dest.Add(IntToStr(i) + U + Piece(uImmunizations[i], U, 2) + U + x);
end;
end;
procedure ListImmunizCodes(Dest: TStrings; SectionIndex: Integer);
{ return procedures within section in format: procedure <TAB> CPT code <TAB><TAB> CPT code}
var
i: Integer;
begin
Dest.Clear;
i := SectionIndex + 1; // first line after the section name
while (i < uImmunizations.Count) and (CharAt(uImmunizations[i], 1) <> U) do
begin
Dest.Add(Pieces(uImmunizations[i], U, 1, 2));
Inc(i);
end;
end;
{Procedures--------------------------------------------------------------------}
procedure ListProcedureSections(Dest: TStrings);
{ return section names in format: ListIndex^SectionName (sections begin with '^') }
var
i: Integer;
x: string;
begin
if (uLastLocation <> uEncLocation) then LoadEncounterForm;
for i := 0 to uProcedures.Count - 1 do if CharAt(uProcedures[i], 1) = U then
begin
x := Piece(uProcedures[i], U, 2);
if Length(x) = 0 then x := '<No Section Name>';
Dest.Add(IntToStr(i) + U + Piece(uProcedures[i], U, 2) + U + x);
end;
end;
procedure ListProcedureCodes(Dest: TStrings; SectionIndex: Integer);
{ return procedures within section in format: procedure <TAB> CPT code <TAB><TAB> CPT code}
//Piece 12 are CPT Modifiers, Piece 13 is a flag indicating conversion of Piece 12 from
//modifier code to modifier IEN (updated in UpdateModifierList routine)
var
i: Integer;
begin
Dest.Clear;
i := SectionIndex + 1; // first line after the section name
while (i < uProcedures.Count) and (CharAt(uProcedures[i], 1) <> U) do
begin
Dest.Add(Pieces(uProcedures[i], U, 1, 2) + U + Piece(uProcedures[i], U, 1) + U +
Piece(uProcedures[i], U, 12) + U + Piece(uProcedures[i], U, 13) + U +
IntToStr(i));
Inc(i);
end;
end;
function MixedCaseModifier(const inStr: string): string;
begin
Result := inStr;
SetPiece(Result, U, 2, MixedCase(Trim(Piece(Result, U, 2))));
end;
function ModifierIdx(ModIEN: string): integer;
var
EncDt: TFMDateTime;
begin
Result := uModifiers.IndexOfPiece(ModIEN);
if(Result < 0) then
begin
if Assigned(uEncPCEData) then // may not exist yet on display of note and PCE data
EncDT := Trunc(uEncPCEData.VisitDateTime)
else if Encounter.DateTime > 0 then // really need note date/time next, but can't get to it
EncDT := Trunc(Encounter.DateTime)
else
EncDT := FMToday;
Result := uModifiers.Add(MixedCaseModifier(sCallV('ORWPCE GETMOD', [ModIEN, EncDt])));
end;
end;
function ModifierList(CPTCode: string): string;
// uModifiers list contains <@>CPTCode;ModCount;^Mod1Index^Mod2Index^...^ModNIndex
// or MODIEN^MODDescription^ModCode
const
CPTCodeHeader = '<@>';
var
i, idx: integer;
s, ModIEN: string;
EncDt: TFMDateTime;
begin
EncDT := Trunc(uEncPCEData.VisitDateTime);
idx := uModifiers.IndexOfPiece(CPTCodeHeader + CPTCode, ';', 1);
if(idx < 0) then
begin
CallV('ORWPCE CPTMODS', [CPTCode, EncDt]);
s := CPTCodeHeader + CPTCode + ';' + IntToStr(RPCBrokerV.Results.Count) + ';' + U;
for i := 0 to RPCBrokerV.Results.Count - 1 do
begin
ModIEN := piece(RPCBrokerV.Results[i], U, 1);
idx := uModifiers.IndexOfPiece(ModIEN);
if(idx < 0) then
idx := uModifiers.Add(MixedCaseModifier(RPCBrokerV.Results[i]));
s := s + IntToStr(idx) + U;
end;
idx := uModifiers.Add(s);
end;
Result := uModifiers[idx];
end;
procedure ListCPTModifiers(Dest: TStrings; CPTCodes, NeededModifiers: string);
//CPTCodes expected in the format of code^code^code
//NeededModifiers in format of ModIEN1;ModIEN2;ModIEN3
var
TmpSL: TStringList;
i, j, idx, cnt, found: integer;
s, Code: string;
begin
if(not assigned(uModifiers)) then uModifiers := TORStringList.Create;
if(copy(CPTCodes, length(CPTCodes), 1) <> U) then
CPTCodes := CPTCodes + U;
if(copy(NeededModifiers, length(NeededModifiers), 1) <> ';') then
NeededModifiers := NeededModifiers + ';';
TmpSL := TStringList.Create;
try
repeat
i := pos(U, CPTCodes);
if(i > 0) then
begin
Code := copy(CPTCodes, 1, i-1);
delete(CPTCodes,1,i);
if(Code <> '') then
TmpSL.Add(ModifierList(Code));
i := pos(U, CPTCodes);
end;
until(i = 0);
if(TmpSL.Count = 0) then
s := ';0;'
else
if(TmpSL.Count = 1) then
s := TmpSL[0]
else
begin
s := '';
found := 0;
cnt := StrToIntDef(piece(TmpSL[0], ';', 2), 0);
for i := 1 to cnt do
begin
Code := U + Piece(TmpSL[0], U, i+1);
for j := 1 to TmpSL.Count-1 do
begin
if(pos(Code + U, TmpSL[j]) = 0) then
begin
Code := '';
break;
end;
end;
if(Code <> '') then
begin
s := s + Code;
inc(found);
end;
end;
s := s + U;
SetPiece(s , U, 1, ';' + IntToStr(Found) + ';');
end;
finally
TmpSL.Free;
end;
Dest.Clear;
cnt := StrToIntDef(piece(s, ';', 2), 0);
if(NeededModifiers <> '') then
begin
found := cnt;
repeat
i := pos(';',NeededModifiers);
if(i > 0) then
begin
idx := StrToIntDef(copy(NeededModifiers,1,i-1),0);
if(idx > 0) then
begin
Code := IntToStr(ModifierIdx(IntToStr(idx))) + U;
if(pos(U+Code, s) = 0) then
begin
s := s + Code;
inc(cnt);
end;
end;
delete(NeededModifiers,1,i);
end;
until(i = 0);
if(found <> cnt) then
SetPiece(s , ';', 2, IntToStr(cnt));
end;
for i := 1 to cnt do
begin
idx := StrToIntDef(piece(s, U, i + 1), -1);
if(idx >= 0) then
Dest.Add(uModifiers[idx]);
end;
end;
function ModifierName(ModIEN: string): string;
begin
if(not assigned(uModifiers)) then uModifiers := TORStringList.Create;
Result := piece(uModifiers[ModifierIdx(ModIEN)], U, 2);
end;
function ModifierCode(ModIEN: string): string;
begin
if(not assigned(uModifiers)) then uModifiers := TORStringList.Create;
Result := piece(uModifiers[ModifierIdx(ModIEN)], U, 3);
end;
function UpdateModifierList(Dest: TStrings; Index: integer): string;
var
i, idx, LastIdx: integer;
Tmp, OKMods, Code: string;
OK: boolean;
begin
if(Piece(Dest[Index], U, 5) = '1') then
Result := Piece(Dest[Index],U,4)
else
begin
Tmp := Piece(Dest[Index], U, 4);
Result := '';
OKMods := ModifierList(Piece(Dest[Index], U, 1))+U;
i := 1;
repeat
Code := Piece(Tmp,';',i);
if(Code <> '') then
begin
LastIdx := -1;
OK := FALSE;
repeat
idx := uModifiers.IndexOfPiece(Code, U, 3, LastIdx);
if(idx >= 0) then
begin
if(pos(U + IntToStr(idx) + U, OKMods)>0) then
begin
Result := Result + piece(uModifiers[idx],U,1) + ';';
OK := TRUE;
end
else
LastIdx := Idx;
end;
until(idx < 0) or OK;
inc(i);
end
until(Code = '');
Tmp := Dest[Index];
SetPiece(Tmp,U,4,Result);
SetPiece(Tmp,U,5,'1');
Dest[Index] := Tmp;
idx := StrToIntDef(piece(Tmp,U,6),-1);
if(idx >= 0) then
begin
Tmp := uProcedures[idx];
SetPiece(Tmp,U,12,Result);
SetPiece(Tmp,U,13,'1');
uProcedures[idx] := Tmp;
end;
end;
end;
function UpdateVisitTypeModifierList(Dest: TStrings; Index: integer): string;
var
i, idx, LastIdx: integer;
Tmp, OKMods, Code: string;
OK: boolean;
begin
if(Piece(Dest[Index], U, 7) = '1') then
Result := Piece(Dest[Index],U,6)
else
begin
Tmp := Piece(Dest[Index], U, 6);
Result := '';
OKMods := ModifierList(Piece(Dest[Index], U, 1))+U;
i := 1;
repeat
Code := Piece(Tmp,';',i);
if(Code <> '') then
begin
LastIdx := -1;
OK := FALSE;
repeat
idx := uModifiers.IndexOfPiece(Code, U, 3, LastIdx);
if(idx >= 0) then
begin
if(pos(U + IntToStr(idx) + U, OKMods)>0) then
begin
Result := Result + piece(uModifiers[idx],U,1) + ';';
OK := TRUE;
end
else
LastIdx := Idx;
end;
until(idx < 0) or OK;
inc(i);
end
until(Code = '');
Tmp := Dest[Index];
SetPiece(Tmp,U,6,Result);
SetPiece(Tmp,U,7,'1');
Dest[Index] := Tmp;
idx := StrToIntDef(piece(Tmp,U,8),-1);
if(idx >= 0) then
begin
Tmp := uProcedures[idx];
SetPiece(Tmp,U,12,Result);
SetPiece(Tmp,U,13,'1');
uProcedures[idx] := Tmp;
end;
end;
end;
{SkinTests---------------------------------------------------------------------}
procedure LoadSkResultsItems(Dest: TStrings);
begin
tCallV(Dest,'ORWPCE GET SET OF CODES',['9000010.12','.04','1']);
end;
procedure ListSkinSections(Dest: TStrings);
{ return section names in format: ListIndex^SectionName (sections begin with '^') }
var
i: Integer;
x: string;
begin
if (uLastLocation <> uEncLocation) then LoadEncounterForm;
for i := 0 to uSkinTests.Count - 1 do if CharAt(uSkinTests[i], 1) = U then
begin
x := Piece(uSkinTests[i], U, 2);
if Length(x) = 0 then x := '<No Section Name>';
Dest.Add(IntToStr(i) + U + Piece(uSkinTests[i], U, 2) + U + x);
end;
end;
procedure ListSkinCodes(Dest: TStrings; SectionIndex: Integer);
{ return procedures within section in format: procedure <TAB> CPT code <TAB><TAB> CPT code}
var
i: Integer;
begin
Dest.Clear;
i := SectionIndex + 1; // first line after the section name
while (i < uSkinTests.Count) and (CharAt(uSkinTests[i], 1) <> U) do
begin
Dest.Add(Pieces(uSkinTests[i], U, 1, 2));
Inc(i);
end;
end;
{Patient Education-------------------------------------------------------------}
procedure LoadPEDLevelItems(Dest: TStrings);
begin
tCallV(Dest,'ORWPCE GET SET OF CODES',['9000010.16','.06','1']);
end;
procedure ListPatientSections(Dest: TStrings);
{ return Sections in format: ListIndex^SectionName (sections begin with '^') }
var
i: Integer;
x: string;
begin
if (uLastLocation <> uEncLocation) then LoadEncounterForm;
for i := 0 to uPatientEds.Count - 1 do if CharAt(uPatientEds[i], 1) = U then
begin
x := Piece(uPatientEds[i], U, 2);
if Length(x) = 0 then x := '<No Section Name>';
Dest.Add(IntToStr(i) + U + Piece(uPatientEds[i], U, 2) + U + x);
end;
end;
procedure ListPatientCodes(Dest: TStrings; SectionIndex: Integer);
{ return PatientEds within section in format: procedure <TAB> CPT code <TAB><TAB> CPT code}
var
i: Integer;
begin
Dest.Clear;
i := SectionIndex + 1; // first line after the section name
while (i < uPatientEds.Count) and (CharAt(uPatientEds[i], 1) <> U) do
begin
Dest.Add(Pieces(uPatientEds[i], U, 1, 2));
Inc(i);
end;
end;
{HealthFactors-------------------------------------------------------------}
procedure LoadHFLevelItems(Dest: TStrings);
begin
tCallV(Dest,'ORWPCE GET SET OF CODES',['9000010.23','.04','1']);
end;
procedure ListHealthSections(Dest: TStrings);
{ return Sections in format: ListIndex^SectionName (sections begin with '^') }
var
i: Integer;
x: string;
begin
if (uLastLocation <> uEncLocation) then LoadEncounterForm;
for i := 0 to uHealthFactors.Count - 1 do if CharAt(uHealthFactors[i], 1) = U then
begin
x := Piece(uHealthFactors[i], U, 2);
if Length(x) = 0 then x := '<No Section Name>';
Dest.Add(IntToStr(i) + U + Piece(uHealthFactors[i], U, 2) + U + x);
end;
end;
procedure ListHealthCodes(Dest: TStrings; SectionIndex: Integer);
{ return PatientEds within section in format: procedure <TAB> CPT code <TAB><TAB> CPT code}
var
i: Integer;
begin
Dest.Clear;
i := SectionIndex + 1; // first line after the section name
while (i < uHealthFactors.Count) and (CharAt(uHealthFactors[i], 1) <> U) do
begin
Dest.Add(Pieces(uHealthFactors[i], U, 1, 2));
Inc(i);
end;
end;
{Exams-------------------------------------------------------------------------}
procedure LoadXAMResultsItems(Dest: TStrings);
begin
tCallV(Dest,'ORWPCE GET SET OF CODES',['9000010.13','.04','1']);
end;
procedure LoadHistLocations(Dest: TStrings);
var
i, j, tlen: integer;
tmp: string;
begin
tCallV(Dest,'ORQQPX GET HIST LOCATIONS',[]);
for i := 0 to (Dest.Count - 1) do
begin
tmp := MixedCase(dest[i]);
j := pos(', ',tmp);
tlen := length(tmp);
if(j > 0) and (j < (tlen - 2)) and (pos(tmp[j+2],UpperCaseLetters) > 0) and
(pos(tmp[j+3],LowerCaseLetters)>0) and ((j = (tlen-3)) or (pos(tmp[j+4],LowerCaseLetters)=0)) then
tmp[j+3] := UpCase(tmp[j+3]);
if(tlen > 1) then
begin
if(pos(tmp[tlen],Digits) > 0) and (pos(tmp[tlen-1],Digits)=0) then
insert(' ',tmp, tlen);
end;
dest[i] := tmp;
end;
end;
procedure ListExamsSections(Dest: TStrings);
{ return Sections in format: ListIndex^SectionName (sections begin with '^') }
var
i: Integer;
x: string;
begin
if (uLastLocation <> uEncLocation) then LoadEncounterForm;
for i := 0 to uExams.Count - 1 do if CharAt(uExams[i], 1) = U then
begin
x := Piece(uExams[i], U, 2);
if Length(x) = 0 then x := '<No Section Name>';
Dest.Add(IntToStr(i) + U + Piece(uExams[i], U, 2) + U + x);
end;
end;
procedure ListExamsCodes(Dest: TStrings; SectionIndex: Integer);
{ return PatientEds within section in format: procedure <TAB> CPT code <TAB><TAB> CPT code}
var
i: Integer;
begin
Dest.Clear;
i := SectionIndex + 1; // first line after the section name
while (i < uExams.Count) and (CharAt(uExams[i], 1) <> U) do
begin
Dest.Add(Pieces(uExams[i], U, 1, 2));
Inc(i);
end;
end;
{------------------------------------------------------------------------------}
function EligbleConditions: TSCConditions;
{ return a record listing the conditions for which a patient is eligible }
var
x: string;
begin
x := sCallV('ORWPCE SCSEL', [Patient.DFN, Encounter.DateTime, uEncLocation]);
with Result do
begin
SCAllow := Piece(Piece(x, ';', 1), U, 1) = '1';
SCDflt := Piece(Piece(x, ';', 1), U, 2) = '1';
AOAllow := Piece(Piece(x, ';', 2), U, 1) = '1';
AODflt := Piece(Piece(x, ';', 2), U, 2) = '1';
IRAllow := Piece(Piece(x, ';', 3), U, 1) = '1';
IRDflt := Piece(Piece(x, ';', 3), U, 2) = '1';
ECAllow := Piece(Piece(x, ';', 4), U, 1) = '1';
ECDflt := Piece(Piece(x, ';', 4), U, 2) = '1';
MSTAllow := Piece(Piece(x, ';', 5), U, 1) = '1';
MSTDflt := Piece(Piece(x, ';', 5), U, 2) = '1';
HNCAllow := Piece(Piece(x, ';', 6), U, 1) = '1';
HNCDflt := Piece(Piece(x, ';', 6), U, 2) = '1';
CVAllow := Piece(Piece(x, ';', 7), U, 1) = '1';
CVDflt := Piece(Piece(x, ';', 7), U, 2) = '1';
SHDAllow := Piece(Piece(x, ';', 8), U, 1) = '1';
SHDDflt := Piece(Piece(x, ';', 8), U, 2) = '1';
// Camp Lejeune
if IsLejeuneActive then
begin
CLAllow := Piece(Piece(x, ';', 9), U, 1) = '1';
CLDflt := Piece(Piece(x, ';', 9), U, 2) = '1';
end;
end;
end;
procedure ListSCDisabilities(Dest: TStrings);
{ return text listing a patient's rated disabilities and % service connected }
begin
CallV('ORWPCE SCDIS', [Patient.DFN]);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure LoadPCEDataForNote(Dest: TStrings; ANoteIEN: Integer; VStr: string);
begin
if(ANoteIEN < 1) then
CallV('ORWPCE PCE4NOTE', [ANoteIEN, Patient.DFN, VStr])
else
CallV('ORWPCE PCE4NOTE', [ANoteIEN]);
FastAssign(RPCBrokerV.Results, Dest);
end;
function GetVisitIEN(NoteIEN: Integer): string;
begin
if(NoteIEN < 1) then
CallV('ORWPCE GET VISIT', [NoteIEN, Patient.DFN, Encounter.VisitStr])
else
CallV('ORWPCE GET VISIT', [NoteIEN]);
if(RPCBrokerV.Results.Count > 0) then
Result := RPCBrokerV.Results[0]
else
Result := '0';
end;
procedure SavePCEData(PCEList: TStringList; ANoteIEN, ALocation: integer);
var
alist: TStrings;
begin
// CallV('ORWPCE SAVE', [PCEList, ANoteIEN, ALocation]);
aList := TStringList.create;
try
CallVistA('ORWPCE SAVE', [PCEList, ANoteIEN, ALocation], alist);
finally
FreeAndNil(aList);
end;
end;
{-----------------------------------------------------------------------------}
function DataHasCPTCodes(AList: TStrings): boolean;
var
i: integer;
vl: string;
begin
if(not assigned(uHasCPT)) then
uHasCPT := TStringList.Create;
Result := FALSE;
i := 0;
while(i < AList.Count) do
begin
vl := uHasCPT.Values[AList[i]];
if(vl = '1') then
begin
Result := TRUE;
exit;
end
else
if(vl = '0') then
AList.Delete(i)
else
inc(i);
end;
if(AList.Count > 0) then
begin
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'ORWPCE HASCPT';
Param[0].PType := list;
with Param[0] do
begin
for i := 0 to AList.Count-1 do
Mult[inttostr(i+1)] := AList[i];
end;
CallBroker;
for i := 0 to RPCBrokerV.Results.Count-1 do
begin
if(Piece(RPCBrokerV.Results[i],'=',2) = '1') then
begin
Result := TRUE;
break;
end;
end;
FastAddStrings(RPCBrokerV.Results, uHasCPT);
end;
finally
UnlockBroker;
end;
end;
end;
function GetAskPCE(Loc: integer): TAskPCE;
begin
if(uAPUser <> User.DUZ) or (uAPLoc <> Loc) then
begin
uAPUser := User.DUZ;
uAPLoc := Loc;
uAPAsk := TAskPCE(StrToIntDef(sCallV('ORWPCE ASKPCE', [User.DUZ, Loc]), 0));
end;
Result := uAPAsk;
end;
function HasVisit(const ANoteIEN, ALocation: integer; const AVisitDate: TFMDateTime): Integer;
begin
Result := StrToIntDef(sCallV('ORWPCE HASVISIT', [ANoteIEN, Patient.DFN, ALocation, AVisitDate]), -1);
end;
{-----------------------------------------------------------------------------}
function CheckActivePerson(provider:String;DateTime:TFMDateTime): boolean;
var
RetVal: String;
begin
Callv('ORWPCE ACTIVE PROV',[provider,FloatToStr(DateTime)]);
retval := RPCBrokerV.Results[0];
if StrToInt(RetVal) = 1 then result := true
else result := false;
end;
function ForcePCEEntry(Loc: integer): boolean;
begin
if(Loc <> uLastForceLoc) then
begin
uLastForce := (sCallV('ORWPCE FORCE', [User.DUZ, Loc]) = '1');
uLastForceLoc := Loc;
end;
Result := uLastForce;
end;
procedure LoadcboOther(Dest: TStrings; Location, fOtherApp: Integer);
{loads items into combo box on Immunization screen}
var
IEN, RPC: string;
TmpSL: TORStringList;
i, j, idx, typ: integer;
begin
TmpSL := TORStringList.Create;
try
Idx := 0;
case fOtherApp of
PCE_IMM: begin typ := 1; RPC := 'ORWPCE GET IMMUNIZATION TYPE'; end;
PCE_SK: begin typ := 2; RPC := 'ORWPCE GET SKIN TEST TYPE'; end;
PCE_PED: begin typ := 3; RPC := 'ORWPCE GET EDUCATION TOPICS'; end;
PCE_HF: begin typ := 4; RPC := 'ORWPCE GET HEALTH FACTORS TY'; Idx := 1; end;
PCE_XAM: begin typ := 5; RPC := 'ORWPCE GET EXAM TYPE'; end;
else begin typ := 0; RPC := ''; end;
end;
if typ > 0 then
begin
if idx = 0 then
begin
if (typ = 1) or (typ = 2) then
tCallV(TmpSL,RPC,[uEncPCEData.VisitDateTime])
else
tCallV(TmpSL,RPC,[nil]);
end
else
tCallV(TmpSL,RPC,[idx]);
CallV('ORWPCE GET EXCLUDED', [Location, Typ]);
for i := 0 to RPCBrokerV.Results.Count-1 do
begin
IEN := piece(RPCBrokerV.Results[i],U,2);
idx := TmpSL.IndexOfPiece(IEN);
if idx >= 0 then
begin
TmpSL.Delete(idx);
if fOtherApp = PCE_HF then
begin
j := 0;
while (j < TmpSL.Count) do
begin
if IEN = Piece(TmpSL[J],U,4) then
TmpSL.Delete(j)
else
inc(j);
end;
end;
end;
end;
end;
FastAssign(TmpSL, Dest);
finally
TmpSL.Free;
end;
end;
{
function SetRPCEncouterInfo(PCEData: TPCEData): boolean;
begin
if (SetRPCEncLocation(PCEData.location) = False) or (SetRPCEncDateTime(PCEData.DateTime) = False) then
result := False
else result := True;
end;
}
function SetRPCEncLocation(Loc: Integer): boolean;
begin
uEncLocation := Loc;
Result := (uEncLocation <> 0);
end;
{
function SetRPCEncDateTime(DT: TFMDateTime): boolean;
begin
uEncDateTime := 0.0;
result := False;
uEncDateTime := DT;
if uEncDateTime > 0.0 then result := true;
end;
}
function PCERPCEncLocation: integer;
begin
result := uEncLocation;
end;
{
function PCERPCEncDateTime: TFMDateTime;
begin
result := uEncDateTime;
end;
}
function GetLocSecondaryVisitCode(Loc: integer): char;
begin
if (Loc <> uLastIsClinicLoc) then
begin
uLastIsClinicLoc := Loc;
uLastIsClinic := (sCallV('ORWPCE ISCLINIC', [Loc]) = '1');
end;
if uLastIsClinic then
Result := 'I'
else
Result := 'D';
end;
function GAFOK: boolean;
begin
if(not uGAFOKCalled) then
begin
uGAFOK := (sCallV('ORWPCE GAFOK', []) = '1');
uGAFOKCalled := TRUE;
end;
Result := uGAFOK;
end;
function MHClinic(const Location: integer): boolean;
begin
if GAFOK then
Result := (sCallV('ORWPCE MHCLINIC', [Location]) = '1')
else
Result := FALSE;
end;
procedure RecentGAFScores(const Limit: integer);
begin
if(GAFOK) then
begin
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'ORWPCE LOADGAF';
Param[0].PType := list;
with Param[0] do
begin
Mult['"DFN"'] := Patient.DFN;
Mult['"LIMIT"'] := IntToStr(Limit);
end;
CallBroker;
end;
finally
UnlockBroker;
end;
end;
end;
function SaveGAFScore(const Score: integer; GAFDate: TFMDateTime; Staff: Int64): boolean;
begin
Result := FALSE;
if(GAFOK) then
begin
LockBroker;
try
with RPCBrokerV do
begin
ClearParameters := True;
RemoteProcedure := 'ORWPCE SAVEGAF';
Param[0].PType := list;
with Param[0] do
begin
Mult['"DFN"'] := Patient.DFN;
Mult['"GAF"'] := IntToStr(Score);
Mult['"DATE"'] := FloatToStr(GAFDate);
Mult['"STAFF"'] := IntToStr(Staff);
end;
CallBroker;
end;
if(RPCBrokerV.Results.Count > 0) and
(RPCBrokerV.Results[0] = '1') then
Result := TRUE;
finally
UnlockBroker;
end;
end;
end;
function GAFURL: string;
begin
if(not uGAFURLChecked) then
begin
uGAFURL := sCallV('ORWPCE GAFURL', []);
uGAFURLChecked := TRUE;
end;
Result := uGAFURL;
end;
function MHTestsOK: boolean;
begin
if(not uMHOKChecked) then
begin
uMHOK := (sCallV('ORWPCE MHTESTOK', []) = '1');
uMHOKChecked := TRUE;
end;
Result := uMHOK;
end;
function MHTestAuthorized(Test: string): boolean;
begin
Result := (sCallV('ORWPCE MH TEST AUTHORIZED', [Test, User.DUZ]) = '1');
end;
function AnytimeEncounters: boolean;
begin
if uAnytimeEnc < 0 then
uAnytimeEnc := ord(sCallV('ORWPCE ANYTIME', []) = '1');
Result := BOOLEAN(uAnytimeEnc);
end;
function AutoCheckout(Loc: integer): boolean;
begin
if(uLastChkOutLoc <> Loc) then
begin
uLastChkOutLoc := Loc;
uLastChkOut := (sCallV('ORWPCE ALWAYS CHECKOUT', [Loc]) = '1');
end;
Result := uLastChkOut;
end;
{ encounter capture functions ------------------------------------------------ }
function RequireExposures(ANote, ATitle: Integer): Boolean; {*RAB 3/22/99*}
{ returns true if a progress note should require the expossure questions to be answered }
begin
if ANote <= 0
then Result := Piece(sCallV('TIU GET DOCUMENT PARAMETERS', ['0', ATitle]), U, 15) = '1'
else Result := Piece(sCallV('TIU GET DOCUMENT PARAMETERS', [ANote]), U, 15) = '1';
end;
function PromptForWorkload(ANote, ATitle: Integer; VisitCat: Char; StandAlone: boolean): Boolean;
{ returns true if a progress note should prompt for capture of encounter }
var
X: string;
begin
Result := FALSE;
if (VisitCat <> 'A') and (VisitCat <> 'I') and (VisitCat <> 'T') then exit;
if ANote <= 0 then
X := sCallV('TIU GET DOCUMENT PARAMETERS', ['0', ATitle])
else
X := sCallV('TIU GET DOCUMENT PARAMETERS', [ANote]);
if(Piece(X, U, 14) = '1') then exit; // Suppress DX/CPT param is TRUE - don't ask
if StandAlone then
Result := TRUE
else
Result := (Piece(X, U, 16) = '1'); // Check Ask DX/CPT param
end;
function IsCancelOrNoShow(ANote: integer): boolean;
begin
Result := (sCallV('ORWPCE CXNOSHOW', [ANote]) = '0');
end;
function IsNonCountClinic(ALocation: integer): boolean;
begin
Result := (sCallV('ORWPCE1 NONCOUNT', [ALocation]) = '1');
end;
function DefaultProvider(ALocation: integer; AUser: Int64; ADate: TFMDateTime;
ANoteIEN: integer): string;
begin
Result := sCallV('TIU GET DEFAULT PROVIDER', [ALocation, AUser, ADate, ANoteIEN]);
end;
function IsUserAProvider(AUser: Int64; ADate: TFMDateTime): boolean;
begin
Result := (sCallV('TIU IS USER A PROVIDER?', [AUser, ADate]) = '1');
end;
function IsUserAUSRProvider(AUser: Int64; ADate: TFMDateTime): boolean;
begin
Result := (sCallV('TIU IS USER A USR PROVIDER', [AUser, ADate]) = '1');
end;
//function HNCOK: boolean;
//begin
// if uHNCOK < 0 then
// uHNCOK := ord(sCallV('ORWPCE HNCOK', []) = '1');
// Result := boolean(uHNCOK);
//end;
initialization
uLastLocation := 0;
uLastEncDt := 0;
uVTypeLastLoc := 0;
uVTypeLastDate := 0;
uDiagnoses := TStringList.Create;
uExams := TStringList.Create;
uHealthFactors := TStringList.Create;
uImmunizations := TStringList.Create;
uPatientEds := TStringList.Create;
uProcedures := TStringList.Create;
uSkinTests := TStringList.Create;
uVisitTypes := TStringList.Create;
uVTypeForLoc := TStringList.Create;
uProblems := TStringList.Create;
finalization
uDiagnoses.Free;
uExams.Free;
uHealthFactors.Free;
uImmunizations.Free;
uPatientEds.Free;
uProcedures.Free;
uSkinTests.free;
uVisitTypes.Free;
uVTypeForLoc.Free;
uProblems.Free;
KillObj(@uModifiers);
KillObj(@uHasCPT);
end. |
unit Rx.Observable.Just;
interface
uses Rx, Rx.Implementations;
type
TJust<T> = class(TObservableImpl<T>)
type
TValuesCollection = array of TSmartVariable<T>;
strict private
FItems: TValuesCollection;
FEnumerator: IEnumerator<TSmartVariable<T>>;
procedure ItemsEnumerate(O: IObserver<T>);
procedure EnumeratorEnumerate(O: IObserver<T>);
public
constructor Create(const Items: array of TSmartVariable<T>); overload;
constructor Create(Enumerator: IEnumerator<TSmartVariable<T>>); overload;
constructor Create(Enumerable: IEnumerable<TSmartVariable<T>>); overload;
end;
implementation
{ TJust<T> }
constructor TJust<T>.Create(const Items: array of TSmartVariable<T>);
var
I: Integer;
begin
inherited Create(ItemsEnumerate);
SetLength(FItems, Length(Items));
for I := 0 to High(Items) do
FItems[I] := Items[I];
end;
constructor TJust<T>.Create(Enumerator: IEnumerator<TSmartVariable<T>>);
begin
inherited Create(EnumeratorEnumerate);
FEnumerator := Enumerator;
end;
constructor TJust<T>.Create(Enumerable: IEnumerable<TSmartVariable<T>>);
begin
Create(Enumerable.GetEnumerator)
end;
procedure TJust<T>.EnumeratorEnumerate(O: IObserver<T>);
var
I: T;
begin
FEnumerator.Reset;
while FEnumerator.MoveNext do
O.OnNext(FEnumerator.Current);
end;
procedure TJust<T>.ItemsEnumerate(O: IObserver<T>);
var
Item: TSmartVariable<T>;
begin
for Item in FItems do
O.OnNext(Item);
O.OnCompleted;
end;
end.
|
unit Hash;
interface
uses
SysUtils,
Classes;
type
THashItem = class(TObject)
private
FHashIndex: Integer;
FNext, FPrev, // global item list
FBucketNext, FBucketPrev: THashItem; // bucket list
FKey,
FValue: Variant;
public
property HashIndex: Integer read FHashIndex;
property Key: Variant read FKey;
property Value: Variant read FValue write FValue;
end;
TBucket = record
Count: Integer;
FirstItem: THashItem;
end;
THashArray = array[0..0] of TBucket;
PHashArray = ^THashArray;
EHashError = class(Exception);
THashErrMsg = (
hKeyNotFound,
hKeyExists,
hIndexOutOfBounds
);
TCustomHashTable = class(TObject)
private
FItems: THashItem;
FHash: PHashArray;
FHashCount: Integer;
function FindItem(const Key: Variant; bQuiet: Boolean;
HashVal: Integer): THashItem;
procedure HashError(const ErrMsg: THashErrMsg);
function GetValue(const Key: Variant): Variant;
procedure SetValue(const Key: Variant; Value: Variant);
protected
function HashSize: Integer; virtual; abstract;
property Count: Integer read FHashCount;
property Size: Integer read HashSize;
property Value[const Key: Variant]: Variant read GetValue
write SetValue;
public
constructor Create; virtual;
destructor Destroy; override;
function HashFunc(Key: Variant): Integer; virtual; abstract;
procedure AddItem(Key, Value: Variant);
procedure RemoveItem(Key: Variant);
procedure Clear;
function KeyExists(Key: Variant): Boolean;
function BucketCountByIdx(const Idx: Integer): Integer;
function BucketCountByKey(const Key: Variant): Integer;
end;
TStringKeyHashTable = class(TCustomHashTable)
protected
function HashSize: Integer; override;
public
function HashFunc(Key: Variant): Integer; override;
property Count;
property Size;
property Value; default;
end;
implementation
const
HashErrMsgs: array[THashErrMsg] of String =
(
'Hash key not found',
'Hash key already exists',
'Bucket index out of bounds'
);
(*
* TCustomHashTable
*)
constructor TCustomHashTable.Create;
begin
FItems := nil;
FHashCount := 0;
GetMem(FHash, Size * SizeOf(TBucket));
// Ensure that the buckets are zero-initialized.
FillChar(PChar(FHash)^, Size * SizeOf(TBucket), #0);
end;
destructor TCustomHashTable.Destroy;
begin
Clear;
end;
function TCustomHashTable.FindItem(const Key: Variant;
bQuiet: Boolean; HashVal: Integer): THashItem;
begin
result := nil;
if HashVal < 0 then
HashVal := HashFunc(Key);
if (HashVal < 0) then begin
if (not bQuiet) then
HashError(hKeyNotFound);
end else begin
result := FHash[HashVal].FirstItem;
while (result <> nil) and (result.Key <> Key) do result := result.FBucketNext;
if (result = nil) and (not bQuiet) then HashError(hKeyNotFound);
end;
end;
procedure TCustomHashTable.HashError(const ErrMsg: THashErrMsg);
begin
raise EHashError.Create(HashErrMsgs[ErrMsg]);
end;
function TCustomHashTable.GetValue(const Key: Variant): Variant;
begin
result := FindItem(Key, False, -1).Value;
end;
procedure TCustomHashTable.SetValue(const Key: Variant; Value: Variant);
var
p: THashItem;
begin
p := FindItem(Key, True, -1);
if p <> nil then
p.Value := Value
else
AddItem(Key, Value);
end;
procedure TCustomHashTable.AddItem(Key, Value: Variant);
var
i: Integer;
hi: THashItem;
begin
i := HashFunc(Key);
if FindItem(Key, True, i) <> nil then
HashError(hKeyExists);
hi := THashItem.Create;
hi.FKey := Key;
hi.FValue := Value;
hi.FHashIndex := i;
// Insert hi at the beginning of the items list
if (FItems <> nil) then
FItems.FPrev := hi;
hi.FNext := FItems;
FItems := hi;
// Insert hi at the beginning of its hash bucket
if (FHash[hi.FHashIndex].FirstItem <> nil) then
FHash[hi.FHashIndex].FirstItem.FBucketPrev := hi;
hi.FBucketNext := FHash[hi.FHashIndex].FirstItem;
FHash[hi.FHashIndex].FirstItem := hi;
Inc(FHashCount);
Inc(FHash[hi.FHashIndex].Count);
end;
procedure TCustomHashTable.RemoveItem(Key: Variant);
var
hi: THashItem;
begin
hi := FindItem(Key, False, -1);
// Remove hi from the items list
if (hi.FNext <> nil) then
hi.FNext.FPrev := hi.FPrev;
if (hi.FPrev <> nil) then
hi.FPrev.FNext := hi.FNext
else
FItems := hi.FNext;
// Remove hi from its hash bucket
if (hi.FBucketNext <> nil) then
hi.FBucketNext.FBucketPrev := hi.FBucketPrev;
if (hi.FBucketPrev <> nil) then
hi.FBucketPrev.FBucketNext := hi.FBucketNext
else
FHash[hi.FHashIndex].FirstItem := hi.FBucketNext;
Dec(FHashCount);
Dec(FHash[hi.FHashIndex].Count);
// Finally, free hi from memory
hi.Free;
end;
procedure TCustomHashTable.Clear;
var
p: THashItem;
begin
FHashCount := 0;
FillChar(PChar(FHash)^, Size * SizeOf(TBucket), 0);
(*
* Walk FItems and destroy all items.
*)
p := FItems;
while (p <> nil) do begin
FItems := FItems.FNext;
p.Free;
p := FItems;
end;
end;
function TCustomHashTable.KeyExists(Key: Variant): Boolean;
begin
result := (FindItem(Key, True, -1) <> nil);
end;
function TCustomHashTable.BucketCountByIdx(const Idx: Integer): Integer;
begin
if (Idx < 0) or (Idx >= Size) then
HashError(hIndexOutOfBounds);
result := FHash[Idx].Count;
end;
function TCustomHashTable.BucketCountByKey(const Key: Variant): Integer;
begin
result := FHash[HashFunc(Key)].Count;
end;
(*
* TStringKeyHashTable
*)
function TStringKeyHashTable.HashSize: Integer;
begin
result := 256;
end;
function TStringKeyHashTable.HashFunc(Key: Variant): Integer;
var
st: String;
i: Integer;
begin
st := Key;
result := 0;
for i := 1 to Length(st) do Inc(result, Integer(st[i]));
result := result mod Size;
end;
end.
|
1 program SearchTest;
2 { Etienne van Delden, 0618959, 27-20-2006 }
3 { Dit programma test de correctheid van de procedure Find in lists.pas }
4
5 //** USES **********************************
6 uses
7 lists;
8
9 //** GLOBAL VARIABLES **********************
10
11 var
12
13 outFile: Text; // var voor te schrijven bestand
14 output: String; // naam voor de output file
15 aanroepTeller: Integer; // om het aantal aanroepen van Find te tellen
16 foutenTeller: Integer; // om het aantal foutieve aanroepen van Find
17 // te tellen
18
19 //** GLOBAL CONSTANTS **********************
20
21 const
22 indent = ' '; // String waar output moet worden voorafgegaan
23
24 //** PROCEDURE CHECKFIND ******************
25
26 procedure CheckFind ( const s: List; const x: Entry;
27 const expectedFound: Boolean );
28 { globvar: outFile, aanroepTeller, foutenTeller }
29 { doe aanroep Find ( s, x, found, pos ) en controleer postconditie:
30 found = expectedFound, en
31 als found, dan ook 0 <= pos < s.len en s.val[pos] = x }
32 { pre: outFile is geopend om te schrijven
33 aanroepTeller = A, foutenTeller = F
34 s, x voldoen aan preconditie van Find
35 expectedFound = `x komt voor in s'
36 post: aanroepTeller = A + 1,
37 Find is aangeroepen en resultaat is naar outFile geschreven,
38 foutenTeller = F + 1 als fout geconstateerd, anders F }
39 // LOCAL CONSTANTS ****
40 const
41 WriteListIndent = indent + 's'; // wat voor .list en .val moet staan in de
42 // output
43 // LOCAL VARIABLES ****
44 var { lokale variabelen }
45 found: Boolean; // heeft Find een waarde gevonden?
46 pos: Index; // de positie waar het getal gevonden is
47
48 // BEGIN PROCEDURE ****
49 begin
50
51 Find( s, x, found, pos ); // Roept find aan en telt de aanroep teller op
52 aanroepTeller := aanroepTeller + 1;
53
54 // Schrijf de uitkomst
55 writeln( outFile, aanroepTeller, ' Find' );
56 // 1ste regel: volgnummer, aanroepe nroutine
57 WriteList( outFile, WriteListIndent, s );
58 // 2de regel: 's.len', lengte van lijst s
59 // 3de regel: 's.val'
60 writeln( outFile, Indent, 'x: ', x );
61 // 4de regel: waarde van x
62 writeln(outFile, ' found: ', found);
63 // 5de regel: waarde van found
64 writeln(outFile, ' pos: ', pos);
65 // 6de regel: waarden van pos
66
67 // bekijk resultaat van find en bepaal de output
68 if ( expectedFound and found ) then
69 begin
70 if s.len <= pos then // als de lengte kleiner is dan de positie
71 begin
72 writeln( outFile, ' FOUT: pos in aanroep ', aanroepTeller );
73 foutenTeller := foutenTeller + 1
74 end
75 else if s.val[ pos ]<> x then // als de positie niet correct is
76 begin
77 writeln( outFile, ' FOUT: pos in aanroep ', aanroepTeller );
78 foutenTeller := foutenTeller + 1
79 end
80 end
81 else if ( expectedFound or found ) then // als 1 van de 2 is waar is
82 begin
83 writeln( outFile, ' FOUT: found in aanroep ', aanroepTeller );
84 foutenTeller := foutenTeller + 1
85 end; // end If
86
87 end; // end CheckFind
88
89
90 //** PROCEDURE TESTFIND1 ** KAM LIJST ****************
91
92 procedure TestFind1 ( const n: Integer );
93 { globvar: outFile, aanroepTeller, foutenTeller }
94 { pre: outFile is geopend om te schrijven
95 aanroepTeller = A, foutenTeller = F
96 0 <= n <= MaxListLen
97 post: Find(...) is getest met alle lijsten s zodanig dat
98 s.len=n, s.val[i]=2i+1, en alle x=0, ..., 2n
99 uitvoer is zijn naar outFile geschreven
100 aanroepTeller = A + 2n + 1
101 foutenTeller = F + aantal geconstateerde fouten in TestFind1 }
102 var
103 s: List; // invoer voor CheckFind
104 expectedFound: Boolean; // verwachten we dat er de waarde erin zit?
105 i: Integer; // teller var
106 j: Integer; // teller var
107
108 begin
109 // Als lijst met lengte MaxListLen word gevraagd
110 if n = MaxListLen then
111 begin
112 generateList( s, n, 2, 1, 1 ); // genereer een kamlijst
113
114 for i := 0 to ( 2 * n ) do begin // loop van 0 tot 2n
115 expectedFound := ( i mod 2 <> 0 ); // is expected found (on)even?
116 CheckFind( s, i, expectedFound ) // roep checkFind aan
117 end // end for
118
119 end
120 else // als andere lijst lengte
121 begin
122
123 for i := 0 to n do
124 begin // voor alle lengtes
125 generateList( s, i, 2, 1, 1 ); // genereer een kamlijst
126
127 // loop voor alle mogelijke waardes in delijst
128 for j := 0 to ( 2 * i ) do begin
129 expectedFound := ( j mod 2 <> 0) ; // is expected found (on)even?
130 CheckFind( s, j, expectedFound )
131
132
133 end // end for
134
135 end // end for
136
137 end // end if
138
139
140 end; // end procedure
141
142 //** PROCEDURE TESTFIND2 ** CONSTANTE LIJST ****************
143
144 procedure TestFind2 ( const n: Integer );
145 { globvar: outFile, aanroepTeller, foutenTeller }
146 { pre: outFile is geopend om te schrijven
147 aanroepTeller = A, foutenTeller = F
148 0 <= n <= MaxListLen
149 post: Find(...) is getest met alle lijst s zodanig dat
150 s.len=n, s.val[i]=MaxEntry, en alle x=MinEntry, ..., MaxEntry
151 uitvoer is naar outFile geschreven
152 aanroepTeller = A + MaxEntry - MinEntry + 1
153 foutenTeller = F + aantal geconstateerde fouten in TestFind2 }
154
155 var
156 i: Integer; // hulp var
157 s: List; // invoer voor CheckFind
158
159 begin
160 // n hoeveelheid, m is offset, d is deelfactor, c is beginpunt
161 GenerateList( s, n, 1, n, MaxEntry); // maak een constante lijst
162
163 for i := minEntry to MaxEntry do begin
164 checkFind( s, i, ( i = MaxEntry ))
165 end // for i
166
167 end; // end procedure
168
169
170 //** MAIN PRGRAM ******************
171 begin
172
173 // INITIALIZATION ***
174 aanroepTeller := 0; // hoevaak find aangeroepen
175 foutenTeller := 0; // hoeveel fouten
176 output := 'search_test.out'; // naar welk bestand
177
178 // OPEN OUTPUT FILE **
179 AssignFile( outFile, output ); // Open het zojuist ingegeven schrijf bestand
180 Rewrite ( outFile ); // Schrijffile leeg maken
181
182 // Test find meerdere keren
183 testFind1( 5 ); // Kamlijst test: van 1 tot en met 5
184 testFind1( MaxListLen ); // Kamlijst test: maximum lijst lengte
185 testFind2( MaxListLen ); // Constante lijst test: Lengte 10
186 writeln( outFile, foutenTeller, ' FOUT(EN)' ); // schrijf naar output
187
188 CloseFile ( outFile ); // sluit het geschreven bestand
189
190 end. |
Program FunctionTest;
Var
num, pownum, expo: Integer;
Function mypower(x,y:Integer):Integer;
Var
i, value:Integer;
Begin
value:=1;
for i:=1 to y do
value := value * x;
mypower := value;
End;
Begin
Write('Give a number : ');
Readln(num);
Write('Give the exponent : ');
Readln(expo);
pownum := mypower(num,expo);
Writeln ('The ', num, ' raised to ', expo, ' is: ', pownum);
End. |
unit log_core;
// Version 1.3 //with commands
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, StdCtrls, LCLType;
type TprocNoArgs = procedure of object;
type
{ tcommand }
tcommand=class
private
identifier:string;
action:tprocnoargs;
helptext:string;
public
constructor create(_identifier:string;_action:tprocnoargs;_helptext:string);
procedure trigger;
function get_identifier:string;
function get_helptext:string;
end;
{ log }
type
{ tlog }
tlog=class
private
logobj:tmemo;
id:integer;
lnr:integer;
line_nr_enable:boolean;
vlog:tstringlist;
output:boolean; //toggels the output to logobj //false at init
procedure write_log(s:string);
procedure sync_logobj;
public
constructor create(_id:integer);
procedure assign_logobj(_object:tmemo);
procedure print(s:string);
procedure inp(s:string);
procedure outp(s:string);
procedure enable_line_nr;
procedure disable_line_nr;
procedure enable_output; //turns the output to logobj on and sync the logbuffer to the object
procedure disable_output; //turns the output in logobj off. Messages will be buffered.
procedure clear;
end;
type
{ tcommandline }
tcommandline=class
private
input:tedit;
output:tlog;
commands:tlist;
history:tstringlist;
history_pos:integer;
current_input:string;
procedure key_down_handler(Sender: TObject; var Key: Word;Shift: TShiftState);
function get_command(_identifier:string):tcommand;
procedure decode_command(txt:string);
procedure display_help;
public
constructor create(_output:tlog);
procedure assign_input(_input:tedit);
function add_simple_command(_identifier:string;_action:tprocnoargs;_helptext:string):boolean;
end;
implementation
{ tcommandline }
procedure tcommandline.key_down_handler(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case key of
VK_UP:begin
if history_pos=history.count then begin
current_input:=input.Text;
end;
if history_pos>0 then begin
history_pos:=history_pos-1;
input.Text:=history.Strings[history_pos];
end;
end;
VK_DOWN:begin
if history_pos=history.count-1 then begin
history_pos:=history_pos+1;
input.text:=current_input;
end;
if history_pos<history.Count-1 then begin
history_pos:=history_pos+1;
input.Text:=history.Strings[history_pos];
end;
end;
VK_RETURN:begin
history.Add(input.Text);
history_pos:=history.Count;
current_input:='';
decode_command(input.text);
input.text:='';
end;
end;
end;
function tcommandline.get_command(_identifier: string): tcommand;
var i:integer;
begin
result:=nil;
for i:=0 to commands.count-1 do begin
if tcommand(commands.Items[i]).get_identifier=_identifier then result:= tcommand(commands.items[i]);
end;
end;
procedure tcommandline.decode_command(txt: string);
var c:tcommand;
identifier,arg:string;
arguments:tstringlist;
sr:tstringarray;
i:integer;
begin
arguments:=tstringlist.Create;
sr:=txt.Split(' ');
identifier:=sr[0];
if length(sr)>1 then begin
for i:=1 to length(sr)-1 do begin
arg:=sr[i];
if arg<>'' then begin
if arg<>' ' then begin
//output.inp('found arg: '+arg);
arguments.add(arg);
end;
end;
end;
end;
c:=get_command(identifier);
//output.inp('understood: '+identifier);
//output.inp('found: '+c.get_identifier);
if c<>nil then begin
if arguments.count>0 then begin
output.inp('understood argument: '+arguments.strings[0]);
if arguments.strings[0]='help' then output.inp('Help for '''+identifier+''': '+c.get_helptext)
end
else begin
//output.inp('triggered: '+c.get_identifier);
output.inp('--> '+identifier+':');
c.trigger;
end;
end
else begin
output.inp('ERROR: command '''+identifier+''' not found. ');
end;
end;
procedure tcommandline.display_help;
var i:integer;
begin
output.inp('There are the following commands available: ');
for i:=0 to commands.count-1 do begin
output.inp(' - '+tcommand(commands.items[i]).get_identifier+': //'+tcommand(commands.items[i]).get_helptext);
end;
end;
constructor tcommandline.create(_output: tlog);
begin
commands:=tlist.create;
history:=tstringlist.create;
history.Add('');
history_pos:=0;
current_input:='';
output:=_output;
add_simple_command('help',@display_help,'Displays all commands that can be issued from user input');
end;
procedure tcommandline.assign_input(_input: tedit);
begin
input:=_input;
input.OnKeyDown:=@key_down_handler;
end;
function tcommandline.add_simple_command(_identifier: string;
_action: tprocnoargs;_helptext:string): boolean;
var c:tcommand;
begin
c:=tcommand.create(_identifier,_action,_helptext);
if get_command(_identifier)=nil then begin
commands.Add(c);
result:=true;
end
else begin
result:=false;
end;
end;
{ tcommand }
constructor tcommand.create(_identifier: string; _action: tprocnoargs;
_helptext: string);
begin
identifier:=_identifier;
action:=_action;
helptext:=_helptext;
end;
procedure tcommand.trigger;
begin
action;
end;
function tcommand.get_identifier: string;
begin
result:=identifier;
end;
function tcommand.get_helptext: string;
begin
result:=helptext;
end;
{ log }
procedure tlog.write_log(s: string);
begin
//writes to stringlist and sync logobj
vlog.Add(s);
if output then begin
try
logobj.Lines.Add(s);
except
self.disable_output;
end;
end;
end;
procedure tlog.sync_logobj;
var i:integer;
begin
try
logobj.Clear;
if vlog.Count>0 then begin;
for i:=0 to vlog.count-1 do begin
logobj.Lines.add(vlog.Strings[i]);
end;
end;
except
self.disable_output;
end;
end;
constructor tlog.create(_id: integer);
begin
id:=_id;
line_nr_enable:=true;
lnr:=0;
vlog:=tstringlist.Create;
output:=false;
end;
procedure tlog.assign_logobj(_object: tmemo);
begin
logobj:=_object;
end;
procedure tlog.print(s: string);
var o:string;
begin
lnr:=lnr+1;
o:='';
if line_nr_enable then begin
o:=inttostr(lnr)+': ';
end;
o:=o+s;
self.write_log(o);
end;
procedure tlog.inp(s: string);
var o:string;
begin
lnr:=lnr+1;
o:='';
if line_nr_enable then begin
o:=inttostr(lnr)+': ';
end;
o:=o+'>> '+s;
self.write_log(o);
end;
procedure tlog.outp(s: string);
var o:string;
begin
lnr:=lnr+1;
o:='';
if line_nr_enable then begin
o:=inttostr(lnr)+': ';
end;
o:=o+'<< '+s;
self.write_log(o);
end;
procedure tlog.enable_line_nr;
begin
line_nr_enable:=true;
end;
procedure tlog.disable_line_nr;
begin
line_nr_enable:=false;
end;
procedure tlog.enable_output;
begin
output:=true;
self.sync_logobj;
end;
procedure tlog.disable_output;
begin
output:=false;
end;
procedure tlog.clear;
begin
vlog.Clear;
if assigned(logobj) then logobj.Clear;
lnr:=0;
end;
end.
|
{ Unit indcyGraphics from cyGraphics
Description:
Unit with graphic functions
* ***** BEGIN LICENSE BLOCK *****
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Initial Developer of the Original Code is Mauricio
* (https://sourceforge.net/projects/tcycomponents/).
*
* No contributors for now ...
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or the
* GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which
* case the provisions of the GPL or the LGPL are applicable instead of those
* above. If you wish to allow use of your version of this file only under the
* terms of either the GPL or the LGPL, and not to allow others to use your
* version of this file under the terms of the MPL, indicate your decision by
* deleting the provisions above and replace them with the notice and other
* provisions required by the LGPL or the GPL. If you do not delete the
* provisions above, a recipient may use your version of this file under the
* terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK *****}
unit indcyGraphics;
{$mode objfpc}{$H+}
// {$I cyCompilerDefines.inc}
interface
// We need to put jpeg to the uses for avoid run-time not handled jpeg image ...
uses
LCLIntf, LCLType, Types, Classes, Forms, Graphics, Buttons, Controls,
ExtCtrls, SysUtils;
// Objects painting functions :
procedure cyFrame3D(Canvas: TCanvas; var Rect: TRect; TopLeftColor, BottomRightColor: TColor; Width: Integer;
const DrawLeft: Boolean = true; const DrawTop: Boolean = true; const DrawRight: Boolean = true; const DrawBottom: Boolean = true;
const RoundRect: boolean = false);
// TPicture and TGraphic functions:
function PictureIsTransparentAtPos(aPicture: TPicture; aPoint: TPoint): boolean;
function IconIsTransparentAtPos(aIcon: TIcon; aPoint: TPoint): boolean;
function ValidGraphic(aGraphic: TGraphic): Boolean;
// Other functions:
function PointInEllipse(const aPt: TPoint; const aRect: TRect): boolean;
implementation
{ Procedures and functions}
procedure cyFrame3D(Canvas: TCanvas; var Rect: TRect; TopLeftColor, BottomRightColor: TColor; Width: Integer;
const DrawLeft: Boolean = true; const DrawTop: Boolean = true; const DrawRight: Boolean = true; const DrawBottom: Boolean = true;
const RoundRect: boolean = false);
var incValue: Integer;
procedure DrawLines;
begin
with Canvas, Rect do
begin
// Draw Left and Top line :
Pen.Color := TopLeftColor;
if DrawLeft
then begin
MoveTo(Left, Top + incValue);
LineTo(Left, Bottom);
end;
if DrawTop
then begin
MoveTo(Left + incValue, Top);
LineTo(Right, Top);
end;
// Draw right and bottom line :
Pen.Color := BottomRightColor;
if DrawRight
then begin
MoveTo(Right, Top + incValue);
LineTo(Right, Bottom);
end;
if DrawBottom
then begin
MoveTo(Right - incValue, Bottom);
LineTo(Left-1 + incValue, Bottom);
end;
end;
end;
begin
if RoundRect
then incValue := 1
else incValue := 0;
Canvas.Pen.Width := 1;
Dec(Rect.Bottom);
Dec(Rect.Right);
while Width > 0 do
begin
Dec(Width);
DrawLines;
incValue := 0;
InflateRect(Rect, -1, -1);
end;
Inc(Rect.Bottom);
Inc(Rect.Right);
end;
function PointInEllipse(const aPt: TPoint; const aRect: TRect): boolean;
var
CenterEllipseCoord: TPoint;
EllipseWidth, EllipseHeight: Integer;
begin
CenterEllipseCoord := Point((aRect.Right + aRect.Left) div 2, (aRect.Bottom + aRect.Top) div 2);
EllipseWidth := (aRect.Right - aRect.Left) div 2;
EllipseHeight := (aRect.Bottom - aRect.Top) div 2;
RESULT := Sqr((aPt.x - CenterEllipseCoord.x)/EllipseWidth) + Sqr((aPt.y - CenterEllipseCoord.y)/EllipseHeight)
<= 1;
// = 0 On the center of ellipse
// < 1 Inside the ellipse
// = on the border of ellipse
// > 1 Outside the ellipse
end;
function PictureIsTransparentAtPos(aPicture: TPicture; aPoint: TPoint): boolean;
begin
RESULT := false; // TJPEGImage and others formats not handled ...
if aPicture.Graphic = nil then Exit;
if aPicture.Graphic.Empty then Exit;
if aPicture.Graphic is TBitmap
then begin
RESULT := aPicture.Bitmap.Canvas.Pixels[aPoint.X, aPoint.Y]
= aPicture.Bitmap.Canvas.Pixels[0, aPicture.Bitmap.Height-1];
end
else
if aPicture.Graphic is TIcon
then
RESULT := IconIsTransparentAtPos(aPicture.Icon, aPoint)
end;
// 9999 New function for CodeTyphon
function IconIsTransparentAtPos(aIcon: TIcon; aPoint: TPoint): boolean;
var aPic: TPicture;
begin
RESULT := false;
aPic := TPicture.Create;
try
aPic.Bitmap.Width := aIcon.Width;
aPic.Bitmap.Height := aIcon.Height;
aPic.Bitmap.PixelFormat := pf1bit; // Black = not transparent
aPic.Bitmap.Canvas.Brush.Color := clWhite;
aPic.Bitmap.Canvas.FillRect(Rect(0, 0, aIcon.Width, aIcon.Height));
aPic.Assign(aIcon);
aPic.Bitmap.PixelFormat := pf1bit; // Black = not transparent
RESULT := aPic.Bitmap.Canvas.Pixels[aPoint.X, aPoint.Y] <> clBlack;
finally
aPic.Free;
end;
end;
function ValidGraphic(aGraphic: TGraphic): Boolean;
begin
RESULT := false;
if aGraphic <> Nil
then
if not aGraphic.Empty
then RESULT := true;
end;
end.
|
{ $Id: FastMMMonitorTest.pas 23 2008-08-26 04:42:20Z judc $ }
{: DUnit: An XTreme testing framework for Delphi programs.
@author The DUnit Group.
@version $Revision: 23 $
}
(*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is DUnit.
*
* The Initial Developers of the Original Code are Kent Beck, Erich Gamma,
* and Juancarlo Aņez.
* Portions created The Initial Developers are Copyright (C) 1999-2000.
* Portions created by The DUnit Group are Copyright (C) 2000.
* All rights reserved.
*
* Contributor(s):
* Kent Beck <kentbeck@csi.com>
* Erich Gamma <Erich_Gamma@oti.com>
* Juanco Aņez <juanco@users.sourceforge.net>
* Chris Morris <chrismo@users.sourceforge.net>
* Jeff Moore <JeffMoore@users.sourceforge.net>
* Kris Golko <neuromancer@users.sourceforge.net>
* The DUnit group at SourceForge <http://dunit.sourceforge.net>
*
*)
unit FastMMMonitorTest;
interface
uses
{$IFDEF FASTMM}
FastMM4,
{$ENDIF}
TestFramework,
SysUtils,
Contnrs;
type
TBasicMemMonitor = class(TTestCase)
private
MLM : IDUnitMemLeakMonitor;
FLeakList: array[0..4] of integer; // As many as I think one might need
FLeakListIndex : Word;
function Leaks: integer;
procedure SetLeakList(ListOfLeaks : array of integer);
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure CheckMemManagerLoaded;
procedure CheckMemMonitorCreates;
procedure CheckMemMonitorDestroys;
procedure CheckMemMonitorComparesEqual;
procedure CheckMemMonitorRecoversMemOK;
procedure CheckMemMonitorFailsOnMemoryLeak;
procedure CheckMemMonitorPassOnMemRecovery;
procedure CheckMemMonitorFailsOnMemRecovery;
procedure CheckMemMonitorPassesOnAllowedMemRecovery;
procedure CheckMemMonitorPassedOnAllowedPositiveLeak;
procedure CheckMemMonitorPassOnListAllowedNoLeak0;
procedure CheckMemMonitorFailOnEmptyListAndPositiveLeak;
procedure CheckMemMonitorPassOnListAllowedPositiveLeak1;
procedure CheckMemMonitorFailOnEmptyListAndNegativeLeak;
procedure CheckMemMonitorPassOnListNegativeLeak;
procedure CheckMemMonitorPassOnListAllowedNegativeLeak1;
procedure CheckOffsetProperty;
end;
TMemMonitorGetErrorMessage = class(TTestCase)
private
MLM : IDUnitMemLeakMonitor;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure CheckGetMemoryUseMsgOK;
procedure CheckGetRecoveredMemMsg;
procedure CheckGetAllowedRecoveredMemMsg;
procedure CheckGetLeakedMemMsg;
end;
TMemMonitorGetErrorMessageNew = class(TTestCase)
private
MLM : IDUnitMemLeakMonitor;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure CheckSumOfLeaks;
procedure CheckGetMemoryUseMsgOK;
procedure CheckGetRecoveredMemMsg;
procedure CheckGetLeakedMemMsg;
end;
TMemMonitorStringLeakHandling = class(TTestCase)
private
fClearVarsInTearDown: boolean;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure CheckMemManagerNoLeaks1;
procedure CheckMemManagerNoLeaks2;
procedure CheckMemManagerLeaks;
procedure CheckMemManagerNoLeaks3;
procedure CheckMemManagerNoLeaks4;
end;
TMemMonitorObjectLeakHandling = class(TTestCase)
private
fClearVarsInTearDown: boolean;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure CheckMemManagerNoLeaks1;
procedure CheckMemManagerNoLeaks2;
procedure CheckMemManagerLeaks;
procedure CheckMemManagerNoLeaks3;
procedure CheckMemManagerNoLeaks4;
end;
TMemMonitorExceptLeakHandling = class(TTestCase)
private
fClearVarsInTearDown: boolean;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure CheckMemManagerNoLeaks1;
procedure CheckMemManagerNoLeaks2;
procedure CheckMemManagerLeaks;
procedure CheckMemManagerNoLeaks3;
procedure CheckMemManagerNoLeaks4;
end;
TMemMonitorMemAllocLeakHandling = class(TTestCase)
private
fClearVarsInTearDown: boolean;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure CheckMemManagerNoLeaks1;
procedure CheckMemManagerNoLeaks2;
procedure CheckMemManagerLeaks;
procedure CheckMemManagerNoLeaks3;
procedure CheckMemManagerNoLeaks4;
end;
var
LeakedObject: TObject = nil;
Excpt: EAbort;
LeakyArray : array of Byte;
LeakyString : string;
LeakyMemory : PChar;
ObjectList : TObjectList;
procedure ClearVars;
function MemManagerLoaded: boolean;
implementation
uses
FastMMMemLeakMonitor;
procedure ClearVars;
begin
SetLength(LeakyArray,0);
LeakyArray := nil;
SetLength(LeakyString, 0);
LeakyString := '';
FreeAndNil(LeakedObject);
if (LeakyMemory <> nil) then
try
FreeMem(LeakyMemory);
LeakyMemory := nil;
except
LeakyMemory := nil;
end;
try
if Assigned(Excpt) then
raise excpt;
except
Excpt := nil;
end;
try
FreeAndNil(ObjectList);
except
end;
end;
procedure TBasicMemMonitor.SetUp;
begin
inherited;
ClearVars;
MLM := nil;
end;
procedure TBasicMemMonitor.TearDown;
begin
inherited;
try
ClearVars;
finally
MLM := nil;
end;
end;
function MemManagerLoaded: boolean;
begin
Result := IsMemoryManagerSet;
end;
procedure TBasicMemMonitor.CheckMemManagerLoaded;
begin
Check(MemManagerLoaded, 'Memory Manager not loaded');
end;
procedure TBasicMemMonitor.CheckMemMonitorCreates;
begin
try
MLM := TDUnitMemLeakMonitor.Create;
finally
Check(Assigned(MLM), 'MemLeakMonitor failed to create');
MLM := nil;
end;
end;
procedure TBasicMemMonitor.CheckMemMonitorDestroys;
var
yyxx: boolean;
begin
yyxx := False;
try
MLM := TDUnitMemLeakMonitor.Create;
yyxx := True;
finally
Check(Assigned(MLM), 'MemLeakMonitor failed to create');
try
Check(yyxx = True, 'MemLeakMonitor failed to create cleanly');
MLM := nil;
yyxx := False;
finally
Check(yyxx = False, 'MemLeakMonitor failed to Destroy cleanly');
end;
end;
end;
procedure TBasicMemMonitor.CheckMemMonitorComparesEqual;
var
MemUsed : Integer;
status : boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
status := (MLM as IMemLeakMonitor).MemLeakDetected(MemUsed);
Check(not status, 'Return result on equal memory comparison not set false');
Check((MemUsed=0), 'Return value on equal memory comparison does not equal zero');
end;
procedure TBasicMemMonitor.CheckMemMonitorRecoversMemOK;
var
MemUsed : Integer;
status: boolean;
begin
SetLength(LeakyArray, 100);
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 0);
LeakyArray := nil;
status := MLM.MemLeakDetected(0, False, MemUsed);
Check(not status, 'Return result on ignored less memory comparison not set False');
Check((MemUsed < 0), 'Return value on freed up memory comparison not less than zero');
end;
procedure TBasicMemMonitor.CheckMemMonitorPassOnMemRecovery;
var
MemUsed : Integer;
status: boolean;
begin
SetLength(LeakyArray, 100);
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 0);
LeakyArray := nil;
status := MLM.MemLeakDetected(0, False, MemUsed);
Check(not status, 'Return result on memory recovery set True');
Check((MemUsed < 0), 'Return value on freed up memory comparison not less than zero');
end;
procedure TBasicMemMonitor.CheckMemMonitorFailsOnMemRecovery;
var
MemUsed : Integer;
status: boolean;
begin
SetLength(LeakyArray, 100);
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 0);
LeakyArray := nil;
status := MLM.MemLeakDetected(0, True, MemUsed);
Check(status, 'Return result on memory recovery set False');
Check((MemUsed < 0), 'Return value on freed up memory comparison not less than zero');
end;
procedure TBasicMemMonitor.CheckMemMonitorPassesOnAllowedMemRecovery;
var
MemUsed : Integer;
status: boolean;
begin
SetLength(LeakyArray, 100);
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 0);
LeakyArray := nil;
status := MLM.MemLeakDetected(-112, True, MemUsed);
Check(not status, 'Return result on less memory comparison set False');
Check((MemUsed < 0), 'Return value on freed up memory comparison not less than zero');
end;
procedure TBasicMemMonitor.CheckMemMonitorFailsOnMemoryLeak;
var
MemUsed : Integer;
status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 100);
try
status := (MLM as IMemLeakMonitor).MemLeakDetected(MemUsed);
Check(status, 'Return result on less memory comparison not set true');
Check((MemUsed > 0), 'Return value leaked memory comparison not greater than zero');
finally
SetLength(LeakyArray, 0);
LeakyArray := nil;
end;
end;
procedure TBasicMemMonitor.CheckMemMonitorPassedOnAllowedPositiveLeak;
var
MemUsed : Integer;
status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 100);
try
status := MLM.MemLeakDetected(112, True, MemUsed);
Check(not status, 'Return result on offset memory comparison not set true');
Check((MemUsed = 112), 'Return value = ' + IntToStr(MemUsed) +
' Should be 112');
finally
SetLength(LeakyArray, 0);
LeakyArray := nil;
end;
end;
procedure TBasicMemMonitor.CheckMemMonitorFailOnEmptyListAndPositiveLeak;
var
MemUsed : Integer;
status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 100);
try
status := MLM.MemLeakDetected(Integer(Leaks), True, MemUsed);
Check(status, 'Return result on empty array with leak was set False');
Check((MemUsed = 112), 'Return value = ' + IntToStr(MemUsed) +
' Should be 112');
finally
SetLength(LeakyArray, 0);
LeakyArray := nil;
end;
end;
procedure TBasicMemMonitor.CheckMemMonitorPassOnListAllowedNoLeak0;
var
MemUsed : Integer;
status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 100);
try
status := MLM.MemLeakDetected(112, True, MemUsed);
Check(not status, 'Return result on offset memory comparison not set true');
Check((MemUsed = 112), 'Return value = ' + IntToStr(MemUsed) +
' Should be 112');
finally
SetLength(LeakyArray, 0);
LeakyArray := nil;
end;
end;
procedure TBasicMemMonitor.CheckMemMonitorPassOnListAllowedPositiveLeak1;
var
MemUsed : Integer;
status: boolean;
LIndex: integer;
begin
SetLeakList([112]);
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 100);
try
status := MLM.MemLeakDetected(Integer(Leaks), True, MemUsed);
Check(not status, 'Return result on single matching allowed not set true');
SetLeakList([112,1]);
status := MLM.MemLeakDetected(Leaks, True, LIndex, MemUsed);
Check(not status, 'Return result on 1st in list match not set true');
SetLeakList([1, 112]);
status := MLM.MemLeakDetected(Leaks, True, LIndex, MemUsed);
Check(not status, 'Return result on 2nd in list not set true');
Check((MemUsed = 112), 'Return value = ' + IntToStr(MemUsed) +
' Should be 112');
finally
SetLength(LeakyArray, 0);
LeakyArray := nil;
end;
end;
procedure TBasicMemMonitor.CheckMemMonitorFailOnEmptyListAndNegativeLeak;
var
MemUsed : Integer;
status: boolean;
begin
SetLength(LeakyArray, 100);
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 0);
LeakyArray := nil;
SetLeakList([0]);
status := MLM.MemLeakDetected(Integer(Leaks), True, MemUsed);
Check(status, 'Return result on less memory comparison set False');
Check((MemUsed < 0), 'Return value on freed up memory comparison not less than zero');
end;
procedure TBasicMemMonitor.CheckMemMonitorPassOnListNegativeLeak;
var
MemUsed : Integer;
status: boolean;
LIndex: integer;
begin
SetLength(LeakyArray, 100);
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 0);
LeakyArray := nil;
SetLeakList([]);
status := MLM.MemLeakDetected(Integer(Leaks), False, MemUsed);
Check(not status, 'Return result on memory recovery set true');
status := MLM.MemLeakDetected(Leaks, False, LIndex, MemUsed);
Check(not status, 'Return result on empty list memory recovery set true');
Check((MemUsed < 0), 'Return value on freed up memory comparison not less than zero');
end;
procedure TBasicMemMonitor.CheckMemMonitorPassOnListAllowedNegativeLeak1;
var
MemUsed : Integer;
status: boolean;
LIndex: integer;
begin
SetLength(LeakyArray, 100);
MLM := TDUnitMemLeakMonitor.Create;
SetLength(LeakyArray, 0);
LeakyArray := nil;
SetLeakList([-112]);
status := MLM.MemLeakDetected(Integer(Leaks), True, MemUsed);
Check(not status, 'Return result on single matching allowed not set true');
SetLeakList([-112, 1]);
status := MLM.MemLeakDetected(Leaks, True, LIndex, MemUsed);
Check(not status, 'Return result on 1st in list match not set true');
SetLeakList([1, -112]);
status := MLM.MemLeakDetected(Leaks, True, LIndex, MemUsed);
Check(not status, 'Return result on 2nd in list not set true');
Check((MemUsed < 0), 'Return value on freed up memory comparison not less than zero');
end;
procedure TBasicMemMonitor.CheckOffsetProperty;
begin
Check(AllowedMemoryLeakSize = 0,
' AllowedMemoryLeakSize should always be zero on entry but was '
+ IntToStr(AllowedMemoryLeakSize));
AllowedMemoryLeakSize := 10;
Check(AllowedMemoryLeakSize = 10,
' AllowedMemoryLeakSize should always be 10 but was '
+ IntToStr(AllowedMemoryLeakSize));
AllowedMemoryLeakSize := AllowedMemoryLeakSize - 10;
Check(AllowedMemoryLeakSize = 0,
' AllowedMemoryLeakSize should always be 0 but was '
+ IntToStr(AllowedMemoryLeakSize));
end;
{------------------------------------------------------------------------------}
{ TMemMonitorStringLeakHandling }
procedure TMemMonitorStringLeakHandling.SetUp;
begin
inherited;
ClearVars;
fClearVarsInTearDown := True;
end;
procedure TMemMonitorStringLeakHandling.TearDown;
begin
inherited;
if fClearVarsInTearDown then
ClearVars;
end;
procedure TMemMonitorStringLeakHandling.CheckMemManagerLeaks;
begin
Check(IsMemoryManagerSet, 'Memory Manager not loaded');
SetLength(LeakyString,200);
fClearVarsInTearDown := False;
end;
procedure TMemMonitorStringLeakHandling.CheckMemManagerNoLeaks1;
begin
Check(IsMemoryManagerSet, 'Memory Manager not loaded');
SetLength(LeakyString,200);
fClearVarsInTearDown := True;
end;
procedure TMemMonitorStringLeakHandling.CheckMemManagerNoLeaks2;
begin
CheckMemManagerNoLeaks1;
end;
procedure TMemMonitorStringLeakHandling.CheckMemManagerNoLeaks3;
begin
CheckMemManagerNoLeaks1;
end;
procedure TMemMonitorStringLeakHandling.CheckMemManagerNoLeaks4;
begin
CheckMemManagerNoLeaks1;
end;
{ TMemMonitorObjectLeakHandling }
procedure TMemMonitorObjectLeakHandling.SetUp;
begin
inherited;
ClearVars;
fClearVarsInTearDown := True;
end;
procedure TMemMonitorObjectLeakHandling.TearDown;
begin
inherited;
if fClearVarsInTearDown then
ClearVars;
end;
procedure TMemMonitorObjectLeakHandling.CheckMemManagerLeaks;
begin
Check(IsMemoryManagerSet, 'Memory Manager not loaded');
LeakedObject := TObject.Create;
fClearVarsInTearDown := False;
end;
procedure TMemMonitorObjectLeakHandling.CheckMemManagerNoLeaks1;
begin
Check(IsMemoryManagerSet, 'Memory Manager not loaded');
LeakedObject := TObject.Create;
fClearVarsInTearDown := True;
end;
procedure TMemMonitorObjectLeakHandling.CheckMemManagerNoLeaks2;
begin
CheckMemManagerNoLeaks1;
end;
procedure TMemMonitorObjectLeakHandling.CheckMemManagerNoLeaks3;
begin
CheckMemManagerNoLeaks1;
end;
procedure TMemMonitorObjectLeakHandling.CheckMemManagerNoLeaks4;
begin
CheckMemManagerNoLeaks1;
end;
{ TMemMonitorExceptLeakHandling }
procedure TMemMonitorExceptLeakHandling.SetUp;
begin
inherited;
ClearVars;
fClearVarsInTearDown := True;
end;
procedure TMemMonitorExceptLeakHandling.TearDown;
begin
inherited;
if fClearVarsInTearDown then
ClearVars;
end;
procedure TMemMonitorExceptLeakHandling.CheckMemManagerLeaks;
begin
Check(IsMemoryManagerSet, 'Memory Manager not loaded');
Excpt := EAbort.Create('');
fClearVarsInTearDown := False;
end;
procedure TMemMonitorExceptLeakHandling.CheckMemManagerNoLeaks1;
begin
Check(IsMemoryManagerSet, 'Memory Manager not loaded');
Excpt := EAbort.Create('');
fClearVarsInTearDown := True;
end;
procedure TMemMonitorExceptLeakHandling.CheckMemManagerNoLeaks2;
begin
CheckMemManagerNoLeaks1;
end;
procedure TMemMonitorExceptLeakHandling.CheckMemManagerNoLeaks3;
begin
CheckMemManagerNoLeaks1;
end;
procedure TMemMonitorExceptLeakHandling.CheckMemManagerNoLeaks4;
begin
CheckMemManagerNoLeaks1;
end;
{ TMemMonitorMemAllocLeakHandling }
procedure TMemMonitorMemAllocLeakHandling.CheckMemManagerLeaks;
begin
Check(MemManagerLoaded, 'Memory Manager not loaded');
GetMem(LeakyMemory, 1000);
fClearVarsInTearDown := False;
end;
procedure TMemMonitorMemAllocLeakHandling.CheckMemManagerNoLeaks1;
begin
Check(MemManagerLoaded, 'Memory Manager not loaded');
GetMem(LeakyMemory, 1000);
fClearVarsInTearDown := True;
end;
procedure TMemMonitorMemAllocLeakHandling.CheckMemManagerNoLeaks2;
begin
CheckMemManagerNoLeaks1;
end;
procedure TMemMonitorMemAllocLeakHandling.CheckMemManagerNoLeaks3;
begin
CheckMemManagerNoLeaks1;
end;
procedure TMemMonitorMemAllocLeakHandling.CheckMemManagerNoLeaks4;
begin
CheckMemManagerNoLeaks1;
end;
procedure TMemMonitorMemAllocLeakHandling.SetUp;
begin
inherited;
ClearVars;
fClearVarsInTearDown := True;
end;
procedure TMemMonitorMemAllocLeakHandling.TearDown;
begin
inherited;
if fClearVarsInTearDown then
ClearVars;
end;
{ TMemMonitorGetErrorMessage }
procedure TMemMonitorGetErrorMessage.SetUp;
begin
inherited;
ClearVars;
MLM := nil;
end;
procedure TMemMonitorGetErrorMessage.TearDown;
begin
inherited;
try
ClearVars;
finally
MLM := nil;
end;
end;
procedure TMemMonitorGetErrorMessage.CheckGetMemoryUseMsgOK;
var
ErrorStr: string;
Status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
status := MLM.GetMemoryUseMsg(False, 0, ErrorStr);
Check(Status, 'Status should be True');
Check(ErrorStr = '', 'Simple Test String should be empty but = ' + ErrorStr);
status := MLM.GetMemoryUseMsg(True, 0, ErrorStr);
Check(Status, 'Status should be True');
Check(ErrorStr = '', 'Simple Test String should be empty but = ' + ErrorStr);
end;
procedure TMemMonitorGetErrorMessage.CheckGetRecoveredMemMsg;
var
ErrorStr: string;
Status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
status := MLM.GetMemoryUseMsg(False, -1, ErrorStr);
Check(Status, 'Status should be True');
Check(ErrorStr = '', 'Simple Test string should be empty');
end;
procedure TMemMonitorGetErrorMessage.CheckGetAllowedRecoveredMemMsg;
var
ErrorStr: string;
Status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
status := MLM.GetMemoryUseMsg(True, -1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr <> '', 'Simple Test string should not be empty');
Check(ErrorStr = '1 Bytes Memory Recovered in Test Procedure',
' Error String reads <' + ErrorStr +
'> but should read <1 Bytes Memory Recovered in Test Procedure>');
end;
procedure TMemMonitorGetErrorMessage.CheckGetLeakedMemMsg;
var
ErrorStr: string;
Status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
status := MLM.GetMemoryUseMsg(False, 1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '1 Bytes Memory Leak in Test Procedure',
' Error String reads <' + ErrorStr +
'> but should read <1 Bytes Memory Leak in Test Procedure>');
status := MLM.GetMemoryUseMsg(True, 1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '1 Bytes Memory Leak in Test Procedure',
' Error String reads <' + ErrorStr +
'> but should read <1 Bytes Memory Leak in Test Procedure>');
end;
function TBasicMemMonitor.Leaks: integer;
begin
if FLeakListIndex >= Length(FLeakList) then
result := 0
else
begin
result := FLeakList[FLeakListIndex];
inc(FLeakListIndex);
end;
end;
procedure TBasicMemMonitor.SetLeakList(ListOfLeaks: array of integer);
var
I: Integer;
begin
for I := 0 to Length(FLeakList) - 1 do // Iterate
begin
if I < Length(ListOfLeaks) then
FLeakList[I] := ListOfLeaks[I]
else
FLeakList[I] := 0;
end; // for
FLeakListIndex := 0;
end;
{ TMemMonitorGetErrorMessageNew }
procedure TMemMonitorGetErrorMessageNew.SetUp;
begin
inherited;
ClearVars;
MLM := nil;
end;
procedure TMemMonitorGetErrorMessageNew.TearDown;
begin
inherited;
try
ClearVars;
finally
MLM := nil;
end;
end;
procedure TMemMonitorGetErrorMessageNew.CheckSumOfLeaks;
var
ErrorStr: string;
Status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
status := MLM.GetMemoryUseMsg(False, 0, 0, 0, 1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr =
('Error in TestFrameWork. No leaks in Setup, TestProc or Teardown but '+
'1 Bytes Memory Leak reported across TestCase'), 'ErrorStr = ' + ErrorStr);
status := MLM.GetMemoryUseMsg(False, 1, 2, 3, 1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr =
('Error in TestFrameWork. Sum of Setup, TestProc and Teardown leaks <> '+
'1 Bytes Memory Leak reported across TestCase'), 'ErrorStr = ' + ErrorStr);
end;
procedure TMemMonitorGetErrorMessageNew.CheckGetMemoryUseMsgOK;
var
ErrorStr: string;
Status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
status := MLM.GetMemoryUseMsg(False, 0, 0, 0, 0, ErrorStr);
Check(Status, 'Status should be True');
Check(ErrorStr = '', 'Complete Test String should be empty but = ' + ErrorStr);
status := MLM.GetMemoryUseMsg(True, 0, 0, 0, 0, ErrorStr);
Check(Status, 'Status should be True');
Check(ErrorStr = '', 'Complete Test String should be empty but = ' + ErrorStr);
end;
procedure TMemMonitorGetErrorMessageNew.CheckGetRecoveredMemMsg;
var
ErrorStr: string;
Status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
status := MLM.GetMemoryUseMsg(False, -1, 0, 0, -1, ErrorStr);
Check(Status, 'Status should be True. ErrorMessage =' + ErrorStr);
Check(ErrorStr = '', 'Complete Test String should be empty but = ' + ErrorStr);
status := MLM.GetMemoryUseMsg(False, 0, -1, 0, -1, ErrorStr);
Check(Status, 'Status should be True. ErrorMessage =' + ErrorStr);
Check(ErrorStr = '', 'Complete Test String should be empty but = ' + ErrorStr);
status := MLM.GetMemoryUseMsg(False, 0, 0, -1, -1, ErrorStr);
Check(Status, 'Status should be True. ErrorMessage =' + ErrorStr);
Check(ErrorStr = '', 'Complete Test String should be empty but = ' + ErrorStr);
status := MLM.GetMemoryUseMsg(False, -1, -2, 0, -3, ErrorStr);
Check(Status, 'Status should be True. ErrorMessage =' + ErrorStr);
Check(ErrorStr = '', 'Complete Test String should be empty but = ' + ErrorStr);
status := MLM.GetMemoryUseMsg(False, 0, -1, -2, -3, ErrorStr);
Check(Status, 'Status should be True. ErrorMessage =' + ErrorStr);
Check(ErrorStr = '', 'Complete Test String should be empty but = ' + ErrorStr);
status := MLM.GetMemoryUseMsg(False, -1, -2, -3, -6, ErrorStr);
Check(Status, 'Status should be True. ErrorMessage =' + ErrorStr);
Check(ErrorStr = '', 'Complete Test String should be empty but = ' + ErrorStr);
status := MLM.GetMemoryUseMsg(True, -1, 0, 0, -1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '-1 Bytes memory recovered (Setup= -1 )',
'ErrorMsg should read <-1 Bytes memory recovered (Setup= -1 )>'+
' but was <' + ErrorStr + '>');
status := MLM.GetMemoryUseMsg(True, 0, -1, 0, -1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '-1 Bytes memory recovered (' +
'TestProc= -1 )',
'ErrorMsg should read <-1 Bytes memory recovered (TestProc= -1 )>' +
' but was <' + ErrorStr + '>');
status := MLM.GetMemoryUseMsg(True, 0, 0, -1, -1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '-1 Bytes memory recovered (' +
'TearDown= -1 )',
'ErrorMsg should read <-1 Bytes memory recovered (TearDown= -1 )>'+
' but was <' + ErrorStr + '>');
status := MLM.GetMemoryUseMsg(True, -1, -2, -3, -6, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '-6 Bytes memory recovered (' +
'Setup= -1 TestProc= -2 TearDown= -3 )',
'ErrorMsg should read ' +
'<-6 Bytes memory recovered (Setup= -1 TestProc= -2 TearDown= -3 )>' +
' but was <' + ErrorStr + '>');
end;
procedure TMemMonitorGetErrorMessageNew.CheckGetLeakedMemMsg;
var
ErrorStr: string;
Status: boolean;
begin
MLM := TDUnitMemLeakMonitor.Create;
status := MLM.GetMemoryUseMsg(False, 0, 0, 0, 0, ErrorStr);
Check(Status, 'Status should be True');
Check(ErrorStr = '', 'Complete Test String should be empty but = ' + ErrorStr);
status := MLM.GetMemoryUseMsg(False, 1, 0, 0, 1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '1 Bytes memory leak (' +
'Setup= 1 )',
'ErrorMsg should read <1 Bytes memory leak (Setup= 1 )' +
' but was <' + ErrorStr + '>');
status := MLM.GetMemoryUseMsg(False, 1, 0, 0, 1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '1 Bytes memory leak (' +
'Setup= 1 )',
'ErrorMsg should read <1 Bytes memory leak (Setup=1 )' +
' but was <' + ErrorStr + '>');
status := MLM.GetMemoryUseMsg(False, 0, 1, 0, 1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '1 Bytes memory leak (' +
'TestProc= 1 )',
'ErrorMsg should read <1 Bytes memory leak (TestProc= 1 )>' +
' but was <' + ErrorStr + '>');
status := MLM.GetMemoryUseMsg(False, 0, 0, 1, 1, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '1 Bytes memory leak (' +
'TearDown= 1 )',
'ErrorMsg should read <1 Bytes memory leak (TearDown= 1 )>' +
' but was <' + ErrorStr + '>');
status := MLM.GetMemoryUseMsg(False, 1, 2, 0, 3, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '3 Bytes memory leak (' +
'Setup= 1 TestProc= 2 )',
'ErrorMsg should read <3 Bytes memory leak (Setup= 1 TestProc= 2 )>' +
' but was <' + ErrorStr + '>');
status := MLM.GetMemoryUseMsg(False, 0, 2, 1, 3, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '3 Bytes memory leak (' +
'TestProc= 2 TearDown= 1 )',
'ErrorMsg should read <3 Bytes memory leak (TestProc= 2 TearDown= 1 )>' +
' but was <' + ErrorStr + '>');
status := MLM.GetMemoryUseMsg(False, 1, 0, 2, 3, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '3 Bytes memory leak (' +
'Setup= 1 TearDown= 2 )',
'ErrorMsg should read <3 Bytes memory leak (Setup= 1 TearDown= 2 )>' +
' but was <' + ErrorStr + '>');
status := MLM.GetMemoryUseMsg(False, 1, 2, 3, 6, ErrorStr);
Check(not Status, 'Status should be False');
Check(ErrorStr = '6 Bytes memory leak (' +
'Setup= 1 TestProc= 2 TearDown= 3 )',
'ErrorMsg should read ' +
'<3 Bytes memory leak (Setup= 1 TestProc= 2 TearDown= 3 )>' +
' but was <' + ErrorStr + '>');
end;
initialization
Excpt := nil;
LeakyMemory := nil;
LeakyString := '';
ObjectList := nil;
end.
|
unit Evaluator;
interface
uses StrUtils, SysUtils, Classes, Windows, Contnrs,
Messages, Dialogs, Variants, DateUtils;
const
AlphaNum = ['a'..'z', 'A'..'Z', 'а'..'я', 'А'..'Я', '_', '1'..'9', '0'];
type
TPreCheck = procedure (List, SetList : TStringList);
TLog = procedure(S : string);
function EvalExp(const S : string; PreCheck : TPreCheck; VarList, SetList : TStringList) : Variant;
procedure SetCheck(L, SetList : TStringList);
var
eLog : TLog = nil;
implementation
// Op | =, <>, in, *, +, -, or, and, not
// paran | ()[]
// sep | , blank
// правая ! ~ \ = \ унарные + и -
// != <>
// унарные
// * / not
// + -
// < <= > >=
// = <>
// and
// or
type
TKind = (kLeftPar, kOper, kConst);
TOper = (oMult, oSingleAdd, oSingleSub, oAdd, oSub, oIn, oEqual, oNotEqual, oGt, oGtEq, oLt, oLtEq, oNot, oAnd, oOr);
TDataType = (otSet, otBool, otFloat, otDate, otStr);
PItem = ^TItem;
TItem = record
Kind : TKind;
Value: Variant;
StrValue : string;
Src : string;
Oper : TOper;
List : boolean;
DataType : TDataType;
end;
PTrigStateExp = ^TTrigStateExp;
TTrigStateExp = record
Name : string;
TrigID : integer;
State : string;
Expr : string;
end;
TOutState = (osOn, osOff);
TSendUnchanged = set of TOutState;
POutStateDef = ^TOutStateDef;
TOutStateDef = record
Name : string;
OutId : integer;
SendUnchangedTime : TDateTime;
Expr : string;
State : TOutState;
SendUnchanged : TSendUnchanged;
end;
const
SKind : array[ TKind ] of string =
('LeftPar', 'Oper', 'Const');
SOper : array[ TOper ] of string =
('*', '+', '-', '+', '-', 'in', '=', '<>', '>', '>=', '<', '<=', 'not', 'and', 'or');
Pri : array[ TOper ] of integer =
(10, 11, 11, 9, 9, 8, 6, 6, 7, 7, 7, 7, 11, 4, 2);
// (oMult, oSingleAdd, oSingleSub, oAdd, oSub, oIn, oEqual, oNotEqual, oGt, oGtEq, oLt, oLtEq, oNot, oAnd, oOr);
// унарные
// * / not
// + -
// < <= > >=
// = <>
// and
// or
procedure Error(S : string);
begin
raise Exception.Create(S);
end;
function IndInList(const Word, List : string; Sep : string = ',') : integer;
var Pred, P : PChar;
begin
Result := -1;
Pred := PChar(List);
P := AnsiStrPos(Pred, PChar(Sep));
if P = nil then
begin
if Word = Trim(List) then
Inc(Result)
end else
begin
while P <> nil do
begin
Inc(Result);
if SameStr(Word, Trim(Copy(Pred, 1, P - Pred))) then
Exit;
Pred := P + 1;
P := AnsiStrPos(Pred, PChar(Sep));
end;
if SameStr(Word, Trim(Pred)) then
Inc(Result)
else
Result := -1;
end;
end;
function WordByInd(const List : string; Ind : integer; Sep : string = ',') : string;
var Pred, P : PChar;
N : integer;
begin
Result := '';
N := 0;
Pred := PChar(List);
P := AnsiStrPos(PChar(List), PChar(Sep));
while (N <> Ind) and (P <> nil) do
begin
Inc(N);
Pred := P + 1;
P := AnsiStrPos(Pred, PChar(Sep));
end;
if N = Ind then
begin
if P = nil then
P := StrEnd(Pred);
Result := Trim(Copy(Pred, 1, P - Pred));
end;
end;
function ListCount(const List : string; Sep : string = ',') : integer;
var P : PChar;
begin
Result := 1;
P := AnsiStrPos(PChar(List), PChar(Sep));
while P <> nil do
begin
Inc(Result);
P := AnsiStrPos(P + 1, PChar(Sep));
end;
end;
procedure DeleteFromList(const Word : string; var List : string; Sep : string = ',');
var Pred, P : PChar;
nPos : integer;
begin
Pred := PChar(List);
P := AnsiStrPos(PChar(List), PChar(Sep));
if P = nil then
begin
if SameStr(Word, Trim(List)) then
List := ''
end else
begin
while P <> nil do
begin
if SameStr(Word, Trim(Copy(Pred, 1, P - Pred))) then
Break;
Pred := P + 1;
P := AnsiStrPos(Pred, PChar(Sep));
end;
if P = nil then
begin
P := StrEnd(Pred);
if Word <> Trim(Copy(Pred, 1, P - Pred)) then
Exit;
end;
nPos := Pred - PChar(List);
if Pred = PChar(List)then
Inc(nPos);
Delete(List, nPos, P - Pred + 1);
end;
end;
procedure SetRange(List, SetList : TStringList; var Ind : integer);
var S : string;
I, J : integer;
ibeg : integer;
iend : integer;
begin
S := List[ Ind ];
List.Delete(Ind);
I := Pos('..', S);
ibeg := StrToInt(Copy(S, 2, I - 2));
iend := StrToInt(Copy(S, I + 3, MaxInt));
for I := 0 to SetList.Count - 1 do
begin
J := StrToInt(Copy(SetList.Names[ I ], 2, MaxInt));
if (J >= ibeg) and (J <= iend) then
begin
List.Insert(Ind, UpperCase(SetList.ValueFromIndex[ I ]));
Inc(Ind);
end;
end;
end;
procedure SetCheck(L, SetList : TStringList);
var I, J : integer;
begin
I := 0;
while I < L.Count do
if Pos('..', L[ I ]) <> 0 then
SetRange(L, SetList, I)
else
begin
J := SetList.IndexOfName(L[ I ]);
if J <> -1 then
L[ I ] := UpperCase(SetList.ValueFromIndex[ J ]);
Inc(I);
end;
end;
procedure SetOperandType(Item : PItem; IsVar : boolean = False);
var F : Double;
D : TDateTime;
begin
Item.DataType := otStr;
with Item ^ do
if List then
DataType := otSet
else {if not IsVar then} case VarType(Value) of
varBoolean :
DataType := otBool;
varSmallint..varCurrency,
varShortInt..varInt64 :
DataType := otFloat;
varDate :
DataType := otDate;
varString :
if not IsVar then
begin
if TryStrToFloat(Value, F) then
begin
DataType := otFloat;
Value := F;
end else if TryStrToDateTime(Value, D) then
begin
DataType := otDate;
Value := D;
end;
end;
end;
end;
function ParseExp(const S : string; Res : TList; PreCheck : TPreCheck; VarList, SetList : TStringList) : boolean;
var P, P1, B, P0 : PChar;
Stack : TStack;
Op, Op1 : string;
I : integer;
WaitOperand : boolean;
F : Double;
D : TDateTime;
Ch : Char;
Src : string;
procedure StackToRes;
var Tmp : PItem;
begin
Tmp := PItem(Stack.Pop);
Res.Add(Tmp);
end;
procedure AddOp(Op : TOper);
var Item : PItem;
RightAsso : boolean;
function Unload : boolean;
var Item : PItem;
begin
Item := PItem(Stack.Peek);
Result := (Item.Kind = kOper) and
((Pri[ Item.Oper ] > Pri[ Op ]) or not RightAsso
and (Pri[ Item.Oper ] = Pri[ Op ]));
end;
begin
New(Item);
Item.Kind := kOper;
Item.Oper := Op;
if WaitOperand then
begin
if Op in [ oAdd, oSub ] then
Item.Oper := TOper(Ord(Op) - 2)
else if Op <> oNot then
Error('плохое выражение');
end;
Item.Value := null;
Item.List := False;
RightAsso := Op in [ oSingleAdd, oSingleSub, oNotEqual ];
while (Stack.Count > 0) and Unload do
StackToRes;
Stack.Push(Item);
WaitOperand := True;
end;
procedure AddVar(Kind : TKind);
var Item : PItem;
begin
New(Item);
Item.Kind := Kind;
Item.Oper := oMult;
Item.Value := null;
Item.List := False;
Res.Add(Item);
WaitOperand := False;
end;
procedure AddLeftPar;
var Item : PItem;
begin
New(Item);
Item.Kind := kLeftPar;
Item.Oper := oMult;
Item.Value := null;
Item.List := False;
Stack.Push(Item);
WaitOperand := True;
end;
procedure AddOperand(V : Variant; List : boolean; IsVar : boolean = False);
var Item : PItem;
begin
New(Item);
Item.Kind := kConst;
Item.Oper := oMult;
Item.Src := Src;
if VarIsNull(V) then
Item.Value := Op
else
Item.Value := V;
Item.StrValue := Op;
Item.List := List;
SetOperandType(Item, IsVar);
Res.Add(Item);
WaitOperand := False;
end;
function GetList(const S : string) : string;
var L : TStringList;
I, J : integer;
Item : string;
Count : integer;
begin
L := TStringList.Create;
try
L.CommaText := S;
if @PreCheck <> nil then
PreCheck(L, SetList)
else if SetList <> nil then
SetCheck(L, SetList)
else
for I := 0 to L.Count - 1 do
begin
if Pos('..', L[ I ]) <> 0 then
Error('запрещен диапазон');
J := VarList.IndexOfName(L[ I ]);
if J <> -1 then
L[ I ] := UpperCase(VarList.ValueFromIndex[ J ]);
end;
L.Sort;
Count := L.Count;
I := 0;
while I < Count do
begin
Item := L[ I ];
for J := 1 to Length(Item) do
if not (Item[ J ] in AlphaNum) then
Error('Плохой элемент списка');
J := I + 1;
while (J < Count) and (L[ J ] = Item) do
begin
L.Delete(J);
Dec(Count);
end;
Inc(I);
end;
Result := L.CommaText;
finally
L.Free;
end;
end;
begin
if @eLog <> nil then
eLog('--- ' + S);
Stack := TStack.Create;
WaitOperand := True;
try
P := PChar(S);
while P^ <> #0 do
begin
case P^ of
'(' :
begin
Inc(P);
AddLeftPar;
end;
')' :
begin
while (Stack.Count > 0) and (PItem(Stack.Peek).Kind <> kLeftPar) do
StackToRes;
if Stack.Count = 0 then
Error('нет (');
Dispose(PItem(Stack.Pop));
Inc(P);
end;
'[' :
begin
Inc(P);
B := P;
P := StrPos(P, ']');
if P = nil then
Error('нет ]');
Src := '[' + Copy(B, 1, P - B) + ']';
Op := GetList(UpperCase(Copy(B, 1, P - B)));
AddOperand(null, True);
Inc(P);
end;
']' :
Error('нет ]');
' ' :
while P^ = ' ' do Inc(P);
'<' :
begin
Inc(P);
if P^ = '>' then
begin
AddOp(oNotEqual);
Inc(P);
end else if P^ = '=' then
begin
AddOp(oLtEq);
Inc(P);
end else
AddOp(oLt);
end;
'>' :
begin
Inc(P);
if P^ = '=' then
begin
AddOp(oGtEq);
Inc(P);
end else
AddOp(oGt);
end;
'*' :
begin
Inc(P);
AddOp(oMult);
end;
'+' :
begin
Inc(P);
AddOp(oAdd);
end;
'-' :
begin
Inc(P);
AddOp(oSub);
end;
'=' :
begin
Inc(P);
AddOp(oEqual);
end;
'''' :
begin
Src := AnsiExtractQuotedStr(P, '''');
Op := UpperCase(Src);
if P^ = #0 then
Error('нет закрывающей кавычки');
AddOperand(null, False);
end
else
B := P;
while P^ in AlphaNum do Inc(P);
if P = B then
Error('только цифры, буквы)');
Op := UpperCase(TrimRight(Copy(B, 1, P - B)));
if Op = 'AND' then
AddOp(oAnd)
else if Op = 'OR' then
AddOp(oOr)
else if Op = 'IN' then
AddOp(oIn)
else if Op = 'NOT' then
AddOp(oNot)
else
begin
if P^ = ',' then
begin
Inc(P);
while P^ in ['0'..'9'] do
Inc(P);
Op := Copy(B, 1, P - B);
Src := Op;
if TryStrToFloat(Op, F) then
AddOperand(F, False)
else
AddOperand(null, False);
end else if P^ in ['.', ':' ] then
begin
P0 := P;
Ch := P^;
while (P^ = Ch) or (P^ in ['0'..'9']) do
Inc(P);
Op := Copy(B, 1, P - B);
if TryStrToTime(Op, D) then
begin
Src := Op;
AddOperand(D, False);
end else if TryStrToDate(Op, D) then
begin
if (Ch = '.') and (P^ = ' ') then
begin
P1 := P;
while (P1^ in ['0'..'9', '.', ':', ' ']) do
Inc(P1);
Op1 := Copy(B, 1, P1 - B);
if TryStrToDateTime(Op1, D) then
begin
Op := Op1;
P := P1;
end;
end;
Src := Op;
AddOperand(D, False);
end else
begin
SetLength(Op, Length(Op) - 1);
Op := Uppercase(Op);
Src := Op;
P := P0;
AddOperand(null, False);
// Error('плохой операнд');
end;
end else
begin
Src := Op;
I := VarList.IndexOfName(Op);
if I <> -1 then
Op := UpperCase(VarList.ValueFromIndex[ I ]);
AddOperand(null, False{, I <> -1});
end;
end;
end;
end;
while (Stack.Count > 0) and (PItem(Stack.Peek).Kind = kOper) do
StackToRes;
Result := Stack.Count = 0;
if @eLog <> nil then
for I := 0 to Res.Count - 1 do
with PItem(Res[ I ])^ do
if Kind = kOper then
eLog(' ' + SOper[ Oper ])
else
eLog(VarToStr(Value));
finally
while Stack.Count > 0 do
begin
Dispose(PItem(Stack.Peek));
Stack.Pop;
end;
Stack.Free;
end;
end;
function EvalExp(const S : string; PreCheck : TPreCheck; VarList, SetList : TStringList) : Variant;
var I : integer;
Stack : TStack;
Res : TList;
Op1, Op2 : Variant;
S1, S2 : string;
Src1, Src2 : string;
Tp1, Tp2 : TDataType;
procedure Bad;
begin
Error('плохой тип операнда : ' + Src1);
end;
procedure GetOps(Op : TOper);
function CheckTp : boolean;
begin
Result := (Tp1 = Tp2) or
(Tp1 = otDate) and (Tp2 = otFloat) or
(Tp2 = otDate) and (Tp1 = otFloat);
if not Result and ((Tp1 in [otFloat, otDate]) or (Tp2 in [otFloat, otDate])) then
begin
Op1 := S1;
Op2 := S2;
Tp1 := otStr;
Tp2 := otStr;
Result := True;
end;
end;
begin
if not (Op in [oNot, oSingleAdd, oSingleSub]) then
with PItem(Stack.Pop)^ do
begin
case Kind of
kLeftPar, kOper :
Error('плохое выражение');
kConst: Op2 := Value;
end;
Tp2 := DataType;
S2 := StrValue;
Src2 := Src;
end;
with PItem(Stack.Peek)^ do
begin
case Kind of
kLeftPar, kOper :
Error('плохое выражение');
kConst: Op1 := Value;
end;
S1 := StrValue;
Tp1 := DataType;
Src1 := Src;
end;
case Op of
oSingleAdd, oSingleSub:
if Tp1 <> otFloat then
Bad;
oMult :
if not (Tp1 in [otFloat, otSet]) or not CheckTp then
Bad;
oEqual, oNotEqual:
if (Tp1 = otBool) or not CheckTp then
Bad;
oAdd:
if (Tp1 = otBool) or not CheckTp then
Bad;
oSub:
if (Tp1 = otBool) or not CheckTp then
Bad;
oIn:
begin
if Tp1 <> otStr then
begin
Op1 := S1;
Tp1 := otStr;
end;
if Tp2 <> otSet then
Bad;
end;
oNot:
if Tp1 <> otBool then
Bad;
oAnd, oOr:
if (Tp1 <> otBool) or not CheckTp then
Bad;
oGt, oGtEq, oLt, oLtEq :
if (Tp1 in [otBool, otSet]) or not CheckTp then
Bad;
end;
end;
procedure SetRes(V : Variant);
begin
with PItem(Stack.Peek)^ do
begin
Value := V;
Kind := kConst;
List := False;
SetOperandType(PItem(Stack.Peek), True);
end;
end;
procedure MultList;
var Res, S : string;
I : integer;
begin
Res := '';
for I := 0 to ListCount(Op1) - 1 do
begin
S := WordByInd(Op1, I);
if IndInList(S, Op2) <> -1 then
begin
if Res = '' then
Res := S
else
Res := Res + ',' + S;
end;
end;
SetRes(Res);
end;
procedure AddList;
var Res, S : string;
I : integer;
begin
Res := Op2;
for I := 0 to ListCount(Op1) - 1 do
begin
S := WordByInd(Op1, I);
if IndInList(S, Op2) = -1 then
begin
if Res = '' then
Res := S
else
Res := Res + ',' + S;
end;
end;
SetRes(Res);
end;
procedure SubtractList;
var Res, S : string;
I : integer;
begin
Res := Op1;
for I := 0 to ListCount(Op2) - 1 do
begin
S := WordByInd(Op2, I);
if IndInList(S, Res) <> -1 then
DeleteFromList(S, Res);
end;
SetRes(Res);
end;
procedure InList;
begin
SetRes(IndInList(Op1, Op2) <> -1);
end;
begin
if S = '' then
begin
Result := True;
Exit;
end;
Result := False;
Stack := TStack.Create;
try
Res := TList.Create;
try
if ParseExp(S, Res, PreCheck, VarList, SetList) then
for I := 0 to Res.Count - 1 do with PItem(Res[ I ])^ do
begin
if Kind <> kOper then
Stack.Push(Res[ I ])
else
begin
GetOps(Oper);
case Oper of
oSingleAdd :
SetRes(-Op1);
oSingleSub:
SetRes(Op1);
oMult :
case Tp1 of
otSet :
MultList;
otFloat:
SetRes(Op1 * Op2);
end;
oAdd :
case Tp1 of
otSet :
AddList;
otDate :
SetRes(TDateTime(Op1 + Op2));
else
SetRes(Op1 + Op2);
end;
oSub:
case Tp1 of
otSet :
SubtractList;
otDate :
begin
if Tp2 = otDate then
SetRes(Op1 - Op2)
else
SetRes(TDateTime(Op1 - Op2));
end;
else
SetRes(Op1 - Op2);
end;
oIn :
InList;
oEqual:
case Tp1 of
otDate :
SetRes(CompareDateTime(Op1, Op2) = 0);
else
SetRes(VarSameValue(Op1, Op2));
end;
oNotEqual:
case Tp1 of
otDate :
SetRes(CompareDateTime(Op1, Op2) <> 0);
else
SetRes(not VarSameValue(Op1, Op2));
end;
oNot :
SetRes(not Op1);
oAnd :
SetRes(Op1 and Op2);
oOr :
SetRes(Op1 or Op2);
oGt :
if (Tp1 = otDate) or (Tp2 = otDate) then
SetRes(CompareDateTime(Op1, Op2) > 0)
else case Tp1 of
otFloat : SetRes(Op1 > Op2);
otStr : SetRes(CompareStr(Op1, Op2) > 0);
end;
oGtEq :
if (Tp1 = otDate) or (Tp2 = otDate) then
SetRes(CompareDateTime(Op1, Op2) >= 0)
else case Tp1 of
otFloat : SetRes(Op1 >= Op2);
otStr : SetRes(CompareStr(Op1, Op2) >= 0);
end;
oLt :
if (Tp1 = otDate) or (Tp2 = otDate) then
SetRes(CompareDateTime(Op1, Op2) < 0)
else case Tp1 of
otFloat : SetRes(Op1 < Op2);
otStr : SetRes(CompareStr(Op1, Op2) < 0);
end;
oLtEq :
if (Tp1 = otDate) or (Tp2 = otDate) then
SetRes(CompareDateTime(Op1, Op2) <= 0)
else case Tp1 of
otFloat : SetRes(Op1 <= Op2);
otStr : SetRes(CompareStr(Op1, Op2) <= 0);
end;
end;
end;
end;
if Stack.Count = 1 then
Result := PItem(Stack.Peek)^.Value
else
Error('плохое выражение');
finally
for I := 0 to Res.Count - 1 do
Dispose(PItem(Res[ I ]));
Res.Free;
end;
finally
Stack.Free;
end;
end;
initialization
finalization
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.